lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
Java | apache-2.0 | 9b33a129596af41e0ef8e83efb1b7e11c1c82d44 | 0 | TelluIoT/ThingML,TelluIoT/ThingML,TelluIoT/ThingML,TelluIoT/ThingML,TelluIoT/ThingML,TelluIoT/ThingML | /**
* Copyright (C) 2014 SINTEF <[email protected]>
*
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3, 29 June 2007;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.gnu.org/licenses/lgpl-3.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.thingml.testjar;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.thingml.testjar.lang.TargetedLanguage;
import org.thingml.testjar.lang.lArduino;
import org.thingml.testjar.lang.lJava;
import org.thingml.testjar.lang.lJavaScript;
import org.thingml.testjar.lang.lPosix;
/**
*
* @author sintef
*/
public class TestJar {
public static void main(String[] args) throws ExecutionException {
final File workingDir = new File(System.getProperty("user.dir"));
File tmpDir = new File(workingDir, "tmp");
final File testCfgDir = new File(tmpDir, "thingml");
final File codeDir = new File(tmpDir, "genCode");
final File logDir = new File(tmpDir, "log");
final File compilerJar = new File(workingDir, "../compilers/registry/target/compilers.registry-0.7.0-SNAPSHOT-jar-with-dependencies.jar");
tmpDir.delete();
tmpDir = new File(workingDir, "tmp");
final File testFolder = new File(TestJar.class.getClassLoader().getResource("tests").getFile());
String testPattern = "test(.+)\\.thingml";
Set<Command> tasks = new HashSet<>();
List<Future<String>> results = new ArrayList<Future<String>>();
ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
//ExecutorService executor = Executors.newFixedThreadPool(1);
System.out.println("****************************************");
System.out.println("* Test Begin *");
System.out.println("****************************************");
System.out.println("");
System.out.println("Working Directory = " + System.getProperty("user.dir"));
System.out.println("Tmp Directory = " + tmpDir);
System.out.println("Compiler = " + compilerJar);
System.out.println("");
Set<String> wl = new HashSet<>();
wl.add("testEmptyTransition");
wl.add("testInstanceInitializationOrder4");
wl.add("testInstanceInitializationOrder3");
wl.add("testInstanceInitializationOrder2");
wl.add("testInstanceInitializationOrder");
wl.add("testArrays");
wl.add("testDeepCompositeStates");
Set<File> testFiles = whiteListFiles(testFolder, wl);
//Set<File> testFiles = blackListFiles(testFolder, wl);
//Set<File> testFiles = listTestFiles(testFolder, testPattern);
Set<TargetedLanguage> langs = new HashSet<>();
//langs.add(new lPosix());
langs.add(new lJava());
//langs.add(new lJavaScript());
//langs.add(new lArduino());
Set<TestCase> testCases = new HashSet<>();
Map<String,Map<TargetedLanguage,Set<TestCase>>> testBench = new HashMap<>();
testCfgDir.mkdir();
codeDir.mkdir();
logDir.mkdir();
for(TargetedLanguage lang : langs) {
File lCfg = new File(testCfgDir, "_" + lang.compilerID);
lCfg.mkdir();
File lcode = new File(codeDir, "_" + lang.compilerID);
lcode.mkdir();
File llog = new File(logDir, "_" + lang.compilerID);
llog.mkdir();
}
System.out.println("Test Files:");
for(File f : testFiles) {
testBench.put(f.getName(), new HashMap<TargetedLanguage,Set<TestCase>>());
System.out.println(f.getName());
for(TargetedLanguage lang : langs) {
TestCase tc = new TestCase(f, compilerJar, lang, codeDir, testCfgDir, logDir);
testCases.add(tc);
}
}
System.out.println("");
System.out.println("****************************************");
System.out.println("* ThingML Generation *");
System.out.println("****************************************");
for(TestCase tc : testCases) {
Command cmd = tc.lang.generateThingML(tc);
cmd.print();
tasks.add(cmd);
}
try {
results = executor.invokeAll(tasks);
} catch (InterruptedException ex) {
Logger.getLogger(TestJar.class.getName()).log(Level.SEVERE, null, ex);
}
executor.shutdown();
tasks.clear();
System.out.println("Done.");
Set<TestCase> testCfg = new HashSet<>();
for(TestCase tc : testCases) {
Set<TestCase> children = tc.generateChildren();
testCfg.addAll(children);
testBench.get(tc.srcTestCase.getName()).put(tc.lang, children);
}
System.out.println("");
System.out.println("****************************************");
System.out.println("* ThingML Compilation *");
System.out.println("****************************************");
executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
testRun(testCfg, executor);
System.out.println("");
System.out.println("****************************************");
System.out.println("* Generated Code Compilation *");
System.out.println("****************************************");
executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
testRun(testCfg, executor);
System.out.println("");
System.out.println("****************************************");
System.out.println("* Generated Code Execution *");
System.out.println("****************************************");
executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
testRun(testCfg, executor);
System.out.println("");
System.out.println("****************************************");
System.out.println("* Test Results *");
System.out.println("****************************************");
System.out.println("");
writeResultsFile(new File(tmpDir, "results.html"), testBench, langs);
System.out.println("");
System.out.println("More details in " + tmpDir.getAbsolutePath() + "/results.html");
System.out.println("");
}
public static Set<File> listTestFiles(final File folder, String pattern) {
Set<File> res = new HashSet<>();
Pattern p = Pattern.compile(pattern);
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
res.addAll(listTestFiles(fileEntry, pattern));
} else {
Matcher m = p.matcher(fileEntry.getName());
if (m.matches()) {
res.add(fileEntry);
}
}
}
return res;
}
public static Set<File> whiteListFiles(final File folder, Set<String> whiteList) {
String testPattern = "test(.+)\\.thingml";
Set<File> res = new HashSet<>();
for (final File fileEntry : listTestFiles(folder, testPattern)) {
if (fileEntry.isDirectory()) {
res.addAll(whiteListFiles(fileEntry, whiteList));
} else {
String fileName = fileEntry.getName().split("\\.thingml")[0];
boolean found = false;
for(String s : whiteList) {
if (fileName.compareTo(s) == 0) {
found = true;
}
}
if(found)
res.add(fileEntry);
}
}
return res;
}
public static Set<File> blackListFiles(final File folder, Set<String> blackList) {
String testPattern = "test(.+)\\.thingml";
Set<File> res = new HashSet<>();
for (final File fileEntry : listTestFiles(folder, testPattern)) {
if (fileEntry.isDirectory()) {
res.addAll(blackListFiles(fileEntry, blackList));
} else {
String fileName = fileEntry.getName().split("\\.thingml")[0];
boolean found = false;
for(String s : blackList) {
if (fileName.compareTo(s) == 0) {
found = true;
}
}
if(!found)
res.add(fileEntry);
}
}
return res;
}
public static Set<File> listTestDir(final File folder, String pattern) {
Set<File> res = new HashSet<>();
Pattern p = Pattern.compile(pattern);
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
//res.addAll(listTestFiles(fileEntry, pattern));
Matcher m = p.matcher(fileEntry.getName());
if (m.matches()) {
res.add(fileEntry);
}
}
}
return res;
}
public static void testRun(Set<TestCase> tests, ExecutorService executor) {
System.out.println("");
System.out.println("Test Cases:");
Set<Command> tasks = new HashSet<>();
List<Future<String>> results = new ArrayList<Future<String>>();
for(TestCase tc : tests) {
if(tc.isLastStepASuccess) {
Command cmd = tc.ongoingCmd;
cmd.print();
tasks.add(cmd);
}
}
try {
results = executor.invokeAll(tasks);
} catch (InterruptedException ex) {
Logger.getLogger(TestJar.class.getName()).log(Level.SEVERE, null, ex);
}
executor.shutdown();
for(TestCase tc : tests) {
tc.collectResults();
}
System.out.println("Done.");
}
public static void writeResultsFile(File results, Map<String,Map<TargetedLanguage,Set<TestCase>>> tests, Set<TargetedLanguage> langs) {
StringBuilder res = new StringBuilder();
res.append("<!DOCTYPE html>\n" +
"<html>\n" +
" <head>\n" +
" <meta charset=\"utf-8\" />\n" +
" <title>ThingML tests results</title>\n" +
" <style>\n" +
" table\n" +
" {\n" +
" border-collapse: collapse;\n" +
" }\n" +
" td, th \n" +
" {\n" +
" border: 1px solid black;\n" +
" }\n" +
" .green\n" +
" {\n" +
" background: lightgreen\n" +
" }\n" +
" .red\n" +
" {\n" +
" background: red\n" +
" }\n" +
" </style>\n" +
" </head>\n" +
" <body>\n" +
" <table>\n" +
" <tr>\n");
res.append(" <th>Test</th>\n");
for(TargetedLanguage lang : langs) {
res.append(" <th>" + lang.compilerID + "</th>\n");
}
res.append(" </tr>\n");
for(Map.Entry<String,Map<TargetedLanguage,Set<TestCase>>> line : tests.entrySet()) {
StringBuilder lineB = new StringBuilder();
boolean lineSuccess = true;
res.append(" <tr>\n");
res.append(" <td class=\"");
lineB.append(" " + line.getKey() + "\n");
lineB.append(" </td>\n");
for(Map.Entry<TargetedLanguage,Set<TestCase>> cell : line.getValue().entrySet()) {
StringBuilder cellB = new StringBuilder();
boolean cellSuccess = true;
lineB.append(" <td class=\"");
String cellRes = "";
for(TestCase tc : cell.getValue()) {
if(tc.isLastStepASuccess) {
cellRes = "*";
} else {
cellRes = "!";
cellSuccess = false;
}
cellB.append(" <a href=" + tc.logFile.getAbsolutePath() + ">[" +cellRes+ "]</a>\n");
}
if(cellSuccess) {
lineB.append("green");
} else {
lineB.append("red");
cell.getKey().failedTest.add(line.getKey());
}
cell.getKey().testNb++;
lineB.append("\">\n");
lineB.append(cellB);
lineB.append(" </td>\n");
lineSuccess &= cellSuccess;
}
if(lineSuccess) {
res.append("green");
} else {
res.append("red");
}
res.append("\">\n");
res.append(lineB);
res.append(" </tr>\n");
}
res.append(" </table>\n"
+ " </body>\n");
res.append("</html>");
for(TargetedLanguage lang : langs) {
System.out.println("[" + lang.compilerID + "] " + lang.failedTest.size() + " failures out of " + lang.testNb);
System.out.println(" Failed tests:");
for(String fail : lang.failedTest) {
System.out.println(" ! " + fail);
}
System.out.println("");
}
if (!results.getParentFile().exists())
results.getParentFile().mkdirs();
try {
PrintWriter w = new PrintWriter(results);
w.print(res.toString());
w.close();
} catch (Exception ex) {
System.err.println("Problem writting log");
ex.printStackTrace();
}
}
}
| testJar/src/main/java/org/thingml/testjar/TestJar.java | /**
* Copyright (C) 2014 SINTEF <[email protected]>
*
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3, 29 June 2007;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.gnu.org/licenses/lgpl-3.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.thingml.testjar;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.thingml.testjar.lang.TargetedLanguage;
import org.thingml.testjar.lang.lArduino;
import org.thingml.testjar.lang.lJava;
import org.thingml.testjar.lang.lJavaScript;
import org.thingml.testjar.lang.lPosix;
/**
*
* @author sintef
*/
public class TestJar {
public static void main(String[] args) throws ExecutionException {
final File workingDir = new File(System.getProperty("user.dir"));
File tmpDir = new File(workingDir, "tmp");
final File testCfgDir = new File(tmpDir, "thingml");
final File codeDir = new File(tmpDir, "genCode");
final File logDir = new File(tmpDir, "log");
final File compilerJar = new File(workingDir, "../compilers/registry/target/compilers.registry-0.7.0-SNAPSHOT-jar-with-dependencies.jar");
tmpDir.delete();
tmpDir = new File(workingDir, "tmp");
final File testFolder = new File(TestJar.class.getClassLoader().getResource("tests").getFile());
String testPattern = "test(.+)\\.thingml";
Set<Command> tasks = new HashSet<>();
List<Future<String>> results = new ArrayList<Future<String>>();
ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
//ExecutorService executor = Executors.newFixedThreadPool(1);
System.out.println("****************************************");
System.out.println("* Test Begin *");
System.out.println("****************************************");
System.out.println("");
System.out.println("Working Directory = " + System.getProperty("user.dir"));
System.out.println("Tmp Directory = " + tmpDir);
System.out.println("Compiler = " + compilerJar);
System.out.println("");
Set<String> wl = new HashSet<>();
wl.add("testEmptyTransition");
wl.add("testInstanceInitializationOrder4");
wl.add("testInstanceInitializationOrder3");
wl.add("testInstanceInitializationOrder2");
wl.add("testInstanceInitializationOrder");
wl.add("testArrays");
wl.add("testDeepCompositeStates");
//Set<File> testFiles = whiteListFiles(testFolder, wl);
//Set<File> testFiles = blackListFiles(testFolder, wl);
Set<File> testFiles = listTestFiles(testFolder, testPattern);
Set<TargetedLanguage> langs = new HashSet<>();
//langs.add(new lPosix());
langs.add(new lJava());
//langs.add(new lJavaScript());
//langs.add(new lArduino());
Set<TestCase> testCases = new HashSet<>();
Map<String,Map<TargetedLanguage,Set<TestCase>>> testBench = new HashMap<>();
testCfgDir.mkdir();
codeDir.mkdir();
logDir.mkdir();
for(TargetedLanguage lang : langs) {
File lCfg = new File(testCfgDir, "_" + lang.compilerID);
lCfg.mkdir();
File lcode = new File(codeDir, "_" + lang.compilerID);
lcode.mkdir();
File llog = new File(logDir, "_" + lang.compilerID);
llog.mkdir();
}
System.out.println("Test Files:");
for(File f : testFiles) {
testBench.put(f.getName(), new HashMap<TargetedLanguage,Set<TestCase>>());
System.out.println(f.getName());
for(TargetedLanguage lang : langs) {
TestCase tc = new TestCase(f, compilerJar, lang, codeDir, testCfgDir, logDir);
testCases.add(tc);
}
}
System.out.println("");
System.out.println("****************************************");
System.out.println("* ThingML Generation *");
System.out.println("****************************************");
for(TestCase tc : testCases) {
Command cmd = tc.lang.generateThingML(tc);
cmd.print();
tasks.add(cmd);
}
try {
results = executor.invokeAll(tasks);
} catch (InterruptedException ex) {
Logger.getLogger(TestJar.class.getName()).log(Level.SEVERE, null, ex);
}
executor.shutdown();
tasks.clear();
System.out.println("Done.");
Set<TestCase> testCfg = new HashSet<>();
for(TestCase tc : testCases) {
Set<TestCase> children = tc.generateChildren();
testCfg.addAll(children);
testBench.get(tc.srcTestCase.getName()).put(tc.lang, children);
}
System.out.println("");
System.out.println("****************************************");
System.out.println("* ThingML Compilation *");
System.out.println("****************************************");
executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
testRun(testCfg, executor);
System.out.println("");
System.out.println("****************************************");
System.out.println("* Generated Code Compilation *");
System.out.println("****************************************");
executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
testRun(testCfg, executor);
System.out.println("");
System.out.println("****************************************");
System.out.println("* Generated Code Execution *");
System.out.println("****************************************");
executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
testRun(testCfg, executor);
System.out.println("");
System.out.println("****************************************");
System.out.println("* Test Results *");
System.out.println("****************************************");
System.out.println("");
writeResultsFile(new File(tmpDir, "results.html"), testBench, langs);
System.out.println("");
System.out.println("More details in " + tmpDir.getAbsolutePath() + "/results.html");
System.out.println("");
}
public static Set<File> listTestFiles(final File folder, String pattern) {
Set<File> res = new HashSet<>();
Pattern p = Pattern.compile(pattern);
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
res.addAll(listTestFiles(fileEntry, pattern));
} else {
Matcher m = p.matcher(fileEntry.getName());
if (m.matches()) {
res.add(fileEntry);
}
}
}
return res;
}
public static Set<File> whiteListFiles(final File folder, Set<String> whiteList) {
String testPattern = "test(.+)\\.thingml";
Set<File> res = new HashSet<>();
for (final File fileEntry : listTestFiles(folder, testPattern)) {
if (fileEntry.isDirectory()) {
res.addAll(whiteListFiles(fileEntry, whiteList));
} else {
String fileName = fileEntry.getName().split("\\.thingml")[0];
boolean found = false;
for(String s : whiteList) {
if (fileName.compareTo(s) == 0) {
found = true;
}
}
if(found)
res.add(fileEntry);
}
}
return res;
}
public static Set<File> blackListFiles(final File folder, Set<String> blackList) {
String testPattern = "test(.+)\\.thingml";
Set<File> res = new HashSet<>();
for (final File fileEntry : listTestFiles(folder, testPattern)) {
if (fileEntry.isDirectory()) {
res.addAll(blackListFiles(fileEntry, blackList));
} else {
String fileName = fileEntry.getName().split("\\.thingml")[0];
boolean found = false;
for(String s : blackList) {
if (fileName.compareTo(s) == 0) {
found = true;
}
}
if(!found)
res.add(fileEntry);
}
}
return res;
}
public static Set<File> listTestDir(final File folder, String pattern) {
Set<File> res = new HashSet<>();
Pattern p = Pattern.compile(pattern);
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
//res.addAll(listTestFiles(fileEntry, pattern));
Matcher m = p.matcher(fileEntry.getName());
if (m.matches()) {
res.add(fileEntry);
}
}
}
return res;
}
public static void testRun(Set<TestCase> tests, ExecutorService executor) {
System.out.println("");
System.out.println("Test Cases:");
Set<Command> tasks = new HashSet<>();
List<Future<String>> results = new ArrayList<Future<String>>();
for(TestCase tc : tests) {
if(tc.isLastStepASuccess) {
Command cmd = tc.ongoingCmd;
cmd.print();
tasks.add(cmd);
}
}
try {
results = executor.invokeAll(tasks);
} catch (InterruptedException ex) {
Logger.getLogger(TestJar.class.getName()).log(Level.SEVERE, null, ex);
}
executor.shutdown();
for(TestCase tc : tests) {
tc.collectResults();
}
System.out.println("Done.");
}
public static void writeResultsFile(File results, Map<String,Map<TargetedLanguage,Set<TestCase>>> tests, Set<TargetedLanguage> langs) {
StringBuilder res = new StringBuilder();
res.append("<!DOCTYPE html>\n" +
"<html>\n" +
" <head>\n" +
" <meta charset=\"utf-8\" />\n" +
" <title>ThingML tests results</title>\n" +
" <style>\n" +
" table\n" +
" {\n" +
" border-collapse: collapse;\n" +
" }\n" +
" td, th \n" +
" {\n" +
" border: 1px solid black;\n" +
" }\n" +
" .green\n" +
" {\n" +
" background: lightgreen\n" +
" }\n" +
" .red\n" +
" {\n" +
" background: red\n" +
" }\n" +
" </style>\n" +
" </head>\n" +
" <body>\n" +
" <table>\n" +
" <tr>\n");
res.append(" <th>Test</th>\n");
for(TargetedLanguage lang : langs) {
res.append(" <th>" + lang.compilerID + "</th>\n");
}
res.append(" </tr>\n");
for(Map.Entry<String,Map<TargetedLanguage,Set<TestCase>>> line : tests.entrySet()) {
StringBuilder lineB = new StringBuilder();
boolean lineSuccess = true;
res.append(" <tr>\n");
res.append(" <td class=\"");
lineB.append(" " + line.getKey() + "\n");
lineB.append(" </td>\n");
for(Map.Entry<TargetedLanguage,Set<TestCase>> cell : line.getValue().entrySet()) {
StringBuilder cellB = new StringBuilder();
boolean cellSuccess = true;
lineB.append(" <td class=\"");
String cellRes = "";
for(TestCase tc : cell.getValue()) {
if(tc.isLastStepASuccess) {
cellRes = "*";
} else {
cellRes = "!";
cellSuccess = false;
}
cellB.append(" <a href=" + tc.logFile.getAbsolutePath() + ">[" +cellRes+ "]</a>\n");
}
if(cellSuccess) {
lineB.append("green");
} else {
lineB.append("red");
cell.getKey().failedTest.add(line.getKey());
}
cell.getKey().testNb++;
lineB.append("\">\n");
lineB.append(cellB);
lineB.append(" </td>\n");
lineSuccess &= cellSuccess;
}
if(lineSuccess) {
res.append("green");
} else {
res.append("red");
}
res.append("\">\n");
res.append(lineB);
res.append(" </tr>\n");
}
res.append(" </table>\n"
+ " </body>\n");
res.append("</html>");
for(TargetedLanguage lang : langs) {
System.out.println("[" + lang.compilerID + "] " + lang.failedTest.size() + " failures out of " + lang.testNb);
System.out.println(" Failed tests:");
for(String fail : lang.failedTest) {
System.out.println(" ! " + fail);
}
System.out.println("");
}
if (!results.getParentFile().exists())
results.getParentFile().mkdirs();
try {
PrintWriter w = new PrintWriter(results);
w.print(res.toString());
w.close();
} catch (Exception ex) {
System.err.println("Problem writting log");
ex.printStackTrace();
}
}
}
| Arduino tests partially working
| testJar/src/main/java/org/thingml/testjar/TestJar.java | Arduino tests partially working | <ide><path>estJar/src/main/java/org/thingml/testjar/TestJar.java
<ide> wl.add("testInstanceInitializationOrder");
<ide> wl.add("testArrays");
<ide> wl.add("testDeepCompositeStates");
<del> //Set<File> testFiles = whiteListFiles(testFolder, wl);
<add> Set<File> testFiles = whiteListFiles(testFolder, wl);
<ide> //Set<File> testFiles = blackListFiles(testFolder, wl);
<del> Set<File> testFiles = listTestFiles(testFolder, testPattern);
<add> //Set<File> testFiles = listTestFiles(testFolder, testPattern);
<ide>
<ide> Set<TargetedLanguage> langs = new HashSet<>();
<ide> |
|
JavaScript | mit | 796d70629636292fbb2d038f83c142f80c37b989 | 0 | katekourbatova/helium-overflow,katekourbatova/helium-overflow,katekourbatova/helium-overflow | $(document).ready(function() {
$('#show-answer-form').click(function(event){
event.preventDefault();
$.get($(this).attr('href'), showAnswerForm)
})
///////////////////// CALLBACK FUNCTIONS /////////////////////
function showAnswerForm(response){
$('#show-answer-form').hide();
$('.question-container').after(response);
$('#answer-body').focus();
}
});
| public/js/application.js | $(document).ready(function() {
$('#show-answer-form').click(function(event){
event.preventDefault();
$.get($(this).attr('href'), function(response){
$('#show-answer-form').hide();
$('.question-container').after(response);
$('#answer-body').focus();
})
})
});
| refactor with added calback function
| public/js/application.js | refactor with added calback function | <ide><path>ublic/js/application.js
<ide> $(document).ready(function() {
<ide> $('#show-answer-form').click(function(event){
<ide> event.preventDefault();
<del> $.get($(this).attr('href'), function(response){
<del> $('#show-answer-form').hide();
<del> $('.question-container').after(response);
<del> $('#answer-body').focus();
<del> })
<add> $.get($(this).attr('href'), showAnswerForm)
<ide> })
<add>
<add>///////////////////// CALLBACK FUNCTIONS /////////////////////
<add>
<add>function showAnswerForm(response){
<add> $('#show-answer-form').hide();
<add> $('.question-container').after(response);
<add> $('#answer-body').focus();
<add>}
<add>
<ide> }); |
|
Java | apache-2.0 | 885b01a4cdb61c5e61e1449daa42b191c7a64b85 | 0 | hortonworks/cloudbreak,sequenceiq/cloudbreak,hortonworks/cloudbreak,sequenceiq/cloudbreak,sequenceiq/cloudbreak,sequenceiq/cloudbreak,hortonworks/cloudbreak,sequenceiq/cloudbreak,hortonworks/cloudbreak,hortonworks/cloudbreak,hortonworks/cloudbreak | package com.sequenceiq.cloudbreak.service.stack;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import com.sequenceiq.cloudbreak.conf.ReactorConfig;
import com.sequenceiq.cloudbreak.controller.BadRequestException;
import com.sequenceiq.cloudbreak.controller.NotFoundException;
import com.sequenceiq.cloudbreak.converter.StackConverter;
import com.sequenceiq.cloudbreak.domain.CloudPlatform;
import com.sequenceiq.cloudbreak.domain.InstanceMetaData;
import com.sequenceiq.cloudbreak.domain.Stack;
import com.sequenceiq.cloudbreak.domain.StackDescription;
import com.sequenceiq.cloudbreak.domain.Status;
import com.sequenceiq.cloudbreak.domain.StatusRequest;
import com.sequenceiq.cloudbreak.domain.Template;
import com.sequenceiq.cloudbreak.domain.User;
import com.sequenceiq.cloudbreak.domain.UserRole;
import com.sequenceiq.cloudbreak.repository.RetryingStackUpdater;
import com.sequenceiq.cloudbreak.repository.StackRepository;
import com.sequenceiq.cloudbreak.repository.TemplateRepository;
import com.sequenceiq.cloudbreak.repository.UserRepository;
import com.sequenceiq.cloudbreak.service.account.AccountService;
import com.sequenceiq.cloudbreak.service.stack.connector.CloudPlatformConnector;
import com.sequenceiq.cloudbreak.service.stack.event.AddNodeRequest;
import com.sequenceiq.cloudbreak.service.stack.event.ProvisionRequest;
import com.sequenceiq.cloudbreak.service.stack.event.StackDeleteRequest;
import com.sequenceiq.cloudbreak.service.stack.flow.MetadataIncompleteException;
import reactor.core.Reactor;
import reactor.event.Event;
@Service
public class DefaultStackService implements StackService {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultStackService.class);
@Autowired
private StackConverter stackConverter;
@Autowired
private StackRepository stackRepository;
@Autowired
private TemplateRepository templateRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private AccountService accountService;
@Resource
private Map<CloudPlatform, CloudPlatformConnector> cloudPlatformConnectors;
@Autowired
private RetryingStackUpdater stackUpdater;
@Autowired
private Reactor reactor;
@Override
public Set<Stack> getAll(User user) {
Set<Stack> legacyStacks = new HashSet<>();
Set<Stack> terminatedStacks = new HashSet<>();
Set<Stack> userStacks = user.getStacks();
LOGGER.debug("User stacks: #{}", userStacks.size());
if (user.getUserRoles().contains(UserRole.ACCOUNT_ADMIN)) {
LOGGER.debug("Getting company user stacks for company admin; id: [{}]", user.getId());
legacyStacks = getCompanyUserStacks(user);
} else if (user.getUserRoles().contains(UserRole.ACCOUNT_USER)) {
LOGGER.debug("Getting company wide stacks for company user; id: [{}]", user.getId());
legacyStacks = getCompanyStacks(user);
}
LOGGER.debug("Found #{} legacy stacks for user [{}]", legacyStacks.size(), user.getId());
userStacks.addAll(legacyStacks);
return userStacks;
}
private Set<Stack> getCompanyStacks(User user) {
Set<Stack> companyStacks = new HashSet<>();
User adminWithFilteredData = accountService.accountUserData(user.getAccount().getId(), user.getUserRoles().iterator().next());
if (adminWithFilteredData != null) {
companyStacks = adminWithFilteredData.getStacks();
} else {
LOGGER.debug("There's no company admin for user: [{}]", user.getId());
}
return companyStacks;
}
private Set<Stack> getCompanyUserStacks(User user) {
Set<Stack> companyUserStacks = new HashSet<>();
Set<User> companyUsers = accountService.accountUsers(user.getAccount().getId());
companyUsers.remove(user);
for (User cUser : companyUsers) {
LOGGER.debug("Adding blueprints of company user: [{}]", cUser.getId());
companyUserStacks.addAll(cUser.getStacks());
}
return companyUserStacks;
}
@Override
public Stack get(User user, Long id) {
Stack stack = stackRepository.findOne(id);
if (stack == null) {
throw new NotFoundException(String.format("Stack '%s' not found", id));
}
return stack;
}
@Override
public Stack create(User user, Stack stack) {
Template template = templateRepository.findOne(stack.getTemplate().getId());
stack.setUser(user);
stack.setHash(generateHash(stack));
stack = stackRepository.save(stack);
LOGGER.info("Publishing {} event [StackId: '{}']", ReactorConfig.PROVISION_REQUEST_EVENT, stack.getId());
reactor.notify(ReactorConfig.PROVISION_REQUEST_EVENT, Event.wrap(new ProvisionRequest(template.cloudPlatform(), stack.getId())));
return stack;
}
@Override
public void delete(User user, Long id) {
LOGGER.info("Stack delete requested. [StackId: {}]", id);
Stack stack = stackRepository.findOne(id);
if (stack == null) {
throw new NotFoundException(String.format("Stack '%s' not found", id));
}
LOGGER.info("Publishing {} event [StackId: '{}']", ReactorConfig.DELETE_REQUEST_EVENT, stack.getId());
reactor.notify(ReactorConfig.DELETE_REQUEST_EVENT, Event.wrap(new StackDeleteRequest(stack.getTemplate().cloudPlatform(), stack.getId())));
}
@Override
public void updateStatus(User user, Long stackId, StatusRequest status) {
// TODO implement start/stop
}
@Override
public void updateNodeCount(User user, Long stackId, Integer nodeCount) {
Stack stack = stackRepository.findOne(stackId);
if (!Status.AVAILABLE.equals(stack.getStatus())) {
throw new BadRequestException(String.format("Stack '%s' is currently in '%s' state. Node count can only be updated if it's running.", stackId,
stack.getStatus()));
}
if (stack.getNodeCount() == nodeCount) {
throw new BadRequestException(String.format("Stack '%s' already has exactly %s nodes. Nothing to do.", stackId, nodeCount));
}
if (stack.getNodeCount() > nodeCount) {
throw new BadRequestException(
String.format("Requested node count (%s) on stack '%s' is lower than the current node count (%s). "
+ "Decommisioning nodes is not yet supported by the Cloudbreak API.",
nodeCount, stackId, stack.getNodeCount()));
}
stackUpdater.updateStackStatus(stack.getId(), Status.UPDATE_IN_PROGRESS);
LOGGER.info("Publishing {} event [StackId: '{}']", ReactorConfig.ADD_NODE_REQUEST_EVENT, stack.getId());
reactor.notify(ReactorConfig.ADD_NODE_REQUEST_EVENT,
Event.wrap(new AddNodeRequest(stack.getTemplate().cloudPlatform(), stack.getId(), nodeCount - stack.getNodeCount())));
}
@Override
public StackDescription getStackDescription(User user, Stack stack) {
CloudPlatform cp = stack.getTemplate().cloudPlatform();
LOGGER.debug("Getting stack description for cloud platform: {} ...", cp);
StackDescription description = cloudPlatformConnectors.get(cp).describeStackWithResources(user, stack, stack.getCredential());
LOGGER.debug("Found stack description {}", description.getClass());
return description;
}
@Override
public Set<InstanceMetaData> getMetaData(String hash) {
Stack stack = stackRepository.findStackByHash(hash);
if (stack != null) {
if (!Status.UPDATE_IN_PROGRESS.equals(stack.getStatus())) {
if (!stack.isMetadataReady()) {
throw new MetadataIncompleteException("Instance metadata is incomplete.");
} else if (!stack.getInstanceMetaData().isEmpty()) {
return stack.getInstanceMetaData();
}
} else {
throw new MetadataIncompleteException("Instance metadata is incomplete.");
}
}
throw new NotFoundException("Metadata not found on stack.");
}
private String generateHash(Stack stack) {
int hashCode = HashCodeBuilder.reflectionHashCode(stack);
return DigestUtils.md5DigestAsHex(String.valueOf(hashCode).getBytes());
}
}
| src/main/java/com/sequenceiq/cloudbreak/service/stack/DefaultStackService.java | package com.sequenceiq.cloudbreak.service.stack;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import reactor.core.Reactor;
import reactor.event.Event;
import com.sequenceiq.cloudbreak.conf.ReactorConfig;
import com.sequenceiq.cloudbreak.controller.BadRequestException;
import com.sequenceiq.cloudbreak.controller.NotFoundException;
import com.sequenceiq.cloudbreak.converter.StackConverter;
import com.sequenceiq.cloudbreak.domain.CloudPlatform;
import com.sequenceiq.cloudbreak.domain.InstanceMetaData;
import com.sequenceiq.cloudbreak.domain.Stack;
import com.sequenceiq.cloudbreak.domain.StackDescription;
import com.sequenceiq.cloudbreak.domain.Status;
import com.sequenceiq.cloudbreak.domain.StatusRequest;
import com.sequenceiq.cloudbreak.domain.Template;
import com.sequenceiq.cloudbreak.domain.User;
import com.sequenceiq.cloudbreak.domain.UserRole;
import com.sequenceiq.cloudbreak.repository.RetryingStackUpdater;
import com.sequenceiq.cloudbreak.repository.StackRepository;
import com.sequenceiq.cloudbreak.repository.TemplateRepository;
import com.sequenceiq.cloudbreak.repository.UserRepository;
import com.sequenceiq.cloudbreak.service.account.AccountService;
import com.sequenceiq.cloudbreak.service.stack.connector.CloudPlatformConnector;
import com.sequenceiq.cloudbreak.service.stack.event.AddNodeRequest;
import com.sequenceiq.cloudbreak.service.stack.event.ProvisionRequest;
import com.sequenceiq.cloudbreak.service.stack.event.StackDeleteRequest;
import com.sequenceiq.cloudbreak.service.stack.flow.MetadataIncompleteException;
@Service
public class DefaultStackService implements StackService {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultStackService.class);
@Autowired
private StackConverter stackConverter;
@Autowired
private StackRepository stackRepository;
@Autowired
private TemplateRepository templateRepository;
@Autowired
private UserRepository userRepository;
@Autowired
private AccountService accountService;
@Resource
private Map<CloudPlatform, CloudPlatformConnector> cloudPlatformConnectors;
@Autowired
private RetryingStackUpdater stackUpdater;
@Autowired
private Reactor reactor;
@Override
public Set<Stack> getAll(User user) {
Set<Stack> legacyStacks = new HashSet<>();
Set<Stack> terminatedStacks = new HashSet<>();
Set<Stack> userStacks = user.getStacks();
LOGGER.debug("User stacks: #{}", userStacks.size());
if (user.getUserRoles().contains(UserRole.ACCOUNT_ADMIN)) {
LOGGER.debug("Getting company user stacks for company admin; id: [{}]", user.getId());
legacyStacks = getCompanyUserStacks(user);
} else if (user.getUserRoles().contains(UserRole.ACCOUNT_USER)) {
LOGGER.debug("Getting company wide stacks for company user; id: [{}]", user.getId());
legacyStacks = getCompanyStacks(user);
}
LOGGER.debug("Found #{} legacy stacks for user [{}]", legacyStacks.size(), user.getId());
userStacks.addAll(legacyStacks);
return userStacks;
}
private Set<Stack> getCompanyStacks(User user) {
Set<Stack> companyStacks = new HashSet<>();
User adminWithFilteredData = accountService.accountUserData(user.getAccount().getId(), user.getUserRoles().iterator().next());
if (adminWithFilteredData != null) {
companyStacks = adminWithFilteredData.getStacks();
} else {
LOGGER.debug("There's no company admin for user: [{}]", user.getId());
}
return companyStacks;
}
private Set<Stack> getCompanyUserStacks(User user) {
Set<Stack> companyUserStacks = new HashSet<>();
Set<User> companyUsers = accountService.accountUsers(user.getAccount().getId());
companyUsers.remove(user);
for (User cUser : companyUsers) {
LOGGER.debug("Adding blueprints of company user: [{}]", cUser.getId());
companyUserStacks.addAll(cUser.getStacks());
}
return companyUserStacks;
}
@Override
public Stack get(User user, Long id) {
Stack stack = stackRepository.findOne(id);
if (stack == null) {
throw new NotFoundException(String.format("Stack '%s' not found", id));
}
return stack;
}
@Override
public Stack create(User user, Stack stack) {
Template template = templateRepository.findOne(stack.getTemplate().getId());
stack.setUser(user);
stack.setHash(generateHash(stack));
stack = stackRepository.save(stack);
LOGGER.info("Publishing {} event [StackId: '{}']", ReactorConfig.PROVISION_REQUEST_EVENT, stack.getId());
reactor.notify(ReactorConfig.PROVISION_REQUEST_EVENT, Event.wrap(new ProvisionRequest(template.cloudPlatform(), stack.getId())));
return stack;
}
@Override
public void delete(User user, Long id) {
LOGGER.info("Stack delete requested. [StackId: {}]", id);
Stack stack = stackRepository.findOne(id);
if (stack == null) {
throw new NotFoundException(String.format("Stack '%s' not found", id));
}
LOGGER.info("Publishing {} event [StackId: '{}']", ReactorConfig.DELETE_REQUEST_EVENT, stack.getId());
reactor.notify(ReactorConfig.DELETE_REQUEST_EVENT, Event.wrap(new StackDeleteRequest(stack.getTemplate().cloudPlatform(), stack.getId())));
}
@Override
public void updateStatus(User user, Long stackId, StatusRequest status) {
// TODO implement start/stop
}
@Override
public void updateNodeCount(User user, Long stackId, Integer nodeCount) {
Stack stack = stackRepository.findOne(stackId);
if (!Status.AVAILABLE.equals(stack.getStatus())) {
throw new BadRequestException(String.format("Stack '%s' is currently in '%s' state. Node count can only be updated if it's running.", stackId,
stack.getStatus()));
}
if (stack.getNodeCount() == nodeCount) {
throw new BadRequestException(String.format("Stack '%s' already has exactly %s nodes. Nothing to do.", stackId, nodeCount));
}
if (stack.getNodeCount() > nodeCount) {
throw new BadRequestException(
String.format("Requested node count (%s) on stack '%s' is lower than the current node count (%s). "
+ "Decommisioning nodes is not yet supported by the Cloudbreak API.",
nodeCount, stackId, stack.getNodeCount()));
}
stackUpdater.updateStackStatus(stack.getId(), Status.UPDATE_IN_PROGRESS);
LOGGER.info("Publishing {} event [StackId: '{}']", ReactorConfig.ADD_NODE_REQUEST_EVENT, stack.getId());
reactor.notify(ReactorConfig.ADD_NODE_REQUEST_EVENT,
Event.wrap(new AddNodeRequest(stack.getTemplate().cloudPlatform(), stack.getId(), nodeCount - stack.getNodeCount())));
}
@Override
public StackDescription getStackDescription(User user, Stack stack) {
CloudPlatform cp = stack.getTemplate().cloudPlatform();
LOGGER.debug("Getting stack description for cloud platform: {} ...", cp);
StackDescription description = cloudPlatformConnectors.get(cp).describeStackWithResources(user, stack, stack.getCredential());
LOGGER.debug("Found stack description {}", description.getClass());
return description;
}
@Override
public Set<InstanceMetaData> getMetaData(String hash) {
Stack stack = stackRepository.findStackByHash(hash);
if (stack != null) {
if (!stack.isMetadataReady()) {
throw new MetadataIncompleteException("Instance metadata is incomplete.");
} else if (!stack.getInstanceMetaData().isEmpty()) {
return stack.getInstanceMetaData();
}
}
throw new NotFoundException("Metadata not found on stack.");
}
private String generateHash(Stack stack) {
int hashCode = HashCodeBuilder.reflectionHashCode(stack);
return DigestUtils.md5DigestAsHex(String.valueOf(hashCode).getBytes());
}
}
| CLOUD-39 fixed metadata problem when new node adding
| src/main/java/com/sequenceiq/cloudbreak/service/stack/DefaultStackService.java | CLOUD-39 fixed metadata problem when new node adding | <ide><path>rc/main/java/com/sequenceiq/cloudbreak/service/stack/DefaultStackService.java
<ide> import org.springframework.beans.factory.annotation.Autowired;
<ide> import org.springframework.stereotype.Service;
<ide> import org.springframework.util.DigestUtils;
<del>
<del>import reactor.core.Reactor;
<del>import reactor.event.Event;
<ide>
<ide> import com.sequenceiq.cloudbreak.conf.ReactorConfig;
<ide> import com.sequenceiq.cloudbreak.controller.BadRequestException;
<ide> import com.sequenceiq.cloudbreak.service.stack.event.StackDeleteRequest;
<ide> import com.sequenceiq.cloudbreak.service.stack.flow.MetadataIncompleteException;
<ide>
<add>import reactor.core.Reactor;
<add>import reactor.event.Event;
<add>
<ide> @Service
<ide> public class DefaultStackService implements StackService {
<ide>
<ide> public Set<InstanceMetaData> getMetaData(String hash) {
<ide> Stack stack = stackRepository.findStackByHash(hash);
<ide> if (stack != null) {
<del> if (!stack.isMetadataReady()) {
<add> if (!Status.UPDATE_IN_PROGRESS.equals(stack.getStatus())) {
<add> if (!stack.isMetadataReady()) {
<add> throw new MetadataIncompleteException("Instance metadata is incomplete.");
<add> } else if (!stack.getInstanceMetaData().isEmpty()) {
<add> return stack.getInstanceMetaData();
<add> }
<add> } else {
<ide> throw new MetadataIncompleteException("Instance metadata is incomplete.");
<del> } else if (!stack.getInstanceMetaData().isEmpty()) {
<del> return stack.getInstanceMetaData();
<ide> }
<ide> }
<ide> throw new NotFoundException("Metadata not found on stack."); |
|
Java | apache-2.0 | 76fc9a82f769480aaaa908645bec27e8fd9ec2bb | 0 | damingerdai/web-qq,damingerdai/web-qq,damingerdai/web-qq,damingerdai/web-qq | package org.aming.web.qq.utils;
import org.aming.web.qq.exceptions.WebQQException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Optional;
/**
* @author aming
* @version 2017-10-10
*/
public class SecurityContextUtils {
/**
* 获取当前登录的用户信息
* 仅仅包含用户名和密码
* @return
*/
public static UserDetails getCurrentUser() {
try{
return Optional
.of(
(UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()
).get();
} catch (NullPointerException ex){
throw new WebQQException(5001,"没有发现当前用户");
} catch (Exception ex){
throw new WebQQException();
}
}
}
| src/main/java/org/aming/web/qq/utils/SecurityContextUtils.java | package org.aming.web.qq.utils;
import org.aming.web.qq.exceptions.WebQQException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Optional;
/**
* @author aming
* @version 2017-10-10
*/
public class SecurityContextUtils {
/**
* 获取当前登录的用户信息
* 仅仅包含用户名和密码
* @return
*/
public static UserDetails getCurrentUser() {
try{
return Optional
.of(
(UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()
).get();
} catch (NullPointerException ex){
throw new WebQQException(5001,"没有发现当前用户",ex);
} catch (Exception ex){
throw new WebQQException();
}
}
}
| fix bug
| src/main/java/org/aming/web/qq/utils/SecurityContextUtils.java | fix bug | <ide><path>rc/main/java/org/aming/web/qq/utils/SecurityContextUtils.java
<ide> (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal()
<ide> ).get();
<ide> } catch (NullPointerException ex){
<del> throw new WebQQException(5001,"没有发现当前用户",ex);
<add> throw new WebQQException(5001,"没有发现当前用户");
<ide> } catch (Exception ex){
<ide> throw new WebQQException();
<ide> } |
|
Java | apache-2.0 | 115623a6ee4eb7391c7c26e1728fa153c0698803 | 0 | wwjiang007/hadoop,wwjiang007/hadoop,apache/hadoop,mapr/hadoop-common,JingchengDu/hadoop,nandakumar131/hadoop,mapr/hadoop-common,JingchengDu/hadoop,apache/hadoop,nandakumar131/hadoop,apurtell/hadoop,mapr/hadoop-common,mapr/hadoop-common,JingchengDu/hadoop,nandakumar131/hadoop,wwjiang007/hadoop,nandakumar131/hadoop,JingchengDu/hadoop,apurtell/hadoop,mapr/hadoop-common,apache/hadoop,JingchengDu/hadoop,apurtell/hadoop,apache/hadoop,wwjiang007/hadoop,apache/hadoop,apurtell/hadoop,apurtell/hadoop,wwjiang007/hadoop,wwjiang007/hadoop,apache/hadoop,apurtell/hadoop,mapr/hadoop-common,apache/hadoop,nandakumar131/hadoop,JingchengDu/hadoop,apurtell/hadoop,nandakumar131/hadoop,nandakumar131/hadoop,JingchengDu/hadoop,wwjiang007/hadoop,mapr/hadoop-common | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.server.namenode;
import static org.apache.hadoop.util.Time.monotonicNow;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.security.DigestOutputStream;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Iterator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.protocol.ErasureCodingPolicyInfo;
import org.apache.hadoop.hdfs.protocolPB.PBHelperClient;
import org.apache.hadoop.io.compress.CompressionOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CacheDirectiveInfoProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CachePoolInfoProto;
import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.ErasureCodingPolicyProto;
import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenSecretManager;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockIdManager;
import org.apache.hadoop.hdfs.server.common.HdfsServerConstants;
import org.apache.hadoop.hdfs.server.namenode.FsImageProto.CacheManagerSection;
import org.apache.hadoop.hdfs.server.namenode.FsImageProto.FileSummary;
import org.apache.hadoop.hdfs.server.namenode.FsImageProto.NameSystemSection;
import org.apache.hadoop.hdfs.server.namenode.FsImageProto.SecretManagerSection;
import org.apache.hadoop.hdfs.server.namenode.FsImageProto.StringTableSection;
import org.apache.hadoop.hdfs.server.namenode.FsImageProto.ErasureCodingSection;
import org.apache.hadoop.hdfs.server.namenode.snapshot.FSImageFormatPBSnapshot;
import org.apache.hadoop.hdfs.server.namenode.startupprogress.Phase;
import org.apache.hadoop.hdfs.server.namenode.startupprogress.StartupProgress;
import org.apache.hadoop.hdfs.server.namenode.startupprogress.StartupProgress.Counter;
import org.apache.hadoop.hdfs.server.namenode.startupprogress.Step;
import org.apache.hadoop.hdfs.server.namenode.startupprogress.StepType;
import org.apache.hadoop.hdfs.util.MD5FileUtils;
import org.apache.hadoop.io.MD5Hash;
import org.apache.hadoop.io.compress.CompressionCodec;
import org.apache.hadoop.util.LimitInputStream;
import org.apache.hadoop.util.Time;
import org.apache.hadoop.thirdparty.com.google.common.collect.Lists;
import org.apache.hadoop.thirdparty.com.google.common.collect.Maps;
import org.apache.hadoop.thirdparty.protobuf.CodedOutputStream;
/**
* Utility class to read / write fsimage in protobuf format.
*/
@InterfaceAudience.Private
public final class FSImageFormatProtobuf {
private static final Logger LOG = LoggerFactory
.getLogger(FSImageFormatProtobuf.class);
public static final class LoaderContext {
private SerialNumberManager.StringTable stringTable;
private final ArrayList<INodeReference> refList = Lists.newArrayList();
public SerialNumberManager.StringTable getStringTable() {
return stringTable;
}
public ArrayList<INodeReference> getRefList() {
return refList;
}
}
public static final class SaverContext {
public static class DeduplicationMap<E> {
private final Map<E, Integer> map = Maps.newHashMap();
private DeduplicationMap() {}
static <T> DeduplicationMap<T> newMap() {
return new DeduplicationMap<T>();
}
int getId(E value) {
if (value == null) {
return 0;
}
Integer v = map.get(value);
if (v == null) {
int nv = map.size() + 1;
map.put(value, nv);
return nv;
}
return v;
}
int size() {
return map.size();
}
Set<Entry<E, Integer>> entrySet() {
return map.entrySet();
}
}
private final ArrayList<INodeReference> refList = Lists.newArrayList();
public ArrayList<INodeReference> getRefList() {
return refList;
}
}
public static final class Loader implements FSImageFormat.AbstractLoader {
static final int MINIMUM_FILE_LENGTH = 8;
private final Configuration conf;
private final FSNamesystem fsn;
private final LoaderContext ctx;
/** The MD5 sum of the loaded file */
private MD5Hash imgDigest;
/** The transaction ID of the last edit represented by the loaded file */
private long imgTxId;
/**
* Whether the image's layout version must be the same with
* {@link HdfsServerConstants#NAMENODE_LAYOUT_VERSION}. This is only set to true
* when we're doing (rollingUpgrade rollback).
*/
private final boolean requireSameLayoutVersion;
private File filename;
Loader(Configuration conf, FSNamesystem fsn,
boolean requireSameLayoutVersion) {
this.conf = conf;
this.fsn = fsn;
this.ctx = new LoaderContext();
this.requireSameLayoutVersion = requireSameLayoutVersion;
}
@Override
public MD5Hash getLoadedImageMd5() {
return imgDigest;
}
@Override
public long getLoadedImageTxId() {
return imgTxId;
}
public LoaderContext getLoaderContext() {
return ctx;
}
/**
* Thread to compute the MD5 of a file as this can be in parallel while
* loading the image without interfering much.
*/
private static class DigestThread extends Thread {
/**
* Exception thrown when computing the digest if it cannot be calculated.
*/
private volatile IOException ioe = null;
/**
* Calculated digest if there are no error.
*/
private volatile MD5Hash digest = null;
/**
* FsImage file computed MD5.
*/
private final File file;
DigestThread(File inFile) {
file = inFile;
setName(inFile.getName() + " MD5 compute");
setDaemon(true);
}
public MD5Hash getDigest() throws IOException {
if (ioe != null) {
throw ioe;
}
return digest;
}
public IOException getException() {
return ioe;
}
@Override
public void run() {
try {
digest = MD5FileUtils.computeMd5ForFile(file);
} catch (IOException e) {
ioe = e;
} catch (Throwable t) {
ioe = new IOException(t);
}
}
@Override
public String toString() {
return "DigestThread{ ThreadName=" + getName() + ", digest=" + digest
+ ", file=" + file + '}';
}
}
void load(File file) throws IOException {
filename = file;
long start = Time.monotonicNow();
DigestThread dt = new DigestThread(file);
dt.start();
RandomAccessFile raFile = new RandomAccessFile(file, "r");
FileInputStream fin = new FileInputStream(file);
try {
loadInternal(raFile, fin);
try {
dt.join();
imgDigest = dt.getDigest();
} catch (InterruptedException ie) {
throw new IOException(ie);
}
long end = Time.monotonicNow();
LOG.info("Loaded FSImage in {} seconds.", (end - start) / 1000);
} finally {
fin.close();
raFile.close();
}
}
/**
* Given a FSImage FileSummary.section, return a LimitInput stream set to
* the starting position of the section and limited to the section length.
* @param section The FileSummary.Section containing the offset and length
* @param compressionCodec The compression codec in use, if any
* @return An InputStream for the given section
* @throws IOException
*/
public InputStream getInputStreamForSection(FileSummary.Section section,
String compressionCodec)
throws IOException {
FileInputStream fin = new FileInputStream(filename);
try {
FileChannel channel = fin.getChannel();
channel.position(section.getOffset());
InputStream in = new BufferedInputStream(new LimitInputStream(fin,
section.getLength()));
in = FSImageUtil.wrapInputStreamForCompression(conf,
compressionCodec, in);
return in;
} catch (IOException e) {
fin.close();
throw e;
}
}
/**
* Takes an ArrayList of Section's and removes all Section's whose
* name ends in _SUB, indicating they are sub-sections. The original
* array list is modified and a new list of the removed Section's is
* returned.
* @param sections Array List containing all Sections and Sub Sections
* in the image.
* @return ArrayList of the sections removed, or an empty list if none are
* removed.
*/
private ArrayList<FileSummary.Section> getAndRemoveSubSections(
ArrayList<FileSummary.Section> sections) {
ArrayList<FileSummary.Section> subSections = new ArrayList<>();
Iterator<FileSummary.Section> iter = sections.iterator();
while (iter.hasNext()) {
FileSummary.Section s = iter.next();
String name = s.getName();
if (name.matches(".*_SUB$")) {
subSections.add(s);
iter.remove();
}
}
return subSections;
}
/**
* Given an ArrayList of Section's, return all Section's with the given
* name, or an empty list if none are found.
* @param sections ArrayList of the Section's to search though
* @param name The name of the Sections to search for
* @return ArrayList of the sections matching the given name
*/
private ArrayList<FileSummary.Section> getSubSectionsOfName(
ArrayList<FileSummary.Section> sections, SectionName name) {
ArrayList<FileSummary.Section> subSec = new ArrayList<>();
for (FileSummary.Section s : sections) {
String n = s.getName();
SectionName sectionName = SectionName.fromString(n);
if (sectionName == name) {
subSec.add(s);
}
}
return subSec;
}
/**
* Checks the number of threads configured for parallel loading and
* return an ExecutorService with configured number of threads. If the
* thread count is set to less than 1, it will be reset to the default
* value
* @return ExecutorServie with the correct number of threads
*/
private ExecutorService getParallelExecutorService() {
int threads = conf.getInt(DFSConfigKeys.DFS_IMAGE_PARALLEL_THREADS_KEY,
DFSConfigKeys.DFS_IMAGE_PARALLEL_THREADS_DEFAULT);
if (threads < 1) {
LOG.warn("Parallel is enabled and {} is set to {}. Setting to the " +
"default value {}", DFSConfigKeys.DFS_IMAGE_PARALLEL_THREADS_KEY,
threads, DFSConfigKeys.DFS_IMAGE_PARALLEL_THREADS_DEFAULT);
threads = DFSConfigKeys.DFS_IMAGE_PARALLEL_THREADS_DEFAULT;
}
ExecutorService executorService = Executors.newFixedThreadPool(
threads);
LOG.info("The fsimage will be loaded in parallel using {} threads",
threads);
return executorService;
}
private void loadInternal(RandomAccessFile raFile, FileInputStream fin)
throws IOException {
if (!FSImageUtil.checkFileFormat(raFile)) {
throw new IOException("Unrecognized file format");
}
FileSummary summary = FSImageUtil.loadSummary(raFile);
if (requireSameLayoutVersion && summary.getLayoutVersion() !=
HdfsServerConstants.NAMENODE_LAYOUT_VERSION) {
throw new IOException("Image version " + summary.getLayoutVersion() +
" is not equal to the software version " +
HdfsServerConstants.NAMENODE_LAYOUT_VERSION);
}
FileChannel channel = fin.getChannel();
FSImageFormatPBINode.Loader inodeLoader = new FSImageFormatPBINode.Loader(
fsn, this);
FSImageFormatPBSnapshot.Loader snapshotLoader = new FSImageFormatPBSnapshot.Loader(
fsn, this);
ArrayList<FileSummary.Section> sections = Lists.newArrayList(summary
.getSectionsList());
Collections.sort(sections, new Comparator<FileSummary.Section>() {
@Override
public int compare(FileSummary.Section s1, FileSummary.Section s2) {
SectionName n1 = SectionName.fromString(s1.getName());
SectionName n2 = SectionName.fromString(s2.getName());
if (n1 == null) {
return n2 == null ? 0 : -1;
} else if (n2 == null) {
return -1;
} else {
return n1.ordinal() - n2.ordinal();
}
}
});
StartupProgress prog = NameNode.getStartupProgress();
/**
* beginStep() and the endStep() calls do not match the boundary of the
* sections. This is because that the current implementation only allows
* a particular step to be started for once.
*/
Step currentStep = null;
boolean loadInParallel = enableParallelSaveAndLoad(conf);
ExecutorService executorService = null;
ArrayList<FileSummary.Section> subSections =
getAndRemoveSubSections(sections);
if (loadInParallel) {
executorService = getParallelExecutorService();
}
for (FileSummary.Section s : sections) {
channel.position(s.getOffset());
InputStream in = new BufferedInputStream(new LimitInputStream(fin,
s.getLength()));
in = FSImageUtil.wrapInputStreamForCompression(conf,
summary.getCodec(), in);
String n = s.getName();
SectionName sectionName = SectionName.fromString(n);
if (sectionName == null) {
throw new IOException("Unrecognized section " + n);
}
ArrayList<FileSummary.Section> stageSubSections;
switch (sectionName) {
case NS_INFO:
loadNameSystemSection(in);
break;
case STRING_TABLE:
loadStringTableSection(in);
break;
case INODE: {
currentStep = new Step(StepType.INODES);
prog.beginStep(Phase.LOADING_FSIMAGE, currentStep);
stageSubSections = getSubSectionsOfName(
subSections, SectionName.INODE_SUB);
if (loadInParallel && (stageSubSections.size() > 0)) {
inodeLoader.loadINodeSectionInParallel(executorService,
stageSubSections, summary.getCodec(), prog, currentStep);
} else {
inodeLoader.loadINodeSection(in, prog, currentStep);
}
}
break;
case INODE_REFERENCE:
snapshotLoader.loadINodeReferenceSection(in);
break;
case INODE_DIR:
stageSubSections = getSubSectionsOfName(
subSections, SectionName.INODE_DIR_SUB);
if (loadInParallel && stageSubSections.size() > 0) {
inodeLoader.loadINodeDirectorySectionInParallel(executorService,
stageSubSections, summary.getCodec());
} else {
inodeLoader.loadINodeDirectorySection(in);
}
inodeLoader.waitBlocksMapAndNameCacheUpdateFinished();
break;
case FILES_UNDERCONSTRUCTION:
inodeLoader.loadFilesUnderConstructionSection(in);
break;
case SNAPSHOT:
snapshotLoader.loadSnapshotSection(in);
break;
case SNAPSHOT_DIFF:
snapshotLoader.loadSnapshotDiffSection(in);
break;
case SECRET_MANAGER: {
prog.endStep(Phase.LOADING_FSIMAGE, currentStep);
Step step = new Step(StepType.DELEGATION_TOKENS);
prog.beginStep(Phase.LOADING_FSIMAGE, step);
loadSecretManagerSection(in, prog, step);
prog.endStep(Phase.LOADING_FSIMAGE, step);
}
break;
case CACHE_MANAGER: {
Step step = new Step(StepType.CACHE_POOLS);
prog.beginStep(Phase.LOADING_FSIMAGE, step);
loadCacheManagerSection(in, prog, step);
prog.endStep(Phase.LOADING_FSIMAGE, step);
}
break;
case ERASURE_CODING:
Step step = new Step(StepType.ERASURE_CODING_POLICIES);
prog.beginStep(Phase.LOADING_FSIMAGE, step);
loadErasureCodingSection(in);
prog.endStep(Phase.LOADING_FSIMAGE, step);
break;
default:
LOG.warn("Unrecognized section {}", n);
break;
}
}
if (executorService != null) {
executorService.shutdown();
}
}
private void loadNameSystemSection(InputStream in) throws IOException {
NameSystemSection s = NameSystemSection.parseDelimitedFrom(in);
BlockIdManager blockIdManager = fsn.getBlockManager().getBlockIdManager();
blockIdManager.setLegacyGenerationStamp(s.getGenstampV1());
blockIdManager.setGenerationStamp(s.getGenstampV2());
blockIdManager.setLegacyGenerationStampLimit(s.getGenstampV1Limit());
blockIdManager.setLastAllocatedContiguousBlockId(s.getLastAllocatedBlockId());
if (s.hasLastAllocatedStripedBlockId()) {
blockIdManager.setLastAllocatedStripedBlockId(
s.getLastAllocatedStripedBlockId());
}
imgTxId = s.getTransactionId();
if (s.hasRollingUpgradeStartTime()
&& fsn.getFSImage().hasRollbackFSImage()) {
// we set the rollingUpgradeInfo only when we make sure we have the
// rollback image
fsn.setRollingUpgradeInfo(true, s.getRollingUpgradeStartTime());
}
}
private void loadStringTableSection(InputStream in) throws IOException {
StringTableSection s = StringTableSection.parseDelimitedFrom(in);
ctx.stringTable =
SerialNumberManager.newStringTable(s.getNumEntry(), s.getMaskBits());
for (int i = 0; i < s.getNumEntry(); ++i) {
StringTableSection.Entry e = StringTableSection.Entry
.parseDelimitedFrom(in);
ctx.stringTable.put(e.getId(), e.getStr());
}
}
private void loadSecretManagerSection(InputStream in, StartupProgress prog,
Step currentStep) throws IOException {
SecretManagerSection s = SecretManagerSection.parseDelimitedFrom(in);
int numKeys = s.getNumKeys(), numTokens = s.getNumTokens();
ArrayList<SecretManagerSection.DelegationKey> keys = Lists
.newArrayListWithCapacity(numKeys);
ArrayList<SecretManagerSection.PersistToken> tokens = Lists
.newArrayListWithCapacity(numTokens);
for (int i = 0; i < numKeys; ++i)
keys.add(SecretManagerSection.DelegationKey.parseDelimitedFrom(in));
prog.setTotal(Phase.LOADING_FSIMAGE, currentStep, numTokens);
Counter counter = prog.getCounter(Phase.LOADING_FSIMAGE, currentStep);
for (int i = 0; i < numTokens; ++i) {
tokens.add(SecretManagerSection.PersistToken.parseDelimitedFrom(in));
counter.increment();
}
fsn.loadSecretManagerState(s, keys, tokens);
}
private void loadCacheManagerSection(InputStream in, StartupProgress prog,
Step currentStep) throws IOException {
CacheManagerSection s = CacheManagerSection.parseDelimitedFrom(in);
int numPools = s.getNumPools();
ArrayList<CachePoolInfoProto> pools = Lists
.newArrayListWithCapacity(numPools);
ArrayList<CacheDirectiveInfoProto> directives = Lists
.newArrayListWithCapacity(s.getNumDirectives());
prog.setTotal(Phase.LOADING_FSIMAGE, currentStep, numPools);
Counter counter = prog.getCounter(Phase.LOADING_FSIMAGE, currentStep);
for (int i = 0; i < numPools; ++i) {
pools.add(CachePoolInfoProto.parseDelimitedFrom(in));
counter.increment();
}
for (int i = 0; i < s.getNumDirectives(); ++i)
directives.add(CacheDirectiveInfoProto.parseDelimitedFrom(in));
fsn.getCacheManager().loadState(
new CacheManager.PersistState(s, pools, directives));
}
private void loadErasureCodingSection(InputStream in)
throws IOException {
ErasureCodingSection s = ErasureCodingSection.parseDelimitedFrom(in);
List<ErasureCodingPolicyInfo> ecPolicies = Lists
.newArrayListWithCapacity(s.getPoliciesCount());
for (int i = 0; i < s.getPoliciesCount(); ++i) {
ecPolicies.add(PBHelperClient.convertErasureCodingPolicyInfo(
s.getPolicies(i)));
}
fsn.getErasureCodingPolicyManager().loadPolicies(ecPolicies, conf);
}
}
private static boolean enableParallelSaveAndLoad(Configuration conf) {
boolean loadInParallel =
conf.getBoolean(DFSConfigKeys.DFS_IMAGE_PARALLEL_LOAD_KEY,
DFSConfigKeys.DFS_IMAGE_PARALLEL_LOAD_DEFAULT);
boolean compressionEnabled = conf.getBoolean(
DFSConfigKeys.DFS_IMAGE_COMPRESS_KEY,
DFSConfigKeys.DFS_IMAGE_COMPRESS_DEFAULT);
if (loadInParallel) {
if (compressionEnabled) {
LOG.warn("Parallel Image loading and saving is not supported when {}" +
" is set to true. Parallel will be disabled.",
DFSConfigKeys.DFS_IMAGE_COMPRESS_KEY);
loadInParallel = false;
}
}
return loadInParallel;
}
public static final class Saver {
public static final int CHECK_CANCEL_INTERVAL = 4096;
private boolean writeSubSections = false;
private int inodesPerSubSection = Integer.MAX_VALUE;
private final SaveNamespaceContext context;
private final SaverContext saverContext;
private long currentOffset = FSImageUtil.MAGIC_HEADER.length;
private long subSectionOffset = currentOffset;
private MD5Hash savedDigest;
private FileChannel fileChannel;
// OutputStream for the section data
private OutputStream sectionOutputStream;
private CompressionCodec codec;
private OutputStream underlyingOutputStream;
private Configuration conf;
Saver(SaveNamespaceContext context, Configuration conf) {
this.context = context;
this.saverContext = new SaverContext();
this.conf = conf;
}
public MD5Hash getSavedDigest() {
return savedDigest;
}
public SaveNamespaceContext getContext() {
return context;
}
public SaverContext getSaverContext() {
return saverContext;
}
public int getInodesPerSubSection() {
return inodesPerSubSection;
}
public boolean shouldWriteSubSections() {
return writeSubSections;
}
/**
* Commit the length and offset of a fsimage section to the summary index,
* including the sub section, which will be committed before the section is
* committed.
* @param summary The image summary object
* @param name The name of the section to commit
* @param subSectionName The name of the sub-section to commit
* @throws IOException
*/
public void commitSectionAndSubSection(FileSummary.Builder summary,
SectionName name, SectionName subSectionName) throws IOException {
commitSubSection(summary, subSectionName);
commitSection(summary, name);
}
public void commitSection(FileSummary.Builder summary, SectionName name)
throws IOException {
long oldOffset = currentOffset;
flushSectionOutputStream();
if (codec != null) {
sectionOutputStream = codec.createOutputStream(underlyingOutputStream);
} else {
sectionOutputStream = underlyingOutputStream;
}
long length = fileChannel.position() - oldOffset;
summary.addSections(FileSummary.Section.newBuilder().setName(name.name)
.setLength(length).setOffset(currentOffset));
currentOffset += length;
subSectionOffset = currentOffset;
}
/**
* Commit the length and offset of a fsimage sub-section to the summary
* index.
* @param summary The image summary object
* @param name The name of the sub-section to commit
* @throws IOException
*/
public void commitSubSection(FileSummary.Builder summary, SectionName name)
throws IOException {
if (!writeSubSections) {
return;
}
LOG.debug("Saving a subsection for {}", name.toString());
// The output stream must be flushed before the length is obtained
// as the flush can move the length forward.
sectionOutputStream.flush();
long length = fileChannel.position() - subSectionOffset;
if (length == 0) {
LOG.warn("The requested section for {} is empty. It will not be " +
"output to the image", name.toString());
return;
}
summary.addSections(FileSummary.Section.newBuilder().setName(name.name)
.setLength(length).setOffset(subSectionOffset));
subSectionOffset += length;
}
private void flushSectionOutputStream() throws IOException {
if (codec != null) {
((CompressionOutputStream) sectionOutputStream).finish();
}
sectionOutputStream.flush();
}
/**
* @return number of non-fatal errors detected while writing the image.
* @throws IOException on fatal error.
*/
long save(File file, FSImageCompression compression) throws IOException {
enableSubSectionsIfRequired();
FileOutputStream fout = new FileOutputStream(file);
fileChannel = fout.getChannel();
try {
LOG.info("Saving image file {} using {}", file, compression);
long startTime = monotonicNow();
long numErrors = saveInternal(
fout, compression, file.getAbsolutePath());
LOG.info("Image file {} of size {} bytes saved in {} seconds {}.", file,
file.length(), (monotonicNow() - startTime) / 1000,
(numErrors > 0 ? (" with" + numErrors + " errors") : ""));
return numErrors;
} finally {
fout.close();
}
}
private void enableSubSectionsIfRequired() {
boolean parallelEnabled = enableParallelSaveAndLoad(conf);
int inodeThreshold = conf.getInt(
DFSConfigKeys.DFS_IMAGE_PARALLEL_INODE_THRESHOLD_KEY,
DFSConfigKeys.DFS_IMAGE_PARALLEL_INODE_THRESHOLD_DEFAULT);
int targetSections = conf.getInt(
DFSConfigKeys.DFS_IMAGE_PARALLEL_TARGET_SECTIONS_KEY,
DFSConfigKeys.DFS_IMAGE_PARALLEL_TARGET_SECTIONS_DEFAULT);
if (parallelEnabled) {
if (targetSections <= 0) {
LOG.warn("{} is set to {}. It must be greater than zero. Setting to" +
" default of {}",
DFSConfigKeys.DFS_IMAGE_PARALLEL_TARGET_SECTIONS_KEY,
targetSections,
DFSConfigKeys.DFS_IMAGE_PARALLEL_TARGET_SECTIONS_DEFAULT);
targetSections =
DFSConfigKeys.DFS_IMAGE_PARALLEL_TARGET_SECTIONS_DEFAULT;
}
if (inodeThreshold <= 0) {
LOG.warn("{} is set to {}. It must be greater than zero. Setting to" +
" default of {}",
DFSConfigKeys.DFS_IMAGE_PARALLEL_INODE_THRESHOLD_KEY,
inodeThreshold,
DFSConfigKeys.DFS_IMAGE_PARALLEL_INODE_THRESHOLD_DEFAULT);
inodeThreshold =
DFSConfigKeys.DFS_IMAGE_PARALLEL_INODE_THRESHOLD_DEFAULT;
}
int inodeCount = context.getSourceNamesystem().dir.getInodeMapSize();
// Only enable parallel sections if there are enough inodes
if (inodeCount >= inodeThreshold) {
writeSubSections = true;
// Calculate the inodes per section rounded up to the nearest int
inodesPerSubSection = (inodeCount + targetSections - 1) /
targetSections;
}
} else {
writeSubSections = false;
}
}
private static void saveFileSummary(OutputStream out, FileSummary summary)
throws IOException {
summary.writeDelimitedTo(out);
int length = getOndiskTrunkSize(summary);
byte[] lengthBytes = new byte[4];
ByteBuffer.wrap(lengthBytes).asIntBuffer().put(length);
out.write(lengthBytes);
}
private long saveInodes(FileSummary.Builder summary) throws IOException {
FSImageFormatPBINode.Saver saver = new FSImageFormatPBINode.Saver(this,
summary);
saver.serializeINodeSection(sectionOutputStream);
saver.serializeINodeDirectorySection(sectionOutputStream);
saver.serializeFilesUCSection(sectionOutputStream);
return saver.getNumImageErrors();
}
/**
* @return number of non-fatal errors detected while saving the image.
* @throws IOException on fatal error.
*/
private long saveSnapshots(FileSummary.Builder summary) throws IOException {
FSImageFormatPBSnapshot.Saver snapshotSaver = new FSImageFormatPBSnapshot.Saver(
this, summary, context, context.getSourceNamesystem());
snapshotSaver.serializeSnapshotSection(sectionOutputStream);
// Skip snapshot-related sections when there is no snapshot.
if (context.getSourceNamesystem().getSnapshotManager()
.getNumSnapshots() > 0) {
snapshotSaver.serializeSnapshotDiffSection(sectionOutputStream);
}
snapshotSaver.serializeINodeReferenceSection(sectionOutputStream);
return snapshotSaver.getNumImageErrors();
}
/**
* @return number of non-fatal errors detected while writing the FsImage.
* @throws IOException on fatal error.
*/
private long saveInternal(FileOutputStream fout,
FSImageCompression compression, String filePath) throws IOException {
StartupProgress prog = NameNode.getStartupProgress();
MessageDigest digester = MD5Hash.getDigester();
int layoutVersion =
context.getSourceNamesystem().getEffectiveLayoutVersion();
underlyingOutputStream = new DigestOutputStream(new BufferedOutputStream(
fout), digester);
underlyingOutputStream.write(FSImageUtil.MAGIC_HEADER);
fileChannel = fout.getChannel();
FileSummary.Builder b = FileSummary.newBuilder()
.setOndiskVersion(FSImageUtil.FILE_VERSION)
.setLayoutVersion(
context.getSourceNamesystem().getEffectiveLayoutVersion());
codec = compression.getImageCodec();
if (codec != null) {
b.setCodec(codec.getClass().getCanonicalName());
sectionOutputStream = codec.createOutputStream(underlyingOutputStream);
} else {
sectionOutputStream = underlyingOutputStream;
}
saveNameSystemSection(b);
// Check for cancellation right after serializing the name system section.
// Some unit tests, such as TestSaveNamespace#testCancelSaveNameSpace
// depends on this behavior.
context.checkCancelled();
Step step;
// Erasure coding policies should be saved before inodes
if (NameNodeLayoutVersion.supports(
NameNodeLayoutVersion.Feature.ERASURE_CODING, layoutVersion)) {
step = new Step(StepType.ERASURE_CODING_POLICIES, filePath);
prog.beginStep(Phase.SAVING_CHECKPOINT, step);
saveErasureCodingSection(b);
prog.endStep(Phase.SAVING_CHECKPOINT, step);
}
step = new Step(StepType.INODES, filePath);
prog.beginStep(Phase.SAVING_CHECKPOINT, step);
// Count number of non-fatal errors when saving inodes and snapshots.
long numErrors = saveInodes(b);
numErrors += saveSnapshots(b);
prog.endStep(Phase.SAVING_CHECKPOINT, step);
step = new Step(StepType.DELEGATION_TOKENS, filePath);
prog.beginStep(Phase.SAVING_CHECKPOINT, step);
saveSecretManagerSection(b);
prog.endStep(Phase.SAVING_CHECKPOINT, step);
step = new Step(StepType.CACHE_POOLS, filePath);
prog.beginStep(Phase.SAVING_CHECKPOINT, step);
saveCacheManagerSection(b);
prog.endStep(Phase.SAVING_CHECKPOINT, step);
saveStringTableSection(b);
// We use the underlyingOutputStream to write the header. Therefore flush
// the buffered stream (which is potentially compressed) first.
flushSectionOutputStream();
FileSummary summary = b.build();
saveFileSummary(underlyingOutputStream, summary);
underlyingOutputStream.close();
savedDigest = new MD5Hash(digester.digest());
return numErrors;
}
private void saveSecretManagerSection(FileSummary.Builder summary)
throws IOException {
final FSNamesystem fsn = context.getSourceNamesystem();
DelegationTokenSecretManager.SecretManagerState state = fsn
.saveSecretManagerState();
state.section.writeDelimitedTo(sectionOutputStream);
for (SecretManagerSection.DelegationKey k : state.keys)
k.writeDelimitedTo(sectionOutputStream);
for (SecretManagerSection.PersistToken t : state.tokens)
t.writeDelimitedTo(sectionOutputStream);
commitSection(summary, SectionName.SECRET_MANAGER);
}
private void saveCacheManagerSection(FileSummary.Builder summary)
throws IOException {
final FSNamesystem fsn = context.getSourceNamesystem();
CacheManager.PersistState state = fsn.getCacheManager().saveState();
state.section.writeDelimitedTo(sectionOutputStream);
for (CachePoolInfoProto p : state.pools)
p.writeDelimitedTo(sectionOutputStream);
for (CacheDirectiveInfoProto p : state.directives)
p.writeDelimitedTo(sectionOutputStream);
commitSection(summary, SectionName.CACHE_MANAGER);
}
private void saveErasureCodingSection(
FileSummary.Builder summary) throws IOException {
final FSNamesystem fsn = context.getSourceNamesystem();
ErasureCodingPolicyInfo[] ecPolicies =
fsn.getErasureCodingPolicyManager().getPersistedPolicies();
ArrayList<ErasureCodingPolicyProto> ecPolicyProtoes =
new ArrayList<ErasureCodingPolicyProto>();
for (ErasureCodingPolicyInfo p : ecPolicies) {
ecPolicyProtoes.add(PBHelperClient.convertErasureCodingPolicy(p));
}
ErasureCodingSection section = ErasureCodingSection.newBuilder().
addAllPolicies(ecPolicyProtoes).build();
section.writeDelimitedTo(sectionOutputStream);
commitSection(summary, SectionName.ERASURE_CODING);
}
private void saveNameSystemSection(FileSummary.Builder summary)
throws IOException {
final FSNamesystem fsn = context.getSourceNamesystem();
OutputStream out = sectionOutputStream;
BlockIdManager blockIdManager = fsn.getBlockManager().getBlockIdManager();
NameSystemSection.Builder b = NameSystemSection.newBuilder()
.setGenstampV1(blockIdManager.getLegacyGenerationStamp())
.setGenstampV1Limit(blockIdManager.getLegacyGenerationStampLimit())
.setGenstampV2(blockIdManager.getGenerationStamp())
.setLastAllocatedBlockId(blockIdManager.getLastAllocatedContiguousBlockId())
.setLastAllocatedStripedBlockId(blockIdManager.getLastAllocatedStripedBlockId())
.setTransactionId(context.getTxId());
// We use the non-locked version of getNamespaceInfo here since
// the coordinating thread of saveNamespace already has read-locked
// the namespace for us. If we attempt to take another readlock
// from the actual saver thread, there's a potential of a
// fairness-related deadlock. See the comments on HDFS-2223.
b.setNamespaceId(fsn.unprotectedGetNamespaceInfo().getNamespaceID());
if (fsn.isRollingUpgrade()) {
b.setRollingUpgradeStartTime(fsn.getRollingUpgradeInfo().getStartTime());
}
NameSystemSection s = b.build();
s.writeDelimitedTo(out);
commitSection(summary, SectionName.NS_INFO);
}
private void saveStringTableSection(FileSummary.Builder summary)
throws IOException {
OutputStream out = sectionOutputStream;
SerialNumberManager.StringTable stringTable =
SerialNumberManager.getStringTable();
StringTableSection.Builder b = StringTableSection.newBuilder()
.setNumEntry(stringTable.size())
.setMaskBits(stringTable.getMaskBits());
b.build().writeDelimitedTo(out);
for (Entry<Integer, String> e : stringTable) {
StringTableSection.Entry.Builder eb = StringTableSection.Entry
.newBuilder().setId(e.getKey()).setStr(e.getValue());
eb.build().writeDelimitedTo(out);
}
commitSection(summary, SectionName.STRING_TABLE);
}
}
/**
* Supported section name. The order of the enum determines the order of
* loading.
*/
public enum SectionName {
NS_INFO("NS_INFO"),
STRING_TABLE("STRING_TABLE"),
EXTENDED_ACL("EXTENDED_ACL"),
ERASURE_CODING("ERASURE_CODING"),
INODE("INODE"),
INODE_SUB("INODE_SUB"),
INODE_REFERENCE("INODE_REFERENCE"),
INODE_REFERENCE_SUB("INODE_REFERENCE_SUB"),
SNAPSHOT("SNAPSHOT"),
INODE_DIR("INODE_DIR"),
INODE_DIR_SUB("INODE_DIR_SUB"),
FILES_UNDERCONSTRUCTION("FILES_UNDERCONSTRUCTION"),
SNAPSHOT_DIFF("SNAPSHOT_DIFF"),
SNAPSHOT_DIFF_SUB("SNAPSHOT_DIFF_SUB"),
SECRET_MANAGER("SECRET_MANAGER"),
CACHE_MANAGER("CACHE_MANAGER");
private static final SectionName[] values = SectionName.values();
public static SectionName fromString(String name) {
for (SectionName n : values) {
if (n.name.equals(name))
return n;
}
return null;
}
private final String name;
private SectionName(String name) {
this.name = name;
}
}
private static int getOndiskTrunkSize(
org.apache.hadoop.thirdparty.protobuf.GeneratedMessageV3 s) {
return CodedOutputStream.computeUInt32SizeNoTag(s.getSerializedSize())
+ s.getSerializedSize();
}
private FSImageFormatProtobuf() {
}
}
| hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/FSImageFormatProtobuf.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hdfs.server.namenode;
import static org.apache.hadoop.util.Time.monotonicNow;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.security.DigestOutputStream;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Iterator;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.protocol.ErasureCodingPolicyInfo;
import org.apache.hadoop.hdfs.protocolPB.PBHelperClient;
import org.apache.hadoop.io.compress.CompressionOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CacheDirectiveInfoProto;
import org.apache.hadoop.hdfs.protocol.proto.ClientNamenodeProtocolProtos.CachePoolInfoProto;
import org.apache.hadoop.hdfs.protocol.proto.HdfsProtos.ErasureCodingPolicyProto;
import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenSecretManager;
import org.apache.hadoop.hdfs.server.blockmanagement.BlockIdManager;
import org.apache.hadoop.hdfs.server.common.HdfsServerConstants;
import org.apache.hadoop.hdfs.server.namenode.FsImageProto.CacheManagerSection;
import org.apache.hadoop.hdfs.server.namenode.FsImageProto.FileSummary;
import org.apache.hadoop.hdfs.server.namenode.FsImageProto.NameSystemSection;
import org.apache.hadoop.hdfs.server.namenode.FsImageProto.SecretManagerSection;
import org.apache.hadoop.hdfs.server.namenode.FsImageProto.StringTableSection;
import org.apache.hadoop.hdfs.server.namenode.FsImageProto.ErasureCodingSection;
import org.apache.hadoop.hdfs.server.namenode.snapshot.FSImageFormatPBSnapshot;
import org.apache.hadoop.hdfs.server.namenode.startupprogress.Phase;
import org.apache.hadoop.hdfs.server.namenode.startupprogress.StartupProgress;
import org.apache.hadoop.hdfs.server.namenode.startupprogress.StartupProgress.Counter;
import org.apache.hadoop.hdfs.server.namenode.startupprogress.Step;
import org.apache.hadoop.hdfs.server.namenode.startupprogress.StepType;
import org.apache.hadoop.hdfs.util.MD5FileUtils;
import org.apache.hadoop.io.MD5Hash;
import org.apache.hadoop.io.compress.CompressionCodec;
import org.apache.hadoop.util.LimitInputStream;
import org.apache.hadoop.util.Time;
import org.apache.hadoop.thirdparty.com.google.common.collect.Lists;
import org.apache.hadoop.thirdparty.com.google.common.collect.Maps;
import org.apache.hadoop.thirdparty.protobuf.CodedOutputStream;
/**
* Utility class to read / write fsimage in protobuf format.
*/
@InterfaceAudience.Private
public final class FSImageFormatProtobuf {
private static final Logger LOG = LoggerFactory
.getLogger(FSImageFormatProtobuf.class);
public static final class LoaderContext {
private SerialNumberManager.StringTable stringTable;
private final ArrayList<INodeReference> refList = Lists.newArrayList();
public SerialNumberManager.StringTable getStringTable() {
return stringTable;
}
public ArrayList<INodeReference> getRefList() {
return refList;
}
}
public static final class SaverContext {
public static class DeduplicationMap<E> {
private final Map<E, Integer> map = Maps.newHashMap();
private DeduplicationMap() {}
static <T> DeduplicationMap<T> newMap() {
return new DeduplicationMap<T>();
}
int getId(E value) {
if (value == null) {
return 0;
}
Integer v = map.get(value);
if (v == null) {
int nv = map.size() + 1;
map.put(value, nv);
return nv;
}
return v;
}
int size() {
return map.size();
}
Set<Entry<E, Integer>> entrySet() {
return map.entrySet();
}
}
private final ArrayList<INodeReference> refList = Lists.newArrayList();
public ArrayList<INodeReference> getRefList() {
return refList;
}
}
public static final class Loader implements FSImageFormat.AbstractLoader {
static final int MINIMUM_FILE_LENGTH = 8;
private final Configuration conf;
private final FSNamesystem fsn;
private final LoaderContext ctx;
/** The MD5 sum of the loaded file */
private MD5Hash imgDigest;
/** The transaction ID of the last edit represented by the loaded file */
private long imgTxId;
/**
* Whether the image's layout version must be the same with
* {@link HdfsServerConstants#NAMENODE_LAYOUT_VERSION}. This is only set to true
* when we're doing (rollingUpgrade rollback).
*/
private final boolean requireSameLayoutVersion;
private File filename;
Loader(Configuration conf, FSNamesystem fsn,
boolean requireSameLayoutVersion) {
this.conf = conf;
this.fsn = fsn;
this.ctx = new LoaderContext();
this.requireSameLayoutVersion = requireSameLayoutVersion;
}
@Override
public MD5Hash getLoadedImageMd5() {
return imgDigest;
}
@Override
public long getLoadedImageTxId() {
return imgTxId;
}
public LoaderContext getLoaderContext() {
return ctx;
}
/**
* Thread to compute the MD5 of a file as this can be in parallel while
* loading the image without interfering much.
*/
private static class DigestThread extends Thread {
/**
* Exception thrown when computing the digest if it cannot be calculated.
*/
private volatile IOException ioe = null;
/**
* Calculated digest if there are no error.
*/
private volatile MD5Hash digest = null;
/**
* FsImage file computed MD5.
*/
private final File file;
DigestThread(File inFile) {
file = inFile;
setName(inFile.getName() + " MD5 compute");
setDaemon(true);
}
public MD5Hash getDigest() throws IOException {
if (ioe != null) {
throw ioe;
}
return digest;
}
public IOException getException() {
return ioe;
}
@Override
public void run() {
try {
digest = MD5FileUtils.computeMd5ForFile(file);
} catch (IOException e) {
ioe = e;
} catch (Throwable t) {
ioe = new IOException(t);
}
}
@Override
public String toString() {
return "DigestThread{ ThreadName=" + getName() + ", digest=" + digest
+ ", file=" + file + '}';
}
}
void load(File file) throws IOException {
filename = file;
long start = Time.monotonicNow();
DigestThread dt = new DigestThread(file);
dt.start();
RandomAccessFile raFile = new RandomAccessFile(file, "r");
FileInputStream fin = new FileInputStream(file);
try {
loadInternal(raFile, fin);
try {
dt.join();
imgDigest = dt.getDigest();
} catch (InterruptedException ie) {
throw new IOException(ie);
}
long end = Time.monotonicNow();
LOG.info("Loaded FSImage in {} seconds.", (end - start) / 1000);
} finally {
fin.close();
raFile.close();
}
}
/**
* Given a FSImage FileSummary.section, return a LimitInput stream set to
* the starting position of the section and limited to the section length.
* @param section The FileSummary.Section containing the offset and length
* @param compressionCodec The compression codec in use, if any
* @return An InputStream for the given section
* @throws IOException
*/
public InputStream getInputStreamForSection(FileSummary.Section section,
String compressionCodec)
throws IOException {
FileInputStream fin = new FileInputStream(filename);
FileChannel channel = fin.getChannel();
channel.position(section.getOffset());
InputStream in = new BufferedInputStream(new LimitInputStream(fin,
section.getLength()));
in = FSImageUtil.wrapInputStreamForCompression(conf,
compressionCodec, in);
return in;
}
/**
* Takes an ArrayList of Section's and removes all Section's whose
* name ends in _SUB, indicating they are sub-sections. The original
* array list is modified and a new list of the removed Section's is
* returned.
* @param sections Array List containing all Sections and Sub Sections
* in the image.
* @return ArrayList of the sections removed, or an empty list if none are
* removed.
*/
private ArrayList<FileSummary.Section> getAndRemoveSubSections(
ArrayList<FileSummary.Section> sections) {
ArrayList<FileSummary.Section> subSections = new ArrayList<>();
Iterator<FileSummary.Section> iter = sections.iterator();
while (iter.hasNext()) {
FileSummary.Section s = iter.next();
String name = s.getName();
if (name.matches(".*_SUB$")) {
subSections.add(s);
iter.remove();
}
}
return subSections;
}
/**
* Given an ArrayList of Section's, return all Section's with the given
* name, or an empty list if none are found.
* @param sections ArrayList of the Section's to search though
* @param name The name of the Sections to search for
* @return ArrayList of the sections matching the given name
*/
private ArrayList<FileSummary.Section> getSubSectionsOfName(
ArrayList<FileSummary.Section> sections, SectionName name) {
ArrayList<FileSummary.Section> subSec = new ArrayList<>();
for (FileSummary.Section s : sections) {
String n = s.getName();
SectionName sectionName = SectionName.fromString(n);
if (sectionName == name) {
subSec.add(s);
}
}
return subSec;
}
/**
* Checks the number of threads configured for parallel loading and
* return an ExecutorService with configured number of threads. If the
* thread count is set to less than 1, it will be reset to the default
* value
* @return ExecutorServie with the correct number of threads
*/
private ExecutorService getParallelExecutorService() {
int threads = conf.getInt(DFSConfigKeys.DFS_IMAGE_PARALLEL_THREADS_KEY,
DFSConfigKeys.DFS_IMAGE_PARALLEL_THREADS_DEFAULT);
if (threads < 1) {
LOG.warn("Parallel is enabled and {} is set to {}. Setting to the " +
"default value {}", DFSConfigKeys.DFS_IMAGE_PARALLEL_THREADS_KEY,
threads, DFSConfigKeys.DFS_IMAGE_PARALLEL_THREADS_DEFAULT);
threads = DFSConfigKeys.DFS_IMAGE_PARALLEL_THREADS_DEFAULT;
}
ExecutorService executorService = Executors.newFixedThreadPool(
threads);
LOG.info("The fsimage will be loaded in parallel using {} threads",
threads);
return executorService;
}
private void loadInternal(RandomAccessFile raFile, FileInputStream fin)
throws IOException {
if (!FSImageUtil.checkFileFormat(raFile)) {
throw new IOException("Unrecognized file format");
}
FileSummary summary = FSImageUtil.loadSummary(raFile);
if (requireSameLayoutVersion && summary.getLayoutVersion() !=
HdfsServerConstants.NAMENODE_LAYOUT_VERSION) {
throw new IOException("Image version " + summary.getLayoutVersion() +
" is not equal to the software version " +
HdfsServerConstants.NAMENODE_LAYOUT_VERSION);
}
FileChannel channel = fin.getChannel();
FSImageFormatPBINode.Loader inodeLoader = new FSImageFormatPBINode.Loader(
fsn, this);
FSImageFormatPBSnapshot.Loader snapshotLoader = new FSImageFormatPBSnapshot.Loader(
fsn, this);
ArrayList<FileSummary.Section> sections = Lists.newArrayList(summary
.getSectionsList());
Collections.sort(sections, new Comparator<FileSummary.Section>() {
@Override
public int compare(FileSummary.Section s1, FileSummary.Section s2) {
SectionName n1 = SectionName.fromString(s1.getName());
SectionName n2 = SectionName.fromString(s2.getName());
if (n1 == null) {
return n2 == null ? 0 : -1;
} else if (n2 == null) {
return -1;
} else {
return n1.ordinal() - n2.ordinal();
}
}
});
StartupProgress prog = NameNode.getStartupProgress();
/**
* beginStep() and the endStep() calls do not match the boundary of the
* sections. This is because that the current implementation only allows
* a particular step to be started for once.
*/
Step currentStep = null;
boolean loadInParallel = enableParallelSaveAndLoad(conf);
ExecutorService executorService = null;
ArrayList<FileSummary.Section> subSections =
getAndRemoveSubSections(sections);
if (loadInParallel) {
executorService = getParallelExecutorService();
}
for (FileSummary.Section s : sections) {
channel.position(s.getOffset());
InputStream in = new BufferedInputStream(new LimitInputStream(fin,
s.getLength()));
in = FSImageUtil.wrapInputStreamForCompression(conf,
summary.getCodec(), in);
String n = s.getName();
SectionName sectionName = SectionName.fromString(n);
if (sectionName == null) {
throw new IOException("Unrecognized section " + n);
}
ArrayList<FileSummary.Section> stageSubSections;
switch (sectionName) {
case NS_INFO:
loadNameSystemSection(in);
break;
case STRING_TABLE:
loadStringTableSection(in);
break;
case INODE: {
currentStep = new Step(StepType.INODES);
prog.beginStep(Phase.LOADING_FSIMAGE, currentStep);
stageSubSections = getSubSectionsOfName(
subSections, SectionName.INODE_SUB);
if (loadInParallel && (stageSubSections.size() > 0)) {
inodeLoader.loadINodeSectionInParallel(executorService,
stageSubSections, summary.getCodec(), prog, currentStep);
} else {
inodeLoader.loadINodeSection(in, prog, currentStep);
}
}
break;
case INODE_REFERENCE:
snapshotLoader.loadINodeReferenceSection(in);
break;
case INODE_DIR:
stageSubSections = getSubSectionsOfName(
subSections, SectionName.INODE_DIR_SUB);
if (loadInParallel && stageSubSections.size() > 0) {
inodeLoader.loadINodeDirectorySectionInParallel(executorService,
stageSubSections, summary.getCodec());
} else {
inodeLoader.loadINodeDirectorySection(in);
}
inodeLoader.waitBlocksMapAndNameCacheUpdateFinished();
break;
case FILES_UNDERCONSTRUCTION:
inodeLoader.loadFilesUnderConstructionSection(in);
break;
case SNAPSHOT:
snapshotLoader.loadSnapshotSection(in);
break;
case SNAPSHOT_DIFF:
snapshotLoader.loadSnapshotDiffSection(in);
break;
case SECRET_MANAGER: {
prog.endStep(Phase.LOADING_FSIMAGE, currentStep);
Step step = new Step(StepType.DELEGATION_TOKENS);
prog.beginStep(Phase.LOADING_FSIMAGE, step);
loadSecretManagerSection(in, prog, step);
prog.endStep(Phase.LOADING_FSIMAGE, step);
}
break;
case CACHE_MANAGER: {
Step step = new Step(StepType.CACHE_POOLS);
prog.beginStep(Phase.LOADING_FSIMAGE, step);
loadCacheManagerSection(in, prog, step);
prog.endStep(Phase.LOADING_FSIMAGE, step);
}
break;
case ERASURE_CODING:
Step step = new Step(StepType.ERASURE_CODING_POLICIES);
prog.beginStep(Phase.LOADING_FSIMAGE, step);
loadErasureCodingSection(in);
prog.endStep(Phase.LOADING_FSIMAGE, step);
break;
default:
LOG.warn("Unrecognized section {}", n);
break;
}
}
if (executorService != null) {
executorService.shutdown();
}
}
private void loadNameSystemSection(InputStream in) throws IOException {
NameSystemSection s = NameSystemSection.parseDelimitedFrom(in);
BlockIdManager blockIdManager = fsn.getBlockManager().getBlockIdManager();
blockIdManager.setLegacyGenerationStamp(s.getGenstampV1());
blockIdManager.setGenerationStamp(s.getGenstampV2());
blockIdManager.setLegacyGenerationStampLimit(s.getGenstampV1Limit());
blockIdManager.setLastAllocatedContiguousBlockId(s.getLastAllocatedBlockId());
if (s.hasLastAllocatedStripedBlockId()) {
blockIdManager.setLastAllocatedStripedBlockId(
s.getLastAllocatedStripedBlockId());
}
imgTxId = s.getTransactionId();
if (s.hasRollingUpgradeStartTime()
&& fsn.getFSImage().hasRollbackFSImage()) {
// we set the rollingUpgradeInfo only when we make sure we have the
// rollback image
fsn.setRollingUpgradeInfo(true, s.getRollingUpgradeStartTime());
}
}
private void loadStringTableSection(InputStream in) throws IOException {
StringTableSection s = StringTableSection.parseDelimitedFrom(in);
ctx.stringTable =
SerialNumberManager.newStringTable(s.getNumEntry(), s.getMaskBits());
for (int i = 0; i < s.getNumEntry(); ++i) {
StringTableSection.Entry e = StringTableSection.Entry
.parseDelimitedFrom(in);
ctx.stringTable.put(e.getId(), e.getStr());
}
}
private void loadSecretManagerSection(InputStream in, StartupProgress prog,
Step currentStep) throws IOException {
SecretManagerSection s = SecretManagerSection.parseDelimitedFrom(in);
int numKeys = s.getNumKeys(), numTokens = s.getNumTokens();
ArrayList<SecretManagerSection.DelegationKey> keys = Lists
.newArrayListWithCapacity(numKeys);
ArrayList<SecretManagerSection.PersistToken> tokens = Lists
.newArrayListWithCapacity(numTokens);
for (int i = 0; i < numKeys; ++i)
keys.add(SecretManagerSection.DelegationKey.parseDelimitedFrom(in));
prog.setTotal(Phase.LOADING_FSIMAGE, currentStep, numTokens);
Counter counter = prog.getCounter(Phase.LOADING_FSIMAGE, currentStep);
for (int i = 0; i < numTokens; ++i) {
tokens.add(SecretManagerSection.PersistToken.parseDelimitedFrom(in));
counter.increment();
}
fsn.loadSecretManagerState(s, keys, tokens);
}
private void loadCacheManagerSection(InputStream in, StartupProgress prog,
Step currentStep) throws IOException {
CacheManagerSection s = CacheManagerSection.parseDelimitedFrom(in);
int numPools = s.getNumPools();
ArrayList<CachePoolInfoProto> pools = Lists
.newArrayListWithCapacity(numPools);
ArrayList<CacheDirectiveInfoProto> directives = Lists
.newArrayListWithCapacity(s.getNumDirectives());
prog.setTotal(Phase.LOADING_FSIMAGE, currentStep, numPools);
Counter counter = prog.getCounter(Phase.LOADING_FSIMAGE, currentStep);
for (int i = 0; i < numPools; ++i) {
pools.add(CachePoolInfoProto.parseDelimitedFrom(in));
counter.increment();
}
for (int i = 0; i < s.getNumDirectives(); ++i)
directives.add(CacheDirectiveInfoProto.parseDelimitedFrom(in));
fsn.getCacheManager().loadState(
new CacheManager.PersistState(s, pools, directives));
}
private void loadErasureCodingSection(InputStream in)
throws IOException {
ErasureCodingSection s = ErasureCodingSection.parseDelimitedFrom(in);
List<ErasureCodingPolicyInfo> ecPolicies = Lists
.newArrayListWithCapacity(s.getPoliciesCount());
for (int i = 0; i < s.getPoliciesCount(); ++i) {
ecPolicies.add(PBHelperClient.convertErasureCodingPolicyInfo(
s.getPolicies(i)));
}
fsn.getErasureCodingPolicyManager().loadPolicies(ecPolicies, conf);
}
}
private static boolean enableParallelSaveAndLoad(Configuration conf) {
boolean loadInParallel =
conf.getBoolean(DFSConfigKeys.DFS_IMAGE_PARALLEL_LOAD_KEY,
DFSConfigKeys.DFS_IMAGE_PARALLEL_LOAD_DEFAULT);
boolean compressionEnabled = conf.getBoolean(
DFSConfigKeys.DFS_IMAGE_COMPRESS_KEY,
DFSConfigKeys.DFS_IMAGE_COMPRESS_DEFAULT);
if (loadInParallel) {
if (compressionEnabled) {
LOG.warn("Parallel Image loading and saving is not supported when {}" +
" is set to true. Parallel will be disabled.",
DFSConfigKeys.DFS_IMAGE_COMPRESS_KEY);
loadInParallel = false;
}
}
return loadInParallel;
}
public static final class Saver {
public static final int CHECK_CANCEL_INTERVAL = 4096;
private boolean writeSubSections = false;
private int inodesPerSubSection = Integer.MAX_VALUE;
private final SaveNamespaceContext context;
private final SaverContext saverContext;
private long currentOffset = FSImageUtil.MAGIC_HEADER.length;
private long subSectionOffset = currentOffset;
private MD5Hash savedDigest;
private FileChannel fileChannel;
// OutputStream for the section data
private OutputStream sectionOutputStream;
private CompressionCodec codec;
private OutputStream underlyingOutputStream;
private Configuration conf;
Saver(SaveNamespaceContext context, Configuration conf) {
this.context = context;
this.saverContext = new SaverContext();
this.conf = conf;
}
public MD5Hash getSavedDigest() {
return savedDigest;
}
public SaveNamespaceContext getContext() {
return context;
}
public SaverContext getSaverContext() {
return saverContext;
}
public int getInodesPerSubSection() {
return inodesPerSubSection;
}
public boolean shouldWriteSubSections() {
return writeSubSections;
}
/**
* Commit the length and offset of a fsimage section to the summary index,
* including the sub section, which will be committed before the section is
* committed.
* @param summary The image summary object
* @param name The name of the section to commit
* @param subSectionName The name of the sub-section to commit
* @throws IOException
*/
public void commitSectionAndSubSection(FileSummary.Builder summary,
SectionName name, SectionName subSectionName) throws IOException {
commitSubSection(summary, subSectionName);
commitSection(summary, name);
}
public void commitSection(FileSummary.Builder summary, SectionName name)
throws IOException {
long oldOffset = currentOffset;
flushSectionOutputStream();
if (codec != null) {
sectionOutputStream = codec.createOutputStream(underlyingOutputStream);
} else {
sectionOutputStream = underlyingOutputStream;
}
long length = fileChannel.position() - oldOffset;
summary.addSections(FileSummary.Section.newBuilder().setName(name.name)
.setLength(length).setOffset(currentOffset));
currentOffset += length;
subSectionOffset = currentOffset;
}
/**
* Commit the length and offset of a fsimage sub-section to the summary
* index.
* @param summary The image summary object
* @param name The name of the sub-section to commit
* @throws IOException
*/
public void commitSubSection(FileSummary.Builder summary, SectionName name)
throws IOException {
if (!writeSubSections) {
return;
}
LOG.debug("Saving a subsection for {}", name.toString());
// The output stream must be flushed before the length is obtained
// as the flush can move the length forward.
sectionOutputStream.flush();
long length = fileChannel.position() - subSectionOffset;
if (length == 0) {
LOG.warn("The requested section for {} is empty. It will not be " +
"output to the image", name.toString());
return;
}
summary.addSections(FileSummary.Section.newBuilder().setName(name.name)
.setLength(length).setOffset(subSectionOffset));
subSectionOffset += length;
}
private void flushSectionOutputStream() throws IOException {
if (codec != null) {
((CompressionOutputStream) sectionOutputStream).finish();
}
sectionOutputStream.flush();
}
/**
* @return number of non-fatal errors detected while writing the image.
* @throws IOException on fatal error.
*/
long save(File file, FSImageCompression compression) throws IOException {
enableSubSectionsIfRequired();
FileOutputStream fout = new FileOutputStream(file);
fileChannel = fout.getChannel();
try {
LOG.info("Saving image file {} using {}", file, compression);
long startTime = monotonicNow();
long numErrors = saveInternal(
fout, compression, file.getAbsolutePath());
LOG.info("Image file {} of size {} bytes saved in {} seconds {}.", file,
file.length(), (monotonicNow() - startTime) / 1000,
(numErrors > 0 ? (" with" + numErrors + " errors") : ""));
return numErrors;
} finally {
fout.close();
}
}
private void enableSubSectionsIfRequired() {
boolean parallelEnabled = enableParallelSaveAndLoad(conf);
int inodeThreshold = conf.getInt(
DFSConfigKeys.DFS_IMAGE_PARALLEL_INODE_THRESHOLD_KEY,
DFSConfigKeys.DFS_IMAGE_PARALLEL_INODE_THRESHOLD_DEFAULT);
int targetSections = conf.getInt(
DFSConfigKeys.DFS_IMAGE_PARALLEL_TARGET_SECTIONS_KEY,
DFSConfigKeys.DFS_IMAGE_PARALLEL_TARGET_SECTIONS_DEFAULT);
if (parallelEnabled) {
if (targetSections <= 0) {
LOG.warn("{} is set to {}. It must be greater than zero. Setting to" +
" default of {}",
DFSConfigKeys.DFS_IMAGE_PARALLEL_TARGET_SECTIONS_KEY,
targetSections,
DFSConfigKeys.DFS_IMAGE_PARALLEL_TARGET_SECTIONS_DEFAULT);
targetSections =
DFSConfigKeys.DFS_IMAGE_PARALLEL_TARGET_SECTIONS_DEFAULT;
}
if (inodeThreshold <= 0) {
LOG.warn("{} is set to {}. It must be greater than zero. Setting to" +
" default of {}",
DFSConfigKeys.DFS_IMAGE_PARALLEL_INODE_THRESHOLD_KEY,
inodeThreshold,
DFSConfigKeys.DFS_IMAGE_PARALLEL_INODE_THRESHOLD_DEFAULT);
inodeThreshold =
DFSConfigKeys.DFS_IMAGE_PARALLEL_INODE_THRESHOLD_DEFAULT;
}
int inodeCount = context.getSourceNamesystem().dir.getInodeMapSize();
// Only enable parallel sections if there are enough inodes
if (inodeCount >= inodeThreshold) {
writeSubSections = true;
// Calculate the inodes per section rounded up to the nearest int
inodesPerSubSection = (inodeCount + targetSections - 1) /
targetSections;
}
} else {
writeSubSections = false;
}
}
private static void saveFileSummary(OutputStream out, FileSummary summary)
throws IOException {
summary.writeDelimitedTo(out);
int length = getOndiskTrunkSize(summary);
byte[] lengthBytes = new byte[4];
ByteBuffer.wrap(lengthBytes).asIntBuffer().put(length);
out.write(lengthBytes);
}
private long saveInodes(FileSummary.Builder summary) throws IOException {
FSImageFormatPBINode.Saver saver = new FSImageFormatPBINode.Saver(this,
summary);
saver.serializeINodeSection(sectionOutputStream);
saver.serializeINodeDirectorySection(sectionOutputStream);
saver.serializeFilesUCSection(sectionOutputStream);
return saver.getNumImageErrors();
}
/**
* @return number of non-fatal errors detected while saving the image.
* @throws IOException on fatal error.
*/
private long saveSnapshots(FileSummary.Builder summary) throws IOException {
FSImageFormatPBSnapshot.Saver snapshotSaver = new FSImageFormatPBSnapshot.Saver(
this, summary, context, context.getSourceNamesystem());
snapshotSaver.serializeSnapshotSection(sectionOutputStream);
// Skip snapshot-related sections when there is no snapshot.
if (context.getSourceNamesystem().getSnapshotManager()
.getNumSnapshots() > 0) {
snapshotSaver.serializeSnapshotDiffSection(sectionOutputStream);
}
snapshotSaver.serializeINodeReferenceSection(sectionOutputStream);
return snapshotSaver.getNumImageErrors();
}
/**
* @return number of non-fatal errors detected while writing the FsImage.
* @throws IOException on fatal error.
*/
private long saveInternal(FileOutputStream fout,
FSImageCompression compression, String filePath) throws IOException {
StartupProgress prog = NameNode.getStartupProgress();
MessageDigest digester = MD5Hash.getDigester();
int layoutVersion =
context.getSourceNamesystem().getEffectiveLayoutVersion();
underlyingOutputStream = new DigestOutputStream(new BufferedOutputStream(
fout), digester);
underlyingOutputStream.write(FSImageUtil.MAGIC_HEADER);
fileChannel = fout.getChannel();
FileSummary.Builder b = FileSummary.newBuilder()
.setOndiskVersion(FSImageUtil.FILE_VERSION)
.setLayoutVersion(
context.getSourceNamesystem().getEffectiveLayoutVersion());
codec = compression.getImageCodec();
if (codec != null) {
b.setCodec(codec.getClass().getCanonicalName());
sectionOutputStream = codec.createOutputStream(underlyingOutputStream);
} else {
sectionOutputStream = underlyingOutputStream;
}
saveNameSystemSection(b);
// Check for cancellation right after serializing the name system section.
// Some unit tests, such as TestSaveNamespace#testCancelSaveNameSpace
// depends on this behavior.
context.checkCancelled();
Step step;
// Erasure coding policies should be saved before inodes
if (NameNodeLayoutVersion.supports(
NameNodeLayoutVersion.Feature.ERASURE_CODING, layoutVersion)) {
step = new Step(StepType.ERASURE_CODING_POLICIES, filePath);
prog.beginStep(Phase.SAVING_CHECKPOINT, step);
saveErasureCodingSection(b);
prog.endStep(Phase.SAVING_CHECKPOINT, step);
}
step = new Step(StepType.INODES, filePath);
prog.beginStep(Phase.SAVING_CHECKPOINT, step);
// Count number of non-fatal errors when saving inodes and snapshots.
long numErrors = saveInodes(b);
numErrors += saveSnapshots(b);
prog.endStep(Phase.SAVING_CHECKPOINT, step);
step = new Step(StepType.DELEGATION_TOKENS, filePath);
prog.beginStep(Phase.SAVING_CHECKPOINT, step);
saveSecretManagerSection(b);
prog.endStep(Phase.SAVING_CHECKPOINT, step);
step = new Step(StepType.CACHE_POOLS, filePath);
prog.beginStep(Phase.SAVING_CHECKPOINT, step);
saveCacheManagerSection(b);
prog.endStep(Phase.SAVING_CHECKPOINT, step);
saveStringTableSection(b);
// We use the underlyingOutputStream to write the header. Therefore flush
// the buffered stream (which is potentially compressed) first.
flushSectionOutputStream();
FileSummary summary = b.build();
saveFileSummary(underlyingOutputStream, summary);
underlyingOutputStream.close();
savedDigest = new MD5Hash(digester.digest());
return numErrors;
}
private void saveSecretManagerSection(FileSummary.Builder summary)
throws IOException {
final FSNamesystem fsn = context.getSourceNamesystem();
DelegationTokenSecretManager.SecretManagerState state = fsn
.saveSecretManagerState();
state.section.writeDelimitedTo(sectionOutputStream);
for (SecretManagerSection.DelegationKey k : state.keys)
k.writeDelimitedTo(sectionOutputStream);
for (SecretManagerSection.PersistToken t : state.tokens)
t.writeDelimitedTo(sectionOutputStream);
commitSection(summary, SectionName.SECRET_MANAGER);
}
private void saveCacheManagerSection(FileSummary.Builder summary)
throws IOException {
final FSNamesystem fsn = context.getSourceNamesystem();
CacheManager.PersistState state = fsn.getCacheManager().saveState();
state.section.writeDelimitedTo(sectionOutputStream);
for (CachePoolInfoProto p : state.pools)
p.writeDelimitedTo(sectionOutputStream);
for (CacheDirectiveInfoProto p : state.directives)
p.writeDelimitedTo(sectionOutputStream);
commitSection(summary, SectionName.CACHE_MANAGER);
}
private void saveErasureCodingSection(
FileSummary.Builder summary) throws IOException {
final FSNamesystem fsn = context.getSourceNamesystem();
ErasureCodingPolicyInfo[] ecPolicies =
fsn.getErasureCodingPolicyManager().getPersistedPolicies();
ArrayList<ErasureCodingPolicyProto> ecPolicyProtoes =
new ArrayList<ErasureCodingPolicyProto>();
for (ErasureCodingPolicyInfo p : ecPolicies) {
ecPolicyProtoes.add(PBHelperClient.convertErasureCodingPolicy(p));
}
ErasureCodingSection section = ErasureCodingSection.newBuilder().
addAllPolicies(ecPolicyProtoes).build();
section.writeDelimitedTo(sectionOutputStream);
commitSection(summary, SectionName.ERASURE_CODING);
}
private void saveNameSystemSection(FileSummary.Builder summary)
throws IOException {
final FSNamesystem fsn = context.getSourceNamesystem();
OutputStream out = sectionOutputStream;
BlockIdManager blockIdManager = fsn.getBlockManager().getBlockIdManager();
NameSystemSection.Builder b = NameSystemSection.newBuilder()
.setGenstampV1(blockIdManager.getLegacyGenerationStamp())
.setGenstampV1Limit(blockIdManager.getLegacyGenerationStampLimit())
.setGenstampV2(blockIdManager.getGenerationStamp())
.setLastAllocatedBlockId(blockIdManager.getLastAllocatedContiguousBlockId())
.setLastAllocatedStripedBlockId(blockIdManager.getLastAllocatedStripedBlockId())
.setTransactionId(context.getTxId());
// We use the non-locked version of getNamespaceInfo here since
// the coordinating thread of saveNamespace already has read-locked
// the namespace for us. If we attempt to take another readlock
// from the actual saver thread, there's a potential of a
// fairness-related deadlock. See the comments on HDFS-2223.
b.setNamespaceId(fsn.unprotectedGetNamespaceInfo().getNamespaceID());
if (fsn.isRollingUpgrade()) {
b.setRollingUpgradeStartTime(fsn.getRollingUpgradeInfo().getStartTime());
}
NameSystemSection s = b.build();
s.writeDelimitedTo(out);
commitSection(summary, SectionName.NS_INFO);
}
private void saveStringTableSection(FileSummary.Builder summary)
throws IOException {
OutputStream out = sectionOutputStream;
SerialNumberManager.StringTable stringTable =
SerialNumberManager.getStringTable();
StringTableSection.Builder b = StringTableSection.newBuilder()
.setNumEntry(stringTable.size())
.setMaskBits(stringTable.getMaskBits());
b.build().writeDelimitedTo(out);
for (Entry<Integer, String> e : stringTable) {
StringTableSection.Entry.Builder eb = StringTableSection.Entry
.newBuilder().setId(e.getKey()).setStr(e.getValue());
eb.build().writeDelimitedTo(out);
}
commitSection(summary, SectionName.STRING_TABLE);
}
}
/**
* Supported section name. The order of the enum determines the order of
* loading.
*/
public enum SectionName {
NS_INFO("NS_INFO"),
STRING_TABLE("STRING_TABLE"),
EXTENDED_ACL("EXTENDED_ACL"),
ERASURE_CODING("ERASURE_CODING"),
INODE("INODE"),
INODE_SUB("INODE_SUB"),
INODE_REFERENCE("INODE_REFERENCE"),
INODE_REFERENCE_SUB("INODE_REFERENCE_SUB"),
SNAPSHOT("SNAPSHOT"),
INODE_DIR("INODE_DIR"),
INODE_DIR_SUB("INODE_DIR_SUB"),
FILES_UNDERCONSTRUCTION("FILES_UNDERCONSTRUCTION"),
SNAPSHOT_DIFF("SNAPSHOT_DIFF"),
SNAPSHOT_DIFF_SUB("SNAPSHOT_DIFF_SUB"),
SECRET_MANAGER("SECRET_MANAGER"),
CACHE_MANAGER("CACHE_MANAGER");
private static final SectionName[] values = SectionName.values();
public static SectionName fromString(String name) {
for (SectionName n : values) {
if (n.name.equals(name))
return n;
}
return null;
}
private final String name;
private SectionName(String name) {
this.name = name;
}
}
private static int getOndiskTrunkSize(
org.apache.hadoop.thirdparty.protobuf.GeneratedMessageV3 s) {
return CodedOutputStream.computeUInt32SizeNoTag(s.getSerializedSize())
+ s.getSerializedSize();
}
private FSImageFormatProtobuf() {
}
}
| HDFS-15791. Possible Resource Leak in FSImageFormatProtobuf. (#2652)
| hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/FSImageFormatProtobuf.java | HDFS-15791. Possible Resource Leak in FSImageFormatProtobuf. (#2652) | <ide><path>adoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/FSImageFormatProtobuf.java
<ide> String compressionCodec)
<ide> throws IOException {
<ide> FileInputStream fin = new FileInputStream(filename);
<del> FileChannel channel = fin.getChannel();
<del> channel.position(section.getOffset());
<del> InputStream in = new BufferedInputStream(new LimitInputStream(fin,
<del> section.getLength()));
<del>
<del> in = FSImageUtil.wrapInputStreamForCompression(conf,
<del> compressionCodec, in);
<del> return in;
<add> try {
<add>
<add> FileChannel channel = fin.getChannel();
<add> channel.position(section.getOffset());
<add> InputStream in = new BufferedInputStream(new LimitInputStream(fin,
<add> section.getLength()));
<add>
<add> in = FSImageUtil.wrapInputStreamForCompression(conf,
<add> compressionCodec, in);
<add> return in;
<add> } catch (IOException e) {
<add> fin.close();
<add> throw e;
<add> }
<ide> }
<ide>
<ide> /** |
|
Java | lgpl-2.1 | a965f4f6b7de0943129e7b9819a66ceaab8a2e67 | 0 | pbondoer/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.observation.remote.internal.jgroups;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jgroups.ChannelException;
import org.jgroups.JChannel;
import org.jgroups.Message;
import org.jgroups.conf.ConfiguratorFactory;
import org.jgroups.conf.ProtocolStackConfigurator;
import org.jgroups.conf.XmlConfigurator;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.logging.AbstractLogEnabled;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.component.manager.ComponentManager;
import org.xwiki.container.Container;
import org.xwiki.observation.remote.NetworkAdapter;
import org.xwiki.observation.remote.RemoteEventData;
import org.xwiki.observation.remote.RemoteEventException;
import org.xwiki.observation.remote.jgroups.JGroupsReceiver;
/**
* JGroups based implementation of {@link NetworkAdapter}.
*
* @version $Id$
* @since 2.0RC1
*/
@Component
@Named("jgroups")
@Singleton
public class JGroupsNetworkAdapter extends AbstractLogEnabled implements NetworkAdapter
{
/**
* Relative path where to find jgroups channels configurations.
*/
public static final String CONFIGURATION_PATH = "observation/remote/jgroups/";
/**
* The container used to access configuration files.
*/
@Inject
private Container container;
/**
* Used to lookup the receiver corresponding to the channel identifier.
*/
@Inject
private ComponentManager componentManager;
/**
* The network channels.
*/
private Map<String, JChannel> channels = new ConcurrentHashMap<String, JChannel>();
/**
* {@inheritDoc}
*
* @see org.xwiki.observation.remote.NetworkAdapter#send(org.xwiki.observation.remote.RemoteEventData)
*/
public void send(RemoteEventData remoteEvent)
{
getLogger().debug("Send JGroups remote event [" + remoteEvent + "]");
Message message = new Message(null, null, remoteEvent);
// Send message to jgroups channels
for (Map.Entry<String, JChannel> entry : this.channels.entrySet()) {
try {
entry.getValue().send(message);
} catch (Exception e) {
getLogger().error("Fail to send message to the channel [" + entry.getKey() + "]", e);
}
}
}
/**
* {@inheritDoc}
*
* @see org.xwiki.observation.remote.NetworkAdapter#startChannel(java.lang.String)
*/
public void startChannel(String channelId) throws RemoteEventException
{
if (this.channels.containsKey(channelId)) {
throw new RemoteEventException(MessageFormat.format("Channel [{0}] already started", channelId));
}
JChannel channel;
try {
channel = createChannel(channelId);
channel.connect("event");
this.channels.put(channelId, channel);
} catch (Exception e) {
throw new RemoteEventException("Failed to create channel [" + channelId + "]", e);
}
getLogger().info(MessageFormat.format("Channel [{0}] started", channelId));
}
/**
* {@inheritDoc}
*
* @see org.xwiki.observation.remote.NetworkAdapter#stopChannel(java.lang.String)
*/
public void stopChannel(String channelId) throws RemoteEventException
{
JChannel channel = this.channels.get(channelId);
if (channel == null) {
throw new RemoteEventException(MessageFormat.format("Channel [{0}] is not started", channelId));
}
channel.close();
this.channels.remove(channelId);
getLogger().info(MessageFormat.format("Channel [{0}] stoped", channelId));
}
/**
* Create a new channel.
*
* @param channelId the identifier of the channel to create
* @return the new channel
* @throws ComponentLookupException failed to get default {@link JGroupsReceiver}
* @throws ChannelException failed to create channel
*/
private JChannel createChannel(String channelId) throws ComponentLookupException, ChannelException
{
// load configuration
ProtocolStackConfigurator channelConf;
try {
channelConf = loadChannelConfiguration(channelId);
} catch (IOException e) {
throw new ChannelException("Failed to load configuration for the channel [" + channelId + "]", e);
}
// get Receiver
JGroupsReceiver channelReceiver;
try {
channelReceiver = this.componentManager.lookup(JGroupsReceiver.class, channelId);
} catch (ComponentLookupException e) {
channelReceiver = this.componentManager.lookup(JGroupsReceiver.class);
}
// create channel
JChannel channel = new JChannel(channelConf);
channel.setReceiver(channelReceiver);
channel.setOpt(JChannel.LOCAL, false);
return channel;
}
/**
* Load channel configuration.
*
* @param channelId the identifier of the channel
* @return the channel configuration
* @throws IOException failed to load configuration file
* @throws ChannelException failed to creation channel configuration
*/
private ProtocolStackConfigurator loadChannelConfiguration(String channelId) throws IOException, ChannelException
{
ProtocolStackConfigurator configurator = null;
String path = "/WEB-INF/" + CONFIGURATION_PATH + channelId + ".xml";
InputStream is = this.container.getApplicationContext().getResourceAsStream(path);
if (is != null) {
configurator = XmlConfigurator.getInstance(is);
} else {
getLogger().warn(
"Can't find a configuration for channel [" + channelId + "] at [" + path + "]. Using "
+ JChannel.DEFAULT_PROTOCOL_STACK + " JGRoups default configuration.");
configurator = ConfiguratorFactory.getStackConfigurator(JChannel.DEFAULT_PROTOCOL_STACK);
}
return configurator;
}
/**
* {@inheritDoc}
*
* @see org.xwiki.observation.remote.NetworkAdapter#stopAllChannels()
*/
public void stopAllChannels() throws RemoteEventException
{
for (Map.Entry<String, JChannel> channelEntry : this.channels.entrySet()) {
channelEntry.getValue().close();
}
this.channels.clear();
getLogger().info("All channels stoped");
}
}
| xwiki-platform-core/xwiki-platform-observation/xwiki-platform-observation-remote/src/main/java/org/xwiki/observation/remote/internal/jgroups/JGroupsNetworkAdapter.java | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xwiki.observation.remote.internal.jgroups;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.jgroups.ChannelException;
import org.jgroups.JChannel;
import org.jgroups.Message;
import org.jgroups.conf.ConfiguratorFactory;
import org.jgroups.conf.ProtocolStackConfigurator;
import org.jgroups.conf.XmlConfigurator;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.annotation.Requirement;
import org.xwiki.component.logging.AbstractLogEnabled;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.component.manager.ComponentManager;
import org.xwiki.container.Container;
import org.xwiki.observation.remote.NetworkAdapter;
import org.xwiki.observation.remote.RemoteEventData;
import org.xwiki.observation.remote.RemoteEventException;
import org.xwiki.observation.remote.jgroups.JGroupsReceiver;
/**
* JGroups based implementation of {@link NetworkAdapter}.
*
* @version $Id$
* @since 2.0RC1
*/
@Component("jgroups")
public class JGroupsNetworkAdapter extends AbstractLogEnabled implements NetworkAdapter
{
/**
* Relative path where to find jgroups channels configurations.
*/
public static final String CONFIGURATION_PATH = "observation/remote/jgroups/";
/**
* The container used to access configuration files.
*/
@Requirement
private Container container;
/**
* Used to lookup the receiver corresponding to the channel identifier.
*/
@Requirement
private ComponentManager componentManager;
/**
* The network channels.
*/
private Map<String, JChannel> channels = new ConcurrentHashMap<String, JChannel>();
/**
* {@inheritDoc}
*
* @see org.xwiki.observation.remote.NetworkAdapter#send(org.xwiki.observation.remote.RemoteEventData)
*/
public void send(RemoteEventData remoteEvent)
{
getLogger().debug("Send JGroups remote event [" + remoteEvent + "]");
Message message = new Message(null, null, remoteEvent);
// Send message to jgroups channels
for (Map.Entry<String, JChannel> entry : this.channels.entrySet()) {
try {
entry.getValue().send(message);
} catch (Exception e) {
getLogger().error("Fail to send message to the channel [" + entry.getKey() + "]", e);
}
}
}
/**
* {@inheritDoc}
*
* @see org.xwiki.observation.remote.NetworkAdapter#startChannel(java.lang.String)
*/
public void startChannel(String channelId) throws RemoteEventException
{
if (this.channels.containsKey(channelId)) {
throw new RemoteEventException(MessageFormat.format("Channel [{0}] already started", channelId));
}
JChannel channel;
try {
channel = createChannel(channelId);
channel.connect("event");
this.channels.put(channelId, channel);
} catch (Exception e) {
throw new RemoteEventException("Failed to create channel [" + channelId + "]", e);
}
getLogger().info(MessageFormat.format("Channel [{0}] started", channelId));
}
/**
* {@inheritDoc}
*
* @see org.xwiki.observation.remote.NetworkAdapter#stopChannel(java.lang.String)
*/
public void stopChannel(String channelId) throws RemoteEventException
{
JChannel channel = this.channels.get(channelId);
if (channel == null) {
throw new RemoteEventException(MessageFormat.format("Channel [{0}] is not started", channelId));
}
channel.close();
this.channels.remove(channelId);
getLogger().info(MessageFormat.format("Channel [{0}] stoped", channelId));
}
/**
* Create a new channel.
*
* @param channelId the identifier of the channel to create
* @return the new channel
* @throws ComponentLookupException failed to get default {@link JGroupsReceiver}
* @throws ChannelException failed to create channel
*/
private JChannel createChannel(String channelId) throws ComponentLookupException, ChannelException
{
// load configuration
ProtocolStackConfigurator channelConf;
try {
channelConf = loadChannelConfiguration(channelId);
} catch (IOException e) {
throw new ChannelException("Failed to load configuration for the channel [" + channelId + "]", e);
}
// get Receiver
JGroupsReceiver channelReceiver;
try {
channelReceiver = this.componentManager.lookup(JGroupsReceiver.class, channelId);
} catch (ComponentLookupException e) {
channelReceiver = this.componentManager.lookup(JGroupsReceiver.class);
}
// create channel
JChannel channel = new JChannel(channelConf);
channel.setReceiver(channelReceiver);
channel.setOpt(JChannel.LOCAL, false);
return channel;
}
/**
* Load channel configuration.
*
* @param channelId the identifier of the channel
* @return the channel configuration
* @throws IOException failed to load configuration file
* @throws ChannelException failed to creation channel configuration
*/
private ProtocolStackConfigurator loadChannelConfiguration(String channelId) throws IOException, ChannelException
{
ProtocolStackConfigurator configurator = null;
String path = "/WEB-INF/" + CONFIGURATION_PATH + channelId + ".xml";
InputStream is = this.container.getApplicationContext().getResourceAsStream(path);
if (is != null) {
configurator = XmlConfigurator.getInstance(is);
} else {
getLogger().warn(
"Can't find a configuration for channel [" + channelId + "] at [" + path + "]. Using "
+ JChannel.DEFAULT_PROTOCOL_STACK + " JGRoups default configuration.");
configurator = ConfiguratorFactory.getStackConfigurator(JChannel.DEFAULT_PROTOCOL_STACK);
}
return configurator;
}
/**
* {@inheritDoc}
*
* @see org.xwiki.observation.remote.NetworkAdapter#stopAllChannels()
*/
public void stopAllChannels() throws RemoteEventException
{
for (Map.Entry<String, JChannel> channelEntry : this.channels.entrySet()) {
channelEntry.getValue().close();
}
this.channels.clear();
getLogger().info("All channels stoped");
}
}
| Use javax.inject annotations
| xwiki-platform-core/xwiki-platform-observation/xwiki-platform-observation-remote/src/main/java/org/xwiki/observation/remote/internal/jgroups/JGroupsNetworkAdapter.java | Use javax.inject annotations | <ide><path>wiki-platform-core/xwiki-platform-observation/xwiki-platform-observation-remote/src/main/java/org/xwiki/observation/remote/internal/jgroups/JGroupsNetworkAdapter.java
<ide> import java.util.Map;
<ide> import java.util.concurrent.ConcurrentHashMap;
<ide>
<add>import javax.inject.Inject;
<add>import javax.inject.Named;
<add>import javax.inject.Singleton;
<add>
<ide> import org.jgroups.ChannelException;
<ide> import org.jgroups.JChannel;
<ide> import org.jgroups.Message;
<ide> import org.jgroups.conf.ProtocolStackConfigurator;
<ide> import org.jgroups.conf.XmlConfigurator;
<ide> import org.xwiki.component.annotation.Component;
<del>import org.xwiki.component.annotation.Requirement;
<ide> import org.xwiki.component.logging.AbstractLogEnabled;
<ide> import org.xwiki.component.manager.ComponentLookupException;
<ide> import org.xwiki.component.manager.ComponentManager;
<ide> * @version $Id$
<ide> * @since 2.0RC1
<ide> */
<del>@Component("jgroups")
<add>@Component
<add>@Named("jgroups")
<add>@Singleton
<ide> public class JGroupsNetworkAdapter extends AbstractLogEnabled implements NetworkAdapter
<ide> {
<ide> /**
<ide> /**
<ide> * The container used to access configuration files.
<ide> */
<del> @Requirement
<add> @Inject
<ide> private Container container;
<ide>
<ide> /**
<ide> * Used to lookup the receiver corresponding to the channel identifier.
<ide> */
<del> @Requirement
<add> @Inject
<ide> private ComponentManager componentManager;
<ide>
<ide> /** |
|
Java | apache-2.0 | 3acb8d8dff0517a4364d627bb8d8fdcd31e01e9a | 0 | ibinti/intellij-community,da1z/intellij-community,fitermay/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,hurricup/intellij-community,FHannes/intellij-community,fitermay/intellij-community,FHannes/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,da1z/intellij-community,fitermay/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,ibinti/intellij-community,xfournet/intellij-community,ibinti/intellij-community,xfournet/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,allotria/intellij-community,xfournet/intellij-community,FHannes/intellij-community,semonte/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,semonte/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,da1z/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,apixandru/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,da1z/intellij-community,signed/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,da1z/intellij-community,youdonghai/intellij-community,semonte/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,signed/intellij-community,hurricup/intellij-community,semonte/intellij-community,apixandru/intellij-community,allotria/intellij-community,vvv1559/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,asedunov/intellij-community,FHannes/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,FHannes/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,apixandru/intellij-community,asedunov/intellij-community,da1z/intellij-community,allotria/intellij-community,hurricup/intellij-community,hurricup/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,signed/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,da1z/intellij-community,hurricup/intellij-community,hurricup/intellij-community,semonte/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,ibinti/intellij-community,allotria/intellij-community,signed/intellij-community,hurricup/intellij-community,fitermay/intellij-community,ibinti/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,signed/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,signed/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,fitermay/intellij-community,allotria/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,xfournet/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,FHannes/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,FHannes/intellij-community,ibinti/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,da1z/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,xfournet/intellij-community,xfournet/intellij-community,xfournet/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,allotria/intellij-community,allotria/intellij-community,hurricup/intellij-community,signed/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,allotria/intellij-community,asedunov/intellij-community,asedunov/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,asedunov/intellij-community,apixandru/intellij-community,allotria/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,semonte/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,signed/intellij-community,mglukhikh/intellij-community,signed/intellij-community,youdonghai/intellij-community,FHannes/intellij-community | /*
* Copyright 2000-2010 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.vcs.actions;
import com.intellij.diff.DiffDialogHints;
import com.intellij.diff.util.DiffUserDataKeysEx;
import com.intellij.icons.AllIcons;
import com.intellij.idea.ActionsBundle;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.diff.DiffNavigationContext;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.LineTokenizer;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.*;
import com.intellij.openapi.vcs.annotate.FileAnnotation;
import com.intellij.openapi.vcs.annotate.UpToDateLineNumberListener;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vcs.changes.ChangeListManager;
import com.intellij.openapi.vcs.changes.actions.diff.ShowDiffAction;
import com.intellij.openapi.vcs.changes.actions.diff.ShowDiffContext;
import com.intellij.openapi.vcs.changes.ui.ChangesComparator;
import com.intellij.openapi.vcs.history.VcsRevisionNumber;
import com.intellij.openapi.vcs.ui.VcsBalloonProblemNotifier;
import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.containers.CacheOneStepIterator;
import com.intellij.vcsUtil.VcsUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* @author Konstantin Bulenkov
*/
class ShowDiffFromAnnotation extends DumbAwareAction implements UpToDateLineNumberListener {
private final FileAnnotation myFileAnnotation;
private final AbstractVcs myVcs;
private final VirtualFile myFile;
private int currentLine;
private boolean myEnabled;
ShowDiffFromAnnotation(final FileAnnotation fileAnnotation, final AbstractVcs vcs, final VirtualFile file) {
super(ActionsBundle.message("action.Diff.UpdatedFiles.text"),
ActionsBundle.message("action.Diff.UpdatedFiles.description"),
AllIcons.Actions.Diff);
myFileAnnotation = fileAnnotation;
myVcs = vcs;
myFile = file;
currentLine = -1;
myEnabled = ProjectLevelVcsManager.getInstance(vcs.getProject()).getVcsFor(myFile) != null;
}
@Override
public void consume(Integer integer) {
currentLine = integer;
}
@Override
public void update(AnActionEvent e) {
final int number = currentLine;
e.getPresentation().setVisible(myEnabled);
e.getPresentation().setEnabled(myEnabled && number >= 0 && number < myFileAnnotation.getLineCount());
}
@Override
public void actionPerformed(AnActionEvent e) {
final int actualNumber = currentLine;
if (actualNumber < 0) return;
final VcsRevisionNumber revisionNumber = myFileAnnotation.getLineRevisionNumber(actualNumber);
if (revisionNumber != null) {
final VcsException[] exc = new VcsException[1];
final List<Change> changes = new LinkedList<Change>();
final FilePath[] targetPath = new FilePath[1];
ProgressManager.getInstance().run(new Task.Backgroundable(myVcs.getProject(),
"Loading revision " + revisionNumber.asString() + " contents", true) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
final CommittedChangesProvider provider = myVcs.getCommittedChangesProvider();
try {
final Pair<CommittedChangeList, FilePath> pair = provider.getOneList(myFile, revisionNumber);
if (pair == null || pair.getFirst() == null) {
VcsBalloonProblemNotifier.showOverChangesView(myVcs.getProject(), "Can not load data for show diff", MessageType.ERROR);
return;
}
targetPath[0] = pair.getSecond() == null ? VcsUtil.getFilePath(myFile) : pair.getSecond();
final CommittedChangeList cl = pair.getFirst();
changes.addAll(cl.getChanges());
Collections.sort(changes, ChangesComparator.getInstance(true));
}
catch (VcsException e1) {
exc[0] = e1;
}
}
@Override
public void onSuccess() {
if (exc[0] != null) {
VcsBalloonProblemNotifier
.showOverChangesView(myVcs.getProject(), "Can not show diff: " + exc[0].getMessage(), MessageType.ERROR);
}
else if (!changes.isEmpty()) {
int idx = findSelfInList(changes, targetPath[0]);
final ShowDiffContext context = new ShowDiffContext(DiffDialogHints.FRAME);
if (idx != -1) {
context.putChangeContext(changes.get(idx), DiffUserDataKeysEx.NAVIGATION_CONTEXT, createDiffNavigationContext(actualNumber));
}
if (ChangeListManager.getInstance(myVcs.getProject()).isFreezedWithNotification(null)) return;
ShowDiffAction.showDiffForChange(myVcs.getProject(), changes, idx, context);
}
}
});
}
}
private static int findSelfInList(@NotNull List<Change> changes, @NotNull FilePath filePath) {
int idx = -1;
for (int i = 0; i < changes.size(); i++) {
final Change change = changes.get(i);
if ((change.getAfterRevision() != null) && (change.getAfterRevision().getFile().equals(filePath))) {
idx = i;
break;
}
}
if (idx >= 0) return idx;
idx = 0;
// try to use name only
final String name = filePath.getName();
for (int i = 0; i < changes.size(); i++) {
final Change change = changes.get(i);
if ((change.getAfterRevision() != null) && (change.getAfterRevision().getFile().getName().equals(name))) {
idx = i;
break;
}
}
return idx;
}
/*
* Locate line in annotated content, using lines that are known to be modified in this revision
*/
@Nullable
private DiffNavigationContext createDiffNavigationContext(int actualLine) {
String annotatedContent = myFileAnnotation.getAnnotatedContent();
if (StringUtil.isEmptyOrSpaces(annotatedContent)) return null;
String[] contentsLines = LineTokenizer.tokenize(annotatedContent, false, false);
if (contentsLines.length <= actualLine) return null;
final int correctedLine = correctActualLineIfTextEmpty(contentsLines, actualLine);
return new DiffNavigationContext(new Iterable<String>() {
@Override
public Iterator<String> iterator() {
return new CacheOneStepIterator<String>(new ContextLineIterator(contentsLines, myFileAnnotation, correctedLine));
}
}, contentsLines[correctedLine]);
}
private final static int ourVicinity = 5;
private int correctActualLineIfTextEmpty(@NotNull String[] contentsLines, final int actualLine) {
final VcsRevisionNumber revision = myFileAnnotation.getLineRevisionNumber(actualLine);
if (revision == null) return actualLine;
if (!StringUtil.isEmptyOrSpaces(contentsLines[actualLine])) return actualLine;
int upperBound = Math.min(actualLine + ourVicinity, contentsLines.length);
for (int i = actualLine + 1; i < upperBound; i++) {
if (revision.equals(myFileAnnotation.getLineRevisionNumber(i)) && !StringUtil.isEmptyOrSpaces(contentsLines[i])) {
return i;
}
}
int lowerBound = Math.max(actualLine - ourVicinity, 0);
for (int i = actualLine - 1; i >= lowerBound; --i) {
if (revision.equals(myFileAnnotation.getLineRevisionNumber(i)) && !StringUtil.isEmptyOrSpaces(contentsLines[i])) {
return i;
}
}
return actualLine;
}
/**
* Slightly break the contract: can return null from next() while had claimed hasNext()
*/
private static class ContextLineIterator implements Iterator<String> {
@NotNull private final String[] myContentsLines;
private final VcsRevisionNumber myRevisionNumber;
@NotNull private final FileAnnotation myAnnotation;
private final int myStopAtLine;
// we assume file has at least one line ;)
private int myCurrentLine; // to start looking for next line with revision from
private ContextLineIterator(@NotNull String[] contentLines, @NotNull FileAnnotation annotation, int stopAtLine) {
myAnnotation = annotation;
myRevisionNumber = myAnnotation.originalRevision(stopAtLine);
myStopAtLine = stopAtLine;
myContentsLines = contentLines;
}
@Override
public boolean hasNext() {
return myRevisionNumber != null && lineNumberInBounds();
}
private boolean lineNumberInBounds() {
return (myCurrentLine < myContentsLines.length) && (myCurrentLine < myStopAtLine);
}
@Override
public String next() {
while (lineNumberInBounds()) {
final VcsRevisionNumber vcsRevisionNumber = myAnnotation.originalRevision(myCurrentLine);
final String text = myContentsLines[myCurrentLine];
++myCurrentLine;
if (myRevisionNumber.equals(vcsRevisionNumber) && !StringUtil.isEmptyOrSpaces(text)) {
return text;
}
}
return null;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
}
| platform/vcs-impl/src/com/intellij/openapi/vcs/actions/ShowDiffFromAnnotation.java | /*
* Copyright 2000-2010 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.vcs.actions;
import com.intellij.diff.DiffDialogHints;
import com.intellij.diff.util.DiffUserDataKeysEx;
import com.intellij.icons.AllIcons;
import com.intellij.idea.ActionsBundle;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.diff.DiffNavigationContext;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.LineTokenizer;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.*;
import com.intellij.openapi.vcs.annotate.FileAnnotation;
import com.intellij.openapi.vcs.annotate.UpToDateLineNumberListener;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vcs.changes.ChangeListManager;
import com.intellij.openapi.vcs.changes.actions.diff.ShowDiffAction;
import com.intellij.openapi.vcs.changes.actions.diff.ShowDiffContext;
import com.intellij.openapi.vcs.changes.ui.ChangesComparator;
import com.intellij.openapi.vcs.history.VcsRevisionNumber;
import com.intellij.openapi.vcs.ui.VcsBalloonProblemNotifier;
import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.containers.CacheOneStepIterator;
import com.intellij.vcsUtil.VcsUtil;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* @author Konstantin Bulenkov
*/
class ShowDiffFromAnnotation extends DumbAwareAction implements UpToDateLineNumberListener {
private final FileAnnotation myFileAnnotation;
private final AbstractVcs myVcs;
private final VirtualFile myFile;
private int currentLine;
private boolean myEnabled;
ShowDiffFromAnnotation(final FileAnnotation fileAnnotation, final AbstractVcs vcs, final VirtualFile file) {
super(ActionsBundle.message("action.Diff.UpdatedFiles.text"),
ActionsBundle.message("action.Diff.UpdatedFiles.description"),
AllIcons.Actions.Diff);
myFileAnnotation = fileAnnotation;
myVcs = vcs;
myFile = file;
currentLine = -1;
myEnabled = ProjectLevelVcsManager.getInstance(vcs.getProject()).getVcsFor(myFile) != null;
}
@Override
public void consume(Integer integer) {
currentLine = integer;
}
@Override
public void update(AnActionEvent e) {
final int number = currentLine;
e.getPresentation().setVisible(myEnabled);
e.getPresentation().setEnabled(myEnabled && number >= 0 && number < myFileAnnotation.getLineCount());
}
@Override
public void actionPerformed(AnActionEvent e) {
final int actualNumber = currentLine;
if (actualNumber < 0) return;
final VcsRevisionNumber revisionNumber = myFileAnnotation.getLineRevisionNumber(actualNumber);
if (revisionNumber != null) {
final VcsException[] exc = new VcsException[1];
final List<Change> changes = new LinkedList<Change>();
final FilePath[] targetPath = new FilePath[1];
ProgressManager.getInstance().run(new Task.Backgroundable(myVcs.getProject(),
"Loading revision " + revisionNumber.asString() + " contents", true) {
@Override
public void run(@NotNull ProgressIndicator indicator) {
final CommittedChangesProvider provider = myVcs.getCommittedChangesProvider();
try {
final Pair<CommittedChangeList, FilePath> pair = provider.getOneList(myFile, revisionNumber);
if (pair == null || pair.getFirst() == null) {
VcsBalloonProblemNotifier.showOverChangesView(myVcs.getProject(), "Can not load data for show diff", MessageType.ERROR);
return;
}
targetPath[0] = pair.getSecond() == null ? VcsUtil.getFilePath(myFile) : pair.getSecond();
final CommittedChangeList cl = pair.getFirst();
changes.addAll(cl.getChanges());
Collections.sort(changes, ChangesComparator.getInstance(true));
}
catch (VcsException e1) {
exc[0] = e1;
}
}
@Override
public void onSuccess() {
if (exc[0] != null) {
VcsBalloonProblemNotifier
.showOverChangesView(myVcs.getProject(), "Can not show diff: " + exc[0].getMessage(), MessageType.ERROR);
}
else if (!changes.isEmpty()) {
int idx = findSelfInList(changes, targetPath[0]);
final ShowDiffContext context = new ShowDiffContext(DiffDialogHints.FRAME);
if (idx != -1) {
context.putChangeContext(changes.get(idx), DiffUserDataKeysEx.NAVIGATION_CONTEXT, createDiffNavigationContext(actualNumber));
}
if (ChangeListManager.getInstance(myVcs.getProject()).isFreezedWithNotification(null)) return;
ShowDiffAction.showDiffForChange(myVcs.getProject(), changes, idx, context);
}
}
});
}
}
private static int findSelfInList(List<Change> changes, final FilePath filePath) {
int idx = -1;
for (int i = 0; i < changes.size(); i++) {
final Change change = changes.get(i);
if ((change.getAfterRevision() != null) && (change.getAfterRevision().getFile().equals(filePath))) {
idx = i;
break;
}
}
if (idx >= 0) return idx;
idx = 0;
// try to use name only
final String name = filePath.getName();
for (int i = 0; i < changes.size(); i++) {
final Change change = changes.get(i);
if ((change.getAfterRevision() != null) && (change.getAfterRevision().getFile().getName().equals(name))) {
idx = i;
break;
}
}
return idx;
}
// for current line number
private DiffNavigationContext createDiffNavigationContext(int actualLine) {
String annotatedContent = myFileAnnotation.getAnnotatedContent();
if (StringUtil.isEmptyOrSpaces(annotatedContent)) return null;
String[] contentsLines = LineTokenizer.tokenize(annotatedContent, false, false);
if (contentsLines.length <= actualLine) return null;
final int correctedLine = correctActualLineIfTextEmpty(contentsLines, actualLine);
return new DiffNavigationContext(new Iterable<String>() {
@Override
public Iterator<String> iterator() {
return new CacheOneStepIterator<String>(new ContextLineIterator(contentsLines, myFileAnnotation, correctedLine));
}
}, contentsLines[correctedLine]);
}
private final static int ourVicinity = 5;
private int correctActualLineIfTextEmpty(final String[] contentsLines, final int actualLine) {
final VcsRevisionNumber revision = myFileAnnotation.getLineRevisionNumber(actualLine);
if (revision == null) return actualLine;
if (!StringUtil.isEmptyOrSpaces(contentsLines[actualLine])) return actualLine;
int upperBound = Math.min(actualLine + ourVicinity, contentsLines.length);
for (int i = actualLine + 1; i < upperBound; i++) {
if (revision.equals(myFileAnnotation.getLineRevisionNumber(i)) && !StringUtil.isEmptyOrSpaces(contentsLines[i])) {
return i;
}
}
int lowerBound = Math.max(actualLine - ourVicinity, 0);
for (int i = actualLine - 1; i >= lowerBound; --i) {
if (revision.equals(myFileAnnotation.getLineRevisionNumber(i)) && !StringUtil.isEmptyOrSpaces(contentsLines[i])) {
return i;
}
}
return actualLine;
}
/**
* Slightly break the contract: can return null from next() while had claimed hasNext()
*/
private static class ContextLineIterator implements Iterator<String> {
private final String[] myContentsLines;
private final VcsRevisionNumber myRevisionNumber;
private final FileAnnotation myAnnotation;
private final int myStopAtLine;
// we assume file has at least one line ;)
private int myCurrentLine; // to start looking for next line with revision from
private ContextLineIterator(final String[] contentLines, final FileAnnotation annotation, final int stopAtLine) {
myAnnotation = annotation;
myRevisionNumber = myAnnotation.originalRevision(stopAtLine);
myStopAtLine = stopAtLine;
myContentsLines = contentLines;
}
@Override
public boolean hasNext() {
return myRevisionNumber != null && lineNumberInBounds();
}
private boolean lineNumberInBounds() {
return (myCurrentLine < myContentsLines.length) && (myCurrentLine < myStopAtLine);
}
@Override
public String next() {
while (lineNumberInBounds()) {
final VcsRevisionNumber vcsRevisionNumber = myAnnotation.originalRevision(myCurrentLine);
final String text = myContentsLines[myCurrentLine];
++myCurrentLine;
if (myRevisionNumber.equals(vcsRevisionNumber) && !StringUtil.isEmptyOrSpaces(text)) {
return text;
}
}
return null;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
}
| diff: @NotNull
| platform/vcs-impl/src/com/intellij/openapi/vcs/actions/ShowDiffFromAnnotation.java | diff: @NotNull | <ide><path>latform/vcs-impl/src/com/intellij/openapi/vcs/actions/ShowDiffFromAnnotation.java
<ide> import com.intellij.util.containers.CacheOneStepIterator;
<ide> import com.intellij.vcsUtil.VcsUtil;
<ide> import org.jetbrains.annotations.NotNull;
<add>import org.jetbrains.annotations.Nullable;
<ide>
<ide> import java.util.Collections;
<ide> import java.util.Iterator;
<ide> }
<ide> }
<ide>
<del> private static int findSelfInList(List<Change> changes, final FilePath filePath) {
<add> private static int findSelfInList(@NotNull List<Change> changes, @NotNull FilePath filePath) {
<ide> int idx = -1;
<ide> for (int i = 0; i < changes.size(); i++) {
<ide> final Change change = changes.get(i);
<ide> return idx;
<ide> }
<ide>
<del> // for current line number
<add> /*
<add> * Locate line in annotated content, using lines that are known to be modified in this revision
<add> */
<add> @Nullable
<ide> private DiffNavigationContext createDiffNavigationContext(int actualLine) {
<ide> String annotatedContent = myFileAnnotation.getAnnotatedContent();
<ide> if (StringUtil.isEmptyOrSpaces(annotatedContent)) return null;
<ide>
<ide> private final static int ourVicinity = 5;
<ide>
<del> private int correctActualLineIfTextEmpty(final String[] contentsLines, final int actualLine) {
<add> private int correctActualLineIfTextEmpty(@NotNull String[] contentsLines, final int actualLine) {
<ide> final VcsRevisionNumber revision = myFileAnnotation.getLineRevisionNumber(actualLine);
<ide> if (revision == null) return actualLine;
<ide> if (!StringUtil.isEmptyOrSpaces(contentsLines[actualLine])) return actualLine;
<ide> * Slightly break the contract: can return null from next() while had claimed hasNext()
<ide> */
<ide> private static class ContextLineIterator implements Iterator<String> {
<del> private final String[] myContentsLines;
<add> @NotNull private final String[] myContentsLines;
<ide>
<ide> private final VcsRevisionNumber myRevisionNumber;
<del> private final FileAnnotation myAnnotation;
<add> @NotNull private final FileAnnotation myAnnotation;
<ide> private final int myStopAtLine;
<ide> // we assume file has at least one line ;)
<ide> private int myCurrentLine; // to start looking for next line with revision from
<ide>
<del> private ContextLineIterator(final String[] contentLines, final FileAnnotation annotation, final int stopAtLine) {
<add> private ContextLineIterator(@NotNull String[] contentLines, @NotNull FileAnnotation annotation, int stopAtLine) {
<ide> myAnnotation = annotation;
<ide> myRevisionNumber = myAnnotation.originalRevision(stopAtLine);
<ide> myStopAtLine = stopAtLine; |
|
Java | apache-2.0 | d0622d14b151dcfaa2888c37359460e50b79bbfc | 0 | domdomegg/apps-android-commons,nicolas-raoul/apps-android-commons,domdomegg/apps-android-commons,maskaravivek/apps-android-commons,RSBat/apps-android-commons,whym/apps-android-commons,misaochan/apps-android-commons,sandarumk/apps-android-commons,psh/apps-android-commons,misaochan/apps-android-commons,nicolas-raoul/apps-android-commons,psh/apps-android-commons,commons-app/apps-android-commons,psh/apps-android-commons,psh/apps-android-commons,domdomegg/apps-android-commons,RSBat/apps-android-commons,tobias47n9e/apps-android-commons,akaita/apps-android-commons,nicolas-raoul/apps-android-commons,sandarumk/apps-android-commons,tobias47n9e/apps-android-commons,neslihanturan/apps-android-commons,commons-app/apps-android-commons,commons-app/apps-android-commons,whym/apps-android-commons,neslihanturan/apps-android-commons,akaita/apps-android-commons,psh/apps-android-commons,nicolas-raoul/apps-android-commons,neslihanturan/apps-android-commons,maskaravivek/apps-android-commons,whym/apps-android-commons,akaita/apps-android-commons,neslihanturan/apps-android-commons,domdomegg/apps-android-commons,RSBat/apps-android-commons,maskaravivek/apps-android-commons,misaochan/apps-android-commons,neslihanturan/apps-android-commons,dbrant/apps-android-commons,misaochan/apps-android-commons,misaochan/apps-android-commons,commons-app/apps-android-commons,whym/apps-android-commons,tobias47n9e/apps-android-commons,domdomegg/apps-android-commons,dbrant/apps-android-commons,maskaravivek/apps-android-commons,commons-app/apps-android-commons,dbrant/apps-android-commons,maskaravivek/apps-android-commons,dbrant/apps-android-commons,sandarumk/apps-android-commons,misaochan/apps-android-commons | package fr.free.nrw.commons.nearby;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import fr.free.nrw.commons.location.LatLng;
import fr.free.nrw.commons.location.LocationServiceManager;
import fr.free.nrw.commons.theme.BaseActivity;
import fr.free.nrw.commons.utils.UriSerializer;
import fr.free.nrw.commons.R;
import java.util.List;
public class NearbyActivity extends BaseActivity {
@BindView(R.id.progressBar)
ProgressBar progressBar;
private boolean isMapViewActive = false;
private LocationServiceManager locationManager;
private LatLng curLatLang;
private Gson gson;
private String gsonPlaceList;
private String gsonCurLatLng;
private Bundle bundle;
private NearbyAsyncTask nearbyAsyncTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nearby);
ButterKnife.bind(this);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
bundle = new Bundle();
locationManager = new LocationServiceManager(this);
locationManager.registerLocationManager();
curLatLang = locationManager.getLatestLocation();
nearbyAsyncTask = new NearbyAsyncTask(this);
nearbyAsyncTask.execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_nearby, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.action_refresh:
refreshView();
return true;
case R.id.action_map:
showMapView();
if (isMapViewActive) {
item.setIcon(R.drawable.ic_list_white_24dp);
} else {
item.setIcon(R.drawable.ic_map_white_24dp);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void showMapView() {
if (!isMapViewActive) {
isMapViewActive = true;
if (nearbyAsyncTask.getStatus() == AsyncTask.Status.FINISHED) {
setMapFragment();
}
} else {
isMapViewActive = false;
if (nearbyAsyncTask.getStatus() == AsyncTask.Status.FINISHED) {
setListFragment();
}
}
}
@Override
protected void onResume() {
super.onResume();
}
protected void refreshView() {
nearbyAsyncTask = new NearbyAsyncTask(this);
nearbyAsyncTask.execute();
}
public LocationServiceManager getLocationManager() {
return locationManager;
}
@Override
protected void onDestroy() {
super.onDestroy();
locationManager.unregisterLocationManager();
}
private class NearbyAsyncTask extends AsyncTask<Void, Integer, List<Place>> {
private Context mContext;
private NearbyAsyncTask (Context context) {
mContext = context;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
@Override
protected List<Place> doInBackground(Void... params) {
return NearbyController
.loadAttractionsFromLocation(curLatLang, getApplicationContext()
);
}
@Override
protected void onPostExecute(List<Place> placeList) {
super.onPostExecute(placeList);
if (isCancelled()) {
return;
}
gson = new GsonBuilder()
.registerTypeAdapter(Uri.class, new UriSerializer())
.create();
gsonPlaceList = gson.toJson(placeList);
gsonCurLatLng = gson.toJson(curLatLang);
if (placeList.size() == 0) {
CharSequence text = "No nearby places found";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(mContext, text, duration);
toast.show();
}
bundle.clear();
bundle.putString("PlaceList", gsonPlaceList);
bundle.putString("CurLatLng", gsonCurLatLng);
// Begin the transaction
if (isMapViewActive) {
setMapFragment();
} else {
setListFragment();
}
if (progressBar != null) {
progressBar.setVisibility(View.GONE);
}
}
}
/**
* Calls fragment for map view.
*/
public void setMapFragment() {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
Fragment fragment = new NearbyMapFragment();
fragment.setArguments(bundle);
fragmentTransaction.replace(R.id.container, fragment);
fragmentTransaction.commit();
}
/**
* Calls fragment for list view.
*/
public void setListFragment() {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
Fragment fragment = new NearbyListFragment();
fragment.setArguments(bundle);
fragmentTransaction.replace(R.id.container, fragment);
fragmentTransaction.commit();
}
}
| app/src/main/java/fr/free/nrw/commons/nearby/NearbyActivity.java | package fr.free.nrw.commons.nearby;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import fr.free.nrw.commons.location.LatLng;
import fr.free.nrw.commons.location.LocationServiceManager;
import fr.free.nrw.commons.theme.BaseActivity;
import fr.free.nrw.commons.utils.UriSerializer;
import fr.free.nrw.commons.R;
import java.util.List;
public class NearbyActivity extends BaseActivity {
@BindView(R.id.progressBar)
ProgressBar progressBar;
private boolean isMapViewActive = false;
private LocationServiceManager locationManager;
private LatLng curLatLang;
private Gson gson;
private String gsonPlaceList;
private String gsonCurLatLng;
private Bundle bundle;
private NearbyAsyncTask nearbyAsyncTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nearby);
ButterKnife.bind(this);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
bundle = new Bundle();
locationManager = new LocationServiceManager(this);
locationManager.registerLocationManager();
curLatLang = locationManager.getLatestLocation();
nearbyAsyncTask = new NearbyAsyncTask();
nearbyAsyncTask.execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_nearby, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.action_refresh:
refreshView();
return true;
case R.id.action_map:
showMapView();
if (isMapViewActive) {
item.setIcon(R.drawable.ic_list_white_24dp);
} else {
item.setIcon(R.drawable.ic_map_white_24dp);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void showMapView() {
if (!isMapViewActive) {
isMapViewActive = true;
if (nearbyAsyncTask.getStatus() == AsyncTask.Status.FINISHED) {
setMapFragment();
}
} else {
isMapViewActive = false;
if (nearbyAsyncTask.getStatus() == AsyncTask.Status.FINISHED) {
setListFragment();
}
}
}
@Override
protected void onResume() {
super.onResume();
}
protected void refreshView() {
nearbyAsyncTask = new NearbyAsyncTask();
nearbyAsyncTask.execute();
}
public LocationServiceManager getLocationManager() {
return locationManager;
}
@Override
protected void onDestroy() {
super.onDestroy();
locationManager.unregisterLocationManager();
}
private class NearbyAsyncTask extends AsyncTask<Void, Integer, List<Place>> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
@Override
protected List<Place> doInBackground(Void... params) {
return NearbyController
.loadAttractionsFromLocation(curLatLang, getApplicationContext()
);
}
@Override
protected void onPostExecute(List<Place> placeList) {
super.onPostExecute(placeList);
if (isCancelled()) {
return;
}
gson = new GsonBuilder()
.registerTypeAdapter(Uri.class, new UriSerializer())
.create();
gsonPlaceList = gson.toJson(placeList);
gsonCurLatLng = gson.toJson(curLatLang);
bundle.clear();
bundle.putString("PlaceList", gsonPlaceList);
bundle.putString("CurLatLng", gsonCurLatLng);
// Begin the transaction
if (isMapViewActive) {
setMapFragment();
} else {
setListFragment();
}
if (progressBar != null) {
progressBar.setVisibility(View.GONE);
}
}
}
/**
* Calls fragment for map view.
*/
public void setMapFragment() {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
Fragment fragment = new NearbyMapFragment();
fragment.setArguments(bundle);
fragmentTransaction.replace(R.id.container, fragment);
fragmentTransaction.commit();
}
/**
* Calls fragment for list view.
*/
public void setListFragment() {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
Fragment fragment = new NearbyListFragment();
fragment.setArguments(bundle);
fragmentTransaction.replace(R.id.container, fragment);
fragmentTransaction.commit();
}
}
| Display toast if no nearby places found
| app/src/main/java/fr/free/nrw/commons/nearby/NearbyActivity.java | Display toast if no nearby places found | <ide><path>pp/src/main/java/fr/free/nrw/commons/nearby/NearbyActivity.java
<ide> package fr.free.nrw.commons.nearby;
<ide>
<add>import android.content.Context;
<ide> import android.net.Uri;
<ide> import android.os.AsyncTask;
<ide> import android.os.Bundle;
<ide> import android.view.MenuItem;
<ide> import android.view.View;
<ide> import android.widget.ProgressBar;
<add>import android.widget.Toast;
<ide>
<ide> import butterknife.BindView;
<ide> import butterknife.ButterKnife;
<ide> locationManager = new LocationServiceManager(this);
<ide> locationManager.registerLocationManager();
<ide> curLatLang = locationManager.getLatestLocation();
<del> nearbyAsyncTask = new NearbyAsyncTask();
<add> nearbyAsyncTask = new NearbyAsyncTask(this);
<ide> nearbyAsyncTask.execute();
<ide>
<ide> }
<ide> }
<ide>
<ide> protected void refreshView() {
<del> nearbyAsyncTask = new NearbyAsyncTask();
<add> nearbyAsyncTask = new NearbyAsyncTask(this);
<ide> nearbyAsyncTask.execute();
<ide> }
<ide>
<ide> }
<ide>
<ide> private class NearbyAsyncTask extends AsyncTask<Void, Integer, List<Place>> {
<add>
<add> private Context mContext;
<add>
<add> private NearbyAsyncTask (Context context) {
<add> mContext = context;
<add> }
<ide>
<ide> @Override
<ide> protected void onPreExecute() {
<ide> .create();
<ide> gsonPlaceList = gson.toJson(placeList);
<ide> gsonCurLatLng = gson.toJson(curLatLang);
<add>
<add> if (placeList.size() == 0) {
<add> CharSequence text = "No nearby places found";
<add> int duration = Toast.LENGTH_SHORT;
<add>
<add> Toast toast = Toast.makeText(mContext, text, duration);
<add> toast.show();
<add> }
<ide>
<ide> bundle.clear();
<ide> bundle.putString("PlaceList", gsonPlaceList); |
|
Java | mit | 556cd679acb68e04ea5a0715af8e919511356978 | 0 | HumBuch/HumBuch,HumBuch/HumBuch,HumBuch/HumBuch | package de.dhbw.humbuch.util;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* Util class for looking up a book by its isbn
* <ul>
* <li>Standard ISBN API is isbndb.com</li>
* <li>Document retrieval, validation and parsing can be overridden in subclass</li>
* </ul>
*
* @author davherrmann
*/
public class BookLookup {
private final static String KEY = "CONBNUOZ";
private final static String LOOKUP_URL = "http://isbndb.com/api/v2/xml/"
+ KEY + "/book/";
/**
* Look up a book by its ISBN
*
* @param isbn
* {@link String} containing the ISBN - all non-numerical
* characters are ignored
* @return {@link Book} containing the book data
* @throws BookNotFoundException
* when a book is not found
*/
public static Book lookup(String isbn) throws BookNotFoundException {
Document document = retrieveDocument(buildLookupURL(processISBN(isbn)));
validateDocument(document);
return parseDocument(document);
}
/**
* Removes all non-numerical characters from the isbn
*
* @param isbn
* {@link String} containing the ISBN
* @return {@link String} without all non-numerical characters
*/
protected static String processISBN(String isbn) {
return isbn.replaceAll("[^\\d]", "");
}
/**
* Builds the URI for the ISBN API
*
* @param isbn
* {@link String} containing the ISBN
* @return {@link String} containing the ISBN API URL
*/
protected static String buildLookupURL(String isbn) {
return LOOKUP_URL + isbn;
}
/**
* Retrieve an document from a given URI
*
* @param uri
* {@link String} containing the URI
* @return {@link Document} retrieved from the URI
* @throws BookNotFoundException
* thrown when an error occurs while retrieving the document
*/
protected static Document retrieveDocument(String uri)
throws BookNotFoundException {
try {
DocumentBuilder documentBuilder = DocumentBuilderFactory
.newInstance().newDocumentBuilder();
Document document = documentBuilder.parse(uri);
document.getDocumentElement().normalize();
return document;
} catch (ParserConfigurationException | SAXException | IOException e) {
throw new BookNotFoundException(
"Error during retrieving the XML document...", e);
}
}
/**
* Checks if the document contains valid data for a book
*
* @param document
* {@link Document} to be validated
* @throws BookNotFoundException
* thrown when the document contains no valid book data
*/
protected static void validateDocument(Document document)
throws BookNotFoundException {
Object error = getNodeValue(document, "error");
if (error != null) {
throw new BookNotFoundException("No book found...");
}
}
/**
* Parse a document and extract the book data
*
* @param document
* {@link Document} containing the book data
* @return {@link Book} with the extracted data
*/
protected static Book parseDocument(Document document) {
return new Book.Builder(getNodeValue(document, "title"))
.author(getNodeValue(document, "name"))
.isbn10(getNodeValue(document, "isbn10"))
.isbn13(getNodeValue(document, "isbn13"))
.publisher(getNodeValue(document, "publisher_name")).build();
}
/**
* Extract the value of the first node of an element
*
* @param document
* the {@link Document}
* @param elementName
* name of the element of which the value should be extracted
* @return {@link String} containing the content of the element if it
* exists, otherwise <code>null</code>
*/
private static String getNodeValue(Document document, String elementName) {
NodeList data = document.getElementsByTagName(elementName);
Element element = (Element) data.item(0);
if (element != null) {
Node node = element.getChildNodes().item(0);
if (node != null) {
return node.getNodeValue();
}
}
return null;
}
/**
* Exception indicating a book was not found
*/
public static class BookNotFoundException extends Exception {
private static final long serialVersionUID = -644882332116172763L;
public BookNotFoundException() {
super();
}
public BookNotFoundException(String message, Throwable cause,
boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public BookNotFoundException(String message, Throwable cause) {
super(message, cause);
}
public BookNotFoundException(String message) {
super(message);
}
public BookNotFoundException(Throwable cause) {
super(cause);
}
}
/**
* POJO holding information about the book
*/
public static class Book {
public final String author;
public final String isbn10;
public final String isbn13;
public final String publisher;
public final String title;
private Book(Builder builder) {
this.author = builder.author;
this.isbn10 = builder.isbn10;
this.isbn13 = builder.isbn13;
this.publisher = builder.publisher;
this.title = builder.title;
}
public static class Builder {
private String author;
private String isbn10;
private String isbn13;
private String publisher;
private String title;
public Builder(String title) {
this.title = title;
}
public Builder author(String author) {
this.author = author;
return this;
}
public Builder isbn10(String isbn10) {
this.isbn10 = isbn10;
return this;
}
public Builder isbn13(String isbn13) {
this.isbn13 = isbn13;
return this;
}
public Builder publisher(String publisher) {
this.publisher = publisher;
return this;
}
public Book build() {
return new Book(this);
}
}
}
}
| src/main/java/de/dhbw/humbuch/util/BookLookup.java | package de.dhbw.humbuch.util;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* Util class for looking up a book by its isbn
* <ul>
* <li>Standard ISBN API is isbndb.com</li>
* <li>Document retrieval, validation and parsing can be overridden in subclass</li>
* </ul>
*
* @author davherrmann
*/
public class BookLookup {
private final static String KEY = "CONBNUOZ";
private final static String LOOKUP_URL = "http://isbndb.com/api/v2/xml/"
+ KEY + "/book/";
/**
* Look up a book by its ISBN
*
* @param isbn
* {@link String} containing the ISBN - all non-numerical
* characters are ignored
* @return {@link Book} containing the book data
* @throws BookNotFoundException
* when a book is not found
*/
public static Book lookup(String isbn) throws BookNotFoundException {
Document document = retrieveDocument(buildLookupURL(processISBN(isbn)));
validateDocument(document);
return parseDocument(document);
}
/**
* Removes all non-numerical characters from the isbn
*
* @param isbn
* {@link String} containing the ISBN
* @return {@link String} without all non-numerical characters
*/
protected static String processISBN(String isbn) {
return isbn.replaceAll("[^\\d]", "");
}
/**
* Builds the URI for the ISBN API
*
* @param isbn
* {@link String} containing the ISBN
* @return {@link String} containing the ISBN API URL
*/
protected static String buildLookupURL(String isbn) {
return LOOKUP_URL + isbn;
}
/**
* Retrieve an document from a given URI
*
* @param uri
* {@link String} containing the URI
* @return {@link Document} retrieved from the URI
* @throws BookNotFoundException
* thrown when an error occurs while retrieving the document
*/
protected static Document retrieveDocument(String uri)
throws BookNotFoundException {
try {
DocumentBuilder documentBuilder = DocumentBuilderFactory
.newInstance().newDocumentBuilder();
Document document = documentBuilder.parse(uri);
document.getDocumentElement().normalize();
return document;
} catch (ParserConfigurationException | SAXException | IOException e) {
throw new BookNotFoundException(
"Error during retrieving the XML document...", e);
}
}
/**
* Checks if the document contains valid data for a book
*
* @param document
* {@link Document} to be validated
* @throws BookNotFoundException
* thrown when the document contains no valid book data
*/
protected static void validateDocument(Document document)
throws BookNotFoundException {
Object error = getNodeValue(document, "error");
if (error != null) {
throw new BookNotFoundException("No book found...");
}
}
/**
* Parse a document and extract the book data
*
* @param document
* {@link Document} containing the book data
* @return {@link Book} with the extracted data
*/
protected static Book parseDocument(Document document) {
return new Book.Builder(getNodeValue(document, "title"))
.author(getNodeValue(document, "name"))
.isbn10(getNodeValue(document, "isbn10"))
.isbn13(getNodeValue(document, "isbn13"))
.publisher(getNodeValue(document, "publisher_name")).build();
}
/**
* Extract the value of the first node of an element
*
* @param document
* the {@link Document}
* @param elementName
* name of the element of which the value should be extracted
* @return {@link String} containing the content of the element if it
* exists, otherwise <code>null</code>
*/
private static String getNodeValue(Document document, String elementName) {
NodeList data = document.getElementsByTagName(elementName);
Element element = (Element) data.item(0);
if (element != null) {
Node node = element.getChildNodes().item(0);
return node.getNodeValue();
}
return null;
}
/**
* Exception indicating a book was not found
*/
public static class BookNotFoundException extends Exception {
private static final long serialVersionUID = -644882332116172763L;
public BookNotFoundException() {
super();
}
public BookNotFoundException(String message, Throwable cause,
boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public BookNotFoundException(String message, Throwable cause) {
super(message, cause);
}
public BookNotFoundException(String message) {
super(message);
}
public BookNotFoundException(Throwable cause) {
super(cause);
}
}
/**
* POJO holding information about the book
*/
public static class Book {
public final String author;
public final String isbn10;
public final String isbn13;
public final String publisher;
public final String title;
private Book(Builder builder) {
this.author = builder.author;
this.isbn10 = builder.isbn10;
this.isbn13 = builder.isbn13;
this.publisher = builder.publisher;
this.title = builder.title;
}
public static class Builder {
private String author;
private String isbn10;
private String isbn13;
private String publisher;
private String title;
public Builder(String title) {
this.title = title;
}
public Builder author(String author) {
this.author = author;
return this;
}
public Builder isbn10(String isbn10) {
this.isbn10 = isbn10;
return this;
}
public Builder isbn13(String isbn13) {
this.isbn13 = isbn13;
return this;
}
public Builder publisher(String publisher) {
this.publisher = publisher;
return this;
}
public Book build() {
return new Book(this);
}
}
}
}
| Fixed NullPointer | src/main/java/de/dhbw/humbuch/util/BookLookup.java | Fixed NullPointer | <ide><path>rc/main/java/de/dhbw/humbuch/util/BookLookup.java
<ide> Element element = (Element) data.item(0);
<ide> if (element != null) {
<ide> Node node = element.getChildNodes().item(0);
<del> return node.getNodeValue();
<add> if (node != null) {
<add> return node.getNodeValue();
<add> }
<ide> }
<ide> return null;
<ide> } |
|
Java | mit | 59fd546860355105623d95b3a35a9db8fd4c084e | 0 | cs2103aug2015-t10-4j/care-lender,cs2103aug2015-t10-4j/main | package carelender.model.data;
import java.text.SimpleDateFormat;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import carelender.controller.Controller;
import carelender.controller.Search;
import carelender.model.Model;
/**
* Used for list queries
*/
public class QueryList extends QueryBase {
private HashMap<SortParam, Comparator<Event>> sortComparators = new HashMap<SortParam, Comparator<Event>>();
private HashMap<SearchParam, Object> searchParamsList = new HashMap<SearchParam, Object>();
private void defineComparators () {
sortComparators.put(SortParam.NAME, new Comparator<Event>() {
@Override
public int compare(Event eventAgainst, Event eventTo) {
// TODO Auto-generated method stub
return eventAgainst.getName().compareTo(eventTo.getName());
}
});
sortComparators.put(SortParam.DATE, new Comparator<Event>() {
@Override
public int compare(Event eventAgainst, Event eventTo) {
// TODO Auto-generated method stub
if (eventAgainst.getEarliestDate().before(eventTo.getEarliestDate())) {
return 1;
} else if (eventAgainst.getEarliestDate().after(eventTo.getEarliestDate())) {
return -1;
}
return 0;
}
});
}
public QueryList() {
super(QueryType.LIST);
this.defineComparators();
}
public QueryList (QueryType type) {
super(type);
this.defineComparators();
}
public void addSearchParam (SearchParam key, Object value) {
this.searchParamsList.put(key, value);
}
public HashMap<SearchParam, Object> getSearchParamsList () {
return this.searchParamsList;
}
public enum SearchParam {
DATE_START,
DATE_END,
NAME_CONTAINS,
NAME_EXACT,
TYPE,
LIMIT,
SORT
};
public enum SortParam {
NAME,
DATE,
CATEGORY,
COMPLETE
};
@Override
public void controllerExecute() {
EventList searchResults = searchExecute();
if ( this.searchParamsList.containsKey(SearchParam.SORT) ) {
}
SimpleDateFormat dateFormat = new SimpleDateFormat("E dd MMM yyyy h:mma Z");
Controller.displayMessage("Listing events");
if ( this.searchParamsList.containsKey(SearchParam.DATE_START) ) {
Date fromDate = (Date)this.searchParamsList.get(SearchParam.DATE_START);
Controller.displayMessage(" from " + dateFormat.format(fromDate));
}
if ( this.searchParamsList.containsKey(SearchParam.DATE_END) ) {
Date toDate = (Date)this.searchParamsList.get(SearchParam.DATE_END);
Controller.displayMessage(" till " + dateFormat.format(toDate));
}
if ( this.searchParamsList.containsKey(SearchParam.NAME_CONTAINS) ) {
String search = (String)this.searchParamsList.get(SearchParam.NAME_CONTAINS);
Controller.displayMessage(" matching: " + search);
}
if (searchResults.size() > 0) {
Controller.displayMessage(searchResults.toString());
} else {
Controller.displayMessage("No results");
}
}
@Override
public EventList searchExecute() {
EventList returnList = new EventList();
//TODO: Replace the null parameter in retrieveEvent to something that makes sense.
if (Model.getInstance().retrieveEvent() != null) {
for (Event event : Model.getInstance().retrieveEvent()) {
if (Search.eventMatchesParams(event, getSearchParamsList())) {
returnList.add(event.copy());
}
}
}
return returnList;
}
}
| src/carelender/model/data/QueryList.java | package carelender.model.data;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import carelender.controller.Controller;
import carelender.controller.Search;
import carelender.model.Model;
/**
* Used for list queries
*/
public class QueryList extends QueryBase {
private HashMap<SearchParam, Object> searchParamsList = new HashMap<SearchParam, Object>();
public QueryList() {
super(QueryType.LIST);
}
public QueryList (QueryType type) {
super(type);
}
public void addSearchParam (SearchParam key, Object value) {
this.searchParamsList.put(key, value);
}
public HashMap<SearchParam, Object> getSearchParamsList () {
return searchParamsList;
}
public enum SearchParam {
DATE_START,
DATE_END,
NAME_CONTAINS,
NAME_EXACT,
TYPE
};
@Override
public void controllerExecute() {
EventList searchResults = searchExecute();
SimpleDateFormat dateFormat = new SimpleDateFormat("E dd MMM yyyy h:mma Z");
Controller.displayMessage("Listing events");
HashMap<QueryList.SearchParam, Object> paramList = getSearchParamsList();
if ( paramList.containsKey(QueryList.SearchParam.DATE_START) ) {
Date fromDate = (Date)paramList.get(QueryList.SearchParam.DATE_START);
Controller.displayMessage(" from " + dateFormat.format(fromDate));
}
if ( paramList.containsKey(QueryList.SearchParam.DATE_END) ) {
Date toDate = (Date)paramList.get(QueryList.SearchParam.DATE_END);
Controller.displayMessage(" till " + dateFormat.format(toDate));
}
if ( paramList.containsKey(QueryList.SearchParam.NAME_CONTAINS) ) {
String search = (String)paramList.get(QueryList.SearchParam.NAME_CONTAINS);
Controller.displayMessage(" matching: " + search);
}
if (searchResults.size() > 0) {
Controller.displayMessage(searchResults.toString());
} else {
Controller.displayMessage("No results");
}
}
@Override
public EventList searchExecute() {
EventList returnList = new EventList();
//TODO: Replace the null parameter in retrieveEvent to something that makes sense.
if (Model.getInstance().retrieveEvent() != null) {
for (Event event : Model.getInstance().retrieveEvent()) {
if (Search.eventMatchesParams(event, getSearchParamsList())) {
returnList.add(event.copy());
}
}
}
return returnList;
}
}
| Modified Code - Sorting for QueryList
TODO: Actually use the comparators and Collections.sort
| src/carelender/model/data/QueryList.java | Modified Code - Sorting for QueryList | <ide><path>rc/carelender/model/data/QueryList.java
<ide> package carelender.model.data;
<ide>
<ide> import java.text.SimpleDateFormat;
<add>import java.util.Comparator;
<ide> import java.util.Date;
<ide> import java.util.HashMap;
<ide>
<ide>
<ide> public class QueryList extends QueryBase {
<ide>
<add> private HashMap<SortParam, Comparator<Event>> sortComparators = new HashMap<SortParam, Comparator<Event>>();
<ide> private HashMap<SearchParam, Object> searchParamsList = new HashMap<SearchParam, Object>();
<add>
<add> private void defineComparators () {
<add> sortComparators.put(SortParam.NAME, new Comparator<Event>() {
<add> @Override
<add> public int compare(Event eventAgainst, Event eventTo) {
<add> // TODO Auto-generated method stub
<add> return eventAgainst.getName().compareTo(eventTo.getName());
<add> }
<add> });
<add> sortComparators.put(SortParam.DATE, new Comparator<Event>() {
<add> @Override
<add> public int compare(Event eventAgainst, Event eventTo) {
<add> // TODO Auto-generated method stub
<add> if (eventAgainst.getEarliestDate().before(eventTo.getEarliestDate())) {
<add> return 1;
<add> } else if (eventAgainst.getEarliestDate().after(eventTo.getEarliestDate())) {
<add> return -1;
<add> }
<add> return 0;
<add> }
<add> });
<add> }
<ide>
<ide> public QueryList() {
<ide> super(QueryType.LIST);
<add> this.defineComparators();
<ide> }
<ide>
<ide> public QueryList (QueryType type) {
<ide> super(type);
<del> }
<add> this.defineComparators();
<add> }
<ide>
<ide> public void addSearchParam (SearchParam key, Object value) {
<ide> this.searchParamsList.put(key, value);
<ide> }
<ide>
<ide> public HashMap<SearchParam, Object> getSearchParamsList () {
<del> return searchParamsList;
<add> return this.searchParamsList;
<ide> }
<ide>
<ide> public enum SearchParam {
<ide> DATE_END,
<ide> NAME_CONTAINS,
<ide> NAME_EXACT,
<del> TYPE
<add> TYPE,
<add> LIMIT,
<add> SORT
<add> };
<add>
<add> public enum SortParam {
<add> NAME,
<add> DATE,
<add> CATEGORY,
<add> COMPLETE
<ide> };
<ide>
<ide> @Override
<ide> public void controllerExecute() {
<ide> EventList searchResults = searchExecute();
<add>
<add> if ( this.searchParamsList.containsKey(SearchParam.SORT) ) {
<add>
<add> }
<ide>
<ide> SimpleDateFormat dateFormat = new SimpleDateFormat("E dd MMM yyyy h:mma Z");
<ide> Controller.displayMessage("Listing events");
<del> HashMap<QueryList.SearchParam, Object> paramList = getSearchParamsList();
<del> if ( paramList.containsKey(QueryList.SearchParam.DATE_START) ) {
<del> Date fromDate = (Date)paramList.get(QueryList.SearchParam.DATE_START);
<add>
<add> if ( this.searchParamsList.containsKey(SearchParam.DATE_START) ) {
<add> Date fromDate = (Date)this.searchParamsList.get(SearchParam.DATE_START);
<ide> Controller.displayMessage(" from " + dateFormat.format(fromDate));
<ide> }
<del> if ( paramList.containsKey(QueryList.SearchParam.DATE_END) ) {
<del> Date toDate = (Date)paramList.get(QueryList.SearchParam.DATE_END);
<add> if ( this.searchParamsList.containsKey(SearchParam.DATE_END) ) {
<add> Date toDate = (Date)this.searchParamsList.get(SearchParam.DATE_END);
<ide> Controller.displayMessage(" till " + dateFormat.format(toDate));
<ide> }
<del> if ( paramList.containsKey(QueryList.SearchParam.NAME_CONTAINS) ) {
<del> String search = (String)paramList.get(QueryList.SearchParam.NAME_CONTAINS);
<add> if ( this.searchParamsList.containsKey(SearchParam.NAME_CONTAINS) ) {
<add> String search = (String)this.searchParamsList.get(SearchParam.NAME_CONTAINS);
<ide> Controller.displayMessage(" matching: " + search);
<ide> }
<ide> |
|
Java | apache-2.0 | d115e4895eda0b41f60a38da60da4e7c7f099eeb | 0 | beyond-snail/ImageLoad | package com.example.imageload.load;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.util.LruCache;
import android.widget.ImageView;
/**
* ͼƬ
* @author Administrator
*
*/
public class ImageLoader {
//ͼƬ
ImageCache mImageCache = new ImageCache();
//̳߳أ߳ΪCPU
ExecutorService mExecutorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
//ͼƬ
public void displayImage(final String url, final ImageView imageView){
Bitmap bitmap = mImageCache.get(url);
if (bitmap != null){
imageView.setImageBitmap(bitmap);
return;
}
imageView.setTag(url);
mExecutorService.submit(new Runnable() {
@Override
public void run() {
Bitmap bitmap = downLoadImage(url);
if (bitmap == null){
return;
}
if (imageView.getTag().equals(url)){
imageView.setImageBitmap(bitmap);
}
mImageCache.put(url, bitmap);
}
});
}
protected Bitmap downLoadImage(String imageUrl) {
Bitmap bitmap = null;
try {
URL url = new URL(imageUrl);
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
bitmap = BitmapFactory.decodeStream(conn.getInputStream());
conn.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
}
| src/com/example/imageload/load/ImageLoader.java | package com.example.imageload.load;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.util.LruCache;
import android.widget.ImageView;
/**
* ͼƬ
* @author Administrator
*
*/
public class ImageLoader {
//ͼƬ
ImageCache mImageCache = new ImageCache();
//̳߳أ߳ΪCPU
ExecutorService mExecutorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
//ͼƬ
public void displayImage(final String url, final ImageView imageView){
imageView.setTag(url);
mExecutorService.submit(new Runnable() {
@Override
public void run() {
Bitmap bitmap = downLoadImage(url);
if (bitmap == null){
return;
}
if (imageView.getTag().equals(url)){
imageView.setImageBitmap(bitmap);
}
mImageCache.put(url, bitmap);
}
});
}
protected Bitmap downLoadImage(String imageUrl) {
Bitmap bitmap = null;
try {
URL url = new URL(imageUrl);
final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
bitmap = BitmapFactory.decodeStream(conn.getInputStream());
conn.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
}
| 修正加载图片,添加从缓存中加载
| src/com/example/imageload/load/ImageLoader.java | 修正加载图片,添加从缓存中加载 | <ide><path>rc/com/example/imageload/load/ImageLoader.java
<ide>
<ide> //ͼƬ
<ide> public void displayImage(final String url, final ImageView imageView){
<add> Bitmap bitmap = mImageCache.get(url);
<add> if (bitmap != null){
<add> imageView.setImageBitmap(bitmap);
<add> return;
<add> }
<ide> imageView.setTag(url);
<ide> mExecutorService.submit(new Runnable() {
<ide> @Override |
|
Java | apache-2.0 | 537422fed559f444b201713bf0cd81700fd155b2 | 0 | ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE | package uk.ac.ebi.quickgo.ontology.controller;
import uk.ac.ebi.quickgo.graphics.ontology.RenderingGraphException;
import uk.ac.ebi.quickgo.graphics.service.GraphImageService;
import uk.ac.ebi.quickgo.ontology.common.document.OntologyFields;
import uk.ac.ebi.quickgo.ontology.common.document.OntologyType;
import uk.ac.ebi.quickgo.ontology.controller.validation.OBOControllerValidationHelper;
import uk.ac.ebi.quickgo.ontology.controller.validation.OBOControllerValidationHelperImpl;
import uk.ac.ebi.quickgo.ontology.model.OBOTerm;
import uk.ac.ebi.quickgo.ontology.model.OntologyRelationType;
import uk.ac.ebi.quickgo.ontology.model.OntologyRelationship;
import uk.ac.ebi.quickgo.ontology.service.OntologyService;
import uk.ac.ebi.quickgo.ontology.service.search.SearchServiceConfig;
import uk.ac.ebi.quickgo.rest.ParameterException;
import uk.ac.ebi.quickgo.rest.ResponseExceptionHandler;
import uk.ac.ebi.quickgo.rest.search.*;
import uk.ac.ebi.quickgo.rest.search.query.Page;
import uk.ac.ebi.quickgo.rest.search.query.QueryRequest;
import uk.ac.ebi.quickgo.rest.search.query.QuickGOQuery;
import uk.ac.ebi.quickgo.rest.search.results.QueryResult;
import io.swagger.annotations.ApiOperation;
import java.awt.image.RenderedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.imageio.ImageIO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import static com.google.common.base.Preconditions.checkArgument;
import static uk.ac.ebi.quickgo.ontology.model.OntologyRelationType.DEFAULT_TRAVERSAL_TYPES_CSV;
import static uk.ac.ebi.quickgo.rest.search.query.QuickGOQuery.and;
/**
* Abstract controller defining common end-points of an OBO related
* REST API.
*
* Created 27/11/15
* @author Edd
*/
public abstract class OBOController<T extends OBOTerm> {
static final String TERMS_RESOURCE = "terms";
static final String SEARCH_RESOUCE = "search";
static final String COMPLETE_SUB_RESOURCE = "complete";
static final String HISTORY_SUB_RESOURCE = "history";
static final String XREFS_SUB_RESOURCE = "xrefs";
static final String CONSTRAINTS_SUB_RESOURCE = "constraints";
static final String XRELATIONS_SUB_RESOURCE = "xontologyrelations";
static final String GUIDELINES_SUB_RESOURCE = "guidelines";
static final String ANCESTORS_SUB_RESOURCE = "ancestors";
static final String DESCENDANTS_SUB_RESOURCE = "descendants";
static final String PATHS_SUB_RESOURCE = "paths";
static final String CHART_SUB_RESOURCE = "chart";
static final int MAX_PAGE_RESULTS = 100;
private static final Logger LOGGER = LoggerFactory.getLogger(OBOController.class);
private static final String COLON = ":";
private static final String DEFAULT_ENTRIES_PER_PAGE = "25";
private static final String DEFAULT_PAGE_NUMBER = "1";
private final OntologyService<T> ontologyService;
private final SearchService<OBOTerm> ontologySearchService;
private final StringToQuickGOQueryConverter ontologyQueryConverter;
private final SearchServiceConfig.OntologyCompositeRetrievalConfig ontologyRetrievalConfig;
private final OBOControllerValidationHelper validationHelper;
private final GraphImageService graphImageService;
public OBOController(OntologyService<T> ontologyService,
SearchService<OBOTerm> ontologySearchService,
SearchableField searchableField,
SearchServiceConfig.OntologyCompositeRetrievalConfig ontologyRetrievalConfig,
GraphImageService graphImageService) {
checkArgument(ontologyService != null, "Ontology service cannot be null");
checkArgument(ontologySearchService != null, "Ontology search service cannot be null");
checkArgument(searchableField != null, "Ontology searchable field cannot be null");
checkArgument(ontologyRetrievalConfig != null, "Ontology retrieval configuration cannot be null");
checkArgument(graphImageService != null, "Graph image service cannot be null");
this.ontologyService = ontologyService;
this.ontologySearchService = ontologySearchService;
this.ontologyQueryConverter = new StringToQuickGOQueryConverter(searchableField);
this.ontologyRetrievalConfig = ontologyRetrievalConfig;
this.validationHelper = new OBOControllerValidationHelperImpl(MAX_PAGE_RESULTS, idValidator());
this.graphImageService = graphImageService;
}
/**
* An empty or unknown path should result in a bad request
*
* @return a 400 response
*/
@ApiOperation(value = "Catches any bad requests and returns an error response with a 400 status")
@RequestMapping(value = "/*", method = {RequestMethod.GET}, produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<ResponseExceptionHandler.ErrorInfo> emptyId() {
throw new ParameterException("The requested end-point does not exist.");
}
/**
* Get all information about all terms and page through the results.
*
* @param page the page number of results to retrieve
* @return the specified page of results as a {@link QueryResult} instance or a 400 response
* if the page number is invalid
*/
@ApiOperation(value = "Get all information on all terms and page through the results")
@RequestMapping(value = "/" + TERMS_RESOURCE, method = {RequestMethod.GET},
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<QueryResult<T>> baseUrl(
@RequestParam(value = "page", defaultValue = DEFAULT_PAGE_NUMBER) int page) {
validationHelper.validateRequestedPages(page);
return new ResponseEntity<>(ontologyService.findAllByOntologyType(getOntologyType(),
new Page(page, MAX_PAGE_RESULTS)), HttpStatus.OK);
}
/**
* Get core information about a list of terms in comma-separated-value (CSV) format
*
* @param ids ontology identifiers in CSV format
* @return
* <ul>
* <li>all ids are valid: response consists of a 200 with the chosen information about the ontology terms</li>
* <li>any id is not found: response returns 404</li>
* <li>any id is of the an invalid format: response returns 400</li>
* </ul>
*/
@ApiOperation(value = "Get core information about a (CSV) list of terms based on their ids",
notes = "If possible, response fields include: id, isObsolete, name, definition, ancestors, synonyms, " +
"aspect and usage.")
@RequestMapping(value = TERMS_RESOURCE + "/{ids}", method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<QueryResult<T>> findTermsCoreAttr(@PathVariable(value = "ids") String ids) {
return getResultsResponse(
ontologyService.findCoreInfoByOntologyId(validationHelper.validateCSVIds(ids)));
}
/**
* Get complete information about a list of terms in comma-separated-value (CSV) format
*
* @param ids ontology identifiers in CSV format
* @return
* <ul>
* <li>all ids are valid: response consists of a 200 with the chosen information about the ontology terms</li>
* <li>any id is not found: response returns 404</li>
* <li>any id is of the an invalid format: response returns 400</li>
* </ul>
*/
@ApiOperation(value = "Get complete information about a (CSV) list of terms based on their ids",
notes = "All fields will be populated providing they have a value.")
@RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + COMPLETE_SUB_RESOURCE, method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<QueryResult<T>> findTermsComplete(@PathVariable(value = "ids") String ids) {
return getResultsResponse(
ontologyService.findCompleteInfoByOntologyId(validationHelper.validateCSVIds(ids)));
}
/**
* Get history information about a list of terms in comma-separated-value (CSV) format
*
* @param ids ontology identifiers in CSV format
* @return
* <ul>
* <li>all ids are valid: response consists of a 200 with the chosen information about the ontology terms</li>
* <li>any id is not found: response returns 404</li>
* <li>any id is of the an invalid format: response returns 400</li>
* </ul>
*/
@ApiOperation(value = "Get history information about a (CSV) list of terms based on their ids",
notes = "If possible, response fields include: id, isObsolete, name, definition, history.")
@RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + HISTORY_SUB_RESOURCE, method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<QueryResult<T>> findTermsHistory(@PathVariable(value = "ids") String ids) {
return getResultsResponse(
ontologyService.findHistoryInfoByOntologyId(validationHelper.validateCSVIds(ids)));
}
/**
* Get cross-reference information about a list of terms in comma-separated-value (CSV) format
*
* @param ids ontology identifiers in CSV format
* @return
* <ul>
* <li>all ids are valid: response consists of a 200 with the chosen information about the ontology terms</li>
* <li>any id is not found: response returns 404</li>
* <li>any id is of the an invalid format: response returns 400</li>
* </ul>
*/
@ApiOperation(value = "Get cross-reference information about a (CSV) list of terms based on their ids",
notes = "If possible, response fields include: id, isObsolete, name, definition, xRefs.")
@RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + XREFS_SUB_RESOURCE, method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<QueryResult<T>> findTermsXRefs(@PathVariable(value = "ids") String ids) {
return getResultsResponse(
ontologyService.findXRefsInfoByOntologyId(validationHelper.validateCSVIds(ids)));
}
/**
* Get taxonomy constraint information about a list of terms in comma-separated-value (CSV) format
*
* @param ids ontology identifiers in CSV format
* @return
* <ul>
* <li>all ids are valid: response consists of a 200 with the chosen information about the ontology terms</li>
* <li>any id is not found: response returns 404</li>
* <li>any id is of the an invalid format: response returns 400</li>
* </ul>
*/
@ApiOperation(value = "Get taxonomy constraint information about a (CSV) list of terms based on their ids",
notes = "If possible, response fields include: id, isObsolete, name, definition, taxonConstraints.")
@RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + CONSTRAINTS_SUB_RESOURCE, method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<QueryResult<T>> findTermsTaxonConstraints(@PathVariable(value = "ids") String ids) {
return getResultsResponse(
ontologyService.findTaxonConstraintsInfoByOntologyId(validationHelper.validateCSVIds(ids)));
}
/**
* Get cross-ontology relationship information about a list of terms in comma-separated-value (CSV) format
*
* @param ids ontology identifiers in CSV format
* @return
* <ul>
* <li>all ids are valid: response consists of a 200 with the chosen information about the ontology terms</li>
* <li>any id is not found: response returns 404</li>
* <li>any id is of the an invalid format: response returns 400</li>
* </ul>
*/
@ApiOperation(value = "Get cross ontology relationship information about a (CSV) list of terms based on their ids",
notes = "If possible, response fields include: id, isObsolete, name, definition, xRelations.")
@RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + XRELATIONS_SUB_RESOURCE, method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<QueryResult<T>> findTermsXOntologyRelations(@PathVariable(value = "ids") String ids) {
return getResultsResponse(
ontologyService.findXORelationsInfoByOntologyId(validationHelper.validateCSVIds(ids)));
}
/**
* Get annotation guideline information about a list of terms in comma-separated-value (CSV) format
*
* @param ids ontology identifiers in CSV format
* @return
* <ul>
* <li>all ids are valid: response consists of a 200 with the chosen information about the ontology terms</li>
* <li>any id is not found: response returns 404</li>
* <li>any id is of the an invalid format: response returns 400</li>
* </ul>
*/
@ApiOperation(value = "Get annotation guideline information about a (CSV) list of terms based on their ids",
notes = "If possible, response fields include: id, isObsolete, name, definition, annotationGuidelines.")
@RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + GUIDELINES_SUB_RESOURCE, method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<QueryResult<T>> findTermsAnnotationGuideLines(@PathVariable(value = "ids") String ids) {
return getResultsResponse(ontologyService
.findAnnotationGuideLinesInfoByOntologyId(validationHelper.validateCSVIds(ids)));
}
/**
* Search for an ontology term via its identifier, or a generic query search
*
* @param query the query to search against
* @param limit the amount of queries to return
* @return a {@link QueryResult} instance containing the results of the search
*/
@ApiOperation(value = "Searches a simple user query, e.g., query=apopto",
notes = "If possible, response fields include: id, name, definition, isObsolete")
@RequestMapping(value = "/" + SEARCH_RESOUCE, method = {RequestMethod.GET},
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<QueryResult<OBOTerm>> ontologySearch(
@RequestParam(value = "query") String query,
@RequestParam(value = "limit", defaultValue = DEFAULT_ENTRIES_PER_PAGE) int limit,
@RequestParam(value = "page", defaultValue = DEFAULT_PAGE_NUMBER) int page) {
validationHelper.validateRequestedResults(limit);
validationHelper.validateRequestedPages(page);
QueryRequest request = buildRequest(
query,
limit,
page,
ontologyQueryConverter);
return SearchDispatcher.search(request, ontologySearchService);
}
/**
* Retrieves the ancestors of ontology terms
* @param ids the term ids in CSV format
* @param relations the ontology relationships over which ancestors will be found
* @return a result instance containing the ancestors
*/
@ApiOperation(value = "Retrieves the ancestors of specified ontology terms")
@RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + ANCESTORS_SUB_RESOURCE, method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<QueryResult<T>> findAncestors(
@PathVariable(value = "ids") String ids,
@RequestParam(value = "relations", defaultValue = DEFAULT_TRAVERSAL_TYPES_CSV) String relations) {
return getResultsResponse(
ontologyService.findAncestorsInfoByOntologyId(
validationHelper.validateCSVIds(ids),
asOntologyRelationTypeArray(validationHelper.validateRelationTypes(relations))));
}
/**
* Retrieves the descendants of ontology terms
* @param ids the term ids in CSV format
* @param relations the ontology relationships over which descendants will be found
* @return a result containing the descendants
*/
@ApiOperation(value = "Retrieves the descendants of specified ontology terms")
@RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + DESCENDANTS_SUB_RESOURCE, method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<QueryResult<T>> findDescendants(
@PathVariable(value = "ids") String ids,
@RequestParam(value = "relations", defaultValue = DEFAULT_TRAVERSAL_TYPES_CSV) String relations) {
return getResultsResponse(
ontologyService.findDescendantsInfoByOntologyId(
validationHelper.validateCSVIds(ids),
asOntologyRelationTypeArray(validationHelper.validateRelationTypes(relations))));
}
/**
* Retrieves the paths between ontology terms
* @param ids the term ids in CSV format, from which paths begin
* @param toIds the term ids in CSV format, to which the paths lead
* @param relations the ontology relationships over which descendants will be found
* @return a result containing a list of paths between the {@code ids} terms, and {@code toIds} terms
*/
@ApiOperation(value = "Retrieves the paths between two specified sets of ontology terms. Each path is " +
"formed from a list of (term, relationship, term) triples.")
@RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + PATHS_SUB_RESOURCE + "/{toIds}", method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<QueryResult<List<OntologyRelationship>>> findPaths(
@PathVariable(value = "ids") String ids,
@PathVariable(value = "toIds") String toIds,
@RequestParam(value = "relations", defaultValue = DEFAULT_TRAVERSAL_TYPES_CSV) String relations) {
return getResultsResponse(
ontologyService.paths(
asSet(validationHelper.validateCSVIds(ids)),
asSet(validationHelper.validateCSVIds(toIds)),
asOntologyRelationTypeArray(validationHelper.validateRelationTypes(relations))
));
}
/**
* Retrieves the graphical image corresponding to ontology terms.
*
* @param ids the term ids whose image is required
* @return the image corresponding to the requested term ids
*/
@RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + CHART_SUB_RESOURCE, method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.IMAGE_PNG_VALUE})
public ResponseEntity<InputStreamResource> getChart(@PathVariable(value = "ids") String ids) {
try {
return createChartResponseEntity(validationHelper.validateCSVIds(ids));
} catch (IOException | RenderingGraphException e) {
throw new RetrievalException(e);
}
}
/**
* Delegates the creation of an graphical image, corresponding to the specified list
* of {@code ids} and returns the appropriate {@link ResponseEntity}.
*
* @param ids the terms whose corresponding graphical image is required
* @return the image corresponding to the specified terms
* @throws IOException if there is an error during creation of the image {@link InputStreamResource}
* @throws RenderingGraphException if there was an error during the rendering of the image
*/
private ResponseEntity<InputStreamResource> createChartResponseEntity(List<String> ids)
throws IOException, RenderingGraphException {
RenderedImage renderedImage =
graphImageService
.createChart(ids, getOntologyType().name())
.getGraphImage()
.render();
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(renderedImage, "png", os);
InputStream is = new ByteArrayInputStream(os.toByteArray());
return ResponseEntity
.ok()
.contentLength(os.size())
.contentType(MediaType.IMAGE_PNG)
.body(new InputStreamResource(is));
}
/**
* Predicate that determines the validity of an ID.
* @return {@link Predicate<String>} indicating the validity of an ID.
*/
protected abstract Predicate<String> idValidator();
/**
* Returns the {@link OntologyType} that corresponds to this controller.
*
* @return the ontology type corresponding to this controller's behaviour.
*/
protected abstract OntologyType getOntologyType();
/**
* Wrap a collection as a {@link Set}
* @param items the items to wrap as a {@link Set}
* @param <ItemType> the type of the {@link Collection}, i.e., this method works for any type
* @return a {@link Set} wrapping the items in a {@link Collection}
*/
private static <ItemType> Set<ItemType> asSet(Collection<ItemType> items) {
return items.stream().collect(Collectors.toSet());
}
/**
* Converts a {@link Collection} of {@link OntologyRelationType}s to a corresponding array of
* {@link OntologyRelationType}s
* @param relations the {@link OntologyRelationType}s
* @return an array of {@link OntologyRelationType}s
*/
private static OntologyRelationType[] asOntologyRelationTypeArray(Collection<OntologyRelationType> relations) {
return relations.stream().toArray(OntologyRelationType[]::new);
}
/**
* Creates a {@link ResponseEntity} containing a {@link QueryResult} for a list of results.
*
* @param results a list of results
* @return a {@link ResponseEntity} containing a {@link QueryResult} for a list of results
*/
<ResponseType> ResponseEntity<QueryResult<ResponseType>> getResultsResponse(List<ResponseType> results) {
List<ResponseType> resultsToShow;
if (results == null) {
resultsToShow = Collections.emptyList();
} else {
resultsToShow = results;
}
QueryResult<ResponseType> queryResult = new QueryResult.Builder<>(resultsToShow.size(), resultsToShow).build();
return new ResponseEntity<>(queryResult, HttpStatus.OK);
}
private QueryRequest buildRequest(String query,
int limit,
int page,
StringToQuickGOQueryConverter converter) {
QuickGOQuery userQuery = converter.convert(query);
QuickGOQuery restrictedUserQuery = restrictQueryToOTypeResults(userQuery);
QueryRequest.Builder builder = new QueryRequest
.Builder(restrictedUserQuery)
.setPageParameters(page, limit);
if (!ontologyRetrievalConfig.getSearchReturnedFields().isEmpty()) {
ontologyRetrievalConfig.getSearchReturnedFields()
.forEach(builder::addProjectedField);
}
return builder.build();
}
/**
* Given a {@link QuickGOQuery}, create a composite {@link QuickGOQuery} by
* performing a conjunction with another query, which restricts all results
* to be of a type corresponding to that provided by {@link #getOntologyType()}.
*
* @param query the query that is constrained
* @return the new constrained query
*/
private QuickGOQuery restrictQueryToOTypeResults(QuickGOQuery query) {
return and(query,
ontologyQueryConverter.convert(
OntologyFields.Searchable.ONTOLOGY_TYPE + COLON + getOntologyType().name()));
}
} | ontology-rest/src/main/java/uk/ac/ebi/quickgo/ontology/controller/OBOController.java | package uk.ac.ebi.quickgo.ontology.controller;
import uk.ac.ebi.quickgo.graphics.ontology.RenderingGraphException;
import uk.ac.ebi.quickgo.graphics.service.GraphImageService;
import uk.ac.ebi.quickgo.ontology.common.document.OntologyFields;
import uk.ac.ebi.quickgo.ontology.common.document.OntologyType;
import uk.ac.ebi.quickgo.ontology.controller.validation.OBOControllerValidationHelper;
import uk.ac.ebi.quickgo.ontology.controller.validation.OBOControllerValidationHelperImpl;
import uk.ac.ebi.quickgo.ontology.model.OBOTerm;
import uk.ac.ebi.quickgo.ontology.model.OntologyRelationType;
import uk.ac.ebi.quickgo.ontology.model.OntologyRelationship;
import uk.ac.ebi.quickgo.ontology.service.OntologyService;
import uk.ac.ebi.quickgo.ontology.service.search.SearchServiceConfig;
import uk.ac.ebi.quickgo.rest.ResponseExceptionHandler;
import uk.ac.ebi.quickgo.rest.search.*;
import uk.ac.ebi.quickgo.rest.search.query.Page;
import uk.ac.ebi.quickgo.rest.search.query.QueryRequest;
import uk.ac.ebi.quickgo.rest.search.query.QuickGOQuery;
import uk.ac.ebi.quickgo.rest.search.results.QueryResult;
import io.swagger.annotations.ApiOperation;
import java.awt.image.RenderedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.imageio.ImageIO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import static com.google.common.base.Preconditions.checkArgument;
import static uk.ac.ebi.quickgo.ontology.model.OntologyRelationType.DEFAULT_TRAVERSAL_TYPES_CSV;
import static uk.ac.ebi.quickgo.rest.search.query.QuickGOQuery.and;
/**
* Abstract controller defining common end-points of an OBO related
* REST API.
*
* Created 27/11/15
* @author Edd
*/
public abstract class OBOController<T extends OBOTerm> {
static final String TERMS_RESOURCE = "terms";
static final String SEARCH_RESOUCE = "search";
static final String COMPLETE_SUB_RESOURCE = "complete";
static final String HISTORY_SUB_RESOURCE = "history";
static final String XREFS_SUB_RESOURCE = "xrefs";
static final String CONSTRAINTS_SUB_RESOURCE = "constraints";
static final String XRELATIONS_SUB_RESOURCE = "xontologyrelations";
static final String GUIDELINES_SUB_RESOURCE = "guidelines";
static final String ANCESTORS_SUB_RESOURCE = "ancestors";
static final String DESCENDANTS_SUB_RESOURCE = "descendants";
static final String PATHS_SUB_RESOURCE = "paths";
static final String CHART_SUB_RESOURCE = "chart";
static final int MAX_PAGE_RESULTS = 100;
private static final Logger LOGGER = LoggerFactory.getLogger(OBOController.class);
private static final String COLON = ":";
private static final String DEFAULT_ENTRIES_PER_PAGE = "25";
private static final String DEFAULT_PAGE_NUMBER = "1";
private final OntologyService<T> ontologyService;
private final SearchService<OBOTerm> ontologySearchService;
private final StringToQuickGOQueryConverter ontologyQueryConverter;
private final SearchServiceConfig.OntologyCompositeRetrievalConfig ontologyRetrievalConfig;
private final OBOControllerValidationHelper validationHelper;
private final GraphImageService graphImageService;
public OBOController(OntologyService<T> ontologyService,
SearchService<OBOTerm> ontologySearchService,
SearchableField searchableField,
SearchServiceConfig.OntologyCompositeRetrievalConfig ontologyRetrievalConfig,
GraphImageService graphImageService) {
checkArgument(ontologyService != null, "Ontology service cannot be null");
checkArgument(ontologySearchService != null, "Ontology search service cannot be null");
checkArgument(searchableField != null, "Ontology searchable field cannot be null");
checkArgument(ontologyRetrievalConfig != null, "Ontology retrieval configuration cannot be null");
checkArgument(graphImageService != null, "Graph image service cannot be null");
this.ontologyService = ontologyService;
this.ontologySearchService = ontologySearchService;
this.ontologyQueryConverter = new StringToQuickGOQueryConverter(searchableField);
this.ontologyRetrievalConfig = ontologyRetrievalConfig;
this.validationHelper = new OBOControllerValidationHelperImpl(MAX_PAGE_RESULTS, idValidator());
this.graphImageService = graphImageService;
}
/**
* An empty or unknown path should result in a bad request
*
* @return a 400 response
*/
@ApiOperation(value = "Catches any bad requests and returns an error response with a 400 status")
@RequestMapping(value = "/*", method = {RequestMethod.GET}, produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<ResponseExceptionHandler.ErrorInfo> emptyId() {
throw new IllegalArgumentException("The requested end-point does not exist.");
}
/**
* Get all information about all terms and page through the results.
*
* @param page the page number of results to retrieve
* @return the specified page of results as a {@link QueryResult} instance or a 400 response
* if the page number is invalid
*/
@ApiOperation(value = "Get all information on all terms and page through the results")
@RequestMapping(value = "/" + TERMS_RESOURCE, method = {RequestMethod.GET},
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<QueryResult<T>> baseUrl(
@RequestParam(value = "page", defaultValue = DEFAULT_PAGE_NUMBER) int page) {
return new ResponseEntity<>(ontologyService.findAllByOntologyType(getOntologyType(),
new Page(page, MAX_PAGE_RESULTS)), HttpStatus.OK);
}
/**
* Get core information about a list of terms in comma-separated-value (CSV) format
*
* @param ids ontology identifiers in CSV format
* @return
* <ul>
* <li>all ids are valid: response consists of a 200 with the chosen information about the ontology terms</li>
* <li>any id is not found: response returns 404</li>
* <li>any id is of the an invalid format: response returns 400</li>
* </ul>
*/
@ApiOperation(value = "Get core information about a (CSV) list of terms based on their ids",
notes = "If possible, response fields include: id, isObsolete, name, definition, ancestors, synonyms, " +
"aspect and usage.")
@RequestMapping(value = TERMS_RESOURCE + "/{ids}", method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<QueryResult<T>> findTermsCoreAttr(@PathVariable(value = "ids") String ids) {
return getResultsResponse(ontologyService.findCoreInfoByOntologyId(validationHelper.validateCSVIds
(ids)));
}
/**
* Get complete information about a list of terms in comma-separated-value (CSV) format
*
* @param ids ontology identifiers in CSV format
* @return
* <ul>
* <li>all ids are valid: response consists of a 200 with the chosen information about the ontology terms</li>
* <li>any id is not found: response returns 404</li>
* <li>any id is of the an invalid format: response returns 400</li>
* </ul>
*/
@ApiOperation(value = "Get complete information about a (CSV) list of terms based on their ids",
notes = "All fields will be populated providing they have a value.")
@RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + COMPLETE_SUB_RESOURCE, method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<QueryResult<T>> findTermsComplete(@PathVariable(value = "ids") String ids) {
return getResultsResponse(
ontologyService.findCompleteInfoByOntologyId(validationHelper.validateCSVIds(ids)));
}
/**
* Get history information about a list of terms in comma-separated-value (CSV) format
*
* @param ids ontology identifiers in CSV format
* @return
* <ul>
* <li>all ids are valid: response consists of a 200 with the chosen information about the ontology terms</li>
* <li>any id is not found: response returns 404</li>
* <li>any id is of the an invalid format: response returns 400</li>
* </ul>
*/
@ApiOperation(value = "Get history information about a (CSV) list of terms based on their ids",
notes = "If possible, response fields include: id, isObsolete, name, definition, history.")
@RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + HISTORY_SUB_RESOURCE, method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<QueryResult<T>> findTermsHistory(@PathVariable(value = "ids") String ids) {
return getResultsResponse(
ontologyService.findHistoryInfoByOntologyId(validationHelper.validateCSVIds(ids)));
}
/**
* Get cross-reference information about a list of terms in comma-separated-value (CSV) format
*
* @param ids ontology identifiers in CSV format
* @return
* <ul>
* <li>all ids are valid: response consists of a 200 with the chosen information about the ontology terms</li>
* <li>any id is not found: response returns 404</li>
* <li>any id is of the an invalid format: response returns 400</li>
* </ul>
*/
@ApiOperation(value = "Get cross-reference information about a (CSV) list of terms based on their ids",
notes = "If possible, response fields include: id, isObsolete, name, definition, xRefs.")
@RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + XREFS_SUB_RESOURCE, method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<QueryResult<T>> findTermsXRefs(@PathVariable(value = "ids") String ids) {
return getResultsResponse(
ontologyService.findXRefsInfoByOntologyId(validationHelper.validateCSVIds(ids)));
}
/**
* Get taxonomy constraint information about a list of terms in comma-separated-value (CSV) format
*
* @param ids ontology identifiers in CSV format
* @return
* <ul>
* <li>all ids are valid: response consists of a 200 with the chosen information about the ontology terms</li>
* <li>any id is not found: response returns 404</li>
* <li>any id is of the an invalid format: response returns 400</li>
* </ul>
*/
@ApiOperation(value = "Get taxonomy constraint information about a (CSV) list of terms based on their ids",
notes = "If possible, response fields include: id, isObsolete, name, definition, taxonConstraints.")
@RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + CONSTRAINTS_SUB_RESOURCE, method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<QueryResult<T>> findTermsTaxonConstraints(@PathVariable(value = "ids") String ids) {
return getResultsResponse(
ontologyService.findTaxonConstraintsInfoByOntologyId(validationHelper.validateCSVIds(ids)));
}
/**
* Get cross-ontology relationship information about a list of terms in comma-separated-value (CSV) format
*
* @param ids ontology identifiers in CSV format
* @return
* <ul>
* <li>all ids are valid: response consists of a 200 with the chosen information about the ontology terms</li>
* <li>any id is not found: response returns 404</li>
* <li>any id is of the an invalid format: response returns 400</li>
* </ul>
*/
@ApiOperation(value = "Get cross ontology relationship information about a (CSV) list of terms based on their ids",
notes = "If possible, response fields include: id, isObsolete, name, definition, xRelations.")
@RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + XRELATIONS_SUB_RESOURCE, method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<QueryResult<T>> findTermsXOntologyRelations(@PathVariable(value = "ids") String ids) {
return getResultsResponse(
ontologyService.findXORelationsInfoByOntologyId(validationHelper.validateCSVIds(ids)));
}
/**
* Get annotation guideline information about a list of terms in comma-separated-value (CSV) format
*
* @param ids ontology identifiers in CSV format
* @return
* <ul>
* <li>all ids are valid: response consists of a 200 with the chosen information about the ontology terms</li>
* <li>any id is not found: response returns 404</li>
* <li>any id is of the an invalid format: response returns 400</li>
* </ul>
*/
@ApiOperation(value = "Get annotation guideline information about a (CSV) list of terms based on their ids",
notes = "If possible, response fields include: id, isObsolete, name, definition, annotationGuidelines.")
@RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + GUIDELINES_SUB_RESOURCE, method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<QueryResult<T>> findTermsAnnotationGuideLines(@PathVariable(value = "ids") String ids) {
return getResultsResponse(ontologyService
.findAnnotationGuideLinesInfoByOntologyId(validationHelper.validateCSVIds(ids)));
}
/**
* Search for an ontology term via its identifier, or a generic query search
*
* @param query the query to search against
* @param limit the amount of queries to return
* @return a {@link QueryResult} instance containing the results of the search
*/
@ApiOperation(value = "Searches a simple user query, e.g., query=apopto",
notes = "If possible, response fields include: id, name, definition, isObsolete")
@RequestMapping(value = "/" + SEARCH_RESOUCE, method = {RequestMethod.GET},
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<QueryResult<OBOTerm>> ontologySearch(
@RequestParam(value = "query") String query,
@RequestParam(value = "limit", defaultValue = DEFAULT_ENTRIES_PER_PAGE) int limit,
@RequestParam(value = "page", defaultValue = DEFAULT_PAGE_NUMBER) int page) {
validationHelper.validateRequestedResults(limit);
QueryRequest request = buildRequest(
query,
limit,
page,
ontologyQueryConverter);
return SearchDispatcher.search(request, ontologySearchService);
}
/**
* Retrieves the ancestors of ontology terms
* @param ids the term ids in CSV format
* @param relations the ontology relationships over which ancestors will be found
* @return a result instance containing the ancestors
*/
@ApiOperation(value = "Retrieves the ancestors of specified ontology terms")
@RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + ANCESTORS_SUB_RESOURCE, method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<QueryResult<T>> findAncestors(
@PathVariable(value = "ids") String ids,
@RequestParam(value = "relations", defaultValue = DEFAULT_TRAVERSAL_TYPES_CSV) String relations) {
return getResultsResponse(
ontologyService.findAncestorsInfoByOntologyId(
validationHelper.validateCSVIds(ids),
asOntologyRelationTypeArray(validationHelper.validateRelationTypes(relations))));
}
/**
* Retrieves the descendants of ontology terms
* @param ids the term ids in CSV format
* @param relations the ontology relationships over which descendants will be found
* @return a result containing the descendants
*/
@ApiOperation(value = "Retrieves the descendants of specified ontology terms")
@RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + DESCENDANTS_SUB_RESOURCE, method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<QueryResult<T>> findDescendants(
@PathVariable(value = "ids") String ids,
@RequestParam(value = "relations", defaultValue = DEFAULT_TRAVERSAL_TYPES_CSV) String relations) {
return getResultsResponse(
ontologyService.findDescendantsInfoByOntologyId(
validationHelper.validateCSVIds(ids),
asOntologyRelationTypeArray(validationHelper.validateRelationTypes(relations))));
}
/**
* Retrieves the paths between ontology terms
* @param ids the term ids in CSV format, from which paths begin
* @param toIds the term ids in CSV format, to which the paths lead
* @param relations the ontology relationships over which descendants will be found
* @return a result containing a list of paths between the {@code ids} terms, and {@code toIds} terms
*/
@ApiOperation(value = "Retrieves the paths between two specified sets of ontology terms. Each path is " +
"formed from a list of (term, relationship, term) triples.")
@RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + PATHS_SUB_RESOURCE + "/{toIds}", method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<QueryResult<List<OntologyRelationship>>> findPaths(
@PathVariable(value = "ids") String ids,
@PathVariable(value = "toIds") String toIds,
@RequestParam(value = "relations", defaultValue = DEFAULT_TRAVERSAL_TYPES_CSV) String relations) {
return getResultsResponse(
ontologyService.paths(
asSet(validationHelper.validateCSVIds(ids)),
asSet(validationHelper.validateCSVIds(toIds)),
asOntologyRelationTypeArray(validationHelper.validateRelationTypes(relations))
));
}
/**
* Retrieves the graphical image corresponding to ontology terms.
*
* @param ids the term ids whose image is required
* @return the image corresponding to the requested term ids
*/
@RequestMapping(value = TERMS_RESOURCE + "/{ids}/" + CHART_SUB_RESOURCE, method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.IMAGE_PNG_VALUE})
public ResponseEntity<InputStreamResource> getChart(@PathVariable(value = "ids") String ids) {
try {
return createChartResponseEntity(validationHelper.validateCSVIds(ids));
} catch (IOException | RenderingGraphException e) {
throw new RetrievalException(e);
}
}
/**
* Delegates the creation of an graphical image, corresponding to the specified list
* of {@code ids} and returns the appropriate {@link ResponseEntity}.
*
* @param ids the terms whose corresponding graphical image is required
* @return the image corresponding to the specified terms
* @throws IOException if there is an error during creation of the image {@link InputStreamResource}
* @throws RenderingGraphException if there was an error during the rendering of the image
*/
private ResponseEntity<InputStreamResource> createChartResponseEntity(List<String> ids)
throws IOException, RenderingGraphException {
RenderedImage renderedImage =
graphImageService
.createChart(ids, getOntologyType().name())
.getGraphImage()
.render();
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(renderedImage, "png", os);
InputStream is = new ByteArrayInputStream(os.toByteArray());
return ResponseEntity
.ok()
.contentLength(os.size())
.contentType(MediaType.IMAGE_PNG)
.body(new InputStreamResource(is));
}
/**
* Predicate that determines the validity of an ID.
* @return {@link Predicate<String>} indicating the validity of an ID.
*/
protected abstract Predicate<String> idValidator();
/**
* Returns the {@link OntologyType} that corresponds to this controller.
*
* @return the ontology type corresponding to this controller's behaviour.
*/
protected abstract OntologyType getOntologyType();
/**
* Wrap a collection as a {@link Set}
* @param items the items to wrap as a {@link Set}
* @param <ItemType> the type of the {@link Collection}, i.e., this method works for any type
* @return a {@link Set} wrapping the items in a {@link Collection}
*/
private static <ItemType> Set<ItemType> asSet(Collection<ItemType> items) {
return items.stream().collect(Collectors.toSet());
}
/**
* Converts a {@link Collection} of {@link OntologyRelationType}s to a corresponding array of
* {@link OntologyRelationType}s
* @param relations the {@link OntologyRelationType}s
* @return an array of {@link OntologyRelationType}s
*/
private static OntologyRelationType[] asOntologyRelationTypeArray(Collection<OntologyRelationType> relations) {
return relations.stream().toArray(OntologyRelationType[]::new);
}
/**
* Creates a {@link ResponseEntity} containing a {@link QueryResult} for a list of results.
*
* @param results a list of results
* @return a {@link ResponseEntity} containing a {@link QueryResult} for a list of results
*/
<ResponseType> ResponseEntity<QueryResult<ResponseType>> getResultsResponse(List<ResponseType> results) {
List<ResponseType> resultsToShow;
if (results == null) {
resultsToShow = Collections.emptyList();
} else {
resultsToShow = results;
}
QueryResult<ResponseType> queryResult = new QueryResult.Builder<>(resultsToShow.size(), resultsToShow).build();
return new ResponseEntity<>(queryResult, HttpStatus.OK);
}
private QueryRequest buildRequest(String query,
int limit,
int page,
StringToQuickGOQueryConverter converter) {
QuickGOQuery userQuery = converter.convert(query);
QuickGOQuery restrictedUserQuery = restrictQueryToOTypeResults(userQuery);
QueryRequest.Builder builder = new QueryRequest
.Builder(restrictedUserQuery)
.setPageParameters(page, limit);
if (!ontologyRetrievalConfig.getSearchReturnedFields().isEmpty()) {
ontologyRetrievalConfig.getSearchReturnedFields()
.forEach(builder::addProjectedField);
}
return builder.build();
}
/**
* Given a {@link QuickGOQuery}, create a composite {@link QuickGOQuery} by
* performing a conjunction with another query, which restricts all results
* to be of a type corresponding to that provided by {@link #getOntologyType()}.
*
* @param query the query that is constrained
* @return the new constrained query
*/
private QuickGOQuery restrictQueryToOTypeResults(QuickGOQuery query) {
return and(query,
ontologyQueryConverter.convert(
OntologyFields.Searchable.ONTOLOGY_TYPE + COLON + getOntologyType().name()));
}
} | Add page number validation.
| ontology-rest/src/main/java/uk/ac/ebi/quickgo/ontology/controller/OBOController.java | Add page number validation. | <ide><path>ntology-rest/src/main/java/uk/ac/ebi/quickgo/ontology/controller/OBOController.java
<ide> import uk.ac.ebi.quickgo.ontology.model.OntologyRelationship;
<ide> import uk.ac.ebi.quickgo.ontology.service.OntologyService;
<ide> import uk.ac.ebi.quickgo.ontology.service.search.SearchServiceConfig;
<add>import uk.ac.ebi.quickgo.rest.ParameterException;
<ide> import uk.ac.ebi.quickgo.rest.ResponseExceptionHandler;
<ide> import uk.ac.ebi.quickgo.rest.search.*;
<ide> import uk.ac.ebi.quickgo.rest.search.query.Page;
<ide> @ApiOperation(value = "Catches any bad requests and returns an error response with a 400 status")
<ide> @RequestMapping(value = "/*", method = {RequestMethod.GET}, produces = {MediaType.APPLICATION_JSON_VALUE})
<ide> public ResponseEntity<ResponseExceptionHandler.ErrorInfo> emptyId() {
<del> throw new IllegalArgumentException("The requested end-point does not exist.");
<add> throw new ParameterException("The requested end-point does not exist.");
<ide> }
<ide>
<ide> /**
<ide> produces = {MediaType.APPLICATION_JSON_VALUE})
<ide> public ResponseEntity<QueryResult<T>> baseUrl(
<ide> @RequestParam(value = "page", defaultValue = DEFAULT_PAGE_NUMBER) int page) {
<add>
<add> validationHelper.validateRequestedPages(page);
<ide>
<ide> return new ResponseEntity<>(ontologyService.findAllByOntologyType(getOntologyType(),
<ide> new Page(page, MAX_PAGE_RESULTS)), HttpStatus.OK);
<ide> @RequestMapping(value = TERMS_RESOURCE + "/{ids}", method = RequestMethod.GET,
<ide> produces = {MediaType.APPLICATION_JSON_VALUE})
<ide> public ResponseEntity<QueryResult<T>> findTermsCoreAttr(@PathVariable(value = "ids") String ids) {
<del> return getResultsResponse(ontologyService.findCoreInfoByOntologyId(validationHelper.validateCSVIds
<del> (ids)));
<add> return getResultsResponse(
<add> ontologyService.findCoreInfoByOntologyId(validationHelper.validateCSVIds(ids)));
<ide> }
<ide>
<ide> /**
<ide> @RequestParam(value = "page", defaultValue = DEFAULT_PAGE_NUMBER) int page) {
<ide>
<ide> validationHelper.validateRequestedResults(limit);
<add> validationHelper.validateRequestedPages(page);
<ide>
<ide> QueryRequest request = buildRequest(
<ide> query, |
|
JavaScript | mit | 67b79fa6f1239033cf1e10c03760f40a3b70a418 | 0 | LukeLin/data-structure-with-js,soliury/data-structure-with-js,LukeLin/js-stl,sabrinaluo/data-structure-with-js,LukeLin/data-structure-with-js,LukeLin/js-stl | /**
* 图(Graph)
*
* 图(Graph)是一种比线性表和树更为复杂的数据结构。
*
* 线性结构:是研究数据元素之间的一对一关系。在这种结构中,除第一个和最后一个元素外,任何一个元素都有唯一的一个直接前驱和直接后继。
*
* 树结构:是研究数据元素之间的一对多的关系。在这种结构中,每个元素对下(层)可以有0个或多个元素相联系,对上(层)只有唯一的一个元素相关,数据元素之间有明显的层次关系。
*
* 图结构:是研究数据元素之间的多对多的关系。在这种结构中,任意两个元素之间可能存在关系。即结点之间的关系可以是任意的,图中任意元素之间都可能相关。
*
* 图的应用极为广泛,已渗入到诸如语言学、逻辑学、物理、化学、电讯、计算机科学以及数学的其它分支。
*
* 图的基本概念
*
* 一个图(G)定义为一个偶对(V,E) ,记为G=(V,E) 。其中: V是顶点(Vertex)的非空有限集合,记为V(G);E是无序集V&V的一个子集,记为E(G) ,其元素是图的弧(Arc)。
* 将顶点集合为空的图称为空图。其形式化定义为:
G=(V ,E)
V={v|v∈data object}
E={<v,w>| v,w∈V∧p(v,w)}
P(v,w)表示从顶点v到顶点w有一条直接通路。
*
* 弧(Arc) :表示两个顶点v和w之间存在一个关系,用顶点偶对<v,w>表示。通常根据图的顶点偶对将图分为有向图和无向图。
* 有向图(Digraph): 若图G的关系集合E(G)中,顶点偶对<v,w>的v和w之间是有序的,称图G是有向图。
* 在有向图中,若 <v,w>∈E(G) ,表示从顶点v到顶点w有一条弧。 其中:v称为弧尾(tail)或始点(initial node),w称为弧头(head)或终点(terminal node) 。
* 无向图(Undigraph): 若图G的关系集合E(G)中,顶点偶对<v,w>的v和w之间是无序的,称图G是无向图。
* 在无向图中,若<v,w>∈E(G) ,有<w,v>∈E(G) ,即E(G)是对称,则用无序对(v,w) 表示v和w之间的一条边(Edge),因此(v,w) 和(w,v)代表的是同一条边。
*
* 例1:设有有向图G1和无向图G2,形式化定义分别是:
G1=(V1 ,E1)
V1={a,b,c,d,e}
E1={<a,b>,<a,c>, <a,e>,<c,d>,<c,e> ,<d,a>,<d,b>,<e,d>}
G2=(V2 ,E2)
V2={a,b,c,d}
E2={(a,b), (a,c), (a,d), (b,d), (b,c), (c,d)}
*
* 完全无向图:对于无向图,若图中顶点数为n ,用e表示边的数目,则e ∈[0,n(n-1)/2] 。具有n(n-1)/2条边的无向图称为完全无向图。
完全无向图另外的定义是:
* 对于无向图G=(V,E),若vi,vj ∈V ,当vi≠vj时,有(vi ,vj)∈E,即图中任意两个不同的顶点间都有一条无向边,这样的无向图称为完全无向图。
*
* 完全有向图:对于有向图,若图中顶点数为n ,用e表示弧的数目,则e∈[0,n(n-1)] 。具有n(n-1)条边的有向图称为完全有向图。
完全有向图另外的定义是:
* 对于有向图G=(V,E),若vi,vj∈V ,当vi ≠vj时,有<vi ,vj>∈E∧<vj , vi >∈E ,即图中任意两个不同的顶点间都有一条弧,这样的有向图称为完全有向图。
*
* 有很少边或弧的图(e<n㏒n)的图称为稀疏图,反之称为稠密图。
* 权(Weight):与图的边和弧相关的数。权可以表示从一个顶点到另一个顶点的距离或耗费。
*
* 子图和生成子图:设有图G=(V,E)和G’=(V’,E’),若V’∈V且E’∈E ,则称图G’是G的子图;若V’=V且E’∈E,则称图G’是G的一个生成子图。
* 顶点的邻接(Adjacent):对于无向图G=(V,E),若边(v,w)∈E,则称顶点v和w 互为邻接点,即v和w相邻接。边(v,w)依附(incident)与顶点v和w 。
* 对于有向图G=(V ,E),若有向弧<v,w>∈E,则称顶点v “邻接到”顶点w,顶点w “邻接自”顶点v ,弧<v,w> 与顶点v和w “相关联” 。
*
* 顶点的度、入度、出度:对于无向图G=(V,E), vi∈V,图G中依附于vi的边的数目称为顶点vi的度(degree),记为TD(vi)。
显然,在无向图中,所有顶点度的和是图中边的2倍。 即 ∑TD(vi)=2e i=1, 2, …, n ,e为图的边数。
对有向图G=(V,E),若vi ∈V ,图G中以vi作为起点的有向边(弧)的数目称为顶点vi的出度(Outdegree),记为OD(vi) ;以vi作为终点的有向边(弧)的数目称为顶点vi的入度(Indegree),记为ID(vi) 。顶点vi的出度与入度之和称为vi的度,记为TD(vi) 。即
TD(vi)=OD(vi)+ID(vi)
*
* 路径(Path)、路径长度、回路(Cycle) :对无向图G=(V,E),若从顶点vi经过若干条边能到达vj,称顶点vi和vj是连通的,又称顶点vi到vj有路径。
对有向图G=(V,E),从顶点vi到vj有有向路径,指的是从顶点vi经过若干条有向边(弧)能到达vj。
或路径是图G中连接两顶点之间所经过的顶点序列。即
Path=vi0vi1…vim ,vij∈V且(vij-1, vij)∈E j=1,2, …,m
或
Path=vi0vi1 …vim ,vij∈V且<vij-1, vij>∈E j=1,2, …,m
路径上边或有向边(弧)的数目称为该路径的长度。
在一条路径中,若没有重复相同的顶点,该路径称为简单路径;第一个顶点和最后一个顶点相同的路径称为回路(环);在一个回路中,若除第一个与最后一个顶点外,其余顶点不重复出现的回路称为简单回路(简单环)。
*
* 连通图、图的连通分量:对无向图G=(V,E),若vi ,vj ∈V,vi和vj都是连通的,则称图G是连通图,否则称为非连通图。若G是非连通图,则极大的连通子图称为G的连通分量。
对有向图G=(V,E),若vi ,vj ∈V,都有以vi为起点, vj 为终点以及以vj为起点,vi为终点的有向路径,称图G是强连通图,否则称为非强连通图。若G是非强连通图,则极大的强连通子图称为G的强连通分量。
“极大”的含义:指的是对子图再增加图G中的其它顶点,子图就不再连通。
生成树、生成森林:一个连通图(无向图)的生成树是一个极小连通子图,它含有图中全部n个顶点和只有足以构成一棵树的n-1条边,称为图的生成树。
关于无向图的生成树的几个结论:
◆ 一棵有n个顶点的生成树有且仅有n-1条边;
◆ 如果一个图有n个顶点和小于n-1条边,则是非连通图;
◆ 如果多于n-1条边,则一定有环;
◆ 有n-1条边的图不一定是生成树。
有向图的生成森林是这样一个子图,由若干棵有向树组成,含有图中全部顶点。
有向树是只有一个顶点的入度为0 ,其余顶点的入度均为1的有向图。
*
* 网:每个边(或弧)都附加一个权值的图,称为带权图。带权的连通图(包括弱连通的有向图)称为网或网络。网络是工程上常用的一个概念,用来表示一个工程或某种流程
*/
/**
* 图的存储结构
*
图的存储结构比较复杂,其复杂性主要表现在:
◆ 任意顶点之间可能存在联系,无法以数据元素在存储区中的物理位置来表示元素之间的关系。
◆ 图中顶点的度不一样,有的可能相差很大,若按度数最大的顶点设计结构,则会浪费很多存储单元,反之按每个顶点自己的度设计不同的结构,又会影响操作。
图的常用的存储结构有:邻接矩阵、邻接链表、十字链表、邻接多重表和边表。
*/
/*
邻接矩阵(数组)表示法
基本思想:对于有n个顶点的图,用一维数组vexs[n]存储顶点信息,用二维数组A[n][n]存储顶点之间关系的信息。该二维数组称为邻接矩阵。在邻接矩阵中,以顶点在vexs数组中的下标代表顶点,邻接矩阵中的元素A[i][j]存放的是顶点i到顶点j之间关系的信息。
1 无向图的数组表示
(1) 无权图的邻接矩阵
无向无权图G=(V,E)有n(n≧1)个顶点,其邻接矩阵是n阶对称方阵。其元素的定义如下:
-- 1 若(vi , vj)∈E,即vi , vj邻接
A[i][j]=
-- 0 若(vi , vj)∉E,即vi , vj不邻接
(2) 带权图的邻接矩阵
无向带权图G=(V,E) 的邻接矩阵。其元素的定义如下:
-- Wij 若(vi , vj)∈E,即vi , vj邻接,权值为wij
A[i][j]=
-- ∞ 若(vi , vj)∉E,即vi , vj不邻接时
(3) 无向图邻接矩阵的特性
◆ 邻接矩阵是对称方阵
◆ 对于顶点vi,其度数是第i行的非0元素的个数;
◆ 无向图的边数是上(或下)三角形矩阵中非0元素个数。
2 有向图的数组表示
(1) 无权图的邻接矩阵
若有向无权图G=(V,E)有n(n≧1)个顶点,则其邻接矩阵是n阶对称方阵。元素定义如下:
-- 1 若<vi, vj>∈E,从vi到vj有弧
A[i][j]=
-- 0 若<vi , vj>∉E 从vi到vj 没有弧
(2) 带权图的邻接矩阵
有向带权图G=(V,E)的邻接矩阵。其元素的定义如下:
-- wij 若<vi,vj>∈E,即vi , vj邻接,权值为wij
A[i][j]=
∞ 若<vi,vj>∉E,即vi , vj不邻接时
⑶ 有向图邻接矩阵的特性
◆ 对于顶点vi,第i行的非0元素的个数是其出度OD(vi);第i列的非0元素的个数是其入度ID(vi) 。
◆ 邻接矩阵中非0元素的个数就是图的弧的数目。
3 图的邻接矩阵的操作
图的邻接矩阵的实现比较容易,定义两个数组分别存储顶点信息(数据元素)和边或弧的信息(数据元素之间的关系) 。
*/
// 图的数组(邻接矩阵)存储表示
var DG = 1; // 有向图
var DN = 2; // 有向网
var UDG = 3; // 无向图
var UDN = 4; // 无向网
/**
*
* @param {Number} adj
* @param {*} info
* @constructor
*/
function ArcCell(adj, info) {
// 顶点类型。对于无权图,用1或0表示相邻否;对带权图,则为权值类型
this.adj = typeof adj === 'number' ? adj : Infinity;
// 该弧相关信息
this.info = info || null;
}
/**
*
* @param {Array} vexs 顶点向量
* @param {Array} arcs 邻接矩阵
* @param {Number} vexnum
* @param {Number} arcnum
* @param {Number} kind
* @constructor
*/
function AdjacencyMatrixGraph(vexs, arcs, vexnum, arcnum, kind) {
// 顶点向量
this.vexs = vexs || [];
// 邻接矩阵
this.arcs = arcs || [];
// 图的当前顶点数
this.vexnum = vexnum || 0;
// 图的当前弧数
this.arcnum = arcnum || 0;
// 图的种类标志
this.kind = kind || DG;
}
AdjacencyMatrixGraph.prototype = {
createGraph: function () {
switch (this.kind) {
case DG:
return createDG(this); // 构造有向图
case DN:
return createDN(this); // 构造有向网
case UDG:
return createUDG(this); // 构造无向图
case UDN:
return createUDN(this); // 构造无向网
default:
throw new Error('非有效的图类型');
}
},
/**
* 查找顶点
* @param {*} vp 顶点向量
* @returns {number}
*/
locateVex: function (vp) {
for (var i = 0; i < this.vexnum; i++) {
if (this.vexs[i] === vp) return i;
}
return -1;
},
/**
* 向图中增加顶点
* @param {*} vp 顶点向量
*/
addVertex: function (vp) {
if (this.locateVex(vp) !== -1)
throw new Error('Vertex has existed!');
var k = this.vexnum;
this.vexs[this.vexnum++] = vp;
var value = this.kind === DG || this.kind === UDG ?
0 : Infinity;
for (var j = 0; j < this.vexnum; j++) {
this.arcs[j] = this.arcs[j] || [];
this.arcs[k] = this.arcs[k] || [];
this.arcs[j][k] = this.arcs[j][k] || new ArcCell();
this.arcs[k][j] = this.arcs[k][j] || new ArcCell();
this.arcs[j][k].adj = this.arcs[k][j].adj = value;
}
},
/**
* 向图中增加一条弧
* @param {*} vex1 顶点1向量
* @param {*} vex2 顶点2向量
* @param {ArcCell} arc
* @returns {boolean}
*/
addArc: function(vex1, vex2, arc){
var k = this.locateVex(vex1);
var j = this.locateVex(vex2);
if(k === -1 || j === -1)
throw new Error('Arc\'s Vertex do not existed!');
this.arcs[k][j].adj = arc.adj;
this.arcs[k][j].info = arc.info;
// 无向图或无向网
if(this.kind === UDG || this.kind === UDN){
this.arcs[j][k].adj = arc.adj;
this.arcs[j][k].info = arc.info;
}
return true;
}
};
var createDG = createGraph(DG);
var createDN = createGraph(DN);
var createUDG = createGraph(UDG);
var createUDN = createGraph(UDN);
function createGraph(kind){
var adj;
var setMatrixValue;
if(kind === 2 || kind === 4) {
adj = Infinity;
setMatrixValue = function(){
return prompt('weight: ');
};
} else {
adj = 0;
setMatrixValue = function(){
return 1;
};
}
return function(AdjacencyMatrixGraph){
AdjacencyMatrixGraph.vexnum = parseInt(prompt('vexnum: '), 10);
AdjacencyMatrixGraph.arcnum = parseInt(prompt('arcnum: '), 10);
// incInfo为0则各弧不含其他信息
var incInfo = parseInt(prompt('incInfo: '), 10);
// 构造顶点向量
var i , j;
for (i = 0; i < AdjacencyMatrixGraph.vexnum; i++) AdjacencyMatrixGraph.vexs[i] = prompt('顶点向量vex: ');
// 初始化邻接矩阵
for (i = 0; i < AdjacencyMatrixGraph.vexnum; i++) {
for (j = 0; j < AdjacencyMatrixGraph.vexnum; j++) {
AdjacencyMatrixGraph.arcs[i] = AdjacencyMatrixGraph.arcs[i] || [];
AdjacencyMatrixGraph.arcs[i][j] = new ArcCell(adj, null);
}
}
// 构造邻接矩阵
for (var k = 0; k < AdjacencyMatrixGraph.arcnum; k++) {
// 输入一条边依附的顶点及权值
var v1 = prompt('v1: ');
var v2 = prompt('v2: ');
// 确定v1,v2在G中的位置
i = AdjacencyMatrixGraph.locateVex(v1);
j = AdjacencyMatrixGraph.locateVex(v2);
var w = setMatrixValue();
// 弧<v1, v2>的权值
AdjacencyMatrixGraph.arcs[i][j].adj = w;
if (incInfo) AdjacencyMatrixGraph.arcs[i][j].info = prompt('info: ');
if(kind === 3 || kind === 4) AdjacencyMatrixGraph.arcs[j][i] = AdjacencyMatrixGraph.arcs[i][j];
}
};
}
// 第一种创建图方法
var vexs = ['a', 'b', 'c', 'd', 'e'];
var arcs = [
[
{"adj": Infinity, "info": null},
{"adj": "6", "info": null},
{"adj": "2", "info": null},
{"adj": Infinity, "info": null},
{"adj": Infinity, "info": null}
],
[
{"adj": "6", "info": null},
{"adj": Infinity, "info": null},
{"adj": "3", "info": null},
{"adj": "4", "info": null},
{"adj": "3", "info": null}
],
[
{"adj": "2", "info": null},
{"adj": "3", "info": null},
{"adj": Infinity, "info": null},
{"adj": "1", "info": null},
{"adj": Infinity, "info": null}
],
[
{"adj": Infinity, "info": null},
{"adj": "4", "info": null},
{"adj": "1", "info": null},
{"adj": Infinity, "info": null},
{"adj": "5", "info": null}
],
[
{"adj": Infinity, "info": null},
{"adj": "3", "info": null},
{"adj": Infinity, "info": null},
{"adj": "5", "info": null},
{"adj": Infinity, "info": null}
]
];
var udn = new AdjacencyMatrixGraph(vexs, arcs, 5, 7, 4);
// 第二种创建图方法
var dn = new AdjacencyMatrixGraph([], [], 0, 7, 2);
dn.addVertex('a');
dn.addVertex('b');
dn.addVertex('c');
dn.addVertex('d');
dn.addVertex('e');
dn.addArc('a', 'b', {
adj: 6
});
dn.addArc('a', 'c', {
adj: 2
});
dn.addArc('c', 'b', {
adj: 3
});
dn.addArc('c', 'd', {
adj: 1
});
dn.addArc('d', 'b', {
adj: 4
});
dn.addArc('b', 'e', {
adj: 3
});
dn.addArc('d', 'e', {
adj: 5
});
console.log(dn);
/*
// 第三种创建图方法
var g = new AdjacencyMatrixGraph();
g.kind = DN;
g.createGraph();
console.log(g);
*/
/*
邻接链表法
基本思想:对图的每个顶点建立一个单链表,存储该顶点所有邻接顶点及其相关信息。每一个单链表设一个表头结点。
第i个单链表表示依附于顶点Vi的边(对有向图是以顶点Vi为头或尾的弧)。
1 结点结构与邻接链表示例
链表中的结点称为表结点,每个结点由三个域组成。其中邻接点域(adjvex)指示与顶点Vi邻接的顶点在图中的位置(顶点编号),链域(nextarc)指向下一个与顶点Vi邻接的表结点,数据域(info)存储和边或弧相关的信息,如权值等。对于无权图,如果没有与边相关的其他信息,可省略此域。
每个链表设一个表头结点(称为顶点结点),由两个域组成。链域(firstarc)指向链表中的第一个结点,数据域(data) 存储顶点名或其他信息。
在图的邻接链表表示中,所有顶点结点用一个向量 以顺序结构形式存储,可以随机访问任意顶点的链表,该向量称为表头向量,向量的下标指示顶点的序号。
用邻接链表存储图时,对无向图,其邻接链表是唯一的;对有向图,其邻接链表有两种形式。
2 邻接表法的特点
◆ 表头向量中每个分量就是一个单链表的头结点,分量个数就是图中的顶点数目;
◆ 在边或弧稀疏的条件下,用邻接表表示比用邻接矩阵表示节省存储空间;
◆ 在无向图,顶点Vi的度是第i个链表的结点数;
◆ 对有向图可以建立正邻接表或逆邻接表。正邻接表是以顶点Vi为出度(即为弧的起点)而建立的邻接表;逆邻接表是以顶点Vi为入度(即为弧的终点)而建立的邻接表;
◆ 在有向图中,第i个链表中的结点数是顶点Vi的出 (或入)度;求入 (或出)度,须遍历整个邻接表;
◆ 在邻接表上容易找出任一顶点的第一个邻接点和下一个邻接点;
*/
/**
*
* @param {Number} adjVex
* @param {ArcNode} nextArc
* @param {*} info
* @constructor
*/
function ArcNode(adjVex, nextArc, info){
// 该弧所指向的顶点的位置
this.adjVex = adjVex || 0;
// 指向下一条弧的指针
this.nextArc = nextArc || null;
// 该弧相关信息的指针
this.info = info || null;
}
/**
*
* @param {*} data
* @param {ArcNode} firstArc
* @param {Number} indegree
* @constructor
*/
function VexNode(data, firstArc, indegree){
// 顶点信息
this.data = data;
// 指向第一条依附该顶点的弧的指针
this.firstArc = firstArc || null;
// 顶点的度, 有向图是入度或出度或没有
this.indegree = indegree || 0;
}
/**
*
* @param {Array | VexNode} vertices
* @param {Number} vexnum
* @param {Number} arcnum
* @param {Number} kind
* @constructor
*/
function AdjacencyListGraph(vertices, vexnum, arcnum, kind){
this.vertices = vertices || [];
// 图的当前顶点数和弧数
this.vexnum = vexnum || 0;
this.arcnum = arcnum || 0;
// 图的种类标志
this.kind = kind || DG;
}
AdjacencyListGraph.prototype = {
constructor: AdjacencyListGraph,
// 查找顶点位置
locateVex: function(vp){
for(var i = 0; i < this.vexnum; i++){
if(this.vertices[i].data === vp) return i;
}
return -1;
},
// 添加顶点
addVertex: function(vp){
if(this.locateVex(vp) !== -1) throw new Error('Vertex has existed!');
this.vertices[this.vexnum++] = new VexNode(vp, null, 0);
return this.vexnum;
},
/**
* 添加弧
* 如果是无向图或者无向网,arc1和arc2无顺序要求
* 如果是有向图或者有向网,只会添加arc1,因此正邻接表和逆邻接表的顺序需要注意
* @param {ArcNode} arc1
* @param {ArcNode} arc2
* @returns {boolean}
*/
addArc: function(arc1, arc2){
var k = this.locateVex(arc1.adjVex);
var j = this.locateVex(arc2.adjVex);
if(k === -1 || j === -1) throw new Error('Arc\'s Vertex do not existed!');
// 边的起始表结点赋值
var p = new ArcNode(arc1.adjVex, arc1.nextArc || null, arc1.info);
// 边的末尾表结点赋值
var q = new ArcNode(arc2.adjVex, arc2.nextArc || null, arc2.info);
// 是无向图,用头插入法插入到两个单链表
if(this.kind === UDG || this.kind === UDN){
q.nextArc = this.vertices[k].firstArc;
this.vertices[k].firstArc = q;
p.nextArc = this.vertices[j].firstArc;
this.vertices[j].firstArc = p;
}
// 建立有向图的邻接链表,用头插入法
else {
p.nextArc = this.vertices[j].firstArc;
this.vertices[j].firstArc = p;
}
return true;
},
// TODO 其他图类型的创建暂时没弄
createGraph: function(){
this.vexnum = +prompt('vexnum: ');
this.arcnum = +prompt('arcnum: ');
// incInfo为0则各弧不含其他信息
var incInfo = +prompt('incInfo: ');
for(var m = 0; m < this.vexnum; m++){
this.vertices[m] = new VexNode();
this.vertices[m].data = prompt('vertex: ');
}
for(m = 0; m < this.arcnum; m++){
var h = prompt('弧头: ');
var t = prompt('弧尾: ');
var i = this.locateVex(t);
var j = this.locateVex(h);
if(i < 0 || j < 0) {
alert('顶点为找到,请重新输入!');
m--;
continue;
}
var p = new ArcNode(j, null, incInfo && prompt('info: '));
if(!this.vertices[i].firstArc) this.vertices[i].firstArc = p;
else {
for(var q = this.vertices[i].firstArc; q.nextArc; q = q.nextArc);
q.nextArc = p;
}
}
}
};
// 无向图的邻接表
var g = new AdjacencyListGraph([], 0, 7, UDG);
g.addVertex('v1');
g.addVertex('v2');
g.addVertex('v3');
g.addVertex('v4');
g.addVertex('v5');
g.addArc(new ArcNode('v1'), new ArcNode('v2'));
g.addArc(new ArcNode('v1'), new ArcNode('v3'));
g.addArc(new ArcNode('v1'), new ArcNode('v4'));
g.addArc(new ArcNode('v2'), new ArcNode('v3'));
g.addArc(new ArcNode('v3'), new ArcNode('v4'));
g.addArc(new ArcNode('v3'), new ArcNode('v5'));
g.addArc(new ArcNode('v4'), new ArcNode('v5'));
console.log(g);
// 有向图的逆邻接表
var g = new AdjacencyListGraph([], 0, 7, DG);
g.addVertex('v1');
g.addVertex('v2');
g.addVertex('v3');
g.addVertex('v4');
g.addVertex('v5');
g.addArc(new ArcNode('v1'), new ArcNode('v2'));
g.addArc(new ArcNode('v1'), new ArcNode('v4'));
g.addArc(new ArcNode('v3'), new ArcNode('v2'));
g.addArc(new ArcNode('v3'), new ArcNode('v1'));
g.addArc(new ArcNode('v4'), new ArcNode('v3'));
g.addArc(new ArcNode('v3'), new ArcNode('v5'));
g.addArc(new ArcNode('v5'), new ArcNode('v4'));
console.log(g);
// 有向图的正邻接表
var g = new AdjacencyListGraph([], 0, 7, DG);
g.addVertex('v1');
g.addVertex('v2');
g.addVertex('v3');
g.addVertex('v4');
g.addVertex('v5');
g.addArc(new ArcNode('v2'), new ArcNode('v1'));
g.addArc(new ArcNode('v4'), new ArcNode('v1'));
g.addArc(new ArcNode('v2'), new ArcNode('v3'));
g.addArc(new ArcNode('v1'), new ArcNode('v3'));
g.addArc(new ArcNode('v3'), new ArcNode('v4'));
g.addArc(new ArcNode('v5'), new ArcNode('v3'));
g.addArc(new ArcNode('v4'), new ArcNode('v5'));
console.log(g);
/*
十字链表法
十字链表(Orthogonal List)是有向图的另一种链式存储结构,是将有向图的正邻接表和逆邻接表结合起来得到的一种链表。
在这种结构中,每条弧的弧头结点和弧尾结点都存放在链表中,并将弧结点分别组织到以弧尾结点为头(顶点)结点和以弧头结点为头(顶点)结点的链表中。
◆ data域:存储和顶点相关的信息;
◆ 指针域firstin:指向以该顶点为弧头的第一条弧所对应的弧结点;
◆ 指针域firstout:指向以该顶点为弧尾的第一条弧所对应的弧结点;
◆ 尾域tailvex:指示弧尾顶点在图中的位置;
◆ 头域headvex:指示弧头顶点在图中的位置;
◆ 指针域hlink:指向弧头相同的下一条弧;
◆ 指针域tlink:指向弧尾相同的下一条弧;
◆ Info域:指向该弧的相关信息;
从这种存储结构图可以看出,从一个顶点结点的firstout出发,沿表结点的tlink指针构成了正邻接表的链表结构,而从一个顶点结点的firstin出发,沿表结点的hlink指针构成了逆邻接表的链表结构。
*/
/**
*
* @param {Number} headVex 弧的头顶点的位置
* @param {Number} tailVex 弧的尾顶点位置
* @param {ArcBox} hLink 弧头相同的弧的链域
* @param {ArcBox} tLink 弧尾相同的弧的链域
* @param {*} info
* @constructor
*/
function ArcBox(headVex, tailVex, hLink, tLink, info){
this.headVex = headVex || 0;
this.tailVex = tailVex || 0;
this.hLink = hLink || null;
this.tLink = tLink || null;
this.info = info || null;
}
/**
*
* @param {*} data
* @param {ArcBox} firstIn 该顶点第一条入弧
* @param {ArcBox} firstOut 该顶点第一条出弧
* @constructor
*/
function OLVexNode(data, firstIn, firstOut){
this.data = data || null;
this.firstIn = firstIn || null;
this.firstOut = firstOut || null;
}
/**
*
* @param {Array | OLVexNode} xList 表头向量
* @param {Number} vexnum 有向图的当前顶点数
* @param {Number} arcnum 有向图的当前弧数
* @constructor
*/
function OLGraph(xList, vexnum, arcnum){
this.xList = xList || [];
this.vexnum = vexnum || 0;
this.arcnum = arcnum || 0;
}
OLGraph.prototype = {
constructor: OLGraph,
locateVex: function(vp){
for(var i = 0; i < this.vexnum; i++){
if(this.xList[i].data === vp) return i;
}
return -1;
},
createDG: function(){
this.vexnum = prompt('Vexnum: ');
this.arcnum = prompt('Arcnum: ');
// IncInfo为0则各弧不含其他信息
var incInfo = +prompt('IncInfo: ');
// 输入顶点值
for(var i = 0; i < this.vexnum; i++){
this.xList[i] = new OLVexNode(prompt('data: '), null, null);
}
for(var k = 0; k < this.arcnum; k++){
var v1 = prompt('v1: ');
var v2 = prompt('v2: ');
i = this.locateVex(v1);
var j = this.locateVex(v2);
if(i === -1 || j === -1) {
alert('无此顶点,请重新输入!');
k--;
continue;
}
var p = new ArcBox(j, i, this.xList[j].firstIn, this.xList[i].firstOut, incInfo && prompt('info: '));
this.xList[j].firstIn = this.xList[i].firstOut = p;
}
}
};
// todo 貌似有问题..
var g = new OLGraph();
g.createDG();
console.log(g);
| Graph/Graph.js | /**
* 图(Graph)
*
* 图(Graph)是一种比线性表和树更为复杂的数据结构。
*
* 线性结构:是研究数据元素之间的一对一关系。在这种结构中,除第一个和最后一个元素外,任何一个元素都有唯一的一个直接前驱和直接后继。
*
* 树结构:是研究数据元素之间的一对多的关系。在这种结构中,每个元素对下(层)可以有0个或多个元素相联系,对上(层)只有唯一的一个元素相关,数据元素之间有明显的层次关系。
*
* 图结构:是研究数据元素之间的多对多的关系。在这种结构中,任意两个元素之间可能存在关系。即结点之间的关系可以是任意的,图中任意元素之间都可能相关。
*
* 图的应用极为广泛,已渗入到诸如语言学、逻辑学、物理、化学、电讯、计算机科学以及数学的其它分支。
*
* 图的基本概念
*
* 一个图(G)定义为一个偶对(V,E) ,记为G=(V,E) 。其中: V是顶点(Vertex)的非空有限集合,记为V(G);E是无序集V&V的一个子集,记为E(G) ,其元素是图的弧(Arc)。
* 将顶点集合为空的图称为空图。其形式化定义为:
G=(V ,E)
V={v|v∈data object}
E={<v,w>| v,w∈V∧p(v,w)}
P(v,w)表示从顶点v到顶点w有一条直接通路。
*
* 弧(Arc) :表示两个顶点v和w之间存在一个关系,用顶点偶对<v,w>表示。通常根据图的顶点偶对将图分为有向图和无向图。
* 有向图(Digraph): 若图G的关系集合E(G)中,顶点偶对<v,w>的v和w之间是有序的,称图G是有向图。
* 在有向图中,若 <v,w>∈E(G) ,表示从顶点v到顶点w有一条弧。 其中:v称为弧尾(tail)或始点(initial node),w称为弧头(head)或终点(terminal node) 。
* 无向图(Undigraph): 若图G的关系集合E(G)中,顶点偶对<v,w>的v和w之间是无序的,称图G是无向图。
* 在无向图中,若<v,w>∈E(G) ,有<w,v>∈E(G) ,即E(G)是对称,则用无序对(v,w) 表示v和w之间的一条边(Edge),因此(v,w) 和(w,v)代表的是同一条边。
*
* 例1:设有有向图G1和无向图G2,形式化定义分别是:
G1=(V1 ,E1)
V1={a,b,c,d,e}
E1={<a,b>,<a,c>, <a,e>,<c,d>,<c,e> ,<d,a>,<d,b>,<e,d>}
G2=(V2 ,E2)
V2={a,b,c,d}
E2={(a,b), (a,c), (a,d), (b,d), (b,c), (c,d)}
*
* 完全无向图:对于无向图,若图中顶点数为n ,用e表示边的数目,则e ∈[0,n(n-1)/2] 。具有n(n-1)/2条边的无向图称为完全无向图。
完全无向图另外的定义是:
* 对于无向图G=(V,E),若vi,vj ∈V ,当vi≠vj时,有(vi ,vj)∈E,即图中任意两个不同的顶点间都有一条无向边,这样的无向图称为完全无向图。
*
* 完全有向图:对于有向图,若图中顶点数为n ,用e表示弧的数目,则e∈[0,n(n-1)] 。具有n(n-1)条边的有向图称为完全有向图。
完全有向图另外的定义是:
* 对于有向图G=(V,E),若vi,vj∈V ,当vi ≠vj时,有<vi ,vj>∈E∧<vj , vi >∈E ,即图中任意两个不同的顶点间都有一条弧,这样的有向图称为完全有向图。
*
* 有很少边或弧的图(e<n㏒n)的图称为稀疏图,反之称为稠密图。
* 权(Weight):与图的边和弧相关的数。权可以表示从一个顶点到另一个顶点的距离或耗费。
*
* 子图和生成子图:设有图G=(V,E)和G’=(V’,E’),若V’∈V且E’∈E ,则称图G’是G的子图;若V’=V且E’∈E,则称图G’是G的一个生成子图。
* 顶点的邻接(Adjacent):对于无向图G=(V,E),若边(v,w)∈E,则称顶点v和w 互为邻接点,即v和w相邻接。边(v,w)依附(incident)与顶点v和w 。
* 对于有向图G=(V ,E),若有向弧<v,w>∈E,则称顶点v “邻接到”顶点w,顶点w “邻接自”顶点v ,弧<v,w> 与顶点v和w “相关联” 。
*
* 顶点的度、入度、出度:对于无向图G=(V,E), vi∈V,图G中依附于vi的边的数目称为顶点vi的度(degree),记为TD(vi)。
显然,在无向图中,所有顶点度的和是图中边的2倍。 即 ∑TD(vi)=2e i=1, 2, …, n ,e为图的边数。
对有向图G=(V,E),若vi ∈V ,图G中以vi作为起点的有向边(弧)的数目称为顶点vi的出度(Outdegree),记为OD(vi) ;以vi作为终点的有向边(弧)的数目称为顶点vi的入度(Indegree),记为ID(vi) 。顶点vi的出度与入度之和称为vi的度,记为TD(vi) 。即
TD(vi)=OD(vi)+ID(vi)
*
* 路径(Path)、路径长度、回路(Cycle) :对无向图G=(V,E),若从顶点vi经过若干条边能到达vj,称顶点vi和vj是连通的,又称顶点vi到vj有路径。
对有向图G=(V,E),从顶点vi到vj有有向路径,指的是从顶点vi经过若干条有向边(弧)能到达vj。
或路径是图G中连接两顶点之间所经过的顶点序列。即
Path=vi0vi1…vim ,vij∈V且(vij-1, vij)∈E j=1,2, …,m
或
Path=vi0vi1 …vim ,vij∈V且<vij-1, vij>∈E j=1,2, …,m
路径上边或有向边(弧)的数目称为该路径的长度。
在一条路径中,若没有重复相同的顶点,该路径称为简单路径;第一个顶点和最后一个顶点相同的路径称为回路(环);在一个回路中,若除第一个与最后一个顶点外,其余顶点不重复出现的回路称为简单回路(简单环)。
*
* 连通图、图的连通分量:对无向图G=(V,E),若vi ,vj ∈V,vi和vj都是连通的,则称图G是连通图,否则称为非连通图。若G是非连通图,则极大的连通子图称为G的连通分量。
对有向图G=(V,E),若vi ,vj ∈V,都有以vi为起点, vj 为终点以及以vj为起点,vi为终点的有向路径,称图G是强连通图,否则称为非强连通图。若G是非强连通图,则极大的强连通子图称为G的强连通分量。
“极大”的含义:指的是对子图再增加图G中的其它顶点,子图就不再连通。
生成树、生成森林:一个连通图(无向图)的生成树是一个极小连通子图,它含有图中全部n个顶点和只有足以构成一棵树的n-1条边,称为图的生成树。
关于无向图的生成树的几个结论:
◆ 一棵有n个顶点的生成树有且仅有n-1条边;
◆ 如果一个图有n个顶点和小于n-1条边,则是非连通图;
◆ 如果多于n-1条边,则一定有环;
◆ 有n-1条边的图不一定是生成树。
有向图的生成森林是这样一个子图,由若干棵有向树组成,含有图中全部顶点。
有向树是只有一个顶点的入度为0 ,其余顶点的入度均为1的有向图。
*
* 网:每个边(或弧)都附加一个权值的图,称为带权图。带权的连通图(包括弱连通的有向图)称为网或网络。网络是工程上常用的一个概念,用来表示一个工程或某种流程
*/
/**
* 图的存储结构
*
图的存储结构比较复杂,其复杂性主要表现在:
◆ 任意顶点之间可能存在联系,无法以数据元素在存储区中的物理位置来表示元素之间的关系。
◆ 图中顶点的度不一样,有的可能相差很大,若按度数最大的顶点设计结构,则会浪费很多存储单元,反之按每个顶点自己的度设计不同的结构,又会影响操作。
图的常用的存储结构有:邻接矩阵、邻接链表、十字链表、邻接多重表和边表。
*/
/*
邻接矩阵(数组)表示法
基本思想:对于有n个顶点的图,用一维数组vexs[n]存储顶点信息,用二维数组A[n][n]存储顶点之间关系的信息。该二维数组称为邻接矩阵。在邻接矩阵中,以顶点在vexs数组中的下标代表顶点,邻接矩阵中的元素A[i][j]存放的是顶点i到顶点j之间关系的信息。
1 无向图的数组表示
(1) 无权图的邻接矩阵
无向无权图G=(V,E)有n(n≧1)个顶点,其邻接矩阵是n阶对称方阵。其元素的定义如下:
-- 1 若(vi , vj)∈E,即vi , vj邻接
A[i][j]=
-- 0 若(vi , vj)∉E,即vi , vj不邻接
(2) 带权图的邻接矩阵
无向带权图G=(V,E) 的邻接矩阵。其元素的定义如下:
-- Wij 若(vi , vj)∈E,即vi , vj邻接,权值为wij
A[i][j]=
-- ∞ 若(vi , vj)∉E,即vi , vj不邻接时
(3) 无向图邻接矩阵的特性
◆ 邻接矩阵是对称方阵
◆ 对于顶点vi,其度数是第i行的非0元素的个数;
◆ 无向图的边数是上(或下)三角形矩阵中非0元素个数。
2 有向图的数组表示
(1) 无权图的邻接矩阵
若有向无权图G=(V,E)有n(n≧1)个顶点,则其邻接矩阵是n阶对称方阵。元素定义如下:
-- 1 若<vi, vj>∈E,从vi到vj有弧
A[i][j]=
-- 0 若<vi , vj>∉E 从vi到vj 没有弧
(2) 带权图的邻接矩阵
有向带权图G=(V,E)的邻接矩阵。其元素的定义如下:
-- wij 若<vi,vj>∈E,即vi , vj邻接,权值为wij
A[i][j]=
∞ 若<vi,vj>∉E,即vi , vj不邻接时
⑶ 有向图邻接矩阵的特性
◆ 对于顶点vi,第i行的非0元素的个数是其出度OD(vi);第i列的非0元素的个数是其入度ID(vi) 。
◆ 邻接矩阵中非0元素的个数就是图的弧的数目。
3 图的邻接矩阵的操作
图的邻接矩阵的实现比较容易,定义两个数组分别存储顶点信息(数据元素)和边或弧的信息(数据元素之间的关系) 。
*/
// 图的数组(邻接矩阵)存储表示
var DG = 1; // 有向图
var DN = 2; // 有向网
var UDG = 3; // 无向图
var UDN = 4; // 无向网
/**
*
* @param {Number} adj
* @param {*} info
* @constructor
*/
function ArcCell(adj, info) {
// 顶点类型。对于无权图,用1或0表示相邻否;对带权图,则为权值类型
this.adj = typeof adj === 'number' ? adj : Infinity;
// 该弧相关信息
this.info = info || null;
}
/**
*
* @param {Array} vexs 顶点向量
* @param {Array} arcs 邻接矩阵
* @param {Number} vexnum
* @param {Number} arcnum
* @param {Number} kind
* @constructor
*/
function AdjacencyMatrixGraph(vexs, arcs, vexnum, arcnum, kind) {
// 顶点向量
this.vexs = vexs || [];
// 邻接矩阵
this.arcs = arcs || [];
// 图的当前顶点数
this.vexnum = vexnum || 0;
// 图的当前弧数
this.arcnum = arcnum || 0;
// 图的种类标志
this.kind = kind || DG;
}
AdjacencyMatrixGraph.prototype = {
createGraph: function () {
switch (this.kind) {
case DG:
return createDG(this); // 构造有向图
case DN:
return createDN(this); // 构造有向网
case UDG:
return createUDG(this); // 构造无向图
case UDN:
return createUDN(this); // 构造无向网
default:
throw new Error('非有效的图类型');
}
},
/**
* 查找顶点
* @param {*} vp 顶点向量
* @returns {number}
*/
locateVex: function (vp) {
for (var i = 0; i < this.vexnum; i++) {
if (this.vexs[i] === vp) return i;
}
return -1;
},
/**
* 向图中增加顶点
* @param {*} vp 顶点向量
*/
addVertex: function (vp) {
if (this.locateVex(vp) !== -1)
throw new Error('Vertex has existed!');
var k = this.vexnum;
this.vexs[this.vexnum++] = vp;
var value = this.kind === DG || this.kind === UDG ?
0 : Infinity;
for (var j = 0; j < this.vexnum; j++) {
this.arcs[j] = this.arcs[j] || [];
this.arcs[k] = this.arcs[k] || [];
this.arcs[j][k] = this.arcs[j][k] || new ArcCell();
this.arcs[k][j] = this.arcs[k][j] || new ArcCell();
this.arcs[j][k].adj = this.arcs[k][j].adj = value;
}
},
/**
* 向图中增加一条弧
* @param {*} vex1 顶点1向量
* @param {*} vex2 顶点2向量
* @param {ArcCell} arc
* @returns {boolean}
*/
addArc: function(vex1, vex2, arc){
var k = this.locateVex(vex1);
var j = this.locateVex(vex2);
if(k === -1 || j === -1)
throw new Error('Arc\'s Vertex do not existed!');
this.arcs[k][j].adj = arc.adj;
this.arcs[k][j].info = arc.info;
// 无向图或无向网
if(this.kind === UDG || this.kind === UDN){
this.arcs[j][k].adj = arc.adj;
this.arcs[j][k].info = arc.info;
}
return true;
}
};
var createDG = createGraph(DG);
var createDN = createGraph(DN);
var createUDG = createGraph(UDG);
var createUDN = createGraph(UDN);
function createGraph(kind){
var adj;
var setMatrixValue;
if(kind === 2 || kind === 4) {
adj = Infinity;
setMatrixValue = function(){
return prompt('weight: ');
};
} else {
adj = 0;
setMatrixValue = function(){
return 1;
};
}
return function(AdjacencyMatrixGraph){
AdjacencyMatrixGraph.vexnum = parseInt(prompt('vexnum: '), 10);
AdjacencyMatrixGraph.arcnum = parseInt(prompt('arcnum: '), 10);
// incInfo为0则各弧不含其他信息
var incInfo = parseInt(prompt('incInfo: '), 10);
// 构造顶点向量
var i , j;
for (i = 0; i < AdjacencyMatrixGraph.vexnum; i++) AdjacencyMatrixGraph.vexs[i] = prompt('顶点向量vex: ');
// 初始化邻接矩阵
for (i = 0; i < AdjacencyMatrixGraph.vexnum; i++) {
for (j = 0; j < AdjacencyMatrixGraph.vexnum; j++) {
AdjacencyMatrixGraph.arcs[i] = AdjacencyMatrixGraph.arcs[i] || [];
AdjacencyMatrixGraph.arcs[i][j] = new ArcCell(adj, null);
}
}
// 构造邻接矩阵
for (var k = 0; k < AdjacencyMatrixGraph.arcnum; k++) {
// 输入一条边依附的顶点及权值
var v1 = prompt('v1: ');
var v2 = prompt('v2: ');
// 确定v1,v2在G中的位置
i = AdjacencyMatrixGraph.locateVex(v1);
j = AdjacencyMatrixGraph.locateVex(v2);
var w = setMatrixValue();
// 弧<v1, v2>的权值
AdjacencyMatrixGraph.arcs[i][j].adj = w;
if (incInfo) AdjacencyMatrixGraph.arcs[i][j].info = prompt('info: ');
if(kind === 3 || kind === 4) AdjacencyMatrixGraph.arcs[j][i] = AdjacencyMatrixGraph.arcs[i][j];
}
};
}
// 第一种创建图方法
var vexs = ['a', 'b', 'c', 'd', 'e'];
var arcs = [
[
{"adj": Infinity, "info": null},
{"adj": "6", "info": null},
{"adj": "2", "info": null},
{"adj": Infinity, "info": null},
{"adj": Infinity, "info": null}
],
[
{"adj": "6", "info": null},
{"adj": Infinity, "info": null},
{"adj": "3", "info": null},
{"adj": "4", "info": null},
{"adj": "3", "info": null}
],
[
{"adj": "2", "info": null},
{"adj": "3", "info": null},
{"adj": Infinity, "info": null},
{"adj": "1", "info": null},
{"adj": Infinity, "info": null}
],
[
{"adj": Infinity, "info": null},
{"adj": "4", "info": null},
{"adj": "1", "info": null},
{"adj": Infinity, "info": null},
{"adj": "5", "info": null}
],
[
{"adj": Infinity, "info": null},
{"adj": "3", "info": null},
{"adj": Infinity, "info": null},
{"adj": "5", "info": null},
{"adj": Infinity, "info": null}
]
];
var udn = new AdjacencyMatrixGraph(vexs, arcs, 5, 7, 4);
// 第二种创建图方法
var dn = new AdjacencyMatrixGraph([], [], 0, 7, 2);
dn.addVertex('a');
dn.addVertex('b');
dn.addVertex('c');
dn.addVertex('d');
dn.addVertex('e');
dn.addArc('a', 'b', {
adj: 6
});
dn.addArc('a', 'c', {
adj: 2
});
dn.addArc('c', 'b', {
adj: 3
});
dn.addArc('c', 'd', {
adj: 1
});
dn.addArc('d', 'b', {
adj: 4
});
dn.addArc('b', 'e', {
adj: 3
});
dn.addArc('d', 'e', {
adj: 5
});
console.log(dn);
/*
// 第三种创建图方法
var g = new AdjacencyMatrixGraph();
g.kind = DN;
g.createGraph();
console.log(g);
*/
/*
邻接链表法
基本思想:对图的每个顶点建立一个单链表,存储该顶点所有邻接顶点及其相关信息。每一个单链表设一个表头结点。
第i个单链表表示依附于顶点Vi的边(对有向图是以顶点Vi为头或尾的弧)。
1 结点结构与邻接链表示例
链表中的结点称为表结点,每个结点由三个域组成。其中邻接点域(adjvex)指示与顶点Vi邻接的顶点在图中的位置(顶点编号),链域(nextarc)指向下一个与顶点Vi邻接的表结点,数据域(info)存储和边或弧相关的信息,如权值等。对于无权图,如果没有与边相关的其他信息,可省略此域。
每个链表设一个表头结点(称为顶点结点),由两个域组成。链域(firstarc)指向链表中的第一个结点,数据域(data) 存储顶点名或其他信息。
在图的邻接链表表示中,所有顶点结点用一个向量 以顺序结构形式存储,可以随机访问任意顶点的链表,该向量称为表头向量,向量的下标指示顶点的序号。
用邻接链表存储图时,对无向图,其邻接链表是唯一的;对有向图,其邻接链表有两种形式。
2 邻接表法的特点
◆ 表头向量中每个分量就是一个单链表的头结点,分量个数就是图中的顶点数目;
◆ 在边或弧稀疏的条件下,用邻接表表示比用邻接矩阵表示节省存储空间;
◆ 在无向图,顶点Vi的度是第i个链表的结点数;
◆ 对有向图可以建立正邻接表或逆邻接表。正邻接表是以顶点Vi为出度(即为弧的起点)而建立的邻接表;逆邻接表是以顶点Vi为入度(即为弧的终点)而建立的邻接表;
◆ 在有向图中,第i个链表中的结点数是顶点Vi的出 (或入)度;求入 (或出)度,须遍历整个邻接表;
◆ 在邻接表上容易找出任一顶点的第一个邻接点和下一个邻接点;
*/
/**
*
* @param {Number} adjVex
* @param {ArcNode} nextArc
* @param {*} info
* @constructor
*/
function ArcNode(adjVex, nextArc, info){
// 该弧所指向的顶点的位置
this.adjVex = adjVex || 0;
// 指向下一条弧的指针
this.nextArc = nextArc || null;
// 该弧相关信息的指针
this.info = info || null;
}
/**
*
* @param {*} data
* @param {ArcNode} firstArc
* @param {Number} indegree
* @constructor
*/
function VexNode(data, firstArc, indegree){
// 顶点信息
this.data = data;
// 指向第一条依附该顶点的弧的指针
this.firstArc = firstArc || null;
// 顶点的度, 有向图是入度或出度或没有
this.indegree = indegree || 0;
}
/**
*
* @param {Array | VexNode} vertices
* @param {Number} vexnum
* @param {Number} arcnum
* @param {Number} kind
* @constructor
*/
function AdjacencyListGraph(vertices, vexnum, arcnum, kind){
this.vertices = vertices || [];
// 图的当前顶点数和弧数
this.vexnum = vexnum || 0;
this.arcnum = arcnum || 0;
// 图的种类标志
this.kind = kind || DG;
}
AdjacencyListGraph.prototype = {
constructor: AdjacencyListGraph,
// 查找顶点位置
locateVex: function(vp){
for(var i = 0; i < this.vexnum; i++){
if(this.vertices[i].data === vp) return i;
}
return -1;
},
// 添加顶点
addVertex: function(vp){
if(this.locateVex(vp) !== -1) throw new Error('Vertex has existed!');
this.vertices[this.vexnum++] = new VexNode(vp, null, 0);
return this.vexnum;
},
/**
* 添加弧
* 如果是无向图或者无向网,arc1和arc2无顺序要求
* 如果是有向图或者有向网,只会添加arc1,因此正邻接表和逆邻接表的顺序需要注意
* @param {ArcNode} arc1
* @param {ArcNode} arc2
* @returns {boolean}
*/
addArc: function(arc1, arc2){
var k = this.locateVex(arc1.adjVex);
var j = this.locateVex(arc2.adjVex);
if(k === -1 || j === -1) throw new Error('Arc\'s Vertex do not existed!');
// 边的起始表结点赋值
var p = new ArcNode(arc1.adjVex, arc1.nextArc || null, arc1.info);
// 边的末尾表结点赋值
var q = new ArcNode(arc2.adjVex, arc2.nextArc || null, arc2.info);
// 是无向图,用头插入法插入到两个单链表
if(this.kind === UDG || this.kind === UDN){
q.nextArc = this.vertices[k].firstArc;
this.vertices[k].firstArc = q;
p.nextArc = this.vertices[j].firstArc;
this.vertices[j].firstArc = p;
}
// 建立有向图的邻接链表,用头插入法
else {
p.nextArc = this.vertices[j].firstArc;
this.vertices[j].firstArc = p;
}
return true;
},
// TODO 其他图类型的创建暂时没弄
createGraph: function(){
this.vexnum = +prompt('vexnum: ');
this.arcnum = +prompt('arcnum: ');
// incInfo为0则各弧不含其他信息
var incInfo = +prompt('incInfo: ');
for(var m = 0; m < this.vexnum; m++){
this.vertices[m] = new VexNode();
this.vertices[m].data = prompt('vertex: ');
}
for(m = 0; m < this.arcnum; m++){
var h = prompt('弧头: ');
var t = prompt('弧尾: ');
var i = this.locateVex(t);
var j = this.locateVex(h);
if(i < 0 || j < 0) {
alert('顶点为找到,请重新输入!');
m--;
continue;
}
var p = new ArcNode(j, null, incInfo && prompt('info: '));
if(!this.vertices[i].firstArc) this.vertices[i].firstArc = p;
else {
for(var q = this.vertices[i].firstArc; q.nextArc; q = q.nextArc);
q.nextArc = p;
}
}
}
};
// 无向图的邻接表
var g = new AdjacencyListGraph([], 0, 7, UDG);
g.addVertex('v1');
g.addVertex('v2');
g.addVertex('v3');
g.addVertex('v4');
g.addVertex('v5');
g.addArc(new ArcNode('v1'), new ArcNode('v2'));
g.addArc(new ArcNode('v1'), new ArcNode('v3'));
g.addArc(new ArcNode('v1'), new ArcNode('v4'));
g.addArc(new ArcNode('v2'), new ArcNode('v3'));
g.addArc(new ArcNode('v3'), new ArcNode('v4'));
g.addArc(new ArcNode('v3'), new ArcNode('v5'));
g.addArc(new ArcNode('v4'), new ArcNode('v5'));
console.log(g);
// 有向图的逆邻接表
var g = new AdjacencyListGraph([], 0, 7, DG);
g.addVertex('v1');
g.addVertex('v2');
g.addVertex('v3');
g.addVertex('v4');
g.addVertex('v5');
g.addArc(new ArcNode('v1'), new ArcNode('v2'));
g.addArc(new ArcNode('v1'), new ArcNode('v4'));
g.addArc(new ArcNode('v3'), new ArcNode('v2'));
g.addArc(new ArcNode('v3'), new ArcNode('v1'));
g.addArc(new ArcNode('v4'), new ArcNode('v3'));
g.addArc(new ArcNode('v3'), new ArcNode('v5'));
g.addArc(new ArcNode('v5'), new ArcNode('v4'));
console.log(g);
// 有向图的正邻接表
var g = new AdjacencyListGraph([], 0, 7, DG);
g.addVertex('v1');
g.addVertex('v2');
g.addVertex('v3');
g.addVertex('v4');
g.addVertex('v5');
g.addArc(new ArcNode('v2'), new ArcNode('v1'));
g.addArc(new ArcNode('v4'), new ArcNode('v1'));
g.addArc(new ArcNode('v2'), new ArcNode('v3'));
g.addArc(new ArcNode('v1'), new ArcNode('v3'));
g.addArc(new ArcNode('v3'), new ArcNode('v4'));
g.addArc(new ArcNode('v5'), new ArcNode('v3'));
g.addArc(new ArcNode('v4'), new ArcNode('v5'));
console.log(g);
/*
十字链表法
十字链表(Orthogonal List)是有向图的另一种链式存储结构,是将有向图的正邻接表和逆邻接表结合起来得到的一种链表。
在这种结构中,每条弧的弧头结点和弧尾结点都存放在链表中,并将弧结点分别组织到以弧尾结点为头(顶点)结点和以弧头结点为头(顶点)结点的链表中。
◆ data域:存储和顶点相关的信息;
◆ 指针域firstin:指向以该顶点为弧头的第一条弧所对应的弧结点;
◆ 指针域firstout:指向以该顶点为弧尾的第一条弧所对应的弧结点;
◆ 尾域tailvex:指示弧尾顶点在图中的位置;
◆ 头域headvex:指示弧头顶点在图中的位置;
◆ 指针域hlink:指向弧头相同的下一条弧;
◆ 指针域tlink:指向弧尾相同的下一条弧;
◆ Info域:指向该弧的相关信息;
从这种存储结构图可以看出,从一个顶点结点的firstout出发,沿表结点的tlink指针构成了正邻接表的链表结构,而从一个顶点结点的firstin出发,沿表结点的hlink指针构成了逆邻接表的链表结构。
*/
/**
*
* @param {Number} headVex 弧的头顶点的位置
* @param {Number} tailVex 弧的尾顶点位置
* @param {ArcBox} hLink 弧头相同的弧的链域
* @param {ArcBox} tLink 弧尾相同的弧的链域
* @param {*} info
* @constructor
*/
function ArcBox(headVex, tailVex, hLink, tLink, info){
this.headVex = headVex || 0;
this.tailVex = tailVex || 0;
this.hLink = hLink || null;
this.tLink = tLink || null;
this.info = info || null;
}
/**
*
* @param {*} data
* @param {ArcBox} firstIn 该顶点第一条入弧
* @param {ArcBox} firstOut 该顶点第一条出弧
* @constructor
*/
function OLVexNode(data, firstIn, firstOut){
this.data = data || null;
this.firstIn = firstIn || null;
this.firstOut = firstOut || null;
}
/**
*
* @param {Array | OLVexNode} xList 表头向量
* @param {Number} vexnum 有向图的当前顶点数
* @param {Number} arcnum 有向图的当前弧数
* @constructor
*/
function OLGraph(xList, vexnum, arcnum){
this.xList = xList || [];
this.vexnum = vexnum || 0;
this.arcnum = arcnum || 0;
}
OLGraph.prototype = {
constructor: OLGraph,
createDG: function(){
}
};
| modified
| Graph/Graph.js | modified | <ide><path>raph/Graph.js
<ide> }
<ide> OLGraph.prototype = {
<ide> constructor: OLGraph,
<add>
<add> locateVex: function(vp){
<add> for(var i = 0; i < this.vexnum; i++){
<add> if(this.xList[i].data === vp) return i;
<add> }
<add>
<add> return -1;
<add> },
<add>
<ide> createDG: function(){
<del>
<add> this.vexnum = prompt('Vexnum: ');
<add> this.arcnum = prompt('Arcnum: ');
<add> // IncInfo为0则各弧不含其他信息
<add> var incInfo = +prompt('IncInfo: ');
<add>
<add> // 输入顶点值
<add> for(var i = 0; i < this.vexnum; i++){
<add> this.xList[i] = new OLVexNode(prompt('data: '), null, null);
<add> }
<add>
<add> for(var k = 0; k < this.arcnum; k++){
<add> var v1 = prompt('v1: ');
<add> var v2 = prompt('v2: ');
<add>
<add> i = this.locateVex(v1);
<add> var j = this.locateVex(v2);
<add>
<add> if(i === -1 || j === -1) {
<add> alert('无此顶点,请重新输入!');
<add> k--;
<add> continue;
<add> }
<add>
<add> var p = new ArcBox(j, i, this.xList[j].firstIn, this.xList[i].firstOut, incInfo && prompt('info: '));
<add> this.xList[j].firstIn = this.xList[i].firstOut = p;
<add> }
<ide> }
<ide> };
<ide>
<add>// todo 貌似有问题..
<add>var g = new OLGraph();
<add>g.createDG();
<add>console.log(g);
<add> |
|
Java | apache-2.0 | f2a82d1cdd92932ba585c5a42adc5815b6245f5d | 0 | blipinsk/cortado | /*
* Copyright 2017 Bartosz Lipinski
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cortado;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.annotation.VisibleForTesting;
import android.support.test.espresso.Espresso;
import android.support.test.espresso.ViewAction;
import android.support.test.espresso.ViewAssertion;
import android.support.test.espresso.ViewInteraction;
import android.support.test.espresso.matcher.ViewMatchers;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
import static cortado.Chunks.AssignableFrom;
import static cortado.Chunks.ClassName;
import static cortado.Chunks.HasContentDescription;
import static cortado.Chunks.HasDescendant;
import static cortado.Chunks.HasErrorText_Matcher;
import static cortado.Chunks.HasErrorText_String;
import static cortado.Chunks.HasFocus;
import static cortado.Chunks.HasImeAction_Integer;
import static cortado.Chunks.HasImeAction_Matcher;
import static cortado.Chunks.HasLinks;
import static cortado.Chunks.HasSibling;
import static cortado.Chunks.IsChecked;
import static cortado.Chunks.IsClickable;
import static cortado.Chunks.IsCompletelyDisplayed;
import static cortado.Chunks.IsDescendantOfA;
import static cortado.Chunks.IsDisplayed;
import static cortado.Chunks.IsDisplayingAtLeast;
import static cortado.Chunks.IsEnabled;
import static cortado.Chunks.IsFocusable;
import static cortado.Chunks.IsJavascriptEnabled;
import static cortado.Chunks.IsNotChecked;
import static cortado.Chunks.IsRoot;
import static cortado.Chunks.IsSelected;
import static cortado.Chunks.SupportsInputMethods;
import static cortado.Chunks.WithChild;
import static cortado.Chunks.WithContentDescription_Matcher;
import static cortado.Chunks.WithContentDescription_Resource;
import static cortado.Chunks.WithContentDescription_String;
import static cortado.Chunks.WithEffectiveVisibility;
import static cortado.Chunks.WithHint_Matcher;
import static cortado.Chunks.WithHint_Resource;
import static cortado.Chunks.WithHint_String;
import static cortado.Chunks.WithId_Matcher;
import static cortado.Chunks.WithId_Resource;
import static cortado.Chunks.WithInputType;
import static cortado.Chunks.WithParent;
import static cortado.Chunks.WithResourceName_Matcher;
import static cortado.Chunks.WithResourceName_String;
import static cortado.Chunks.WithSpinnerText_Matcher;
import static cortado.Chunks.WithSpinnerText_Resource;
import static cortado.Chunks.WithSpinnerText_String;
import static cortado.Chunks.WithTagKey;
import static cortado.Chunks.WithTagKey_Matcher;
import static cortado.Chunks.WithTagValue;
import static cortado.Chunks.WithText_Matcher;
import static cortado.Chunks.WithText_Resource;
import static cortado.Chunks.WithText_String;
public final class Cortado {
@VisibleForTesting AssignableFrom assignableFrom = new AssignableFrom();
@VisibleForTesting ClassName className = new ClassName();
@VisibleForTesting IsDisplayed isDisplayed = new IsDisplayed();
@VisibleForTesting IsCompletelyDisplayed isCompletelyDisplayed = new IsCompletelyDisplayed();
@VisibleForTesting IsDisplayingAtLeast isDisplayingAtLeast = new IsDisplayingAtLeast();
@VisibleForTesting IsEnabled isEnabled = new IsEnabled();
@VisibleForTesting IsFocusable isFocusable = new IsFocusable();
@VisibleForTesting HasFocus hasFocus = new HasFocus();
@VisibleForTesting IsSelected isSelected = new IsSelected();
@VisibleForTesting HasSibling hasSibling = new HasSibling();
@VisibleForTesting WithContentDescription_Resource withContentDescriptionResource = new WithContentDescription_Resource();
@VisibleForTesting WithContentDescription_String withContentDescriptionString = new WithContentDescription_String();
@VisibleForTesting WithContentDescription_Matcher withContentDescriptionMatcher = new WithContentDescription_Matcher();
@VisibleForTesting WithId_Resource withIdResource = new WithId_Resource();
@VisibleForTesting WithId_Matcher withIdMatcher = new WithId_Matcher();
@VisibleForTesting WithResourceName_String withResourceNameString = new WithResourceName_String();
@VisibleForTesting WithResourceName_Matcher withResourceNameMatcher = new WithResourceName_Matcher();
@VisibleForTesting WithTagKey withTagKey = new WithTagKey();
@VisibleForTesting WithTagKey_Matcher withTagKeyMatcher = new WithTagKey_Matcher();
@VisibleForTesting WithTagValue withTagValue = new WithTagValue();
@VisibleForTesting WithText_String withTextString = new WithText_String();
@VisibleForTesting WithText_Matcher withTextMatcher = new WithText_Matcher();
@VisibleForTesting WithText_Resource withTextResource = new WithText_Resource();
@VisibleForTesting WithHint_String withHintString = new WithHint_String();
@VisibleForTesting WithHint_Matcher withHintMatcher = new WithHint_Matcher();
@VisibleForTesting WithHint_Resource withHintResource = new WithHint_Resource();
@VisibleForTesting IsChecked isChecked = new IsChecked();
@VisibleForTesting IsNotChecked isNotChecked = new IsNotChecked();
@VisibleForTesting HasContentDescription hasContentDescription = new HasContentDescription();
@VisibleForTesting HasDescendant hasDescendant = new HasDescendant();
@VisibleForTesting IsClickable isClickable = new IsClickable();
@VisibleForTesting IsDescendantOfA isDescendantOfA = new IsDescendantOfA();
@VisibleForTesting WithEffectiveVisibility withEffectiveVisibility = new WithEffectiveVisibility();
@VisibleForTesting WithParent withParent = new WithParent();
@VisibleForTesting WithChild withChild = new WithChild();
@VisibleForTesting IsRoot isRoot = new IsRoot();
@VisibleForTesting SupportsInputMethods supportsInputMethods = new SupportsInputMethods();
@VisibleForTesting HasImeAction_Integer hasImeActionInteger = new HasImeAction_Integer();
@VisibleForTesting HasImeAction_Matcher hasImeActionMatcher = new HasImeAction_Matcher();
@VisibleForTesting HasLinks hasLinks = new HasLinks();
@VisibleForTesting WithSpinnerText_Resource withSpinnerTextResource = new WithSpinnerText_Resource();
@VisibleForTesting WithSpinnerText_Matcher withSpinnerTextMatcher = new WithSpinnerText_Matcher();
@VisibleForTesting WithSpinnerText_String withSpinnerTextString = new WithSpinnerText_String();
@VisibleForTesting IsJavascriptEnabled isJavascriptEnabled = new IsJavascriptEnabled();
@VisibleForTesting HasErrorText_Matcher hasErrorTextMatcher = new HasErrorText_Matcher();
@VisibleForTesting HasErrorText_String hasErrorTextString = new HasErrorText_String();
@VisibleForTesting WithInputType withInputType = new WithInputType();
@VisibleForTesting Chunks.Matching matching = new Chunks.Matching();
private Linker linker = Linker.REGULAR;
@Nullable
private org.hamcrest.Matcher<? super View> cached;
private Cortado() {
}
public static Start.ViewInteraction onView() {
return new Cortado().new Start().new ViewInteraction();
}
public static Start.Matcher view() {
return new Cortado().new Start().new Matcher();
}
private synchronized void clearCached() {
cached = null;
}
@NonNull
synchronized org.hamcrest.Matcher<View> get() {
if (cached == null) {
List<org.hamcrest.Matcher<? super View>> matchers = new ArrayList<>();
assignableFrom.applyIfNeeded(matchers);
className.applyIfNeeded(matchers);
isDisplayed.applyIfNeeded(matchers);
isCompletelyDisplayed.applyIfNeeded(matchers);
isDisplayingAtLeast.applyIfNeeded(matchers);
isEnabled.applyIfNeeded(matchers);
isFocusable.applyIfNeeded(matchers);
hasFocus.applyIfNeeded(matchers);
isSelected.applyIfNeeded(matchers);
hasSibling.applyIfNeeded(matchers);
withContentDescriptionResource.applyIfNeeded(matchers);
withContentDescriptionString.applyIfNeeded(matchers);
withContentDescriptionMatcher.applyIfNeeded(matchers);
withIdResource.applyIfNeeded(matchers);
withIdMatcher.applyIfNeeded(matchers);
withResourceNameString.applyIfNeeded(matchers);
withResourceNameMatcher.applyIfNeeded(matchers);
withTagKey.applyIfNeeded(matchers);
withTagKeyMatcher.applyIfNeeded(matchers);
withTagValue.applyIfNeeded(matchers);
withTextString.applyIfNeeded(matchers);
withTextMatcher.applyIfNeeded(matchers);
withTextResource.applyIfNeeded(matchers);
withHintString.applyIfNeeded(matchers);
withHintMatcher.applyIfNeeded(matchers);
withHintResource.applyIfNeeded(matchers);
isChecked.applyIfNeeded(matchers);
isNotChecked.applyIfNeeded(matchers);
hasContentDescription.applyIfNeeded(matchers);
hasDescendant.applyIfNeeded(matchers);
isClickable.applyIfNeeded(matchers);
isDescendantOfA.applyIfNeeded(matchers);
withEffectiveVisibility.applyIfNeeded(matchers);
withParent.applyIfNeeded(matchers);
withChild.applyIfNeeded(matchers);
isRoot.applyIfNeeded(matchers);
supportsInputMethods.applyIfNeeded(matchers);
hasImeActionInteger.applyIfNeeded(matchers);
hasImeActionMatcher.applyIfNeeded(matchers);
hasLinks.applyIfNeeded(matchers);
withSpinnerTextResource.applyIfNeeded(matchers);
withSpinnerTextMatcher.applyIfNeeded(matchers);
withSpinnerTextString.applyIfNeeded(matchers);
isJavascriptEnabled.applyIfNeeded(matchers);
hasErrorTextMatcher.applyIfNeeded(matchers);
hasErrorTextString.applyIfNeeded(matchers);
withInputType.applyIfNeeded(matchers);
matching.applyIfNeeded(matchers);
cached = linker.link(matchers);
}
//noinspection unchecked
return (org.hamcrest.Matcher<View>) cached;
}
@NonNull
ViewInteraction perform(final ViewAction... viewActions) {
return Espresso.onView(get()).perform(viewActions);
}
@NonNull
ViewInteraction check(final ViewAssertion viewAssert) {
return Espresso.onView(get()).check(viewAssert);
}
private void and() {
clearCached();
linker = Linker.AND;
}
private void or() {
clearCached();
linker = Linker.OR;
}
void isAssignableFrom(Class<? extends View> clazz) {
clearCached();
assignableFrom.store(clazz);
}
void withClassName(org.hamcrest.Matcher<String> classNameMatcher) {
clearCached();
className.store(classNameMatcher);
}
void isDisplayed() {
clearCached();
isDisplayed.store(true);
}
void isCompletelyDisplayed() {
clearCached();
isCompletelyDisplayed.store(true);
}
void isDisplayingAtLeast(int areaPercentage) {
clearCached();
isDisplayingAtLeast.store(areaPercentage);
}
void isEnabled() {
clearCached();
isEnabled.store(true);
}
void isFocusable() {
clearCached();
isFocusable.store(true);
}
void hasFocus() {
clearCached();
hasFocus.store(true);
}
void isSelected() {
clearCached();
isSelected.store(true);
}
void hasSibling(org.hamcrest.Matcher<View> siblingMatcher) {
clearCached();
hasSibling.store(siblingMatcher);
}
void hasSibling(Matcher siblingMatcher) {
hasSibling((org.hamcrest.Matcher<View>) siblingMatcher);
}
void withContentDescription(@StringRes int resourceId) {
clearCached();
withContentDescriptionResource.store(resourceId);
}
void withContentDescription(String text) {
clearCached();
withContentDescriptionString.store(text);
}
void withContentDescription(org.hamcrest.Matcher<? extends CharSequence> charSequenceMatcher) {
clearCached();
withContentDescriptionMatcher.store(charSequenceMatcher);
}
void withId(@IdRes int id) {
clearCached();
withIdResource.store(id);
}
void withId(org.hamcrest.Matcher<Integer> integerMatcher) {
clearCached();
withIdMatcher.store(integerMatcher);
}
void withResourceName(String name) {
clearCached();
withResourceNameString.store(name);
}
void withResourceName(org.hamcrest.Matcher<String> stringMatcher) {
clearCached();
withResourceNameMatcher.store(stringMatcher);
}
void withTagKey(int key) {
clearCached();
withTagKey.store(key);
}
void withTagKey(int key, org.hamcrest.Matcher<Object> objectMatcher) {
clearCached();
withTagKeyMatcher.store(new Chunks.TagKeyArgs(key, objectMatcher));
}
void withTagValue(org.hamcrest.Matcher<Object> tagValueMatcher) {
clearCached();
withTagValue.store(tagValueMatcher);
}
void withText(String text) {
clearCached();
withTextString.store(text);
}
void withText(org.hamcrest.Matcher<String> stringMatcher) {
clearCached();
withTextMatcher.store(stringMatcher);
}
void withText(@StringRes int resourceId) {
clearCached();
withTextResource.store(resourceId);
}
void withHint(String hintText) {
clearCached();
withHintString.store(hintText);
}
void withHint(org.hamcrest.Matcher<String> stringMatcher) {
clearCached();
withHintMatcher.store(stringMatcher);
}
void withHint(@StringRes int resourceId) {
clearCached();
withHintResource.store(resourceId);
}
void isChecked() {
clearCached();
isChecked.store(true);
}
void isNotChecked() {
clearCached();
isNotChecked.store(true);
}
void hasContentDescription() {
clearCached();
hasContentDescription.store(true);
}
void hasDescendant(org.hamcrest.Matcher<View> descendantMatcher) {
clearCached();
hasDescendant.store(descendantMatcher);
}
void hasDescendant(Matcher descendantMatcher) {
hasDescendant((org.hamcrest.Matcher<View>) descendantMatcher);
}
void isClickable() {
clearCached();
isClickable.store(true);
}
void isDescendantOfA(org.hamcrest.Matcher<View> ancestorMatcher) {
clearCached();
isDescendantOfA.store(ancestorMatcher);
}
void isDescendantOfA(Matcher ancestorMatcher) {
isDescendantOfA((org.hamcrest.Matcher<View>) ancestorMatcher);
}
void withEffectiveVisibility(ViewMatchers.Visibility visibility) {
clearCached();
withEffectiveVisibility.store(visibility);
}
void withParent(org.hamcrest.Matcher<View> parentMatcher) {
clearCached();
withParent.store(parentMatcher);
}
void withParent(Matcher parentMatcher) {
withParent((org.hamcrest.Matcher<View>) parentMatcher);
}
void withChild(org.hamcrest.Matcher<View> childMatcher) {
clearCached();
withChild.store(childMatcher);
}
void withChild(Matcher childMatcher) {
withChild((org.hamcrest.Matcher<View>) childMatcher);
}
void isRoot() {
clearCached();
isRoot.store(true);
}
void supportsInputMethods() {
clearCached();
supportsInputMethods.store(true);
}
void hasImeAction(int imeAction) {
clearCached();
hasImeActionInteger.store(imeAction);
}
void hasImeAction(org.hamcrest.Matcher<Integer> imeActionMatcher) {
clearCached();
hasImeActionMatcher.store(imeActionMatcher);
}
void hasLinks() {
clearCached();
hasLinks.store(true);
}
void withSpinnerText(@StringRes int resourceId) {
clearCached();
withSpinnerTextResource.store(resourceId);
}
void withSpinnerText(org.hamcrest.Matcher<String> stringMatcher) {
clearCached();
withSpinnerTextMatcher.store(stringMatcher);
}
void withSpinnerText(String text) {
clearCached();
withSpinnerTextString.store(text);
}
void isJavascriptEnabled() {
clearCached();
isJavascriptEnabled.store(true);
}
void hasErrorText(org.hamcrest.Matcher<String> stringMatcher) {
clearCached();
hasErrorTextMatcher.store(stringMatcher);
}
void hasErrorText(String expectedError) {
clearCached();
hasErrorTextString.store(expectedError);
}
void withInputType(int inputType) {
clearCached();
withInputType.store(inputType);
}
void matching(org.hamcrest.Matcher<View> matcher){
clearCached();
matching.store(matcher);
}
void matching(Matcher matcher){
matching((org.hamcrest.Matcher<View>) matcher);
}
public final class Start {
private Start() {
}
public final class Matcher extends NotCompletable<OrAnd.Matcher> {
Matcher() {
super(Cortado.this);
}
@Override
OrAnd.Matcher returned() {
return new OrAnd().new Matcher();
}
@VisibleForTesting
Cortado getCortado() {
return Cortado.this;
}
}
public final class ViewInteraction extends NotCompletable<OrAnd.ViewInteraction> {
ViewInteraction() {
super(Cortado.this);
}
@Override
OrAnd.ViewInteraction returned() {
return new OrAnd().new ViewInteraction();
}
@VisibleForTesting
Cortado getCortado() {
return Cortado.this;
}
}
}
public final class Unfinished {
private Unfinished() {
}
public final class Or {
private Or() {
}
public final class Matcher extends NotCompletable<Cortado.Or.Matcher> {
private Matcher() {
super(Cortado.this);
}
@Override
Cortado.Or.Matcher returned() {
return new Cortado.Or().new Matcher();
}
}
public final class ViewInteraction extends NotCompletable<Cortado.Or.ViewInteraction> {
private ViewInteraction() {
super(Cortado.this);
}
@Override
Cortado.Or.ViewInteraction returned() {
return new Cortado.Or().new ViewInteraction();
}
}
}
public final class And {
private And() {
}
public final class Matcher extends NotCompletable<Cortado.And.Matcher> {
private Matcher() {
super(Cortado.this);
}
@Override
Cortado.And.Matcher returned() {
return new Cortado.And().new Matcher();
}
}
public final class ViewInteraction extends NotCompletable<Cortado.And.ViewInteraction> {
private ViewInteraction() {
super(Cortado.this);
}
@Override
Cortado.And.ViewInteraction returned() {
return new Cortado.And().new ViewInteraction();
}
}
}
}
public final class OrAnd {
OrAnd() {
}
public final class Matcher extends cortado.Matcher {
Matcher() {
super(Cortado.this);
}
public Unfinished.Or.Matcher or() {
Cortado.this.or();
return new Unfinished().new Or().new Matcher();
}
public Unfinished.And.Matcher and() {
Cortado.this.and();
return new Unfinished().new And().new Matcher();
}
}
public final class ViewInteraction extends cortado.ViewInteraction {
ViewInteraction() {
super(Cortado.this);
}
public Unfinished.Or.ViewInteraction or() {
Cortado.this.or();
return new Unfinished().new Or().new ViewInteraction();
}
public Unfinished.And.ViewInteraction and() {
Cortado.this.and();
return new Unfinished().new And().new ViewInteraction();
}
}
}
public final class Or {
private Or() {
}
public final class Matcher extends cortado.Matcher {
private Matcher() {
super(Cortado.this);
}
public Unfinished.Or.Matcher or() {
return new Unfinished().new Or().new Matcher();
}
}
public final class ViewInteraction extends cortado.ViewInteraction {
private ViewInteraction() {
super(Cortado.this);
}
public Unfinished.Or.ViewInteraction or() {
return new Unfinished().new Or().new ViewInteraction();
}
}
}
public final class And {
private And() {
}
public final class Matcher extends cortado.Matcher {
private Matcher() {
super(Cortado.this);
}
public Unfinished.And.Matcher and() {
return new Unfinished().new And().new Matcher();
}
}
public final class ViewInteraction extends cortado.ViewInteraction {
private ViewInteraction() {
super(Cortado.this);
}
public Unfinished.And.ViewInteraction and() {
return new Unfinished().new And().new ViewInteraction();
}
}
}
}
| cortado/src/main/java/cortado/Cortado.java | /*
* Copyright 2017 Bartosz Lipinski
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cortado;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.annotation.VisibleForTesting;
import android.support.test.espresso.Espresso;
import android.support.test.espresso.ViewAction;
import android.support.test.espresso.ViewAssertion;
import android.support.test.espresso.ViewInteraction;
import android.support.test.espresso.matcher.ViewMatchers;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
import static cortado.Chunks.AssignableFrom;
import static cortado.Chunks.ClassName;
import static cortado.Chunks.HasContentDescription;
import static cortado.Chunks.HasDescendant;
import static cortado.Chunks.HasErrorText_Matcher;
import static cortado.Chunks.HasErrorText_String;
import static cortado.Chunks.HasFocus;
import static cortado.Chunks.HasImeAction_Integer;
import static cortado.Chunks.HasImeAction_Matcher;
import static cortado.Chunks.HasLinks;
import static cortado.Chunks.HasSibling;
import static cortado.Chunks.IsChecked;
import static cortado.Chunks.IsClickable;
import static cortado.Chunks.IsCompletelyDisplayed;
import static cortado.Chunks.IsDescendantOfA;
import static cortado.Chunks.IsDisplayed;
import static cortado.Chunks.IsDisplayingAtLeast;
import static cortado.Chunks.IsEnabled;
import static cortado.Chunks.IsFocusable;
import static cortado.Chunks.IsJavascriptEnabled;
import static cortado.Chunks.IsNotChecked;
import static cortado.Chunks.IsRoot;
import static cortado.Chunks.IsSelected;
import static cortado.Chunks.SupportsInputMethods;
import static cortado.Chunks.WithChild;
import static cortado.Chunks.WithContentDescription_Matcher;
import static cortado.Chunks.WithContentDescription_Resource;
import static cortado.Chunks.WithContentDescription_String;
import static cortado.Chunks.WithEffectiveVisibility;
import static cortado.Chunks.WithHint_Matcher;
import static cortado.Chunks.WithHint_Resource;
import static cortado.Chunks.WithHint_String;
import static cortado.Chunks.WithId_Matcher;
import static cortado.Chunks.WithId_Resource;
import static cortado.Chunks.WithInputType;
import static cortado.Chunks.WithParent;
import static cortado.Chunks.WithResourceName_Matcher;
import static cortado.Chunks.WithResourceName_String;
import static cortado.Chunks.WithSpinnerText_Matcher;
import static cortado.Chunks.WithSpinnerText_Resource;
import static cortado.Chunks.WithSpinnerText_String;
import static cortado.Chunks.WithTagKey;
import static cortado.Chunks.WithTagKey_Matcher;
import static cortado.Chunks.WithTagValue;
import static cortado.Chunks.WithText_Matcher;
import static cortado.Chunks.WithText_Resource;
import static cortado.Chunks.WithText_String;
public final class Cortado {
@VisibleForTesting AssignableFrom assignableFrom = new AssignableFrom();
@VisibleForTesting ClassName className = new ClassName();
@VisibleForTesting IsDisplayed isDisplayed = new IsDisplayed();
@VisibleForTesting IsCompletelyDisplayed isCompletelyDisplayed = new IsCompletelyDisplayed();
@VisibleForTesting IsDisplayingAtLeast isDisplayingAtLeast = new IsDisplayingAtLeast();
@VisibleForTesting IsEnabled isEnabled = new IsEnabled();
@VisibleForTesting IsFocusable isFocusable = new IsFocusable();
@VisibleForTesting HasFocus hasFocus = new HasFocus();
@VisibleForTesting IsSelected isSelected = new IsSelected();
@VisibleForTesting HasSibling hasSibling = new HasSibling();
@VisibleForTesting WithContentDescription_Resource withContentDescriptionResource = new WithContentDescription_Resource();
@VisibleForTesting WithContentDescription_String withContentDescriptionString = new WithContentDescription_String();
@VisibleForTesting WithContentDescription_Matcher withContentDescriptionMatcher = new WithContentDescription_Matcher();
@VisibleForTesting WithId_Resource withIdResource = new WithId_Resource();
@VisibleForTesting WithId_Matcher withIdMatcher = new WithId_Matcher();
@VisibleForTesting WithResourceName_String withResourceNameString = new WithResourceName_String();
@VisibleForTesting WithResourceName_Matcher withResourceNameMatcher = new WithResourceName_Matcher();
@VisibleForTesting WithTagKey withTagKey = new WithTagKey();
@VisibleForTesting WithTagKey_Matcher withTagKeyMatcher = new WithTagKey_Matcher();
@VisibleForTesting WithTagValue withTagValue = new WithTagValue();
@VisibleForTesting WithText_String withTextString = new WithText_String();
@VisibleForTesting WithText_Matcher withTextMatcher = new WithText_Matcher();
@VisibleForTesting WithText_Resource withTextResource = new WithText_Resource();
@VisibleForTesting WithHint_String withHintString = new WithHint_String();
@VisibleForTesting WithHint_Matcher withHintMatcher = new WithHint_Matcher();
@VisibleForTesting WithHint_Resource withHintResource = new WithHint_Resource();
@VisibleForTesting IsChecked isChecked = new IsChecked();
@VisibleForTesting IsNotChecked isNotChecked = new IsNotChecked();
@VisibleForTesting HasContentDescription hasContentDescription = new HasContentDescription();
@VisibleForTesting HasDescendant hasDescendant = new HasDescendant();
@VisibleForTesting IsClickable isClickable = new IsClickable();
@VisibleForTesting IsDescendantOfA isDescendantOfA = new IsDescendantOfA();
@VisibleForTesting WithEffectiveVisibility withEffectiveVisibility = new WithEffectiveVisibility();
@VisibleForTesting WithParent withParent = new WithParent();
@VisibleForTesting WithChild withChild = new WithChild();
@VisibleForTesting IsRoot isRoot = new IsRoot();
@VisibleForTesting SupportsInputMethods supportsInputMethods = new SupportsInputMethods();
@VisibleForTesting HasImeAction_Integer hasImeActionInteger = new HasImeAction_Integer();
@VisibleForTesting HasImeAction_Matcher hasImeActionMatcher = new HasImeAction_Matcher();
@VisibleForTesting HasLinks hasLinks = new HasLinks();
@VisibleForTesting WithSpinnerText_Resource withSpinnerTextResource = new WithSpinnerText_Resource();
@VisibleForTesting WithSpinnerText_Matcher withSpinnerTextMatcher = new WithSpinnerText_Matcher();
@VisibleForTesting WithSpinnerText_String withSpinnerTextString = new WithSpinnerText_String();
@VisibleForTesting IsJavascriptEnabled isJavascriptEnabled = new IsJavascriptEnabled();
@VisibleForTesting HasErrorText_Matcher hasErrorTextMatcher = new HasErrorText_Matcher();
@VisibleForTesting HasErrorText_String hasErrorTextString = new HasErrorText_String();
@VisibleForTesting WithInputType withInputType = new WithInputType();
@VisibleForTesting Chunks.Matching matching = new Chunks.Matching();
private Linker linker = Linker.REGULAR;
@Nullable
private org.hamcrest.Matcher<? super View> cached;
private Cortado() {
}
public static Start.ViewInteraction onView() {
return new Cortado().new Start().new ViewInteraction();
}
public static Start.Matcher view() {
return new Cortado().new Start().new Matcher();
}
private synchronized void clearCached() {
cached = null;
}
@NonNull
synchronized org.hamcrest.Matcher<View> get() {
if (cached == null) {
List<org.hamcrest.Matcher<? super View>> matchers = new ArrayList<>();
assignableFrom.applyIfNeeded(matchers);
className.applyIfNeeded(matchers);
isDisplayed.applyIfNeeded(matchers);
isCompletelyDisplayed.applyIfNeeded(matchers);
isDisplayingAtLeast.applyIfNeeded(matchers);
isEnabled.applyIfNeeded(matchers);
isFocusable.applyIfNeeded(matchers);
hasFocus.applyIfNeeded(matchers);
isSelected.applyIfNeeded(matchers);
hasSibling.applyIfNeeded(matchers);
withContentDescriptionResource.applyIfNeeded(matchers);
withContentDescriptionString.applyIfNeeded(matchers);
withContentDescriptionMatcher.applyIfNeeded(matchers);
withIdResource.applyIfNeeded(matchers);
withIdMatcher.applyIfNeeded(matchers);
withResourceNameString.applyIfNeeded(matchers);
withResourceNameMatcher.applyIfNeeded(matchers);
withTagKey.applyIfNeeded(matchers);
withTagKeyMatcher.applyIfNeeded(matchers);
withTagValue.applyIfNeeded(matchers);
withTextString.applyIfNeeded(matchers);
withTextMatcher.applyIfNeeded(matchers);
withTextResource.applyIfNeeded(matchers);
withHintString.applyIfNeeded(matchers);
withHintMatcher.applyIfNeeded(matchers);
withHintResource.applyIfNeeded(matchers);
isChecked.applyIfNeeded(matchers);
isNotChecked.applyIfNeeded(matchers);
hasContentDescription.applyIfNeeded(matchers);
hasDescendant.applyIfNeeded(matchers);
isClickable.applyIfNeeded(matchers);
isDescendantOfA.applyIfNeeded(matchers);
withEffectiveVisibility.applyIfNeeded(matchers);
withParent.applyIfNeeded(matchers);
withChild.applyIfNeeded(matchers);
isRoot.applyIfNeeded(matchers);
supportsInputMethods.applyIfNeeded(matchers);
hasImeActionInteger.applyIfNeeded(matchers);
hasImeActionMatcher.applyIfNeeded(matchers);
hasLinks.applyIfNeeded(matchers);
withSpinnerTextResource.applyIfNeeded(matchers);
withSpinnerTextMatcher.applyIfNeeded(matchers);
withSpinnerTextString.applyIfNeeded(matchers);
isJavascriptEnabled.applyIfNeeded(matchers);
hasErrorTextMatcher.applyIfNeeded(matchers);
hasErrorTextString.applyIfNeeded(matchers);
withInputType.applyIfNeeded(matchers);
matching.applyIfNeeded(matchers);
cached = linker.link(matchers);
}
//noinspection unchecked
return (org.hamcrest.Matcher<View>) cached;
}
@NonNull
ViewInteraction perform(final ViewAction... viewActions) {
return Espresso.onView(get()).perform(viewActions);
}
@NonNull
ViewInteraction check(final ViewAssertion viewAssert) {
return Espresso.onView(get()).check(viewAssert);
}
private void and() {
clearCached();
linker = Linker.AND;
}
private void or() {
clearCached();
linker = Linker.OR;
}
void isAssignableFrom(Class<? extends View> clazz) {
clearCached();
assignableFrom.store(clazz);
}
void withClassName(org.hamcrest.Matcher<String> classNameMatcher) {
clearCached();
className.store(classNameMatcher);
}
void isDisplayed() {
clearCached();
isDisplayed.store(true);
}
void isCompletelyDisplayed() {
clearCached();
isCompletelyDisplayed.store(true);
}
void isDisplayingAtLeast(int areaPercentage) {
clearCached();
isDisplayingAtLeast.store(areaPercentage);
}
void isEnabled() {
clearCached();
isEnabled.store(true);
}
void isFocusable() {
clearCached();
isFocusable.store(true);
}
void hasFocus() {
clearCached();
hasFocus.store(true);
}
void isSelected() {
clearCached();
isSelected.store(true);
}
void hasSibling(org.hamcrest.Matcher<View> siblingMatcher) {
clearCached();
hasSibling.store(siblingMatcher);
}
void hasSibling(Matcher siblingMatcher) {
hasSibling((org.hamcrest.Matcher<View>) siblingMatcher);
}
void withContentDescription(@StringRes int resourceId) {
clearCached();
withContentDescriptionResource.store(resourceId);
}
void withContentDescription(String text) {
clearCached();
withContentDescriptionString.store(text);
}
void withContentDescription(org.hamcrest.Matcher<? extends CharSequence> charSequenceMatcher) {
clearCached();
withContentDescriptionMatcher.store(charSequenceMatcher);
}
void withId(@IdRes int id) {
clearCached();
withIdResource.store(id);
}
void withId(org.hamcrest.Matcher<Integer> integerMatcher) {
clearCached();
withIdMatcher.store(integerMatcher);
}
void withResourceName(String name) {
clearCached();
withResourceNameString.store(name);
}
void withResourceName(org.hamcrest.Matcher<String> stringMatcher) {
clearCached();
withResourceNameMatcher.store(stringMatcher);
}
void withTagKey(int key) {
clearCached();
withTagKey.store(key);
}
void withTagKey(int key, org.hamcrest.Matcher<Object> objectMatcher) {
clearCached();
withTagKeyMatcher.store(new Chunks.TagKeyArgs(key, objectMatcher));
}
void withTagValue(org.hamcrest.Matcher<Object> tagValueMatcher) {
clearCached();
withTagValue.store(tagValueMatcher);
}
void withText(String text) {
clearCached();
withTextString.store(text);
}
void withText(org.hamcrest.Matcher<String> stringMatcher) {
clearCached();
withTextMatcher.store(stringMatcher);
}
void withText(@StringRes int resourceId) {
clearCached();
withTextResource.store(resourceId);
}
void withHint(String hintText) {
clearCached();
withHintString.store(hintText);
}
void withHint(org.hamcrest.Matcher<String> stringMatcher) {
clearCached();
withHintMatcher.store(stringMatcher);
}
void withHint(@StringRes int resourceId) {
clearCached();
withHintResource.store(resourceId);
}
void isChecked() {
clearCached();
isChecked.store(true);
}
void isNotChecked() {
clearCached();
isNotChecked.store(true);
}
void hasContentDescription() {
clearCached();
hasContentDescription.store(true);
}
void hasDescendant(org.hamcrest.Matcher<View> descendantMatcher) {
clearCached();
hasDescendant.store(descendantMatcher);
}
void hasDescendant(Matcher descendantMatcher) {
hasDescendant((org.hamcrest.Matcher<View>) descendantMatcher);
}
void isClickable() {
clearCached();
isClickable.store(true);
}
void isDescendantOfA(org.hamcrest.Matcher<View> ancestorMatcher) {
clearCached();
isDescendantOfA.store(ancestorMatcher);
}
void isDescendantOfA(Matcher ancestorMatcher) {
isDescendantOfA((org.hamcrest.Matcher<View>) ancestorMatcher);
}
void withEffectiveVisibility(ViewMatchers.Visibility visibility) {
clearCached();
withEffectiveVisibility.store(visibility);
}
void withParent(org.hamcrest.Matcher<View> parentMatcher) {
clearCached();
withParent.store(parentMatcher);
}
void withParent(Matcher parentMatcher) {
withParent((org.hamcrest.Matcher<View>) parentMatcher);
}
void withChild(org.hamcrest.Matcher<View> childMatcher) {
clearCached();
withChild.store(childMatcher);
}
void withChild(Matcher childMatcher) {
withChild((org.hamcrest.Matcher<View>) childMatcher);
}
void isRoot() {
clearCached();
isRoot.store(true);
}
void supportsInputMethods() {
clearCached();
supportsInputMethods.store(true);
}
void hasImeAction(int imeAction) {
clearCached();
hasImeActionInteger.store(imeAction);
}
void hasImeAction(org.hamcrest.Matcher<Integer> imeActionMatcher) {
clearCached();
hasImeActionMatcher.store(imeActionMatcher);
}
void hasLinks() {
clearCached();
hasLinks.store(true);
}
void withSpinnerText(@StringRes int resourceId) {
clearCached();
withSpinnerTextResource.store(resourceId);
}
void withSpinnerText(org.hamcrest.Matcher<String> stringMatcher) {
clearCached();
withSpinnerTextMatcher.store(stringMatcher);
}
void withSpinnerText(String text) {
clearCached();
withSpinnerTextString.store(text);
}
void isJavascriptEnabled() {
clearCached();
isJavascriptEnabled.store(true);
}
void hasErrorText(org.hamcrest.Matcher<String> stringMatcher) {
clearCached();
hasErrorTextMatcher.store(stringMatcher);
}
void hasErrorText(String expectedError) {
clearCached();
hasErrorTextString.store(expectedError);
}
void withInputType(int inputType) {
clearCached();
withInputType.store(inputType);
}
void matching(org.hamcrest.Matcher<View> matcher){
clearCached();
matching.store(matcher);
}
void matching(Matcher matcher){
matching((org.hamcrest.Matcher<View>) matcher);
}
public final class Start {
private Start() {
}
public final class Matcher extends NotCompletable<OrAnd.Matcher> {
Matcher() {
super(Cortado.this);
}
@Override
OrAnd.Matcher returned() {
return new OrAnd().new Matcher();
}
@VisibleForTesting
Cortado getCortado() {
return Cortado.this;
}
}
public final class ViewInteraction extends NotCompletable<OrAnd.ViewInteraction> {
ViewInteraction() {
super(Cortado.this);
}
@Override
OrAnd.ViewInteraction returned() {
return new OrAnd().new ViewInteraction();
}
@VisibleForTesting
Cortado getCortado() {
return Cortado.this;
}
}
}
public final class Unfinished {
private Unfinished() {
}
public final class Or {
private Or() {
}
public final class Matcher extends NotCompletable<Cortado.Or.Matcher> {
private Matcher() {
super(Cortado.this);
}
@Override
Cortado.Or.Matcher returned() {
return new Cortado.Or().new Matcher();
}
}
public final class ViewInteraction extends NotCompletable<Cortado.Or.ViewInteraction> {
private ViewInteraction() {
super(Cortado.this);
}
@Override
Cortado.Or.ViewInteraction returned() {
return new Cortado.Or().new ViewInteraction();
}
}
}
public final class And {
private And() {
}
public final class Matcher extends NotCompletable<Cortado.And.Matcher> {
private Matcher() {
super(Cortado.this);
}
@Override
Cortado.And.Matcher returned() {
return new Cortado.And().new Matcher();
}
}
public final class ViewInteraction extends NotCompletable<Cortado.And.ViewInteraction> {
private ViewInteraction() {
super(Cortado.this);
}
@Override
Cortado.And.ViewInteraction returned() {
return new Cortado.And().new ViewInteraction();
}
}
}
}
public final class OrAnd {
OrAnd() {
}
public final class Matcher extends cortado.Matcher {
Matcher() {
super(Cortado.this);
}
public Unfinished.Or.Matcher or() {
Cortado.this.or();
return new Unfinished().new Or().new Matcher();
}
public Unfinished.And.Matcher and() {
Cortado.this.and();
return new Unfinished().new And().new Matcher();
}
}
public final class ViewInteraction extends cortado.ViewInteraction {
ViewInteraction() {
super(Cortado.this);
}
public Unfinished.Or.ViewInteraction or() {
Cortado.this.or();
return new Unfinished().new Or().new ViewInteraction();
}
public Unfinished.And.ViewInteraction and() {
Cortado.this.and();
return new Unfinished().new And().new ViewInteraction();
}
}
}
public final class Or {
private Or() {
}
public final class Matcher extends cortado.Matcher {
private Matcher() {
super(Cortado.this);
}
public Unfinished.Or.Matcher or() {
return new Unfinished().new Or().new Matcher();
}
}
public final class ViewInteraction extends cortado.ViewInteraction {
private ViewInteraction() {
super(Cortado.this);
}
public Unfinished.Or.ViewInteraction or() {
return new Unfinished().new Or().new ViewInteraction();
}
}
}
public final class And {
private And() {
}
public final class Matcher extends cortado.Matcher {
private Matcher() {
super(Cortado.this);
}
public Unfinished.And.Matcher and() {
return new Unfinished().new And().new Matcher();
}
}
public final class ViewInteraction extends cortado.ViewInteraction {
private ViewInteraction() {
super(Cortado.this);
}
public Unfinished.And.ViewInteraction or() {
return new Unfinished().new And().new ViewInteraction();
}
}
}
}
| Fix: method name
| cortado/src/main/java/cortado/Cortado.java | Fix: method name | <ide><path>ortado/src/main/java/cortado/Cortado.java
<ide> super(Cortado.this);
<ide> }
<ide>
<del> public Unfinished.And.ViewInteraction or() {
<add> public Unfinished.And.ViewInteraction and() {
<ide> return new Unfinished().new And().new ViewInteraction();
<ide> }
<ide> } |
|
Java | apache-2.0 | dfe78eab99c25d4cc897a304d35eaece38b2511a | 0 | wasn-lab/visual-positioning,wasn-lab/visual-positioning,wasn-lab/visual-positioning,wasn-lab/visual-positioning,wasn-lab/visual-positioning,wasn-lab/visual-positioning,wasn-lab/visual-positioning,wasn-lab/visual-positioning | /*
* Copyright (C) 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.client.android;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.google.zxing.ResultMetadataType;
import com.google.zxing.ResultPoint;
import com.google.zxing.client.android.camera.CameraManager;
import com.google.zxing.client.android.history.HistoryActivity;
import com.google.zxing.client.android.history.HistoryItem;
import com.google.zxing.client.android.history.HistoryManager;
import com.google.zxing.client.android.result.ResultButtonListener;
import com.google.zxing.client.android.result.ResultHandler;
import com.google.zxing.client.android.result.ResultHandlerFactory;
import com.google.zxing.client.android.result.supplement.SupplementalInfoRetriever;
import com.google.zxing.client.android.share.ShareActivity;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.ClipboardManager;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.IOException;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import com.musicg.math.statistics.StandardDeviation;
/**
* This activity opens the camera and does the actual scanning on a background thread. It draws a
* viewfinder to help the user place the barcode correctly, shows feedback as the image processing
* is happening, and then overlays the results when a scan is successful.
*
* @author [email protected] (Daniel Switkin)
* @author Sean Owen
*/
public final class CaptureActivity extends Activity implements SurfaceHolder.Callback, SensorEventListener, LocationListener {
private static final String TAG = CaptureActivity.class.getSimpleName();
private static final long DEFAULT_INTENT_RESULT_DURATION_MS = 1500L;
private static final long BULK_MODE_SCAN_DELAY_MS = 1000L;
private static final String PACKAGE_NAME = "com.google.zxing.client.android";
private static final String PRODUCT_SEARCH_URL_PREFIX = "http://www.google";
private static final String PRODUCT_SEARCH_URL_SUFFIX = "/m/products/scan";
private static final String[] ZXING_URLS = { "http://zxing.appspot.com/scan", "zxing://scan/" };
public static final int HISTORY_REQUEST_CODE = 0x0000bacc;
private static final Set<ResultMetadataType> DISPLAYABLE_METADATA_TYPES =
EnumSet.of(ResultMetadataType.ISSUE_NUMBER,
ResultMetadataType.SUGGESTED_PRICE,
ResultMetadataType.ERROR_CORRECTION_LEVEL,
ResultMetadataType.POSSIBLE_COUNTRY);
private CameraManager cameraManager;
private CaptureActivityHandler handler;
private Result savedResultToShow;
private ViewfinderView viewfinderView;
private TextView statusView;
private View resultView;
private Result lastResult;
private boolean hasSurface;
private boolean copyToClipboard;
private IntentSource source;
private String sourceUrl;
private ScanFromWebPageManager scanFromWebPageManager;
private Collection<BarcodeFormat> decodeFormats;
private String characterSet;
private HistoryManager historyManager;
private InactivityTimer inactivityTimer;
private BeepManager beepManager;
private AmbientLightManager ambientLightManager;
//for sensors define
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private Sensor mMagneticField;
private Sensor mGyroscope;
private float[] accelerometer_values;
private float[] magnitude_values;
// orientation angles from accel and magnet
private float[] accMagOrientation = new float[3];
// final orientation angles from sensor fusion
private float[] fusedOrientation = new float[3];
private double[] magVpsAxis = new double[3];
private double[] fusVpsAxis = new double[3];
private double[] gpsAxis = new double[3];
public static final float EPSILON = 0.000000001f;
private static final float NS2S = 1.0f / 1000000000.0f;
private float timestamp;
private boolean initState = true;
// angular speeds from gyro
private float[] gyro = new float[3];
// rotation matrix from gyro data
private float[] gyroMatrix = new float[9];
// orientation angles from gyro matrix
private float[] gyroOrientation = new float[3];
//for fusion
public static final int TIME_CONSTANT = 300; //original:30
public static final float FILTER_COEFFICIENT = 0.50f;
public static final float FILTER_COEFFICIENT_AZIMUTH = 0.98f;
private Timer fuseTimer = new Timer();
//for GPS
private LocationManager locationManager; // The minimum distance to change Updates in meters
private Location lastLocation;
private static final double centerLatitude = 24.967185;
private static final double centerLongitude = 121.187019;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // no limit
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000; // 1 second
private float finalDistance = 0;
ViewfinderView getViewfinderView() {
return viewfinderView;
}
public Handler getHandler() {
return handler;
}
CameraManager getCameraManager() {
return cameraManager;
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Log.w("zxing", "onCreate");
//for sensors
// initialise gyroMatrix with identity matrix
gyroMatrix[0] = 1.0f; gyroMatrix[1] = 0.0f; gyroMatrix[2] = 0.0f;
gyroMatrix[3] = 0.0f; gyroMatrix[4] = 1.0f; gyroMatrix[5] = 0.0f;
gyroMatrix[6] = 0.0f; gyroMatrix[7] = 0.0f; gyroMatrix[8] = 1.0f;
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mMagneticField = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
mGyroscope = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
// wait for one second until gyroscope and magnetometer/accelerometer
// data is initialised then scedule the complementary filter task
fuseTimer.scheduleAtFixedRate(new calculateFusedOrientationTask(), 5000, TIME_CONSTANT);
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.capture);
hasSurface = false;
historyManager = new HistoryManager(this);
historyManager.trimHistory();
inactivityTimer = new InactivityTimer(this);
beepManager = new BeepManager(this);
ambientLightManager = new AmbientLightManager(this);
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
showHelpOnFirstLaunch();
}
@Override
protected void onResume() {
super.onResume();
Log.w("zxing", "onResume");
//for sensors
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(this, mMagneticField, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(this, mGyroscope, SensorManager.SENSOR_DELAY_FASTEST);
//for Gyroscope
initState = true;
//for GPS
locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
}
// CameraManager must be initialized here, not in onCreate(). This is necessary because we don't
// want to open the camera driver and measure the screen size if we're going to show the help on
// first launch. That led to bugs where the scanning rectangle was the wrong size and partially
// off screen.
cameraManager = new CameraManager(getApplication());
viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
viewfinderView.setCameraManager(cameraManager);
viewfinderView.setCaptureActivity(this);
resultView = findViewById(R.id.result_view);
statusView = (TextView) findViewById(R.id.status_view);
handler = null;
lastResult = null;
resetStatusView();
SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
SurfaceHolder surfaceHolder = surfaceView.getHolder();
if (hasSurface) {
// The activity was paused but not stopped, so the surface still exists. Therefore
// surfaceCreated() won't be called, so init the camera here.
initCamera(surfaceHolder);
} else {
// Install the callback and wait for surfaceCreated() to init the camera.
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
beepManager.updatePrefs();
ambientLightManager.start(cameraManager);
inactivityTimer.onResume();
Intent intent = getIntent();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
copyToClipboard = prefs.getBoolean(PreferencesActivity.KEY_COPY_TO_CLIPBOARD, true)
&& (intent == null || intent.getBooleanExtra(Intents.Scan.SAVE_HISTORY, true));
source = IntentSource.NONE;
decodeFormats = null;
characterSet = null;
if (intent != null) {
String action = intent.getAction();
String dataString = intent.getDataString();
if (Intents.Scan.ACTION.equals(action)) {
// Scan the formats the intent requested, and return the result to the calling activity.
source = IntentSource.NATIVE_APP_INTENT;
decodeFormats = DecodeFormatManager.parseDecodeFormats(intent);
if (intent.hasExtra(Intents.Scan.WIDTH) && intent.hasExtra(Intents.Scan.HEIGHT)) {
int width = intent.getIntExtra(Intents.Scan.WIDTH, 0);
int height = intent.getIntExtra(Intents.Scan.HEIGHT, 0);
if (width > 0 && height > 0) {
cameraManager.setManualFramingRect(width, height);
}
}
String customPromptMessage = intent.getStringExtra(Intents.Scan.PROMPT_MESSAGE);
if (customPromptMessage != null) {
statusView.setText(customPromptMessage);
}
} else if (dataString != null &&
dataString.contains(PRODUCT_SEARCH_URL_PREFIX) &&
dataString.contains(PRODUCT_SEARCH_URL_SUFFIX)) {
// Scan only products and send the result to mobile Product Search.
source = IntentSource.PRODUCT_SEARCH_LINK;
sourceUrl = dataString;
decodeFormats = DecodeFormatManager.PRODUCT_FORMATS;
} else if (isZXingURL(dataString)) {
// Scan formats requested in query string (all formats if none specified).
// If a return URL is specified, send the results there. Otherwise, handle it ourselves.
source = IntentSource.ZXING_LINK;
sourceUrl = dataString;
Uri inputUri = Uri.parse(dataString);
scanFromWebPageManager = new ScanFromWebPageManager(inputUri);
decodeFormats = DecodeFormatManager.parseDecodeFormats(inputUri);
}
characterSet = intent.getStringExtra(Intents.Scan.CHARACTER_SET);
}
}
private static boolean isZXingURL(String dataString) {
if (dataString == null) {
return false;
}
for (String url : ZXING_URLS) {
if (dataString.startsWith(url)) {
return true;
}
}
return false;
}
@Override
protected void onPause() {
Log.w("zxing", "onPause");
//pause GPS listener
if(locationManager != null){
locationManager.removeUpdates(this);
}
if (handler != null) {
handler.quitSynchronously();
handler = null;
}
inactivityTimer.onPause();
ambientLightManager.stop();
cameraManager.closeDriver();
if (!hasSurface) {
SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
SurfaceHolder surfaceHolder = surfaceView.getHolder();
surfaceHolder.removeCallback(this);
}
super.onPause();
//for sensors
mSensorManager.unregisterListener(this);
}
@Override
protected void onDestroy() {
Log.w("zxing", "onDestroy");
inactivityTimer.shutdown();
super.onDestroy();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (source == IntentSource.NATIVE_APP_INTENT) {
setResult(RESULT_CANCELED);
finish();
return true;
}
if ((source == IntentSource.NONE || source == IntentSource.ZXING_LINK) && lastResult != null) {
restartPreviewAfterDelay(0L);
return true;
}
break;
case KeyEvent.KEYCODE_FOCUS:
case KeyEvent.KEYCODE_CAMERA:
// Handle these events so they don't launch the Camera app
return true;
// Use volume up/down to turn on light
case KeyEvent.KEYCODE_VOLUME_DOWN:
cameraManager.setTorch(false);
return true;
case KeyEvent.KEYCODE_VOLUME_UP:
cameraManager.setTorch(true);
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.capture, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
switch (item.getItemId()) {
case R.id.menu_share:
intent.setClassName(this, ShareActivity.class.getName());
startActivity(intent);
break;
case R.id.menu_history:
intent.setClassName(this, HistoryActivity.class.getName());
startActivityForResult(intent, HISTORY_REQUEST_CODE);
break;
case R.id.menu_settings:
intent.setClassName(this, PreferencesActivity.class.getName());
startActivity(intent);
break;
case R.id.menu_help:
intent.setClassName(this, HelpActivity.class.getName());
startActivity(intent);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (resultCode == RESULT_OK) {
if (requestCode == HISTORY_REQUEST_CODE) {
int itemNumber = intent.getIntExtra(Intents.History.ITEM_NUMBER, -1);
if (itemNumber >= 0) {
HistoryItem historyItem = historyManager.buildHistoryItem(itemNumber);
decodeOrStoreSavedBitmap(null, historyItem.getResult());
}
}
}
}
private void decodeOrStoreSavedBitmap(Bitmap bitmap, Result result) {
// Bitmap isn't used yet -- will be used soon
if (handler == null) {
savedResultToShow = result;
} else {
if (result != null) {
savedResultToShow = result;
}
if (savedResultToShow != null) {
Message message = Message.obtain(handler, R.id.decode_succeeded, savedResultToShow);
handler.sendMessage(message);
}
savedResultToShow = null;
}
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (holder == null) {
Log.e(TAG, "*** WARNING *** surfaceCreated() gave us a null surface!");
}
if (!hasSurface) {
hasSurface = true;
initCamera(holder);
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
hasSurface = false;
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
/**
* A valid barcode has been found, so give an indication of success and show the results.
*
* @param rawResult The contents of the barcode.
* @param scaleFactor amount by which thumbnail was scaled
* @param barcode A greyscale bitmap of the camera data which was decoded.
*/
public void handleDecode(Result rawResult, Bitmap barcode, float scaleFactor) {
inactivityTimer.onActivity();
lastResult = rawResult;
ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
boolean fromLiveScan = barcode != null;
viewfinderView.addSuccessResult(rawResult);
if (fromLiveScan) {
if(!initState) {
//collect 2 point in the same place.
positionData newData = new positionData();
newData.orientation = fusedOrientation.clone();
newData.sasPosition = viewfinderView.sasRelativePosition();
positionItems.add(newData);
if(positionItems.size() == sampleNums)
{
//start calculate optimize angle value
if(positionItems.size() > 1) { //do compensation only have at least 2 sample
float bestCompensation = getCompensation();
fusedOrientation[0] = fusedOrientation[0] + bestCompensation;
//A~cosPZ۰~
}
magVpsAxis = getVps(accMagOrientation, positionItems.get(sampleNums-1).sasPosition).clone();
fusVpsAxis = getVps(fusedOrientation, positionItems.get(sampleNums-1).sasPosition).clone();
gpsAxis = positionItems.get(sampleNums-1).sasPosition.clone();
historyManager.addHistoryItem(magVpsAxis, magVpsAxis, gpsAxis, accMagOrientation.clone(), finalDistance, rawResult, resultHandler);
positionItems.clear();
// Then not from history, so beep/vibrate and we have an image to draw on
beepManager.playBeepSoundAndVibrate();
}
}
drawResultPoints(barcode, scaleFactor, rawResult);
}
switch (source) {
case NATIVE_APP_INTENT:
case PRODUCT_SEARCH_LINK:
handleDecodeExternally(rawResult, resultHandler, barcode);
break;
case ZXING_LINK:
if (scanFromWebPageManager == null || !scanFromWebPageManager.isScanFromWebPage()) {
handleDecodeInternally(rawResult, resultHandler, barcode);
} else {
handleDecodeExternally(rawResult, resultHandler, barcode);
}
break;
case NONE:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (fromLiveScan && prefs.getBoolean(PreferencesActivity.KEY_BULK_MODE, false)) {
// Wait a moment or else it will scan the same barcode continuously about 3 times
restartPreviewAfterDelay(BULK_MODE_SCAN_DELAY_MS);
} else {
handleDecodeInternally(rawResult, resultHandler, barcode);
}
break;
}
}
/*
class positionData {
public float[] orientation;
public double[] sasPosition;
}
private List<positionData> positionItems;
//եvɱסAgTw]SASVOA]NOu]ӪV
double radDiff = finalOrientation[1] - sasAzimuth; //ɱר
sasPosition[2] = sasPosition[2] / (float)Math.cos(radDiff);
finalDistance = sasPosition[2];
*/
//for correct degree error
class positionData {
public float[] orientation;
public double[] sasPosition;
}
private List<positionData> positionItems = new ArrayList<positionData>();
private static final int minDegree = -89;
private static final int maxDegree = 90;
private double gapArray[] = new double[180];
private static final int sampleNums = 1;
private float getCompensation() {
for(int i=0; i < 180; i++) {
gapArray[i] = getStandardDeviation(i+minDegree);
//Log.w("zxing", "gapArray: " + gapArray[i]);
}
int result = findBestCompensation(maxDegree-10); //means 0 degree
result = result + minDegree;
Log.w("zxing", "Compensation:" + result);
return (float)Math.toRadians(result);
}
private int findBestCompensation(int compensation) {
switch (chooseBetterCompensation(compensation, compensation+1)) {
case 1:
if(-1 == chooseBetterCompensation(compensation, compensation-1)) {
if(compensation -1 == 0) {
//bound
compensation = compensation - 1;
break;
} else {
//compensation-1 is smaller
return findBestCompensation(compensation-1);
}
} else {
//compensation is smallest
break;
}
case -1:
if(compensation+1 == 179) {
//bound
compensation = compensation + 1;
break;
}
else {
//compensation + 1 is smaller
return findBestCompensation(compensation+1);
}
case 0:
//equal
break;
}
return compensation; //if case 0 or out of bound
}
/**
* Try to find better compensation from 2 different angle
* @param compensationA
* @param compensationB
* @return 1 means compensationA is better. -1 means compensationB is better. 0 means equal.
*/
private int chooseBetterCompensation(int compensationA, int compensationB) {
if(gapArray[compensationA] < gapArray[compensationB]) {
return 1;
} else if (gapArray[compensationA] == gapArray[compensationB]) {
return 0;
} else {
return -1;
}
}
/**
* Calculate distance between SAS and camera.
* @param compensation An compensation for angle.
* @return
*/
private double getStandardDeviation(int compensation) {
positionData data[] = new positionData[sampleNums];
double tiltAngle[] = new double[sampleNums];
double distance[] = new double[sampleNums];
for(int i=0; i < sampleNums; i++) {
data[i] = positionItems.get(i);
tiltAngle[i] = data[i].orientation[0] + compensation; //not yet rotate to landscape mode. So azimuth is orientation[0]
distance[i] = data[i].sasPosition[2] / Math.cos(Math.toRadians(tiltAngle[i]));
}
StandardDeviation stdDeviation = new StandardDeviation(distance);
return stdDeviation.evaluate();
//return Math.abs(distance[0] - distance[1]);
}
public float[] getOrientationForSas() {
float orientationForSas[] = rotateToLandscape(accMagOrientation.clone());
orientationForSas[1] = orientationForSas[1] - centerAzimuth - (float)Math.PI/2;
return orientationForSas;
}
private float[] rotateToLandscape(float[] beforeRotate) {
float[] finalOrientation = new float[3];
finalOrientation[0] = beforeRotate[1]; //horizontal balance degree. clockwise is positive
if(beforeRotate[0] < Math.PI / 2) {
finalOrientation[1] = (beforeRotate[0] + (float)(Math.PI * 0.5)); //compass degree. clockwise is positive
}
else {
finalOrientation[1] = beforeRotate[0] - (float)(Math.PI * 1.5); //compass degree. clockwise is positive
}
if(beforeRotate[0] < Math.PI / 2) {
finalOrientation[2] = (beforeRotate[2] + (float)(Math.PI * 0.5)); //vertical degree. clockwise is positive
}
else {
finalOrientation[2] = beforeRotate[2] - (float)(Math.PI * 1.5); //vertical degree. clockwise is positive
}
return finalOrientation;
}
private double[] getVps(float[] sourceOrientation, double sasPosition[]) {
double vpsAxis[] = new double[3];
//fine tune values for landscape mode
float[] finalOrientation = rotateToLandscape(sourceOrientation.clone());
//Rotate Y horizontal balance degree
double x1 = sasPosition[0] * Math.cos(finalOrientation[0]) + sasPosition[1] * Math.sin(finalOrientation[0]);
double y1 = sasPosition[2];
double z1 = -sasPosition[0] * Math.sin(finalOrientation[0]) + sasPosition[1] * Math.cos(finalOrientation[0]);
//Rotate X vertical degree
double x2 = x1;
double y2 = y1 * Math.cos(finalOrientation[2] - sasPosition[4]) - z1 * Math.sin(finalOrientation[2] - sasPosition[4]);
double z2 = y1 * Math.sin(finalOrientation[2]) - z1 * Math.cos(finalOrientation[2]);
//Rotate Z compass degree
double x3 = x2 * Math.cos(-finalOrientation[1]) - y2 * Math.sin(-finalOrientation[1]);
double y3 = x2 * Math.sin(-finalOrientation[1]) + y2 * Math.cos(-finalOrientation[1]);
//double y3 = x2 * Math.sin(-finalOrientation[1] + sasPosition[3]) + y2 * Math.cos(-finalOrientation[1] + sasPosition[3]);
double z3 = z2;
//Rotate to world coordinate and convert unit to meters
vpsAxis[0] = -x3 / 100; //mapping to longitudeg
vpsAxis[1] = -y3 / 100; //mapping to latituden
vpsAxis[2] = z3 / 100; //mapping to altitude
return vpsAxis;
}
/**
* Superimpose a line for 1D or dots for 2D to highlight the key features of the barcode.
* bravesheng: This funciton is only for thumbnail view. not for live view. So draw line in this bitmap will have no effect!
* @param barcode A bitmap of the captured image.
* @param scaleFactor amount by which thumbnail was scaled
* @param rawResult The decoded results which contains the points to draw.
*/
private void drawResultPoints(Bitmap barcode, float scaleFactor, Result rawResult) {
ResultPoint[] points = rawResult.getResultPoints();
if (points != null && points.length > 0) {
Canvas canvas = new Canvas(barcode);
Paint paint = new Paint();
paint.setColor(getResources().getColor(R.color.result_points));
if (points.length == 2) {
paint.setStrokeWidth(4.0f);
drawLine(canvas, paint, points[0], points[1], scaleFactor);
} else if (points.length == 4 &&
(rawResult.getBarcodeFormat() == BarcodeFormat.UPC_A ||
rawResult.getBarcodeFormat() == BarcodeFormat.EAN_13)) {
// Hacky special case -- draw two lines, for the barcode and metadata
drawLine(canvas, paint, points[0], points[1], scaleFactor);
drawLine(canvas, paint, points[2], points[3], scaleFactor);
} else {
paint.setStrokeWidth(10.0f);
for (ResultPoint point : points) {
canvas.drawPoint(scaleFactor * point.getX(), scaleFactor * point.getY(), paint);
}
}
}
}
private static void drawLine(Canvas canvas, Paint paint, ResultPoint a, ResultPoint b, float scaleFactor) {
canvas.drawLine(scaleFactor * a.getX(),
scaleFactor * a.getY(),
scaleFactor * b.getX(),
scaleFactor * b.getY(),
paint);
}
// Put up our own UI for how to handle the decoded contents.
private void handleDecodeInternally(Result rawResult, ResultHandler resultHandler, Bitmap barcode) {
statusView.setVisibility(View.GONE);
viewfinderView.setVisibility(View.GONE);
resultView.setVisibility(View.VISIBLE);
ImageView barcodeImageView = (ImageView) findViewById(R.id.barcode_image_view);
if (barcode == null) {
barcodeImageView.setImageBitmap(BitmapFactory.decodeResource(getResources(),
R.drawable.launcher_icon));
} else {
barcodeImageView.setImageBitmap(barcode);
}
TextView formatTextView = (TextView) findViewById(R.id.format_text_view);
formatTextView.setText(rawResult.getBarcodeFormat().toString());
TextView typeTextView = (TextView) findViewById(R.id.type_text_view);
typeTextView.setText(resultHandler.getType().toString());
DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
String formattedTime = formatter.format(new Date(rawResult.getTimestamp()));
TextView timeTextView = (TextView) findViewById(R.id.time_text_view);
timeTextView.setText(formattedTime);
TextView metaTextView = (TextView) findViewById(R.id.meta_text_view);
View metaTextViewLabel = findViewById(R.id.meta_text_view_label);
metaTextView.setVisibility(View.GONE);
metaTextViewLabel.setVisibility(View.GONE);
Map<ResultMetadataType,Object> metadata = rawResult.getResultMetadata();
if (metadata != null) {
StringBuilder metadataText = new StringBuilder(20);
for (Map.Entry<ResultMetadataType,Object> entry : metadata.entrySet()) {
if (DISPLAYABLE_METADATA_TYPES.contains(entry.getKey())) {
metadataText.append(entry.getValue()).append('\n');
}
}
if (metadataText.length() > 0) {
metadataText.setLength(metadataText.length() - 1);
metaTextView.setText(metadataText);
metaTextView.setVisibility(View.VISIBLE);
metaTextViewLabel.setVisibility(View.VISIBLE);
}
}
TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view);
CharSequence displayContents = resultHandler.getDisplayContents();
contentsTextView.setText(displayContents);
// Crudely scale between 22 and 32 -- bigger font for shorter text
int scaledSize = Math.max(22, 32 - displayContents.length() / 4);
contentsTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, scaledSize);
TextView supplementTextView = (TextView) findViewById(R.id.contents_supplement_text_view);
supplementTextView.setText("");
supplementTextView.setOnClickListener(null);
if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(
PreferencesActivity.KEY_SUPPLEMENTAL, true)) {
SupplementalInfoRetriever.maybeInvokeRetrieval(supplementTextView,
resultHandler.getResult(),
historyManager,
this);
}
int buttonCount = resultHandler.getButtonCount();
ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view);
buttonView.requestFocus();
for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) {
TextView button = (TextView) buttonView.getChildAt(x);
if (x < buttonCount) {
button.setVisibility(View.VISIBLE);
button.setText(resultHandler.getButtonText(x));
button.setOnClickListener(new ResultButtonListener(resultHandler, x));
} else {
button.setVisibility(View.GONE);
}
}
if (copyToClipboard && !resultHandler.areContentsSecure()) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
if (displayContents != null) {
try {
clipboard.setText(displayContents);
} catch (NullPointerException npe) {
// Some kind of bug inside the clipboard implementation, not due to null input
Log.w(TAG, "Clipboard bug", npe);
}
}
}
}
// Briefly show the contents of the barcode, then handle the result outside Barcode Scanner.
private void handleDecodeExternally(Result rawResult, ResultHandler resultHandler, Bitmap barcode) {
if (barcode != null) {
viewfinderView.drawResultBitmap(barcode);
}
long resultDurationMS;
if (getIntent() == null) {
resultDurationMS = DEFAULT_INTENT_RESULT_DURATION_MS;
} else {
resultDurationMS = getIntent().getLongExtra(Intents.Scan.RESULT_DISPLAY_DURATION_MS,
DEFAULT_INTENT_RESULT_DURATION_MS);
}
// Since this message will only be shown for a second, just tell the user what kind of
// barcode was found (e.g. contact info) rather than the full contents, which they won't
// have time to read.
if (resultDurationMS > 0) {
statusView.setText(getString(resultHandler.getDisplayTitle()));
}
if (copyToClipboard && !resultHandler.areContentsSecure()) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
CharSequence text = resultHandler.getDisplayContents();
if (text != null) {
try {
clipboard.setText(text);
} catch (NullPointerException npe) {
// Some kind of bug inside the clipboard implementation, not due to null input
Log.w(TAG, "Clipboard bug", npe);
}
}
}
if (source == IntentSource.NATIVE_APP_INTENT) {
// Hand back whatever action they requested - this can be changed to Intents.Scan.ACTION when
// the deprecated intent is retired.
Intent intent = new Intent(getIntent().getAction());
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
intent.putExtra(Intents.Scan.RESULT, rawResult.toString());
intent.putExtra(Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString());
byte[] rawBytes = rawResult.getRawBytes();
if (rawBytes != null && rawBytes.length > 0) {
intent.putExtra(Intents.Scan.RESULT_BYTES, rawBytes);
}
Map<ResultMetadataType,?> metadata = rawResult.getResultMetadata();
if (metadata != null) {
if (metadata.containsKey(ResultMetadataType.UPC_EAN_EXTENSION)) {
intent.putExtra(Intents.Scan.RESULT_UPC_EAN_EXTENSION,
metadata.get(ResultMetadataType.UPC_EAN_EXTENSION).toString());
}
Integer orientation = (Integer) metadata.get(ResultMetadataType.ORIENTATION);
if (orientation != null) {
intent.putExtra(Intents.Scan.RESULT_ORIENTATION, orientation.intValue());
}
String ecLevel = (String) metadata.get(ResultMetadataType.ERROR_CORRECTION_LEVEL);
if (ecLevel != null) {
intent.putExtra(Intents.Scan.RESULT_ERROR_CORRECTION_LEVEL, ecLevel);
}
Iterable<byte[]> byteSegments = (Iterable<byte[]>) metadata.get(ResultMetadataType.BYTE_SEGMENTS);
if (byteSegments != null) {
int i = 0;
for (byte[] byteSegment : byteSegments) {
intent.putExtra(Intents.Scan.RESULT_BYTE_SEGMENTS_PREFIX + i, byteSegment);
i++;
}
}
}
sendReplyMessage(R.id.return_scan_result, intent, resultDurationMS);
} else if (source == IntentSource.PRODUCT_SEARCH_LINK) {
// Reformulate the URL which triggered us into a query, so that the request goes to the same
// TLD as the scan URL.
int end = sourceUrl.lastIndexOf("/scan");
String replyURL = sourceUrl.substring(0, end) + "?q=" + resultHandler.getDisplayContents() + "&source=zxing";
sendReplyMessage(R.id.launch_product_query, replyURL, resultDurationMS);
} else if (source == IntentSource.ZXING_LINK) {
if (scanFromWebPageManager != null && scanFromWebPageManager.isScanFromWebPage()) {
String replyURL = scanFromWebPageManager.buildReplyURL(rawResult, resultHandler);
sendReplyMessage(R.id.launch_product_query, replyURL, resultDurationMS);
}
}
}
private void sendReplyMessage(int id, Object arg, long delayMS) {
Message message = Message.obtain(handler, id, arg);
if (delayMS > 0L) {
handler.sendMessageDelayed(message, delayMS);
} else {
handler.sendMessage(message);
}
}
/**
* We want the help screen to be shown automatically the first time a new version of the app is
* run. The easiest way to do this is to check android:versionCode from the manifest, and compare
* it to a value stored as a preference.
*/
private boolean showHelpOnFirstLaunch() {
try {
PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME, 0);
int currentVersion = info.versionCode;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int lastVersion = prefs.getInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, 0);
if (currentVersion > lastVersion) {
prefs.edit().putInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, currentVersion).commit();
Intent intent = new Intent(this, HelpActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
// Show the default page on a clean install, and the what's new page on an upgrade.
String page = lastVersion == 0 ? HelpActivity.DEFAULT_PAGE : HelpActivity.WHATS_NEW_PAGE;
intent.putExtra(HelpActivity.REQUESTED_PAGE_KEY, page);
startActivity(intent);
return true;
}
} catch (PackageManager.NameNotFoundException e) {
Log.w(TAG, e);
}
return false;
}
private void initCamera(SurfaceHolder surfaceHolder) {
if (surfaceHolder == null) {
throw new IllegalStateException("No SurfaceHolder provided");
}
if (cameraManager.isOpen()) {
Log.w(TAG, "initCamera() while already open -- late SurfaceView callback?");
return;
}
try {
cameraManager.openDriver(surfaceHolder);
// Creating the handler starts the preview, which can also throw a RuntimeException.
if (handler == null) {
handler = new CaptureActivityHandler(this, decodeFormats, characterSet, cameraManager);
}
decodeOrStoreSavedBitmap(null, null);
} catch (IOException ioe) {
Log.w(TAG, ioe);
displayFrameworkBugMessageAndExit();
} catch (RuntimeException e) {
// Barcode Scanner has seen crashes in the wild of this variety:
// java.?lang.?RuntimeException: Fail to connect to camera service
Log.w(TAG, "Unexpected error initializing camera", e);
displayFrameworkBugMessageAndExit();
}
}
private void displayFrameworkBugMessageAndExit() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.app_name));
builder.setMessage(getString(R.string.msg_camera_framework_bug));
builder.setPositiveButton(R.string.button_ok, new FinishListener(this));
builder.setOnCancelListener(new FinishListener(this));
builder.show();
}
public void restartPreviewAfterDelay(long delayMS) {
if (handler != null) {
handler.sendEmptyMessageDelayed(R.id.restart_preview, delayMS);
}
resetStatusView();
}
private String prepareInfoString() {
//Change to position for debug
float tmpOrientation[] = new float[3];
//rotate to landscape
tmpOrientation = rotateToLandscape(accMagOrientation.clone());
String print = String.format("magVpsAxis:%8.2f %8.2f %8.2f", magVpsAxis[0], magVpsAxis[1], magVpsAxis[2])
+ String.format("\ngpsAxis:%8.2f %8.2f %8.2f", gpsAxis[0], gpsAxis[1], gpsAxis[2])
+ String.format("\nMAG:%8.2f %8.2f %8.2f", tmpOrientation[0]*180/Math.PI, tmpOrientation[1]*180/Math.PI, tmpOrientation[2]*180/Math.PI);
//rotate to landscape
tmpOrientation = rotateToLandscape(gyroOrientation.clone());
print = print + String.format("\nGYR:%8.2f %8.2f %8.2f", tmpOrientation[0]*180/Math.PI, tmpOrientation[1]*180/Math.PI, tmpOrientation[2]*180/Math.PI);
tmpOrientation = rotateToLandscape(fusedOrientation.clone());
print = print + String.format("\nFUS:%8.2f %8.2f %8.2f", tmpOrientation[0]*180/Math.PI, tmpOrientation[1]*180/Math.PI, tmpOrientation[2]*180/Math.PI);
return print;
}
//bravesheng: Can add information here. Will display on live screen.
private void resetStatusView() {
resultView.setVisibility(View.GONE);
statusView.setTextSize(20);
//statusView.setTextColor(android.graphics.Color.BLUE);
statusView.setShadowLayer((float)Math.PI, 2, 2, 0xFF000000);
statusView.setText(prepareInfoString());
statusView.setVisibility(View.VISIBLE);
viewfinderView.setVisibility(View.VISIBLE);
lastResult = null;
//Log.w("zxing",print);
}
public void drawViewfinder() {
viewfinderView.drawViewfinder();
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
accelerometer_values = (float[]) event.values.clone();
calculateAccMagOrientation();
}
else if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
magnitude_values = (float[]) event.values.clone();
}
else if(event.sensor.getType() == Sensor.TYPE_GYROSCOPE) {
gyroFunction(event);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (prefs.getBoolean(PreferencesActivity.KEY_BULK_MODE, true)) {
resetStatusView();
}
}
}
// calculates orientation angles from accelerometer and magnetometer output
public void calculateAccMagOrientation() {
float[] rotationMatrix = new float[9];
if((accelerometer_values != null) && (magnitude_values != null)) {
if(SensorManager.getRotationMatrix(rotationMatrix, null, accelerometer_values, magnitude_values)) {
SensorManager.getOrientation(rotationMatrix, accMagOrientation);
accMagOrientation[0] = accMagOrientation[0] - shiftRad;
}
}
}
// This function is borrowed from the Android reference
// at http://developer.android.com/reference/android/hardware/SensorEvent.html#values
// It calculates a rotation vector from the gyroscope angular speed values.
private void getRotationVectorFromGyro(float[] gyroValues,
float[] deltaRotationVector,
float timeFactor)
{
float[] normValues = new float[3];
// Calculate the angular speed of the sample
float omegaMagnitude =
(float)Math.sqrt(gyroValues[0] * gyroValues[0] +
gyroValues[1] * gyroValues[1] +
gyroValues[2] * gyroValues[2]);
// Normalize the rotation vector if it's big enough to get the axis
if(omegaMagnitude > EPSILON) {
normValues[0] = gyroValues[0] / omegaMagnitude;
normValues[1] = gyroValues[1] / omegaMagnitude;
normValues[2] = gyroValues[2] / omegaMagnitude;
}
// Integrate around this axis with the angular speed by the timestep
// in order to get a delta rotation from this sample over the timestep
// We will convert this axis-angle representation of the delta rotation
// into a quaternion before turning it into the rotation matrix.
float thetaOverTwo = omegaMagnitude * timeFactor;
float sinThetaOverTwo = (float)Math.sin(thetaOverTwo);
float cosThetaOverTwo = (float)Math.cos(thetaOverTwo);
deltaRotationVector[0] = sinThetaOverTwo * normValues[0];
deltaRotationVector[1] = sinThetaOverTwo * normValues[1];
deltaRotationVector[2] = sinThetaOverTwo * normValues[2];
deltaRotationVector[3] = cosThetaOverTwo;
}
// This function performs the integration of the gyroscope data.
// It writes the gyroscope based orientation into gyroOrientation.
public void gyroFunction(SensorEvent event) {
// don't start until first accelerometer/magnetometer orientation has been acquired
if (accMagOrientation == null)
return;
// waiting for gyroscope initialize done in calculateFusedOrientationTask
if(initState) {
return;
}
// copy the new gyro values into the gyro array
// convert the raw gyro data into a rotation vector
float[] deltaVector = new float[4];
if(timestamp != 0) {
final float dT = (event.timestamp - timestamp) * NS2S;
System.arraycopy(event.values, 0, gyro, 0, 3);
getRotationVectorFromGyro(gyro, deltaVector, dT / 2.0f);
}
// measurement done, save current time for next interval
timestamp = event.timestamp;
// convert rotation vector into rotation matrix
float[] deltaMatrix = new float[9];
SensorManager.getRotationMatrixFromVector(deltaMatrix, deltaVector);
// apply the new rotation interval on the gyroscope based rotation matrix
gyroMatrix = matrixMultiplication(gyroMatrix, deltaMatrix);
// get the gyroscope based orientation from the rotation matrix
SensorManager.getOrientation(gyroMatrix, gyroOrientation);
}
private float[] getRotationMatrixFromOrientation(float[] o) {
float[] xM = new float[9];
float[] yM = new float[9];
float[] zM = new float[9];
float sinX = (float)Math.sin(o[1]);
float cosX = (float)Math.cos(o[1]);
float sinY = (float)Math.sin(o[2]);
float cosY = (float)Math.cos(o[2]);
float sinZ = (float)Math.sin(o[0]);
float cosZ = (float)Math.cos(o[0]);
// rotation about x-axis (pitch)
xM[0] = 1.0f; xM[1] = 0.0f; xM[2] = 0.0f;
xM[3] = 0.0f; xM[4] = cosX; xM[5] = sinX;
xM[6] = 0.0f; xM[7] = -sinX; xM[8] = cosX;
// rotation about y-axis (roll)
yM[0] = cosY; yM[1] = 0.0f; yM[2] = sinY;
yM[3] = 0.0f; yM[4] = 1.0f; yM[5] = 0.0f;
yM[6] = -sinY; yM[7] = 0.0f; yM[8] = cosY;
// rotation about z-axis (azimuth)
zM[0] = cosZ; zM[1] = sinZ; zM[2] = 0.0f;
zM[3] = -sinZ; zM[4] = cosZ; zM[5] = 0.0f;
zM[6] = 0.0f; zM[7] = 0.0f; zM[8] = 1.0f;
// rotation order is y, x, z (roll, pitch, azimuth)
float[] resultMatrix = matrixMultiplication(xM, yM);
resultMatrix = matrixMultiplication(zM, resultMatrix);
return resultMatrix;
}
private float[] matrixMultiplication(float[] A, float[] B) {
float[] result = new float[9];
result[0] = A[0] * B[0] + A[1] * B[3] + A[2] * B[6];
result[1] = A[0] * B[1] + A[1] * B[4] + A[2] * B[7];
result[2] = A[0] * B[2] + A[1] * B[5] + A[2] * B[8];
result[3] = A[3] * B[0] + A[4] * B[3] + A[5] * B[6];
result[4] = A[3] * B[1] + A[4] * B[4] + A[5] * B[7];
result[5] = A[3] * B[2] + A[4] * B[5] + A[5] * B[8];
result[6] = A[6] * B[0] + A[7] * B[3] + A[8] * B[6];
result[7] = A[6] * B[1] + A[7] * B[4] + A[8] * B[7];
result[8] = A[6] * B[2] + A[7] * B[5] + A[8] * B[8];
return result;
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
Log.w("zxing", "onAccuracyChanged: " + accuracy);
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub. On GPS location changed.
//Log.w("zxing", "onLocationChanged " + location.getLatitude() + " " + location.getLongitude());
lastLocation = location;
float[] results = new float[3];
Location.distanceBetween(centerLatitude, lastLocation.getLongitude(), lastLocation.getLatitude(), lastLocation.getLongitude(), results);
if( (int)results[1] == 0) {
//0 means bearing to north. Otherwise will be 180. Means bearing to south
gpsAxis[0] = results[0];
} else {
gpsAxis[0] = -results[0];
}
Location.distanceBetween(lastLocation.getLatitude(), centerLongitude, lastLocation.getLatitude(), lastLocation.getLongitude(), results);
if((int)results[1] == 89) {
//89 means bearing to east. Otherwise will be -89. Means bearing to west.
gpsAxis[1] = results[0];
} else {
gpsAxis[1] = -results[0];
}
gpsAxis[2] = (float)(150 - lastLocation.getAltitude());
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
Log.w("zxing", "onStatusChanged");
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Log.w("zxing", "onProviderEnabled");
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Log.w("zxing", "onProviderDisabled");
}
//Fusion Sensor
//private float centerAzimuth = (float)-Math.PI; //ܸۥ(]|եVAҥHO-PI)
private float centerAzimuth = (float)-Math.PI/2; //ܸۥ_(]|եVAҥHO-PI/2)
private float shiftRad = 0;
class calculateFusedOrientationTask extends TimerTask {
public void run() {
//initial Gyroscope data
if(initState) {
shiftRad = accMagOrientation[0] - centerAzimuth;
accMagOrientation[0] = accMagOrientation[0] - shiftRad;
gyroMatrix = getRotationMatrixFromOrientation(accMagOrientation);
System.arraycopy(accMagOrientation, 0, gyroOrientation, 0, 3);
initState = false;
}
float oneMinusCoeff = 1.0f - FILTER_COEFFICIENT;
float oneMinusCoeffAzimuth = 1.0f - FILTER_COEFFICIENT_AZIMUTH;
/*
* Fix for 179<--> -179transition problem:
* Check whether one of the two orientation angles (gyro or accMag) is negative while the other one is positive.
* If so, add 360(2 * math.PI) to the negative value, perform the sensor fusion, and remove the 360from the result
* if it is greater than 180 This stabilizes the output in positive-to-negative-transition cases.
*/
// azimuth
//fusedOrientation[0] = (float) -Math.PI;
if (gyroOrientation[0] < -0.5 * Math.PI && accMagOrientation[0] > 0.0) {
fusedOrientation[0] = (float) (FILTER_COEFFICIENT_AZIMUTH * (gyroOrientation[0] + 2.0 * Math.PI) + oneMinusCoeffAzimuth * accMagOrientation[0]);
fusedOrientation[0] -= (fusedOrientation[0] > Math.PI) ? 2.0 * Math.PI : 0;
}
else if (accMagOrientation[0] < -0.5 * Math.PI && gyroOrientation[0] > 0.0) {
fusedOrientation[0] = (float) (FILTER_COEFFICIENT_AZIMUTH * gyroOrientation[0] + oneMinusCoeffAzimuth * (accMagOrientation[0] + 2.0 * Math.PI));
fusedOrientation[0] -= (fusedOrientation[0] > Math.PI)? 2.0 * Math.PI : 0;
}
else {
fusedOrientation[0] = FILTER_COEFFICIENT_AZIMUTH * gyroOrientation[0] + oneMinusCoeffAzimuth * accMagOrientation[0];
}
// pitch
fusedOrientation[1] = accMagOrientation[1];
// roll
fusedOrientation[2] = accMagOrientation[2];
// overwrite gyro matrix and orientation with fused orientation
// to comensate gyro drift
gyroMatrix = getRotationMatrixFromOrientation(fusedOrientation);
System.arraycopy(fusedOrientation, 0, gyroOrientation, 0, 3);
}
}
}
| android/src/com/google/zxing/client/android/CaptureActivity.java | /*
* Copyright (C) 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.client.android;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.google.zxing.ResultMetadataType;
import com.google.zxing.ResultPoint;
import com.google.zxing.client.android.camera.CameraManager;
import com.google.zxing.client.android.history.HistoryActivity;
import com.google.zxing.client.android.history.HistoryItem;
import com.google.zxing.client.android.history.HistoryManager;
import com.google.zxing.client.android.result.ResultButtonListener;
import com.google.zxing.client.android.result.ResultHandler;
import com.google.zxing.client.android.result.ResultHandlerFactory;
import com.google.zxing.client.android.result.supplement.SupplementalInfoRetriever;
import com.google.zxing.client.android.share.ShareActivity;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.ClipboardManager;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.IOException;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import com.musicg.math.statistics.StandardDeviation;
/**
* This activity opens the camera and does the actual scanning on a background thread. It draws a
* viewfinder to help the user place the barcode correctly, shows feedback as the image processing
* is happening, and then overlays the results when a scan is successful.
*
* @author [email protected] (Daniel Switkin)
* @author Sean Owen
*/
public final class CaptureActivity extends Activity implements SurfaceHolder.Callback, SensorEventListener, LocationListener {
private static final String TAG = CaptureActivity.class.getSimpleName();
private static final long DEFAULT_INTENT_RESULT_DURATION_MS = 1500L;
private static final long BULK_MODE_SCAN_DELAY_MS = 1000L;
private static final String PACKAGE_NAME = "com.google.zxing.client.android";
private static final String PRODUCT_SEARCH_URL_PREFIX = "http://www.google";
private static final String PRODUCT_SEARCH_URL_SUFFIX = "/m/products/scan";
private static final String[] ZXING_URLS = { "http://zxing.appspot.com/scan", "zxing://scan/" };
public static final int HISTORY_REQUEST_CODE = 0x0000bacc;
private static final Set<ResultMetadataType> DISPLAYABLE_METADATA_TYPES =
EnumSet.of(ResultMetadataType.ISSUE_NUMBER,
ResultMetadataType.SUGGESTED_PRICE,
ResultMetadataType.ERROR_CORRECTION_LEVEL,
ResultMetadataType.POSSIBLE_COUNTRY);
private CameraManager cameraManager;
private CaptureActivityHandler handler;
private Result savedResultToShow;
private ViewfinderView viewfinderView;
private TextView statusView;
private View resultView;
private Result lastResult;
private boolean hasSurface;
private boolean copyToClipboard;
private IntentSource source;
private String sourceUrl;
private ScanFromWebPageManager scanFromWebPageManager;
private Collection<BarcodeFormat> decodeFormats;
private String characterSet;
private HistoryManager historyManager;
private InactivityTimer inactivityTimer;
private BeepManager beepManager;
private AmbientLightManager ambientLightManager;
//for sensors define
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private Sensor mMagneticField;
private Sensor mGyroscope;
private float[] accelerometer_values;
private float[] magnitude_values;
// orientation angles from accel and magnet
private float[] accMagOrientation = new float[3];
// final orientation angles from sensor fusion
private float[] fusedOrientation = new float[3];
private double[] magVpsAxis = new double[3];
private double[] fusVpsAxis = new double[3];
private double[] gpsAxis = new double[3];
public static final float EPSILON = 0.000000001f;
private static final float NS2S = 1.0f / 1000000000.0f;
private float timestamp;
private boolean initState = true;
// angular speeds from gyro
private float[] gyro = new float[3];
// rotation matrix from gyro data
private float[] gyroMatrix = new float[9];
// orientation angles from gyro matrix
private float[] gyroOrientation = new float[3];
//for fusion
public static final int TIME_CONSTANT = 300; //original:30
public static final float FILTER_COEFFICIENT = 0.50f;
public static final float FILTER_COEFFICIENT_AZIMUTH = 0.98f;
private Timer fuseTimer = new Timer();
//for GPS
private LocationManager locationManager; // The minimum distance to change Updates in meters
private Location lastLocation;
private static final double centerLatitude = 24.967185;
private static final double centerLongitude = 121.187019;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // no limit
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000; // 1 second
private float finalDistance = 0;
ViewfinderView getViewfinderView() {
return viewfinderView;
}
public Handler getHandler() {
return handler;
}
CameraManager getCameraManager() {
return cameraManager;
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Log.w("zxing", "onCreate");
//for sensors
// initialise gyroMatrix with identity matrix
gyroMatrix[0] = 1.0f; gyroMatrix[1] = 0.0f; gyroMatrix[2] = 0.0f;
gyroMatrix[3] = 0.0f; gyroMatrix[4] = 1.0f; gyroMatrix[5] = 0.0f;
gyroMatrix[6] = 0.0f; gyroMatrix[7] = 0.0f; gyroMatrix[8] = 1.0f;
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mMagneticField = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
mGyroscope = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
// wait for one second until gyroscope and magnetometer/accelerometer
// data is initialised then scedule the complementary filter task
fuseTimer.scheduleAtFixedRate(new calculateFusedOrientationTask(), 5000, TIME_CONSTANT);
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.capture);
hasSurface = false;
historyManager = new HistoryManager(this);
historyManager.trimHistory();
inactivityTimer = new InactivityTimer(this);
beepManager = new BeepManager(this);
ambientLightManager = new AmbientLightManager(this);
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
showHelpOnFirstLaunch();
}
@Override
protected void onResume() {
super.onResume();
Log.w("zxing", "onResume");
//for sensors
mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(this, mMagneticField, SensorManager.SENSOR_DELAY_NORMAL);
mSensorManager.registerListener(this, mGyroscope, SensorManager.SENSOR_DELAY_FASTEST);
//for Gyroscope
initState = true;
//for GPS
locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
}
// CameraManager must be initialized here, not in onCreate(). This is necessary because we don't
// want to open the camera driver and measure the screen size if we're going to show the help on
// first launch. That led to bugs where the scanning rectangle was the wrong size and partially
// off screen.
cameraManager = new CameraManager(getApplication());
viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
viewfinderView.setCameraManager(cameraManager);
viewfinderView.setCaptureActivity(this);
resultView = findViewById(R.id.result_view);
statusView = (TextView) findViewById(R.id.status_view);
handler = null;
lastResult = null;
resetStatusView();
SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
SurfaceHolder surfaceHolder = surfaceView.getHolder();
if (hasSurface) {
// The activity was paused but not stopped, so the surface still exists. Therefore
// surfaceCreated() won't be called, so init the camera here.
initCamera(surfaceHolder);
} else {
// Install the callback and wait for surfaceCreated() to init the camera.
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
beepManager.updatePrefs();
ambientLightManager.start(cameraManager);
inactivityTimer.onResume();
Intent intent = getIntent();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
copyToClipboard = prefs.getBoolean(PreferencesActivity.KEY_COPY_TO_CLIPBOARD, true)
&& (intent == null || intent.getBooleanExtra(Intents.Scan.SAVE_HISTORY, true));
source = IntentSource.NONE;
decodeFormats = null;
characterSet = null;
if (intent != null) {
String action = intent.getAction();
String dataString = intent.getDataString();
if (Intents.Scan.ACTION.equals(action)) {
// Scan the formats the intent requested, and return the result to the calling activity.
source = IntentSource.NATIVE_APP_INTENT;
decodeFormats = DecodeFormatManager.parseDecodeFormats(intent);
if (intent.hasExtra(Intents.Scan.WIDTH) && intent.hasExtra(Intents.Scan.HEIGHT)) {
int width = intent.getIntExtra(Intents.Scan.WIDTH, 0);
int height = intent.getIntExtra(Intents.Scan.HEIGHT, 0);
if (width > 0 && height > 0) {
cameraManager.setManualFramingRect(width, height);
}
}
String customPromptMessage = intent.getStringExtra(Intents.Scan.PROMPT_MESSAGE);
if (customPromptMessage != null) {
statusView.setText(customPromptMessage);
}
} else if (dataString != null &&
dataString.contains(PRODUCT_SEARCH_URL_PREFIX) &&
dataString.contains(PRODUCT_SEARCH_URL_SUFFIX)) {
// Scan only products and send the result to mobile Product Search.
source = IntentSource.PRODUCT_SEARCH_LINK;
sourceUrl = dataString;
decodeFormats = DecodeFormatManager.PRODUCT_FORMATS;
} else if (isZXingURL(dataString)) {
// Scan formats requested in query string (all formats if none specified).
// If a return URL is specified, send the results there. Otherwise, handle it ourselves.
source = IntentSource.ZXING_LINK;
sourceUrl = dataString;
Uri inputUri = Uri.parse(dataString);
scanFromWebPageManager = new ScanFromWebPageManager(inputUri);
decodeFormats = DecodeFormatManager.parseDecodeFormats(inputUri);
}
characterSet = intent.getStringExtra(Intents.Scan.CHARACTER_SET);
}
}
private static boolean isZXingURL(String dataString) {
if (dataString == null) {
return false;
}
for (String url : ZXING_URLS) {
if (dataString.startsWith(url)) {
return true;
}
}
return false;
}
@Override
protected void onPause() {
Log.w("zxing", "onPause");
//pause GPS listener
if(locationManager != null){
locationManager.removeUpdates(this);
}
if (handler != null) {
handler.quitSynchronously();
handler = null;
}
inactivityTimer.onPause();
ambientLightManager.stop();
cameraManager.closeDriver();
if (!hasSurface) {
SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
SurfaceHolder surfaceHolder = surfaceView.getHolder();
surfaceHolder.removeCallback(this);
}
super.onPause();
//for sensors
mSensorManager.unregisterListener(this);
}
@Override
protected void onDestroy() {
Log.w("zxing", "onDestroy");
inactivityTimer.shutdown();
super.onDestroy();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (source == IntentSource.NATIVE_APP_INTENT) {
setResult(RESULT_CANCELED);
finish();
return true;
}
if ((source == IntentSource.NONE || source == IntentSource.ZXING_LINK) && lastResult != null) {
restartPreviewAfterDelay(0L);
return true;
}
break;
case KeyEvent.KEYCODE_FOCUS:
case KeyEvent.KEYCODE_CAMERA:
// Handle these events so they don't launch the Camera app
return true;
// Use volume up/down to turn on light
case KeyEvent.KEYCODE_VOLUME_DOWN:
cameraManager.setTorch(false);
return true;
case KeyEvent.KEYCODE_VOLUME_UP:
cameraManager.setTorch(true);
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.capture, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
switch (item.getItemId()) {
case R.id.menu_share:
intent.setClassName(this, ShareActivity.class.getName());
startActivity(intent);
break;
case R.id.menu_history:
intent.setClassName(this, HistoryActivity.class.getName());
startActivityForResult(intent, HISTORY_REQUEST_CODE);
break;
case R.id.menu_settings:
intent.setClassName(this, PreferencesActivity.class.getName());
startActivity(intent);
break;
case R.id.menu_help:
intent.setClassName(this, HelpActivity.class.getName());
startActivity(intent);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (resultCode == RESULT_OK) {
if (requestCode == HISTORY_REQUEST_CODE) {
int itemNumber = intent.getIntExtra(Intents.History.ITEM_NUMBER, -1);
if (itemNumber >= 0) {
HistoryItem historyItem = historyManager.buildHistoryItem(itemNumber);
decodeOrStoreSavedBitmap(null, historyItem.getResult());
}
}
}
}
private void decodeOrStoreSavedBitmap(Bitmap bitmap, Result result) {
// Bitmap isn't used yet -- will be used soon
if (handler == null) {
savedResultToShow = result;
} else {
if (result != null) {
savedResultToShow = result;
}
if (savedResultToShow != null) {
Message message = Message.obtain(handler, R.id.decode_succeeded, savedResultToShow);
handler.sendMessage(message);
}
savedResultToShow = null;
}
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (holder == null) {
Log.e(TAG, "*** WARNING *** surfaceCreated() gave us a null surface!");
}
if (!hasSurface) {
hasSurface = true;
initCamera(holder);
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
hasSurface = false;
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
/**
* A valid barcode has been found, so give an indication of success and show the results.
*
* @param rawResult The contents of the barcode.
* @param scaleFactor amount by which thumbnail was scaled
* @param barcode A greyscale bitmap of the camera data which was decoded.
*/
public void handleDecode(Result rawResult, Bitmap barcode, float scaleFactor) {
inactivityTimer.onActivity();
lastResult = rawResult;
ResultHandler resultHandler = ResultHandlerFactory.makeResultHandler(this, rawResult);
boolean fromLiveScan = barcode != null;
viewfinderView.addSuccessResult(rawResult);
if (fromLiveScan) {
if(!initState) {
//collect 2 point in the same place.
positionData newData = new positionData();
newData.orientation = fusedOrientation.clone();
newData.sasPosition = viewfinderView.sasRelativePosition();
positionItems.add(newData);
if(positionItems.size() == sampleNums)
{
//start calculate optimize angle value
if(positionItems.size() > 1) { //do compensation only have at least 2 sample
float bestCompensation = getCompensation();
fusedOrientation[0] = fusedOrientation[0] + bestCompensation;
//A~cosPZ۰~
}
magVpsAxis = getVps(accMagOrientation, positionItems.get(sampleNums-1).sasPosition).clone();
fusVpsAxis = getVps(fusedOrientation, positionItems.get(sampleNums-1).sasPosition).clone();
gpsAxis = positionItems.get(sampleNums-1).sasPosition.clone();
historyManager.addHistoryItem(magVpsAxis, magVpsAxis, gpsAxis, accMagOrientation.clone(), finalDistance, rawResult, resultHandler);
positionItems.clear();
// Then not from history, so beep/vibrate and we have an image to draw on
beepManager.playBeepSoundAndVibrate();
}
}
drawResultPoints(barcode, scaleFactor, rawResult);
}
switch (source) {
case NATIVE_APP_INTENT:
case PRODUCT_SEARCH_LINK:
handleDecodeExternally(rawResult, resultHandler, barcode);
break;
case ZXING_LINK:
if (scanFromWebPageManager == null || !scanFromWebPageManager.isScanFromWebPage()) {
handleDecodeInternally(rawResult, resultHandler, barcode);
} else {
handleDecodeExternally(rawResult, resultHandler, barcode);
}
break;
case NONE:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (fromLiveScan && prefs.getBoolean(PreferencesActivity.KEY_BULK_MODE, false)) {
// Wait a moment or else it will scan the same barcode continuously about 3 times
restartPreviewAfterDelay(BULK_MODE_SCAN_DELAY_MS);
} else {
handleDecodeInternally(rawResult, resultHandler, barcode);
}
break;
}
}
public void logCatOrientations() {
float tmpOrientation[] = new float[3];
//rotate to landscape
tmpOrientation = rotateToLandscape(accMagOrientation.clone());
String print = String.format("magVpsAxis::%8.2f %8.2f %8.2f", magVpsAxis[0], magVpsAxis[1], magVpsAxis[2])
+ String.format("\ngpsAxis:%8.2f %8.2f %8.2f", gpsAxis[0], gpsAxis[1], gpsAxis[2])
+ String.format("\nMAG:%8.2f %8.2f %8.2f", tmpOrientation[0]*180/Math.PI, tmpOrientation[1]*180/Math.PI, tmpOrientation[2]*180/Math.PI);
//rotate to landscape
tmpOrientation = rotateToLandscape(gyroOrientation.clone());
print = print + String.format("\nGYR:%8.2f %8.2f %8.2f", tmpOrientation[0]*180/Math.PI, tmpOrientation[1]*180/Math.PI, tmpOrientation[2]*180/Math.PI);
tmpOrientation = rotateToLandscape(fusedOrientation.clone());
print = print + String.format("\nFUS:%8.2f %8.2f %8.2f", tmpOrientation[0]*180/Math.PI, tmpOrientation[1]*180/Math.PI, tmpOrientation[2]*180/Math.PI);
Log.w("zxing", print);
}
/*
class positionData {
public float[] orientation;
public double[] sasPosition;
}
private List<positionData> positionItems;
//եvɱסAgTw]SASVOA]NOu]ӪV
double radDiff = finalOrientation[1] - sasAzimuth; //ɱר
sasPosition[2] = sasPosition[2] / (float)Math.cos(radDiff);
finalDistance = sasPosition[2];
*/
//for correct degree error
class positionData {
public float[] orientation;
public double[] sasPosition;
}
private List<positionData> positionItems = new ArrayList<positionData>();
private static final int minDegree = -89;
private static final int maxDegree = 90;
private double gapArray[] = new double[180];
private static final int sampleNums = 1;
private float getCompensation() {
for(int i=0; i < 180; i++) {
gapArray[i] = getStandardDeviation(i+minDegree);
//Log.w("zxing", "gapArray: " + gapArray[i]);
}
int result = findBestCompensation(maxDegree-10); //means 0 degree
result = result + minDegree;
Log.w("zxing", "Compensation:" + result);
return (float)Math.toRadians(result);
}
private int findBestCompensation(int compensation) {
switch (chooseBetterCompensation(compensation, compensation+1)) {
case 1:
if(-1 == chooseBetterCompensation(compensation, compensation-1)) {
if(compensation -1 == 0) {
//bound
compensation = compensation - 1;
break;
} else {
//compensation-1 is smaller
return findBestCompensation(compensation-1);
}
} else {
//compensation is smallest
break;
}
case -1:
if(compensation+1 == 179) {
//bound
compensation = compensation + 1;
break;
}
else {
//compensation + 1 is smaller
return findBestCompensation(compensation+1);
}
case 0:
//equal
break;
}
return compensation; //if case 0 or out of bound
}
/**
* Try to find better compensation from 2 different angle
* @param compensationA
* @param compensationB
* @return 1 means compensationA is better. -1 means compensationB is better. 0 means equal.
*/
private int chooseBetterCompensation(int compensationA, int compensationB) {
if(gapArray[compensationA] < gapArray[compensationB]) {
return 1;
} else if (gapArray[compensationA] == gapArray[compensationB]) {
return 0;
} else {
return -1;
}
}
/**
* Calculate distance between SAS and camera.
* @param compensation An compensation for angle.
* @return
*/
private double getStandardDeviation(int compensation) {
positionData data[] = new positionData[sampleNums];
double tiltAngle[] = new double[sampleNums];
double distance[] = new double[sampleNums];
for(int i=0; i < sampleNums; i++) {
data[i] = positionItems.get(i);
tiltAngle[i] = data[i].orientation[0] + compensation; //not yet rotate to landscape mode. So azimuth is orientation[0]
distance[i] = data[i].sasPosition[2] / Math.cos(Math.toRadians(tiltAngle[i]));
}
StandardDeviation stdDeviation = new StandardDeviation(distance);
return stdDeviation.evaluate();
//return Math.abs(distance[0] - distance[1]);
}
public float[] getOrientationForSas() {
float orientationForSas[] = rotateToLandscape(accMagOrientation.clone());
orientationForSas[1] = orientationForSas[1] - centerAzimuth - (float)Math.PI/2;
return orientationForSas;
}
private float[] rotateToLandscape(float[] beforeRotate) {
float[] finalOrientation = new float[3];
finalOrientation[0] = beforeRotate[1]; //horizontal balance degree. clockwise is positive
if(beforeRotate[0] < Math.PI / 2) {
finalOrientation[1] = (beforeRotate[0] + (float)(Math.PI * 0.5)); //compass degree. clockwise is positive
}
else {
finalOrientation[1] = beforeRotate[0] - (float)(Math.PI * 1.5); //compass degree. clockwise is positive
}
if(beforeRotate[0] < Math.PI / 2) {
finalOrientation[2] = (beforeRotate[2] + (float)(Math.PI * 0.5)); //vertical degree. clockwise is positive
}
else {
finalOrientation[2] = beforeRotate[2] - (float)(Math.PI * 1.5); //vertical degree. clockwise is positive
}
return finalOrientation;
}
private double[] getVps(float[] sourceOrientation, double sasPosition[]) {
double vpsAxis[] = new double[3];
//fine tune values for landscape mode
float[] finalOrientation = rotateToLandscape(sourceOrientation.clone());
//Rotate Y horizontal balance degree
double x1 = sasPosition[0] * Math.cos(finalOrientation[0]) + sasPosition[1] * Math.sin(finalOrientation[0]);
double y1 = sasPosition[2];
double z1 = -sasPosition[0] * Math.sin(finalOrientation[0]) + sasPosition[1] * Math.cos(finalOrientation[0]);
//Rotate X vertical degree
double x2 = x1;
double y2 = y1 * Math.cos(finalOrientation[2] - sasPosition[4]) - z1 * Math.sin(finalOrientation[2] - sasPosition[4]);
double z2 = y1 * Math.sin(finalOrientation[2]) - z1 * Math.cos(finalOrientation[2]);
//Rotate Z compass degree
double x3 = x2 * Math.cos(-finalOrientation[1]) - y2 * Math.sin(-finalOrientation[1]);
double y3 = x2 * Math.sin(-finalOrientation[1]) + y2 * Math.cos(-finalOrientation[1]);
double z3 = z2;
//Rotate to world coordinate and convert unit to meters
vpsAxis[0] = -x3 / 100; //mapping to longitudeg
vpsAxis[1] = -y3 / 100; //mapping to latituden
vpsAxis[2] = z3 / 100; //mapping to altitude
return vpsAxis;
}
/**
* Superimpose a line for 1D or dots for 2D to highlight the key features of the barcode.
* bravesheng: This funciton is only for thumbnail view. not for live view. So draw line in this bitmap will have no effect!
* @param barcode A bitmap of the captured image.
* @param scaleFactor amount by which thumbnail was scaled
* @param rawResult The decoded results which contains the points to draw.
*/
private void drawResultPoints(Bitmap barcode, float scaleFactor, Result rawResult) {
ResultPoint[] points = rawResult.getResultPoints();
if (points != null && points.length > 0) {
Canvas canvas = new Canvas(barcode);
Paint paint = new Paint();
paint.setColor(getResources().getColor(R.color.result_points));
if (points.length == 2) {
paint.setStrokeWidth(4.0f);
drawLine(canvas, paint, points[0], points[1], scaleFactor);
} else if (points.length == 4 &&
(rawResult.getBarcodeFormat() == BarcodeFormat.UPC_A ||
rawResult.getBarcodeFormat() == BarcodeFormat.EAN_13)) {
// Hacky special case -- draw two lines, for the barcode and metadata
drawLine(canvas, paint, points[0], points[1], scaleFactor);
drawLine(canvas, paint, points[2], points[3], scaleFactor);
} else {
paint.setStrokeWidth(10.0f);
for (ResultPoint point : points) {
canvas.drawPoint(scaleFactor * point.getX(), scaleFactor * point.getY(), paint);
}
}
}
}
private static void drawLine(Canvas canvas, Paint paint, ResultPoint a, ResultPoint b, float scaleFactor) {
canvas.drawLine(scaleFactor * a.getX(),
scaleFactor * a.getY(),
scaleFactor * b.getX(),
scaleFactor * b.getY(),
paint);
}
// Put up our own UI for how to handle the decoded contents.
private void handleDecodeInternally(Result rawResult, ResultHandler resultHandler, Bitmap barcode) {
statusView.setVisibility(View.GONE);
viewfinderView.setVisibility(View.GONE);
resultView.setVisibility(View.VISIBLE);
ImageView barcodeImageView = (ImageView) findViewById(R.id.barcode_image_view);
if (barcode == null) {
barcodeImageView.setImageBitmap(BitmapFactory.decodeResource(getResources(),
R.drawable.launcher_icon));
} else {
barcodeImageView.setImageBitmap(barcode);
}
TextView formatTextView = (TextView) findViewById(R.id.format_text_view);
formatTextView.setText(rawResult.getBarcodeFormat().toString());
TextView typeTextView = (TextView) findViewById(R.id.type_text_view);
typeTextView.setText(resultHandler.getType().toString());
DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT);
String formattedTime = formatter.format(new Date(rawResult.getTimestamp()));
TextView timeTextView = (TextView) findViewById(R.id.time_text_view);
timeTextView.setText(formattedTime);
TextView metaTextView = (TextView) findViewById(R.id.meta_text_view);
View metaTextViewLabel = findViewById(R.id.meta_text_view_label);
metaTextView.setVisibility(View.GONE);
metaTextViewLabel.setVisibility(View.GONE);
Map<ResultMetadataType,Object> metadata = rawResult.getResultMetadata();
if (metadata != null) {
StringBuilder metadataText = new StringBuilder(20);
for (Map.Entry<ResultMetadataType,Object> entry : metadata.entrySet()) {
if (DISPLAYABLE_METADATA_TYPES.contains(entry.getKey())) {
metadataText.append(entry.getValue()).append('\n');
}
}
if (metadataText.length() > 0) {
metadataText.setLength(metadataText.length() - 1);
metaTextView.setText(metadataText);
metaTextView.setVisibility(View.VISIBLE);
metaTextViewLabel.setVisibility(View.VISIBLE);
}
}
TextView contentsTextView = (TextView) findViewById(R.id.contents_text_view);
CharSequence displayContents = resultHandler.getDisplayContents();
contentsTextView.setText(displayContents);
// Crudely scale between 22 and 32 -- bigger font for shorter text
int scaledSize = Math.max(22, 32 - displayContents.length() / 4);
contentsTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, scaledSize);
TextView supplementTextView = (TextView) findViewById(R.id.contents_supplement_text_view);
supplementTextView.setText("");
supplementTextView.setOnClickListener(null);
if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean(
PreferencesActivity.KEY_SUPPLEMENTAL, true)) {
SupplementalInfoRetriever.maybeInvokeRetrieval(supplementTextView,
resultHandler.getResult(),
historyManager,
this);
}
int buttonCount = resultHandler.getButtonCount();
ViewGroup buttonView = (ViewGroup) findViewById(R.id.result_button_view);
buttonView.requestFocus();
for (int x = 0; x < ResultHandler.MAX_BUTTON_COUNT; x++) {
TextView button = (TextView) buttonView.getChildAt(x);
if (x < buttonCount) {
button.setVisibility(View.VISIBLE);
button.setText(resultHandler.getButtonText(x));
button.setOnClickListener(new ResultButtonListener(resultHandler, x));
} else {
button.setVisibility(View.GONE);
}
}
if (copyToClipboard && !resultHandler.areContentsSecure()) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
if (displayContents != null) {
try {
clipboard.setText(displayContents);
} catch (NullPointerException npe) {
// Some kind of bug inside the clipboard implementation, not due to null input
Log.w(TAG, "Clipboard bug", npe);
}
}
}
}
// Briefly show the contents of the barcode, then handle the result outside Barcode Scanner.
private void handleDecodeExternally(Result rawResult, ResultHandler resultHandler, Bitmap barcode) {
if (barcode != null) {
viewfinderView.drawResultBitmap(barcode);
}
long resultDurationMS;
if (getIntent() == null) {
resultDurationMS = DEFAULT_INTENT_RESULT_DURATION_MS;
} else {
resultDurationMS = getIntent().getLongExtra(Intents.Scan.RESULT_DISPLAY_DURATION_MS,
DEFAULT_INTENT_RESULT_DURATION_MS);
}
// Since this message will only be shown for a second, just tell the user what kind of
// barcode was found (e.g. contact info) rather than the full contents, which they won't
// have time to read.
if (resultDurationMS > 0) {
statusView.setText(getString(resultHandler.getDisplayTitle()));
}
if (copyToClipboard && !resultHandler.areContentsSecure()) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
CharSequence text = resultHandler.getDisplayContents();
if (text != null) {
try {
clipboard.setText(text);
} catch (NullPointerException npe) {
// Some kind of bug inside the clipboard implementation, not due to null input
Log.w(TAG, "Clipboard bug", npe);
}
}
}
if (source == IntentSource.NATIVE_APP_INTENT) {
// Hand back whatever action they requested - this can be changed to Intents.Scan.ACTION when
// the deprecated intent is retired.
Intent intent = new Intent(getIntent().getAction());
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
intent.putExtra(Intents.Scan.RESULT, rawResult.toString());
intent.putExtra(Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString());
byte[] rawBytes = rawResult.getRawBytes();
if (rawBytes != null && rawBytes.length > 0) {
intent.putExtra(Intents.Scan.RESULT_BYTES, rawBytes);
}
Map<ResultMetadataType,?> metadata = rawResult.getResultMetadata();
if (metadata != null) {
if (metadata.containsKey(ResultMetadataType.UPC_EAN_EXTENSION)) {
intent.putExtra(Intents.Scan.RESULT_UPC_EAN_EXTENSION,
metadata.get(ResultMetadataType.UPC_EAN_EXTENSION).toString());
}
Integer orientation = (Integer) metadata.get(ResultMetadataType.ORIENTATION);
if (orientation != null) {
intent.putExtra(Intents.Scan.RESULT_ORIENTATION, orientation.intValue());
}
String ecLevel = (String) metadata.get(ResultMetadataType.ERROR_CORRECTION_LEVEL);
if (ecLevel != null) {
intent.putExtra(Intents.Scan.RESULT_ERROR_CORRECTION_LEVEL, ecLevel);
}
Iterable<byte[]> byteSegments = (Iterable<byte[]>) metadata.get(ResultMetadataType.BYTE_SEGMENTS);
if (byteSegments != null) {
int i = 0;
for (byte[] byteSegment : byteSegments) {
intent.putExtra(Intents.Scan.RESULT_BYTE_SEGMENTS_PREFIX + i, byteSegment);
i++;
}
}
}
sendReplyMessage(R.id.return_scan_result, intent, resultDurationMS);
} else if (source == IntentSource.PRODUCT_SEARCH_LINK) {
// Reformulate the URL which triggered us into a query, so that the request goes to the same
// TLD as the scan URL.
int end = sourceUrl.lastIndexOf("/scan");
String replyURL = sourceUrl.substring(0, end) + "?q=" + resultHandler.getDisplayContents() + "&source=zxing";
sendReplyMessage(R.id.launch_product_query, replyURL, resultDurationMS);
} else if (source == IntentSource.ZXING_LINK) {
if (scanFromWebPageManager != null && scanFromWebPageManager.isScanFromWebPage()) {
String replyURL = scanFromWebPageManager.buildReplyURL(rawResult, resultHandler);
sendReplyMessage(R.id.launch_product_query, replyURL, resultDurationMS);
}
}
}
private void sendReplyMessage(int id, Object arg, long delayMS) {
Message message = Message.obtain(handler, id, arg);
if (delayMS > 0L) {
handler.sendMessageDelayed(message, delayMS);
} else {
handler.sendMessage(message);
}
}
/**
* We want the help screen to be shown automatically the first time a new version of the app is
* run. The easiest way to do this is to check android:versionCode from the manifest, and compare
* it to a value stored as a preference.
*/
private boolean showHelpOnFirstLaunch() {
try {
PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME, 0);
int currentVersion = info.versionCode;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int lastVersion = prefs.getInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, 0);
if (currentVersion > lastVersion) {
prefs.edit().putInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, currentVersion).commit();
Intent intent = new Intent(this, HelpActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
// Show the default page on a clean install, and the what's new page on an upgrade.
String page = lastVersion == 0 ? HelpActivity.DEFAULT_PAGE : HelpActivity.WHATS_NEW_PAGE;
intent.putExtra(HelpActivity.REQUESTED_PAGE_KEY, page);
startActivity(intent);
return true;
}
} catch (PackageManager.NameNotFoundException e) {
Log.w(TAG, e);
}
return false;
}
private void initCamera(SurfaceHolder surfaceHolder) {
if (surfaceHolder == null) {
throw new IllegalStateException("No SurfaceHolder provided");
}
if (cameraManager.isOpen()) {
Log.w(TAG, "initCamera() while already open -- late SurfaceView callback?");
return;
}
try {
cameraManager.openDriver(surfaceHolder);
// Creating the handler starts the preview, which can also throw a RuntimeException.
if (handler == null) {
handler = new CaptureActivityHandler(this, decodeFormats, characterSet, cameraManager);
}
decodeOrStoreSavedBitmap(null, null);
} catch (IOException ioe) {
Log.w(TAG, ioe);
displayFrameworkBugMessageAndExit();
} catch (RuntimeException e) {
// Barcode Scanner has seen crashes in the wild of this variety:
// java.?lang.?RuntimeException: Fail to connect to camera service
Log.w(TAG, "Unexpected error initializing camera", e);
displayFrameworkBugMessageAndExit();
}
}
private void displayFrameworkBugMessageAndExit() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.app_name));
builder.setMessage(getString(R.string.msg_camera_framework_bug));
builder.setPositiveButton(R.string.button_ok, new FinishListener(this));
builder.setOnCancelListener(new FinishListener(this));
builder.show();
}
public void restartPreviewAfterDelay(long delayMS) {
if (handler != null) {
handler.sendEmptyMessageDelayed(R.id.restart_preview, delayMS);
}
resetStatusView();
}
//bravesheng: Can add information here. Will display on live screen.
private void resetStatusView() {
resultView.setVisibility(View.GONE);
//Change to position for debug
float tmpOrientation[] = new float[3];
//rotate to landscape
tmpOrientation = rotateToLandscape(accMagOrientation.clone());
String print = String.format("magVpsAxis::%8.2f %8.2f %8.2f", magVpsAxis[0], magVpsAxis[1], magVpsAxis[2])
+ String.format("\ngpsAxis:%8.2f %8.2f %8.2f", gpsAxis[0], gpsAxis[1], gpsAxis[2])
+ String.format("\nMAG:%8.2f %8.2f %8.2f", tmpOrientation[0]*180/Math.PI, tmpOrientation[1]*180/Math.PI, tmpOrientation[2]*180/Math.PI);
//rotate to landscape
tmpOrientation = rotateToLandscape(gyroOrientation.clone());
print = print + String.format("\nGYR:%8.2f %8.2f %8.2f", tmpOrientation[0]*180/Math.PI, tmpOrientation[1]*180/Math.PI, tmpOrientation[2]*180/Math.PI);
tmpOrientation = rotateToLandscape(fusedOrientation.clone());
print = print + String.format("\nFUS:%8.2f %8.2f %8.2f", tmpOrientation[0]*180/Math.PI, tmpOrientation[1]*180/Math.PI, tmpOrientation[2]*180/Math.PI);
statusView.setText(print);
statusView.setVisibility(View.VISIBLE);
viewfinderView.setVisibility(View.VISIBLE);
lastResult = null;
//Log.w("zxing",print);
}
public void drawViewfinder() {
viewfinderView.drawViewfinder();
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
accelerometer_values = (float[]) event.values.clone();
calculateAccMagOrientation();
}
else if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
magnitude_values = (float[]) event.values.clone();
}
else if(event.sensor.getType() == Sensor.TYPE_GYROSCOPE) {
gyroFunction(event);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (prefs.getBoolean(PreferencesActivity.KEY_BULK_MODE, true)) {
resetStatusView();
}
}
}
// calculates orientation angles from accelerometer and magnetometer output
public void calculateAccMagOrientation() {
float[] rotationMatrix = new float[9];
if((accelerometer_values != null) && (magnitude_values != null)) {
if(SensorManager.getRotationMatrix(rotationMatrix, null, accelerometer_values, magnitude_values)) {
SensorManager.getOrientation(rotationMatrix, accMagOrientation);
accMagOrientation[0] = accMagOrientation[0] - shiftRad;
}
}
}
// This function is borrowed from the Android reference
// at http://developer.android.com/reference/android/hardware/SensorEvent.html#values
// It calculates a rotation vector from the gyroscope angular speed values.
private void getRotationVectorFromGyro(float[] gyroValues,
float[] deltaRotationVector,
float timeFactor)
{
float[] normValues = new float[3];
// Calculate the angular speed of the sample
float omegaMagnitude =
(float)Math.sqrt(gyroValues[0] * gyroValues[0] +
gyroValues[1] * gyroValues[1] +
gyroValues[2] * gyroValues[2]);
// Normalize the rotation vector if it's big enough to get the axis
if(omegaMagnitude > EPSILON) {
normValues[0] = gyroValues[0] / omegaMagnitude;
normValues[1] = gyroValues[1] / omegaMagnitude;
normValues[2] = gyroValues[2] / omegaMagnitude;
}
// Integrate around this axis with the angular speed by the timestep
// in order to get a delta rotation from this sample over the timestep
// We will convert this axis-angle representation of the delta rotation
// into a quaternion before turning it into the rotation matrix.
float thetaOverTwo = omegaMagnitude * timeFactor;
float sinThetaOverTwo = (float)Math.sin(thetaOverTwo);
float cosThetaOverTwo = (float)Math.cos(thetaOverTwo);
deltaRotationVector[0] = sinThetaOverTwo * normValues[0];
deltaRotationVector[1] = sinThetaOverTwo * normValues[1];
deltaRotationVector[2] = sinThetaOverTwo * normValues[2];
deltaRotationVector[3] = cosThetaOverTwo;
}
// This function performs the integration of the gyroscope data.
// It writes the gyroscope based orientation into gyroOrientation.
public void gyroFunction(SensorEvent event) {
// don't start until first accelerometer/magnetometer orientation has been acquired
if (accMagOrientation == null)
return;
// waiting for gyroscope initialize done in calculateFusedOrientationTask
if(initState) {
return;
}
// copy the new gyro values into the gyro array
// convert the raw gyro data into a rotation vector
float[] deltaVector = new float[4];
if(timestamp != 0) {
final float dT = (event.timestamp - timestamp) * NS2S;
System.arraycopy(event.values, 0, gyro, 0, 3);
getRotationVectorFromGyro(gyro, deltaVector, dT / 2.0f);
}
// measurement done, save current time for next interval
timestamp = event.timestamp;
// convert rotation vector into rotation matrix
float[] deltaMatrix = new float[9];
SensorManager.getRotationMatrixFromVector(deltaMatrix, deltaVector);
// apply the new rotation interval on the gyroscope based rotation matrix
gyroMatrix = matrixMultiplication(gyroMatrix, deltaMatrix);
// get the gyroscope based orientation from the rotation matrix
SensorManager.getOrientation(gyroMatrix, gyroOrientation);
}
private float[] getRotationMatrixFromOrientation(float[] o) {
float[] xM = new float[9];
float[] yM = new float[9];
float[] zM = new float[9];
float sinX = (float)Math.sin(o[1]);
float cosX = (float)Math.cos(o[1]);
float sinY = (float)Math.sin(o[2]);
float cosY = (float)Math.cos(o[2]);
float sinZ = (float)Math.sin(o[0]);
float cosZ = (float)Math.cos(o[0]);
// rotation about x-axis (pitch)
xM[0] = 1.0f; xM[1] = 0.0f; xM[2] = 0.0f;
xM[3] = 0.0f; xM[4] = cosX; xM[5] = sinX;
xM[6] = 0.0f; xM[7] = -sinX; xM[8] = cosX;
// rotation about y-axis (roll)
yM[0] = cosY; yM[1] = 0.0f; yM[2] = sinY;
yM[3] = 0.0f; yM[4] = 1.0f; yM[5] = 0.0f;
yM[6] = -sinY; yM[7] = 0.0f; yM[8] = cosY;
// rotation about z-axis (azimuth)
zM[0] = cosZ; zM[1] = sinZ; zM[2] = 0.0f;
zM[3] = -sinZ; zM[4] = cosZ; zM[5] = 0.0f;
zM[6] = 0.0f; zM[7] = 0.0f; zM[8] = 1.0f;
// rotation order is y, x, z (roll, pitch, azimuth)
float[] resultMatrix = matrixMultiplication(xM, yM);
resultMatrix = matrixMultiplication(zM, resultMatrix);
return resultMatrix;
}
private float[] matrixMultiplication(float[] A, float[] B) {
float[] result = new float[9];
result[0] = A[0] * B[0] + A[1] * B[3] + A[2] * B[6];
result[1] = A[0] * B[1] + A[1] * B[4] + A[2] * B[7];
result[2] = A[0] * B[2] + A[1] * B[5] + A[2] * B[8];
result[3] = A[3] * B[0] + A[4] * B[3] + A[5] * B[6];
result[4] = A[3] * B[1] + A[4] * B[4] + A[5] * B[7];
result[5] = A[3] * B[2] + A[4] * B[5] + A[5] * B[8];
result[6] = A[6] * B[0] + A[7] * B[3] + A[8] * B[6];
result[7] = A[6] * B[1] + A[7] * B[4] + A[8] * B[7];
result[8] = A[6] * B[2] + A[7] * B[5] + A[8] * B[8];
return result;
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
Log.w("zxing", "onAccuracyChanged: " + accuracy);
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub. On GPS location changed.
//Log.w("zxing", "onLocationChanged " + location.getLatitude() + " " + location.getLongitude());
lastLocation = location;
float[] results = new float[3];
Location.distanceBetween(centerLatitude, lastLocation.getLongitude(), lastLocation.getLatitude(), lastLocation.getLongitude(), results);
if( (int)results[1] == 0) {
//0 means bearing to north. Otherwise will be 180. Means bearing to south
gpsAxis[0] = results[0];
} else {
gpsAxis[0] = -results[0];
}
Location.distanceBetween(lastLocation.getLatitude(), centerLongitude, lastLocation.getLatitude(), lastLocation.getLongitude(), results);
if((int)results[1] == 89) {
//89 means bearing to east. Otherwise will be -89. Means bearing to west.
gpsAxis[1] = results[0];
} else {
gpsAxis[1] = -results[0];
}
gpsAxis[2] = (float)(150 - lastLocation.getAltitude());
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
Log.w("zxing", "onStatusChanged");
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Log.w("zxing", "onProviderEnabled");
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Log.w("zxing", "onProviderDisabled");
}
//Fusion Sensor
//private float centerAzimuth = (float)-Math.PI; //ܸۥ(]|եVAҥHO-PI)
private float centerAzimuth = (float)-Math.PI/2; //ܸۥ_(]|եVAҥHO-PI/2)
private float shiftRad = 0;
class calculateFusedOrientationTask extends TimerTask {
public void run() {
//initial Gyroscope data
if(initState) {
shiftRad = accMagOrientation[0] - centerAzimuth;
accMagOrientation[0] = accMagOrientation[0] - shiftRad;
gyroMatrix = getRotationMatrixFromOrientation(accMagOrientation);
System.arraycopy(accMagOrientation, 0, gyroOrientation, 0, 3);
initState = false;
}
float oneMinusCoeff = 1.0f - FILTER_COEFFICIENT;
float oneMinusCoeffAzimuth = 1.0f - FILTER_COEFFICIENT_AZIMUTH;
/*
* Fix for 179<--> -179transition problem:
* Check whether one of the two orientation angles (gyro or accMag) is negative while the other one is positive.
* If so, add 360(2 * math.PI) to the negative value, perform the sensor fusion, and remove the 360from the result
* if it is greater than 180 This stabilizes the output in positive-to-negative-transition cases.
*/
// azimuth
//fusedOrientation[0] = (float) -Math.PI;
if (gyroOrientation[0] < -0.5 * Math.PI && accMagOrientation[0] > 0.0) {
fusedOrientation[0] = (float) (FILTER_COEFFICIENT_AZIMUTH * (gyroOrientation[0] + 2.0 * Math.PI) + oneMinusCoeffAzimuth * accMagOrientation[0]);
fusedOrientation[0] -= (fusedOrientation[0] > Math.PI) ? 2.0 * Math.PI : 0;
}
else if (accMagOrientation[0] < -0.5 * Math.PI && gyroOrientation[0] > 0.0) {
fusedOrientation[0] = (float) (FILTER_COEFFICIENT_AZIMUTH * gyroOrientation[0] + oneMinusCoeffAzimuth * (accMagOrientation[0] + 2.0 * Math.PI));
fusedOrientation[0] -= (fusedOrientation[0] > Math.PI)? 2.0 * Math.PI : 0;
}
else {
fusedOrientation[0] = FILTER_COEFFICIENT_AZIMUTH * gyroOrientation[0] + oneMinusCoeffAzimuth * accMagOrientation[0];
}
// pitch
fusedOrientation[1] = accMagOrientation[1];
// roll
fusedOrientation[2] = accMagOrientation[2];
// overwrite gyro matrix and orientation with fused orientation
// to comensate gyro drift
gyroMatrix = getRotationMatrixFromOrientation(fusedOrientation);
System.arraycopy(fusedOrientation, 0, gyroOrientation, 0, 3);
}
}
}
| change textview and add prepareInfoString funciton for better debug
| android/src/com/google/zxing/client/android/CaptureActivity.java | change textview and add prepareInfoString funciton for better debug | <ide><path>ndroid/src/com/google/zxing/client/android/CaptureActivity.java
<ide> }
<ide> }
<ide>
<del>public void logCatOrientations() {
<del> float tmpOrientation[] = new float[3];
<del>
<del> //rotate to landscape
<del> tmpOrientation = rotateToLandscape(accMagOrientation.clone());
<del>
<del> String print = String.format("magVpsAxis::%8.2f %8.2f %8.2f", magVpsAxis[0], magVpsAxis[1], magVpsAxis[2])
<del> + String.format("\ngpsAxis:%8.2f %8.2f %8.2f", gpsAxis[0], gpsAxis[1], gpsAxis[2])
<del> + String.format("\nMAG:%8.2f %8.2f %8.2f", tmpOrientation[0]*180/Math.PI, tmpOrientation[1]*180/Math.PI, tmpOrientation[2]*180/Math.PI);
<del> //rotate to landscape
<del> tmpOrientation = rotateToLandscape(gyroOrientation.clone());
<del> print = print + String.format("\nGYR:%8.2f %8.2f %8.2f", tmpOrientation[0]*180/Math.PI, tmpOrientation[1]*180/Math.PI, tmpOrientation[2]*180/Math.PI);
<del> tmpOrientation = rotateToLandscape(fusedOrientation.clone());
<del> print = print + String.format("\nFUS:%8.2f %8.2f %8.2f", tmpOrientation[0]*180/Math.PI, tmpOrientation[1]*180/Math.PI, tmpOrientation[2]*180/Math.PI);
<del> Log.w("zxing", print);
<del>}
<del>
<ide> /*
<ide> class positionData {
<ide> public float[] orientation;
<ide> //Rotate Z compass degree
<ide> double x3 = x2 * Math.cos(-finalOrientation[1]) - y2 * Math.sin(-finalOrientation[1]);
<ide> double y3 = x2 * Math.sin(-finalOrientation[1]) + y2 * Math.cos(-finalOrientation[1]);
<add> //double y3 = x2 * Math.sin(-finalOrientation[1] + sasPosition[3]) + y2 * Math.cos(-finalOrientation[1] + sasPosition[3]);
<ide> double z3 = z2;
<ide> //Rotate to world coordinate and convert unit to meters
<ide> vpsAxis[0] = -x3 / 100; //mapping to longitudeg
<ide> resetStatusView();
<ide> }
<ide>
<add> private String prepareInfoString() {
<add> //Change to position for debug
<add> float tmpOrientation[] = new float[3];
<add>
<add> //rotate to landscape
<add> tmpOrientation = rotateToLandscape(accMagOrientation.clone());
<add>
<add> String print = String.format("magVpsAxis:%8.2f %8.2f %8.2f", magVpsAxis[0], magVpsAxis[1], magVpsAxis[2])
<add> + String.format("\ngpsAxis:%8.2f %8.2f %8.2f", gpsAxis[0], gpsAxis[1], gpsAxis[2])
<add> + String.format("\nMAG:%8.2f %8.2f %8.2f", tmpOrientation[0]*180/Math.PI, tmpOrientation[1]*180/Math.PI, tmpOrientation[2]*180/Math.PI);
<add> //rotate to landscape
<add> tmpOrientation = rotateToLandscape(gyroOrientation.clone());
<add> print = print + String.format("\nGYR:%8.2f %8.2f %8.2f", tmpOrientation[0]*180/Math.PI, tmpOrientation[1]*180/Math.PI, tmpOrientation[2]*180/Math.PI);
<add> tmpOrientation = rotateToLandscape(fusedOrientation.clone());
<add> print = print + String.format("\nFUS:%8.2f %8.2f %8.2f", tmpOrientation[0]*180/Math.PI, tmpOrientation[1]*180/Math.PI, tmpOrientation[2]*180/Math.PI);
<add> return print;
<add> }
<add>
<ide> //bravesheng: Can add information here. Will display on live screen.
<ide> private void resetStatusView() {
<ide> resultView.setVisibility(View.GONE);
<del> //Change to position for debug
<del> float tmpOrientation[] = new float[3];
<del>
<del> //rotate to landscape
<del> tmpOrientation = rotateToLandscape(accMagOrientation.clone());
<del>
<del> String print = String.format("magVpsAxis::%8.2f %8.2f %8.2f", magVpsAxis[0], magVpsAxis[1], magVpsAxis[2])
<del> + String.format("\ngpsAxis:%8.2f %8.2f %8.2f", gpsAxis[0], gpsAxis[1], gpsAxis[2])
<del> + String.format("\nMAG:%8.2f %8.2f %8.2f", tmpOrientation[0]*180/Math.PI, tmpOrientation[1]*180/Math.PI, tmpOrientation[2]*180/Math.PI);
<del> //rotate to landscape
<del> tmpOrientation = rotateToLandscape(gyroOrientation.clone());
<del> print = print + String.format("\nGYR:%8.2f %8.2f %8.2f", tmpOrientation[0]*180/Math.PI, tmpOrientation[1]*180/Math.PI, tmpOrientation[2]*180/Math.PI);
<del> tmpOrientation = rotateToLandscape(fusedOrientation.clone());
<del> print = print + String.format("\nFUS:%8.2f %8.2f %8.2f", tmpOrientation[0]*180/Math.PI, tmpOrientation[1]*180/Math.PI, tmpOrientation[2]*180/Math.PI);
<del> statusView.setText(print);
<add> statusView.setTextSize(20);
<add> //statusView.setTextColor(android.graphics.Color.BLUE);
<add> statusView.setShadowLayer((float)Math.PI, 2, 2, 0xFF000000);
<add> statusView.setText(prepareInfoString());
<ide> statusView.setVisibility(View.VISIBLE);
<ide> viewfinderView.setVisibility(View.VISIBLE);
<ide> lastResult = null; |
|
Java | unlicense | 511424cad3d76dfe7922b3c2e82bc4f10423eca1 | 0 | Egga/bootkick,Egga/bootkick,Egga/bootkick | package de.egga.persons;
import de.egga.configuration.MainConfiguration;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import static com.jayway.restassured.RestAssured.*;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
/**
* @author egga
*/
@RunWith(SpringJUnit4ClassRunner.class)
@IntegrationTest
@SpringApplicationConfiguration(classes = MainConfiguration.class)
@WebAppConfiguration
public class PersonControllerTest {
@Test
public void it_should_return_persons() throws Exception {
get("/api/persons/").then().statusCode(200);
}
@Test
public void it_should_return_person() throws Exception {
get("/api/persons/123").then().statusCode(200);
}
@Test
public void it_should_add_person() throws Exception {
Person person = randomPerson();
given()
.body(person)
.header("Content-Type", APPLICATION_JSON_VALUE)
.put("/api/persons/123")
.then()
.statusCode(204);
}
@Test
public void it_should_delete_persons() throws Exception {
delete("/api/persons/123").then().statusCode(204);
}
private Person randomPerson() {
Person person = new Person();
person.setId("123");
person.setName("Hank");
person.setPhone("+555123456");
return person;
}
}
| src/test/java/de/egga/persons/PersonControllerTest.java | package de.egga.persons;
import de.egga.configuration.MainConfiguration;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import static com.jayway.restassured.RestAssured.*;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
/**
* @author egga
*/
@RunWith(SpringJUnit4ClassRunner.class)
@IntegrationTest
@SpringApplicationConfiguration(classes = MainConfiguration.class)
@WebAppConfiguration
public class PersonControllerTest {
@Test
public void it_should_return_persons() throws Exception {
get("/api/persons/").then().statusCode(200);
}
@Test
public void it_should_return_person() throws Exception {
get("/api/persons/123").then().statusCode(200);
}
@Test
public void it_should_add_person() throws Exception {
Person person = randomPerson();
given()
.body(person)
.header("Content-Type", APPLICATION_JSON_VALUE)
.put("/api/persons/123")
.then()
.statusCode(204);
}
@Test
public void it_should_delete_persons() throws Exception {
delete("/api/persons/123").then().statusCode(204);
}
private Person randomPerson() {
Person person = new Person();
person.setId("123");
person.setName("Hank");
person.setPhone("+555123456");
return person;
}
}
| optimize imports
| src/test/java/de/egga/persons/PersonControllerTest.java | optimize imports | <ide><path>rc/test/java/de/egga/persons/PersonControllerTest.java
<ide> import org.junit.runner.RunWith;
<ide> import org.springframework.boot.test.IntegrationTest;
<ide> import org.springframework.boot.test.SpringApplicationConfiguration;
<del>import org.springframework.http.MediaType;
<ide> import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
<ide> import org.springframework.test.context.web.WebAppConfiguration;
<ide>
<ide> import static com.jayway.restassured.RestAssured.*;
<del>import static org.hamcrest.Matchers.equalTo;
<del>import static org.hamcrest.Matchers.is;
<ide> import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
<ide>
<ide> /** |
|
Java | agpl-3.0 | d41315146b9b0e1ec67b9fa79e25e5fb8d7a47cf | 0 | sakazz/exchange,sakazz/exchange,metabit/bitsquare,ManfredKarrer/exchange,bitsquare/bitsquare,haiqu/bitsquare,haiqu/bitsquare,bisq-network/exchange,bisq-network/exchange,metabit/bitsquare,ManfredKarrer/exchange,bitsquare/bitsquare | package io.bitsquare.gui.main.overlays.windows;
import com.google.inject.Inject;
import io.bitsquare.app.BitsquareApp;
import io.bitsquare.gui.main.overlays.Overlay;
import io.bitsquare.user.Preferences;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static io.bitsquare.gui.util.FormBuilder.addHyperlinkWithIcon;
public class TacWindow extends Overlay<TacWindow> {
private static final Logger log = LoggerFactory.getLogger(TacWindow.class);
private final Preferences preferences;
@Inject
public TacWindow(Preferences preferences) {
this.preferences = preferences;
type = Type.Attention;
width = 800;
}
public void showIfNeeded() {
if (!preferences.getTacAccepted() && !BitsquareApp.DEV_MODE) {
headLine("User agreement");
String text = "1. This software is experimental and 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 non-infringement.\n" +
"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.\n\n" +
"2. The user is responsible to use the software in compliance with local laws. Don't use Bitsquare if the usage of Bitcoin is not legal in your jurisdiction.\n\n" +
"3. Bitcoin market price is delivered by 3rd parties (BitcoinAverage, Poloniex). It is your responsibility to double check the price with other sources.\n\n" +
"4. The user confirms that he has read and agreed to the rules regarding the dispute process:\n" +
" - You must finalize trades within the maximum duration specified for each payment method.\n" +
" - You must enter the trade ID in the \"reason for payment\" text field when doing the fiat payment transfer.\n" +
" - If the bank of the fiat sender charges fees the sender (bitcoin buyer) has to cover the fees.\n" +
" - You must cooperate with the arbitrator during the arbitration process.\n" +
" - You must reply within 48 hours to each arbitrator inquiry.\n" +
" - Failure to follow the above requirements may result in loss of your security deposit.\n\n" +
"For more details and a general overview please read the full documentation about the " +
"arbitration system and the dispute process.";
message(text);
actionButtonText("I agree");
closeButtonText("I disagree and quit");
onAction(() -> preferences.setTacAccepted(true));
onClose(BitsquareApp.shutDownHandler::run);
super.show();
}
}
@Override
protected void addMessage() {
super.addMessage();
addHyperlinkWithIcon(gridPane, ++rowIndex, "Arbitration system", "https://bitsquare.io/arbitration_system.pdf", -6);
}
@Override
protected void onShow() {
display();
}
}
| gui/src/main/java/io/bitsquare/gui/main/overlays/windows/TacWindow.java | package io.bitsquare.gui.main.overlays.windows;
import com.google.inject.Inject;
import io.bitsquare.app.BitsquareApp;
import io.bitsquare.gui.main.overlays.Overlay;
import io.bitsquare.user.Preferences;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static io.bitsquare.gui.util.FormBuilder.addHyperlinkWithIcon;
public class TacWindow extends Overlay<TacWindow> {
private static final Logger log = LoggerFactory.getLogger(TacWindow.class);
private final Preferences preferences;
@Inject
public TacWindow(Preferences preferences) {
this.preferences = preferences;
type = Type.Attention;
width = 800;
}
public void showIfNeeded() {
if (!preferences.getTacAccepted() && !BitsquareApp.DEV_MODE) {
headLine("User agreement");
String text = "1. This software is experimental and 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 non-infringement.\n" +
"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.\n\n" +
"2. The user is responsible to use the software in compliance with local laws. Don't use Bitsquare if the usage of Bitcoin is not legal in your jurisdiction.\n\n" +
"3. Bitcoin market price is delivered by 3rd parties (BitcoinAverage, Poloniex). It is your responsibility to double check the price with other sources.\n\n" +
"4. The user confirms that he has read and agreed to the rules regrading the dispute process:\n" +
" - You must finalize trades within the maximum duration specified for each payment method.\n" +
" - You must enter the trade ID in the \"reason for payment\" text field when doing the fiat payment transfer.\n" +
" - If the bank of the fiat sender charges fees the sender (bitcoin buyer) has to cover the fees.\n" +
" - You must cooperate with the arbitrator during the arbitration process.\n" +
" - You must reply within 48 hours to each arbitrator inquiry.\n" +
" - Failure to follow the above requirements may result in loss of your security deposit.\n\n" +
"For more details and a general overview please read the full documentation about the " +
"arbitration system and the dispute process.";
message(text);
actionButtonText("I agree");
closeButtonText("I disagree and quit");
onAction(() -> preferences.setTacAccepted(true));
onClose(BitsquareApp.shutDownHandler::run);
super.show();
}
}
@Override
protected void addMessage() {
super.addMessage();
addHyperlinkWithIcon(gridPane, ++rowIndex, "Arbitration system", "https://bitsquare.io/arbitration_system.pdf", -6);
}
@Override
protected void onShow() {
display();
}
}
| Typo fix. | gui/src/main/java/io/bitsquare/gui/main/overlays/windows/TacWindow.java | Typo fix. | <ide><path>ui/src/main/java/io/bitsquare/gui/main/overlays/windows/TacWindow.java
<ide> "arising from, out of or in connection with the software or the use or other dealings in the software.\n\n" +
<ide> "2. The user is responsible to use the software in compliance with local laws. Don't use Bitsquare if the usage of Bitcoin is not legal in your jurisdiction.\n\n" +
<ide> "3. Bitcoin market price is delivered by 3rd parties (BitcoinAverage, Poloniex). It is your responsibility to double check the price with other sources.\n\n" +
<del> "4. The user confirms that he has read and agreed to the rules regrading the dispute process:\n" +
<add> "4. The user confirms that he has read and agreed to the rules regarding the dispute process:\n" +
<ide> " - You must finalize trades within the maximum duration specified for each payment method.\n" +
<ide> " - You must enter the trade ID in the \"reason for payment\" text field when doing the fiat payment transfer.\n" +
<ide> " - If the bank of the fiat sender charges fees the sender (bitcoin buyer) has to cover the fees.\n" + |
|
Java | apache-2.0 | 1a4f53058cca04b12287b794d4858b57e0324d72 | 0 | gjroelofs/artemis-odb,snorrees/artemis-odb,antag99/artemis-odb,gjroelofs/artemis-odb,Namek/artemis-odb,snorrees/artemis-odb,antag99/artemis-odb,gjroelofs/artemis-odb,DaanVanYperen/artemis-odb | package com.artemis;
import java.util.BitSet;
import java.util.HashMap;
import com.artemis.utils.Bag;
import com.artemis.utils.ImmutableBag;
/**
* The most raw entity system. It should not typically be used, but you can create your own
* entity system handling by extending this. It is recommended that you use the other provided
* entity system implementations.
*
* @author Arni Arent
*
*/
public abstract class EntitySystem implements EntityObserver {
private final int systemIndex;
protected World world;
private Bag<Entity> actives;
private Aspect aspect;
private BitSet allSet;
private BitSet exclusionSet;
private BitSet oneSet;
private boolean passive;
private boolean enabled;
private boolean dummy;
/**
* Creates an entity system that uses the specified aspect as a matcher against entities.
* @param aspect to match against entities
*/
public EntitySystem(Aspect aspect) {
actives = new Bag<Entity>();
this.aspect = aspect;
allSet = aspect.getAllSet();
exclusionSet = aspect.getExclusionSet();
oneSet = aspect.getOneSet();
systemIndex = SystemIndexManager.getIndexFor(this.getClass());
dummy = allSet.isEmpty() && oneSet.isEmpty(); // This system can't possibly be interested in any entity, so it must be "dummy"
enabled = true;
}
/**
* Called before processing of entities begins.
*/
protected void begin() {
}
public final void process() {
if(enabled && checkProcessing()) {
begin();
processEntities(actives);
end();
}
}
/**
* Called after the processing of entities ends.
*/
protected void end() {
}
/**
* Any implementing entity system must implement this method and the logic
* to process the given entities of the system.
*
* @param entities the entities this system contains.
*/
protected abstract void processEntities(ImmutableBag<Entity> entities);
/**
*
* @return true if the system should be processed, false if not.
*/
protected abstract boolean checkProcessing();
/**
* Override to implement code that gets executed when systems are initialized.
*/
protected void initialize() {};
/**
* Called if the system has received a entity it is interested in, e.g. created or a component was added to it.
* @param e the entity that was added to this system.
*/
protected void inserted(Entity e) {};
/**
* Called if a entity was removed from this system, e.g. deleted or had one of it's components removed.
* @param e the entity that was removed from this system.
*/
protected void removed(Entity e) {};
/**
* Returns true if the system is enabled.
*
* @return True if enabled, otherwise false.
*/
public boolean isEnabled() {
return enabled;
}
/**
* Enabled systems are run during {@link #process()}. Systems are enabled by defautl.
*
* @param enabled System will not run when set to false.
*/
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
/**
* Will check if the entity is of interest to this system.
* @param e entity to check
*/
protected final void check(Entity e) {
if(dummy) {
return;
}
boolean contains = e.getSystemBits().get(systemIndex);
boolean interested = true; // possibly interested, let's try to prove it wrong.
BitSet componentBits = e.getComponentBits();
// Check if the entity possesses ALL of the components defined in the aspect.
if(!allSet.isEmpty()) {
for (int i = allSet.nextSetBit(0); i >= 0; i = allSet.nextSetBit(i+1)) {
if(!componentBits.get(i)) {
interested = false;
break;
}
}
}
// Check if the entity possesses ANY of the exclusion components, if it does then the system is not interested.
if(!exclusionSet.isEmpty() && interested) {
interested = !exclusionSet.intersects(componentBits);
}
// Check if the entity possesses ANY of the components in the oneSet. If so, the system is interested.
if(!oneSet.isEmpty()) {
interested = oneSet.intersects(componentBits);
}
if (interested && !contains) {
insertToSystem(e);
} else if (!interested && contains) {
removeFromSystem(e);
}
}
private void removeFromSystem(Entity e) {
actives.remove(e);
e.getSystemBits().clear(systemIndex);
removed(e);
}
private void insertToSystem(Entity e) {
actives.add(e);
e.getSystemBits().set(systemIndex);
inserted(e);
}
@Override
public final void added(Entity e) {
check(e);
}
@Override
public final void changed(Entity e) {
check(e);
}
@Override
public final void deleted(Entity e) {
if(e.getSystemBits().get(systemIndex)) {
removeFromSystem(e);
}
}
@Override
public final void disabled(Entity e) {
if(e.getSystemBits().get(systemIndex)) {
removeFromSystem(e);
}
}
@Override
public final void enabled(Entity e) {
check(e);
}
protected final void setWorld(World world) {
this.world = world;
}
protected boolean isPassive() {
return passive;
}
protected void setPassive(boolean passive) {
this.passive = passive;
}
public ImmutableBag<Entity> getActives() {
return actives;
}
/**
* Used to generate a unique bit for each system.
* Only used internally in EntitySystem.
*/
private static class SystemIndexManager {
private static int INDEX = 0;
private static HashMap<Class<? extends EntitySystem>, Integer> indices = new HashMap<Class<? extends EntitySystem>, Integer>();
private static int getIndexFor(Class<? extends EntitySystem> es){
Integer index = indices.get(es);
if(index == null) {
index = INDEX++;
indices.put(es, index);
}
return index;
}
}
}
| src/com/artemis/EntitySystem.java | package com.artemis;
import java.util.BitSet;
import java.util.HashMap;
import com.artemis.utils.Bag;
import com.artemis.utils.ImmutableBag;
/**
* The most raw entity system. It should not typically be used, but you can create your own
* entity system handling by extending this. It is recommended that you use the other provided
* entity system implementations.
*
* @author Arni Arent
*
*/
public abstract class EntitySystem implements EntityObserver {
private final int systemIndex;
protected World world;
private Bag<Entity> actives;
private Aspect aspect;
private BitSet allSet;
private BitSet exclusionSet;
private BitSet oneSet;
private boolean passive;
private boolean dummy;
/**
* Creates an entity system that uses the specified aspect as a matcher against entities.
* @param aspect to match against entities
*/
public EntitySystem(Aspect aspect) {
actives = new Bag<Entity>();
this.aspect = aspect;
allSet = aspect.getAllSet();
exclusionSet = aspect.getExclusionSet();
oneSet = aspect.getOneSet();
systemIndex = SystemIndexManager.getIndexFor(this.getClass());
dummy = allSet.isEmpty() && oneSet.isEmpty(); // This system can't possibly be interested in any entity, so it must be "dummy"
}
/**
* Called before processing of entities begins.
*/
protected void begin() {
}
public final void process() {
if(checkProcessing()) {
begin();
processEntities(actives);
end();
}
}
/**
* Called after the processing of entities ends.
*/
protected void end() {
}
/**
* Any implementing entity system must implement this method and the logic
* to process the given entities of the system.
*
* @param entities the entities this system contains.
*/
protected abstract void processEntities(ImmutableBag<Entity> entities);
/**
*
* @return true if the system should be processed, false if not.
*/
protected abstract boolean checkProcessing();
/**
* Override to implement code that gets executed when systems are initialized.
*/
protected void initialize() {};
/**
* Called if the system has received a entity it is interested in, e.g. created or a component was added to it.
* @param e the entity that was added to this system.
*/
protected void inserted(Entity e) {};
/**
* Called if a entity was removed from this system, e.g. deleted or had one of it's components removed.
* @param e the entity that was removed from this system.
*/
protected void removed(Entity e) {};
/**
* Will check if the entity is of interest to this system.
* @param e entity to check
*/
protected final void check(Entity e) {
if(dummy) {
return;
}
boolean contains = e.getSystemBits().get(systemIndex);
boolean interested = true; // possibly interested, let's try to prove it wrong.
BitSet componentBits = e.getComponentBits();
// Check if the entity possesses ALL of the components defined in the aspect.
if(!allSet.isEmpty()) {
for (int i = allSet.nextSetBit(0); i >= 0; i = allSet.nextSetBit(i+1)) {
if(!componentBits.get(i)) {
interested = false;
break;
}
}
}
// Check if the entity possesses ANY of the exclusion components, if it does then the system is not interested.
if(!exclusionSet.isEmpty() && interested) {
interested = !exclusionSet.intersects(componentBits);
}
// Check if the entity possesses ANY of the components in the oneSet. If so, the system is interested.
if(!oneSet.isEmpty()) {
interested = oneSet.intersects(componentBits);
}
if (interested && !contains) {
insertToSystem(e);
} else if (!interested && contains) {
removeFromSystem(e);
}
}
private void removeFromSystem(Entity e) {
actives.remove(e);
e.getSystemBits().clear(systemIndex);
removed(e);
}
private void insertToSystem(Entity e) {
actives.add(e);
e.getSystemBits().set(systemIndex);
inserted(e);
}
@Override
public final void added(Entity e) {
check(e);
}
@Override
public final void changed(Entity e) {
check(e);
}
@Override
public final void deleted(Entity e) {
if(e.getSystemBits().get(systemIndex)) {
removeFromSystem(e);
}
}
@Override
public final void disabled(Entity e) {
if(e.getSystemBits().get(systemIndex)) {
removeFromSystem(e);
}
}
@Override
public final void enabled(Entity e) {
check(e);
}
protected final void setWorld(World world) {
this.world = world;
}
protected boolean isPassive() {
return passive;
}
protected void setPassive(boolean passive) {
this.passive = passive;
}
public ImmutableBag<Entity> getActives() {
return actives;
}
/**
* Used to generate a unique bit for each system.
* Only used internally in EntitySystem.
*/
private static class SystemIndexManager {
private static int INDEX = 0;
private static HashMap<Class<? extends EntitySystem>, Integer> indices = new HashMap<Class<? extends EntitySystem>, Integer>();
private static int getIndexFor(Class<? extends EntitySystem> es){
Integer index = indices.get(es);
if(index == null) {
index = INDEX++;
indices.put(es, index);
}
return index;
}
}
}
| Added enabled flag to EntitySystem.
| src/com/artemis/EntitySystem.java | Added enabled flag to EntitySystem. | <ide><path>rc/com/artemis/EntitySystem.java
<ide> private BitSet oneSet;
<ide>
<ide> private boolean passive;
<add> private boolean enabled;
<ide>
<ide> private boolean dummy;
<ide>
<ide> oneSet = aspect.getOneSet();
<ide> systemIndex = SystemIndexManager.getIndexFor(this.getClass());
<ide> dummy = allSet.isEmpty() && oneSet.isEmpty(); // This system can't possibly be interested in any entity, so it must be "dummy"
<add>
<add> enabled = true;
<ide> }
<ide>
<ide> /**
<ide> }
<ide>
<ide> public final void process() {
<del> if(checkProcessing()) {
<add> if(enabled && checkProcessing()) {
<ide> begin();
<ide> processEntities(actives);
<ide> end();
<ide> * @param e the entity that was removed from this system.
<ide> */
<ide> protected void removed(Entity e) {};
<add>
<add>
<add> /**
<add> * Returns true if the system is enabled.
<add> *
<add> * @return True if enabled, otherwise false.
<add> */
<add> public boolean isEnabled() {
<add> return enabled;
<add> }
<add>
<add> /**
<add> * Enabled systems are run during {@link #process()}. Systems are enabled by defautl.
<add> *
<add> * @param enabled System will not run when set to false.
<add> */
<add> public void setEnabled(boolean enabled) {
<add> this.enabled = enabled;
<add> }
<ide>
<ide> /**
<ide> * Will check if the entity is of interest to this system. |
|
Java | apache-2.0 | 506c9ba168755d3349ea0e87f467d92783694ef2 | 0 | speedment/speedment,speedment/speedment | /*
*
* Copyright (c) 2006-2019, Speedment, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); You may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.speedment.tool.core.internal.controller;
import com.speedment.common.injector.annotation.Inject;
import com.speedment.generator.core.component.EventComponent;
import com.speedment.generator.core.event.ProjectLoaded;
import com.speedment.runtime.config.trait.HasEnabled;
import com.speedment.tool.actions.ProjectTreeComponent;
import com.speedment.tool.config.ColumnProperty;
import com.speedment.tool.config.DocumentProperty;
import com.speedment.tool.config.IndexProperty;
import com.speedment.tool.config.PrimaryKeyColumnProperty;
import com.speedment.tool.config.ProjectProperty;
import com.speedment.tool.config.trait.HasEnabledProperty;
import com.speedment.tool.config.trait.HasExpandedProperty;
import com.speedment.tool.config.trait.HasIconPath;
import com.speedment.tool.config.trait.HasNameProperty;
import com.speedment.tool.core.component.UserInterfaceComponent;
import com.speedment.tool.core.resource.SpeedmentIcon;
import javafx.beans.binding.Bindings;
import javafx.beans.value.ChangeListener;
import javafx.collections.ListChangeListener;
import javafx.collections.MapChangeListener;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import java.net.URL;
import java.util.ResourceBundle;
import static java.util.Objects.requireNonNull;
import static javafx.application.Platform.runLater;
import static javafx.scene.control.SelectionMode.SINGLE;
/**
*
* @author Emil Forslund
*/
public final class ProjectTreeController implements Initializable {
private @Inject UserInterfaceComponent ui;
private @Inject ProjectTreeComponent projectTreeComponent;
private @Inject EventComponent events;
private @FXML TreeView<DocumentProperty> hierarchy;
@Override
public void initialize(URL location, ResourceBundle resources) {
runLater(() -> prepareTree(ui.projectProperty()));
}
private void prepareTree(ProjectProperty project) {
requireNonNull(project);
events.notify(new ProjectLoaded(project));
Bindings.bindContent(ui.getSelectedTreeItems(), hierarchy.getSelectionModel().getSelectedItems());
hierarchy.setCellFactory(view -> new DocumentPropertyCell(projectTreeComponent));
hierarchy.getSelectionModel().setSelectionMode(SINGLE);
populateTree(project);
}
private void populateTree(ProjectProperty project) {
requireNonNull(project);
final TreeItem<DocumentProperty> root = branch(project);
hierarchy.setRoot(root);
hierarchy.getSelectionModel().select(root);
}
private <P extends DocumentProperty & HasExpandedProperty>
TreeItem<DocumentProperty> branch(P doc) {
requireNonNull(doc);
final TreeItem<DocumentProperty> branch = new TreeItem<>(doc);
branch.expandedProperty().bindBidirectional(doc.expandedProperty());
final ListChangeListener<? super DocumentProperty> onListChange =
(ListChangeListener.Change<? extends DocumentProperty> change) -> {
while (change.next()) {
if (change.wasAdded()) {
change.getAddedSubList().stream()
.filter(HasExpandedProperty.class::isInstance)
.map(d -> (HasExpandedProperty) d)
.map(this::branch)
.forEachOrdered(branch.getChildren()::add);
}
if (change.wasRemoved()) {
change.getRemoved()
.forEach(val -> branch.getChildren()
.removeIf(item -> val.equals(item.getValue()))
);
}
}
};
// Create a branch for every child
doc.children()
.filter(HasExpandedProperty.class::isInstance)
.map(d -> (HasExpandedProperty) d)
.map(this::branch)
.forEachOrdered(branch.getChildren()::add);
// Listen to changes in the actual map
doc.childrenProperty().addListener(
(MapChangeListener.Change<
? extends String,
? extends ObservableList<DocumentProperty>> change) -> {
if (change.wasAdded()) {
// Listen for changes in the added list
change.getValueAdded().addListener(onListChange);
// Create a branch for every child
change.getValueAdded().stream()
.filter(HasExpandedProperty.class::isInstance)
.map(d -> (DocumentProperty & HasExpandedProperty) d)
.map(this::branch)
.forEachOrdered(branch.getChildren()::add);
}
});
// Listen to changes in every list inside the map
doc.childrenProperty()
.values()
.forEach(list -> list.addListener(onListChange));
return branch;
}
private final static class DocumentPropertyCell extends TreeCell<DocumentProperty> {
private final ChangeListener<Boolean> change = (ob, o, enabled) -> {
if (enabled) {
enable();
} else {
disable();
}
};
private final ProjectTreeComponent projectTreeComponent;
DocumentPropertyCell(ProjectTreeComponent projectTreeComponent) {
this.projectTreeComponent = requireNonNull(projectTreeComponent);
// Listener should be initiated with a listener attached
// that removes enabled-listeners attached to the previous
// node when a new node is selected.
itemProperty().addListener((ob, o, n) -> {
if (o != null && o instanceof HasEnabledProperty) {
final HasEnabledProperty hasEnabled = (HasEnabledProperty) o;
hasEnabled.enabledProperty().removeListener(change);
}
if (n != null && n instanceof HasEnabledProperty) {
final HasEnabledProperty hasEnabled = (HasEnabledProperty) n;
hasEnabled.enabledProperty().addListener(change);
}
});
}
private void disable() {
getStyleClass().add("gui-disabled");
}
private void enable() {
while (getStyleClass().remove("gui-disabled")) {
// Do nothing.
}
}
@Override
protected void updateItem(DocumentProperty item, boolean empty) {
// item can be null
super.updateItem(item, empty);
if (empty || item == null) {
textProperty().unbind();
setText(null);
setGraphic(null);
setContextMenu(null);
disable();
} else {
final ImageView icon;
if (item instanceof HasIconPath) {
final HasIconPath hasIcon = (HasIconPath) item;
icon = new ImageView(new Image(hasIcon.getIconPath()));
} else {
icon = SpeedmentIcon.forNode(item);
}
setGraphic(icon);
if (item instanceof HasNameProperty) {
@SuppressWarnings("unchecked")
final HasNameProperty withName = (HasNameProperty) item;
textProperty().bind(withName.nameProperty());
} else {
textProperty().unbind();
textProperty().setValue(null);
}
projectTreeComponent.createContextMenu(this, item)
.ifPresent(this::setContextMenu);
boolean indicateEnabled = HasEnabled.test(item);
if (item instanceof ColumnProperty) {
indicateEnabled &= ((ColumnProperty) item).getParentOrThrow().isEnabled();
} else if (item instanceof IndexProperty) {
indicateEnabled &= ((IndexProperty) item).getParentOrThrow().isEnabled();
} else if (item instanceof PrimaryKeyColumnProperty) {
indicateEnabled &= ((PrimaryKeyColumnProperty) item).getParentOrThrow().isEnabled();
}
if (indicateEnabled) {
enable();
} else {
disable();
}
getTreeView().refresh();
}
}
}
}
| tool-parent/tool-core/src/main/java/com/speedment/tool/core/internal/controller/ProjectTreeController.java | /*
*
* Copyright (c) 2006-2019, Speedment, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); You may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.speedment.tool.core.internal.controller;
import com.speedment.common.injector.annotation.Inject;
import com.speedment.generator.core.component.EventComponent;
import com.speedment.generator.core.event.ProjectLoaded;
import com.speedment.runtime.config.trait.HasEnabled;
import com.speedment.tool.actions.ProjectTreeComponent;
import com.speedment.tool.config.ColumnProperty;
import com.speedment.tool.config.DocumentProperty;
import com.speedment.tool.config.IndexProperty;
import com.speedment.tool.config.PrimaryKeyColumnProperty;
import com.speedment.tool.config.ProjectProperty;
import com.speedment.tool.config.trait.HasEnabledProperty;
import com.speedment.tool.config.trait.HasExpandedProperty;
import com.speedment.tool.config.trait.HasIconPath;
import com.speedment.tool.config.trait.HasNameProperty;
import com.speedment.tool.core.component.UserInterfaceComponent;
import com.speedment.tool.core.resource.SpeedmentIcon;
import javafx.beans.binding.Bindings;
import javafx.beans.value.ChangeListener;
import javafx.collections.ListChangeListener;
import javafx.collections.MapChangeListener;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import java.net.URL;
import java.util.ResourceBundle;
import static java.util.Objects.requireNonNull;
import static javafx.application.Platform.runLater;
import static javafx.scene.control.SelectionMode.SINGLE;
/**
*
* @author Emil Forslund
*/
public final class ProjectTreeController implements Initializable {
private @Inject UserInterfaceComponent ui;
private @Inject ProjectTreeComponent projectTreeComponent;
private @Inject EventComponent events;
private @FXML TreeView<DocumentProperty> hierarchy;
@Override
public void initialize(URL location, ResourceBundle resources) {
runLater(() -> prepareTree(ui.projectProperty()));
}
private void prepareTree(ProjectProperty project) {
requireNonNull(project);
events.notify(new ProjectLoaded(project));
Bindings.bindContent(ui.getSelectedTreeItems(), hierarchy.getSelectionModel().getSelectedItems());
hierarchy.setCellFactory(view -> new DocumentPropertyCell(projectTreeComponent));
hierarchy.getSelectionModel().setSelectionMode(SINGLE);
populateTree(project);
}
private void populateTree(ProjectProperty project) {
requireNonNull(project);
final TreeItem<DocumentProperty> root = branch(project);
hierarchy.setRoot(root);
hierarchy.getSelectionModel().select(root);
}
private <P extends DocumentProperty & HasExpandedProperty>
TreeItem<DocumentProperty> branch(P doc) {
requireNonNull(doc);
final TreeItem<DocumentProperty> branch = new TreeItem<>(doc);
branch.expandedProperty().bindBidirectional(doc.expandedProperty());
final ListChangeListener<? super DocumentProperty> onListChange =
(ListChangeListener.Change<? extends DocumentProperty> change) -> {
while (change.next()) {
if (change.wasAdded()) {
change.getAddedSubList().stream()
.filter(HasExpandedProperty.class::isInstance)
.map(d -> (HasExpandedProperty) d)
.map(this::branch)
.forEachOrdered(branch.getChildren()::add);
}
if (change.wasRemoved()) {
change.getRemoved()
.forEach(val -> branch.getChildren()
.removeIf(item -> val.equals(item.getValue()))
);
}
}
};
// Create a branch for every child
doc.children()
.filter(HasExpandedProperty.class::isInstance)
.map(d -> (HasExpandedProperty) d)
.map(this::branch)
.forEachOrdered(branch.getChildren()::add);
// Listen to changes in the actual map
doc.childrenProperty().addListener(
(MapChangeListener.Change<
? extends String,
? extends ObservableList<DocumentProperty>> change) -> {
if (change.wasAdded()) {
// Listen for changes in the added list
change.getValueAdded().addListener(onListChange);
// Create a branch for every child
change.getValueAdded().stream()
.filter(HasExpandedProperty.class::isInstance)
.map(d -> (DocumentProperty & HasExpandedProperty) d)
.map(this::branch)
.forEachOrdered(branch.getChildren()::add);
}
});
// Listen to changes in every list inside the map
doc.childrenProperty()
.values()
.forEach(list -> list.addListener(onListChange));
return branch;
}
private final static class DocumentPropertyCell extends TreeCell<DocumentProperty> {
private final ChangeListener<Boolean> change = (ob, o, enabled) -> {
if (enabled) {
enable();
} else {
disable();
}
};
private final ProjectTreeComponent projectTreeComponent;
DocumentPropertyCell(ProjectTreeComponent projectTreeComponent) {
this.projectTreeComponent = requireNonNull(projectTreeComponent);
// Listener should be initiated with a listener attached
// that removes enabled-listeners attached to the previous
// node when a new node is selected.
itemProperty().addListener((ob, o, n) -> {
if (o != null && o instanceof HasEnabledProperty) {
final HasEnabledProperty hasEnabled = (HasEnabledProperty) o;
hasEnabled.enabledProperty().removeListener(change);
}
if (n != null && n instanceof HasEnabledProperty) {
final HasEnabledProperty hasEnabled = (HasEnabledProperty) n;
hasEnabled.enabledProperty().addListener(change);
}
});
}
private void disable() {
getStyleClass().add("gui-disabled");
}
private void enable() {
while (getStyleClass().remove("gui-disabled")) {
// Do nothing.
}
}
@Override
protected void updateItem(DocumentProperty item, boolean empty) {
// item can be null
super.updateItem(item, empty);
if (empty || item == null) {
textProperty().unbind();
setText(null);
setGraphic(null);
setContextMenu(null);
disable();
} else {
final ImageView icon;
if (item instanceof HasIconPath) {
final HasIconPath hasIcon = (HasIconPath) item;
icon = new ImageView(new Image(hasIcon.getIconPath()));
} else {
icon = SpeedmentIcon.forNode(item);
}
setGraphic(icon);
if (item instanceof HasNameProperty) {
@SuppressWarnings("unchecked")
final HasNameProperty withName = (HasNameProperty) item;
textProperty().bind(withName.nameProperty());
} else {
textProperty().unbind();
textProperty().setValue(null);
}
projectTreeComponent.createContextMenu(this, item)
.ifPresent(this::setContextMenu);
boolean indicateEnabled = HasEnabled.test(item);
if (item instanceof ColumnProperty) {
indicateEnabled &= ((ColumnProperty) item).getParentOrThrow().isEnabled();
} else if (item instanceof IndexProperty) {
indicateEnabled &= ((IndexProperty) item).getParentOrThrow().isEnabled();
} else if (item instanceof PrimaryKeyColumnProperty) {
indicateEnabled &= ((PrimaryKeyColumnProperty) item).getParentOrThrow().isEnabled();
}
if (indicateEnabled) {
enable();
} else {
disable();
}
}
}
}
}
| Force tree view refresh
After disabling a table, the columns that are not included in the code generation process stay in the state they were in before the table was disabled until they are clicked on in the tree view. By forcing a render refresh on the tree view we avoid this problem.
| tool-parent/tool-core/src/main/java/com/speedment/tool/core/internal/controller/ProjectTreeController.java | Force tree view refresh | <ide><path>ool-parent/tool-core/src/main/java/com/speedment/tool/core/internal/controller/ProjectTreeController.java
<ide> } else {
<ide> disable();
<ide> }
<add>
<add> getTreeView().refresh();
<ide> }
<ide> }
<ide> } |
|
Java | apache-2.0 | cd6431405409920e42ee376e1a84ae4b016471fd | 0 | ibissource/iaf,ibissource/iaf,ibissource/iaf,ibissource/iaf,ibissource/iaf | /*
* $Log: IdocXmlHandler.java,v $
* Revision 1.2 2008-01-30 14:43:40 europe\L190409
* improved logging
*
* Revision 1.1 2008/01/29 12:36:17 Gerrit van Brakel <[email protected]>
* first version
*
*/
package nl.nn.adapterframework.extensions.sap;
import java.util.ArrayList;
import java.util.List;
import nl.nn.adapterframework.util.LogUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.xml.sax.Attributes;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
import com.sap.mw.idoc.IDoc;
import com.sap.mw.idoc.jco.JCoIDoc;
/**
* DefaultHandler extension to parse SAP Idocs in XML format into JCoIDoc format.
*
* @author Gerrit van Brakel
* @since 4.8
* @version Id
*/
public class IdocXmlHandler extends DefaultHandler {
protected Logger log = LogUtil.getLogger(this.getClass());
private SapSystem sapSystem;
private IDoc.Document doc=null;
private List segmentStack=new ArrayList();
private String currentField;
private StringBuffer currentFieldValue=new StringBuffer();
private boolean parsingEdiDcHeader=false;
private Locator locator;
public IdocXmlHandler(SapSystem sapSystem) {
super();
this.sapSystem=sapSystem;
}
public IDoc.Document getIdoc() {
return doc;
}
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
//log.debug("startElement("+localName+")");
if (doc==null) {
log.debug("creating Idoc ["+localName+"]");
doc = JCoIDoc.createDocument(sapSystem.getIDocRepository(), localName);
IDoc.Segment segment = doc.getRootSegment();
segmentStack.add(segment);
} else {
if (attributes.getIndex("SEGMENT")>=0) {
if (localName.startsWith("EDI_DC")) {
parsingEdiDcHeader=true;
} else {
log.debug("creating segment ["+localName+"]");
IDoc.Segment parentSegment = (IDoc.Segment)segmentStack.get(segmentStack.size()-1);
IDoc.Segment segment = parentSegment.addChild(localName);
segmentStack.add(segment);
}
} else {
currentField=localName;
}
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
//log.debug("endElement("+localName+")");
if (currentField!=null) {
String value=currentFieldValue.toString().trim();
if (StringUtils.isNotEmpty(value)) {
if (parsingEdiDcHeader) {
if (log.isDebugEnabled()) log.debug("parsed header field ["+currentField+"] value ["+value+"]");
if (currentField.equals("ARCKEY")) { doc.setArchiveKey(value); }
else if (currentField.equals("MANDT")) { doc.setClient(value); }
else if (currentField.equals("CREDAT")) { doc.setCreationDate(value); }
else if (currentField.equals("CRETIM")) { doc.setCreationTime(value); }
else if (currentField.equals("DIRECT")) { doc.setDirection(value); }
else if (currentField.equals("REFMES")) { doc.setEDIMessage(value); }
else if (currentField.equals("REFGRP")) { doc.setEDIMessageGroup(value); }
else if (currentField.equals("STDMES")) { doc.setEDIMessageType(value); }
else if (currentField.equals("STD")) { doc.setEDIStandardFlag(value); }
else if (currentField.equals("STDVRS")) { doc.setEDIStandardVersion(value); }
else if (currentField.equals("REFINT")) { doc.setEDITransmissionFile(value); }
else if (currentField.equals("EXPRSS")) { doc.setExpressFlag(value); }
else if (currentField.equals("DOCTYP")) { doc.setIDocCompoundType(value); }
else if (currentField.equals("DOCNUM")) { doc.setIDocNumber(value); }
else if (currentField.equals("DOCREL")) { doc.setIDocSAPRelease(value); }
else if (currentField.equals("IDOCTYP")){ doc.setIDocType(value); }
else if (currentField.equals("CIMTYP")) { doc.setIDocTypeExtension(value); }
else if (currentField.equals("MESCOD")) { doc.setMessageCode(value); }
else if (currentField.equals("MESFCT")) { doc.setMessageFunction(value); }
else if (currentField.equals("MESTYP")) { doc.setMessageType(value); }
else if (currentField.equals("OUTMOD")) { doc.setOutputMode(value); }
else if (currentField.equals("RCVSAD")) { doc.setRecipientAddress(value); }
else if (currentField.equals("RCVLAD")) { doc.setRecipientLogicalAddress(value); }
else if (currentField.equals("RCVPFC")) { doc.setRecipientPartnerFunction(value); }
else if (currentField.equals("RCVPRN")) { doc.setRecipientPartnerNumber(value); }
else if (currentField.equals("RCVPRT")) { doc.setRecipientPartnerType(value); }
else if (currentField.equals("RCVPOR")) { doc.setRecipientPort(value); }
else if (currentField.equals("SNDSAD")) { doc.setSenderAddress(value); }
else if (currentField.equals("SNDLAD")) { doc.setSenderLogicalAddress(value); }
else if (currentField.equals("SNDPFC")) { doc.setSenderPartnerFunction(value); }
else if (currentField.equals("SNDPRN")) { doc.setSenderPartnerNumber(value); }
else if (currentField.equals("SNDPRT")) { doc.setSenderPartnerType(value); }
else if (currentField.equals("SNDPOR")) { doc.setSenderPort(value); }
else if (currentField.equals("SERIAL")) { doc.setSerialization(value); }
else if (currentField.equals("STATUS")) { doc.setStatus(value); }
else if (currentField.equals("TEST")) { doc.setTestFlag(value); }
else {
log.warn("header field ["+currentField+"] value ["+value+"] discarded");
}
} else {
IDoc.Segment segment = (IDoc.Segment)segmentStack.get(segmentStack.size()-1);
if (log.isDebugEnabled()) log.debug("setting field ["+currentField+"] to ["+value+"]");
segment.setField(currentField,value);
}
}
currentField = null;
currentFieldValue.setLength(0);
} else {
if (parsingEdiDcHeader) {
parsingEdiDcHeader=false;
} else {
if (segmentStack.size()>0) {
segmentStack.remove(segmentStack.size()-1);
}
}
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
if (currentField==null) {
String part=new String(ch,start,length).trim();
if (StringUtils.isNotEmpty(part)) {
throw new SAXParseException("found character content ["+part+"] outside a field", locator);
}
return;
}
currentFieldValue.append(ch,start,length);
}
public void error(SAXParseException e) throws SAXException {
log.warn("Parser Error",e);
super.error(e);
}
public void fatalError(SAXParseException e) throws SAXException {
log.warn("Parser FatalError",e);
super.fatalError(e);
}
public void warning(SAXParseException e) throws SAXException {
log.warn("Parser Warning",e);
super.warning(e);
}
public void setDocumentLocator(Locator locator) {
super.setDocumentLocator(locator);
this.locator=locator;
}
}
| JavaSource/nl/nn/adapterframework/extensions/sap/IdocXmlHandler.java | /*
* $Log: IdocXmlHandler.java,v $
* Revision 1.1 2008-01-29 12:36:17 europe\L190409
* first version
*
*/
package nl.nn.adapterframework.extensions.sap;
import java.util.ArrayList;
import java.util.List;
import nl.nn.adapterframework.util.LogUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.xml.sax.Attributes;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
import com.sap.mw.idoc.IDoc;
import com.sap.mw.idoc.jco.JCoIDoc;
/**
* DefaultHandler extension to parse SAP Idocs in XML format into JCoIDoc format.
*
* @author Gerrit van Brakel
* @since 4.8
* @version Id
*/
public class IdocXmlHandler extends DefaultHandler {
protected Logger log = LogUtil.getLogger(this.getClass());
private SapSystem sapSystem;
private IDoc.Document doc=null;
private List segmentStack=new ArrayList();
private String currentField;
private StringBuffer currentFieldValue=new StringBuffer();
private boolean parsingEdiDcHeader=false;
private Locator locator;
public IdocXmlHandler(SapSystem sapSystem) {
super();
this.sapSystem=sapSystem;
}
public IDoc.Document getIdoc() {
return doc;
}
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
//log.debug("startElement("+localName+")");
if (doc==null) {
log.debug("creating Idoc ["+localName+"]");
doc = JCoIDoc.createDocument(sapSystem.getIDocRepository(), localName);
IDoc.Segment segment = doc.getRootSegment();
segmentStack.add(segment);
} else {
if (attributes.getIndex("SEGMENT")>=0) {
if (localName.startsWith("EDI_DC")) {
parsingEdiDcHeader=true;
} else {
log.debug("creating segment ["+localName+"]");
IDoc.Segment parentSegment = (IDoc.Segment)segmentStack.get(segmentStack.size()-1);
IDoc.Segment segment = parentSegment.addChild(localName);
segmentStack.add(segment);
}
} else {
currentField=localName;
}
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
//log.debug("endElement("+localName+")");
if (currentField!=null) {
String value=currentFieldValue.toString().trim();
if (StringUtils.isNotEmpty(value)) {
if (parsingEdiDcHeader) {
if (currentField.equals("ARCKEY")) { doc.setArchiveKey(value); }
else if (currentField.equals("MANDT")) { doc.setClient(value); }
else if (currentField.equals("CREDAT")) { doc.setCreationDate(value); }
else if (currentField.equals("CRETIM")) { doc.setCreationTime(value); }
else if (currentField.equals("DIRECT")) { doc.setDirection(value); }
else if (currentField.equals("REFMES")) { doc.setEDIMessage(value); }
else if (currentField.equals("REFGRP")) { doc.setEDIMessageGroup(value); }
else if (currentField.equals("STDMES")) { doc.setEDIMessageType(value); }
else if (currentField.equals("STD")) { doc.setEDIStandardFlag(value); }
else if (currentField.equals("STDVRS")) { doc.setEDIStandardVersion(value); }
else if (currentField.equals("REFINT")) { doc.setEDITransmissionFile(value); }
else if (currentField.equals("EXPRSS")) { doc.setExpressFlag(value); }
else if (currentField.equals("DOCTYP")) { doc.setIDocCompoundType(value); }
else if (currentField.equals("DOCNUM")) { doc.setIDocNumber(value); }
else if (currentField.equals("DOCREL")) { doc.setIDocSAPRelease(value); }
else if (currentField.equals("IDOCTYP")){ doc.setIDocType(value); }
else if (currentField.equals("CIMTYP")) { doc.setIDocTypeExtension(value); }
else if (currentField.equals("MESCOD")) { doc.setMessageCode(value); }
else if (currentField.equals("MESFCT")) { doc.setMessageFunction(value); }
else if (currentField.equals("MESTYP")) { doc.setMessageType(value); }
else if (currentField.equals("OUTMOD")) { doc.setOutputMode(value); }
else if (currentField.equals("RCVSAD")) { doc.setRecipientAddress(value); }
else if (currentField.equals("RCVLAD")) { doc.setRecipientLogicalAddress(value); }
else if (currentField.equals("RCVPFC")) { doc.setRecipientPartnerFunction(value); }
else if (currentField.equals("RCVPRN")) { doc.setRecipientPartnerNumber(value); }
else if (currentField.equals("RCVPRT")) { doc.setRecipientPartnerType(value); }
else if (currentField.equals("RCVPOR")) { doc.setRecipientPort(value); }
else if (currentField.equals("SNDSAD")) { doc.setSenderAddress(value); }
else if (currentField.equals("SNDLAD")) { doc.setSenderLogicalAddress(value); }
else if (currentField.equals("SNDPFC")) { doc.setSenderPartnerFunction(value); }
else if (currentField.equals("SNDPRN")) { doc.setSenderPartnerNumber(value); }
else if (currentField.equals("SNDPRT")) { doc.setSenderPartnerType(value); }
else if (currentField.equals("SNDPOR")) { doc.setSenderPort(value); }
else if (currentField.equals("SERIAL")) { doc.setSerialization(value); }
else if (currentField.equals("STATUS")) { doc.setStatus(value); }
else if (currentField.equals("TEST")) { doc.setTestFlag(value); }
else {
log.debug("header field ["+currentField+"] value ["+value+"] discarded");
}
} else {
IDoc.Segment segment = (IDoc.Segment)segmentStack.get(segmentStack.size()-1);
if (log.isDebugEnabled()) log.debug("setting field ["+currentField+"] to ["+value+"]");
segment.setField(currentField,value);
}
}
currentField = null;
currentFieldValue.setLength(0);
} else {
if (parsingEdiDcHeader) {
parsingEdiDcHeader=false;
} else {
if (segmentStack.size()>0) {
segmentStack.remove(segmentStack.size()-1);
}
}
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
if (currentField==null) {
String part=new String(ch,start,length).trim();
if (StringUtils.isNotEmpty(part)) {
throw new SAXParseException("found character content ["+part+"] outside a field", locator);
}
return;
}
currentFieldValue.append(ch,start,length);
}
public void error(SAXParseException e) throws SAXException {
log.warn("Parser Error",e);
super.error(e);
}
public void fatalError(SAXParseException e) throws SAXException {
log.warn("Parser FatalError",e);
super.fatalError(e);
}
public void warning(SAXParseException e) throws SAXException {
log.warn("Parser Warning",e);
super.warning(e);
}
public void setDocumentLocator(Locator locator) {
super.setDocumentLocator(locator);
this.locator=locator;
}
}
| improved logging
| JavaSource/nl/nn/adapterframework/extensions/sap/IdocXmlHandler.java | improved logging | <ide><path>avaSource/nl/nn/adapterframework/extensions/sap/IdocXmlHandler.java
<ide> /*
<ide> * $Log: IdocXmlHandler.java,v $
<del> * Revision 1.1 2008-01-29 12:36:17 europe\L190409
<add> * Revision 1.2 2008-01-30 14:43:40 europe\L190409
<add> * improved logging
<add> *
<add> * Revision 1.1 2008/01/29 12:36:17 Gerrit van Brakel <[email protected]>
<ide> * first version
<ide> *
<ide> */
<ide> String value=currentFieldValue.toString().trim();
<ide> if (StringUtils.isNotEmpty(value)) {
<ide> if (parsingEdiDcHeader) {
<add> if (log.isDebugEnabled()) log.debug("parsed header field ["+currentField+"] value ["+value+"]");
<ide> if (currentField.equals("ARCKEY")) { doc.setArchiveKey(value); }
<ide> else if (currentField.equals("MANDT")) { doc.setClient(value); }
<ide> else if (currentField.equals("CREDAT")) { doc.setCreationDate(value); }
<ide> else if (currentField.equals("STATUS")) { doc.setStatus(value); }
<ide> else if (currentField.equals("TEST")) { doc.setTestFlag(value); }
<ide> else {
<del> log.debug("header field ["+currentField+"] value ["+value+"] discarded");
<add> log.warn("header field ["+currentField+"] value ["+value+"] discarded");
<ide> }
<ide> } else {
<ide> IDoc.Segment segment = (IDoc.Segment)segmentStack.get(segmentStack.size()-1); |
|
JavaScript | mit | 995dbb765fb128e349141fa7615b55020d35fe60 | 0 | TylerMcKenzie/BrickVBrick,TylerMcKenzie/BrickVBrick | webpackJsonp([1],[,function(t,e,i){"use strict";(function(e){function s(t){return"[object Array]"===T.call(t)}function n(t){return void 0!==e&&e.isBuffer&&e.isBuffer(t)}function r(t){return"[object ArrayBuffer]"===T.call(t)}function o(t){return"undefined"!=typeof FormData&&t instanceof FormData}function a(t){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer&&t.buffer instanceof ArrayBuffer}function h(t){return"string"==typeof t}function l(t){return"number"==typeof t}function c(t){return void 0===t}function u(t){return null!==t&&"object"==typeof t}function d(t){return"[object Date]"===T.call(t)}function p(t){return"[object File]"===T.call(t)}function f(t){return"[object Blob]"===T.call(t)}function g(t){return"[object Function]"===T.call(t)}function m(t){return u(t)&&g(t.pipe)}function y(t){return"undefined"!=typeof URLSearchParams&&t instanceof URLSearchParams}function v(t){return t.replace(/^\s*/,"").replace(/\s*$/,"")}function b(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product)&&("undefined"!=typeof window&&"undefined"!=typeof document)}function x(t,e){if(null!==t&&void 0!==t)if("object"==typeof t||s(t)||(t=[t]),s(t))for(var i=0,n=t.length;i<n;i++)e.call(null,t[i],i,t);else for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.call(null,t[r],r,t)}function w(){function t(t,i){"object"==typeof e[i]&&"object"==typeof t?e[i]=w(e[i],t):e[i]=t}for(var e={},i=0,s=arguments.length;i<s;i++)x(arguments[i],t);return e}function _(t,e,i){return x(e,function(e,s){t[s]=i&&"function"==typeof e?P(e,i):e}),t}var P=i(18),T=Object.prototype.toString;t.exports={isArray:s,isArrayBuffer:r,isBuffer:n,isFormData:o,isArrayBufferView:a,isString:h,isNumber:l,isObject:u,isUndefined:c,isDate:d,isFile:p,isBlob:f,isFunction:g,isStream:m,isURLSearchParams:y,isStandardBrowserEnv:b,forEach:x,merge:w,extend:_,trim:v}}).call(e,i(65).Buffer)},,,,function(t,e,i){"use strict";i.d(e,"b",function(){return s}),i.d(e,"a",function(){return r}),i.d(e,"c",function(){return o});var s={BLACK:"#060304",DARKBLUE:"#001440",TEAL:"#427a8b",GREEN:"#39bb8f",YELLOWGREEN:"#e2fda7"},n=function(){var t=!1;return function(e){(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4)))&&(t=!0)}(navigator.userAgent||navigator.vendor||window.opera),t},r={SCREENWIDTH:window.innerWidth*window.devicePixelRatio,SCREENHEIGHT:window.innerHeight*window.devicePixelRatio,SCALERATIO:function(){var t=window.innerWidth/window.innerHeight,e=void 0;return e=t>1?window.innerHeight*window.devicePixelRatio/2048:window.innerWidth*window.devicePixelRatio/2048,n()&&(e+=1),e}(),BRICKSIZE:120},o=n()},,,,function(t,e,i){"use strict";(function(e){function s(t,e){!n.isUndefined(t)&&n.isUndefined(t["Content-Type"])&&(t["Content-Type"]=e)}var n=i(1),r=i(52),o={"Content-Type":"application/x-www-form-urlencoded"},a={adapter:function(){var t;return"undefined"!=typeof XMLHttpRequest?t=i(14):void 0!==e&&(t=i(14)),t}(),transformRequest:[function(t,e){return r(e,"Content-Type"),n.isFormData(t)||n.isArrayBuffer(t)||n.isBuffer(t)||n.isStream(t)||n.isFile(t)||n.isBlob(t)?t:n.isArrayBufferView(t)?t.buffer:n.isURLSearchParams(t)?(s(e,"application/x-www-form-urlencoded;charset=utf-8"),t.toString()):n.isObject(t)?(s(e,"application/json;charset=utf-8"),JSON.stringify(t)):t}],transformResponse:[function(t){if("string"==typeof t)try{t=JSON.parse(t)}catch(t){}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,validateStatus:function(t){return t>=200&&t<300}};a.headers={common:{Accept:"application/json, text/plain, */*"}},n.forEach(["delete","get","head"],function(t){a.headers[t]={}}),n.forEach(["post","put","patch"],function(t){a.headers[t]=n.merge(o)}),t.exports=a}).call(e,i(4))},,,,,function(t,e,i){"use strict";var s=i(1),n=i(44),r=i(47),o=i(53),a=i(51),h=i(17),l="undefined"!=typeof window&&window.btoa&&window.btoa.bind(window)||i(46);t.exports=function(t){return new Promise(function(e,c){var u=t.data,d=t.headers;s.isFormData(u)&&delete d["Content-Type"];var p=new XMLHttpRequest,f="onreadystatechange",g=!1;if("undefined"==typeof window||!window.XDomainRequest||"withCredentials"in p||a(t.url)||(p=new window.XDomainRequest,f="onload",g=!0,p.onprogress=function(){},p.ontimeout=function(){}),t.auth){var m=t.auth.username||"",y=t.auth.password||"";d.Authorization="Basic "+l(m+":"+y)}if(p.open(t.method.toUpperCase(),r(t.url,t.params,t.paramsSerializer),!0),p.timeout=t.timeout,p[f]=function(){if(p&&(4===p.readyState||g)&&(0!==p.status||p.responseURL&&0===p.responseURL.indexOf("file:"))){var i="getAllResponseHeaders"in p?o(p.getAllResponseHeaders()):null,s=t.responseType&&"text"!==t.responseType?p.response:p.responseText,r={data:s,status:1223===p.status?204:p.status,statusText:1223===p.status?"No Content":p.statusText,headers:i,config:t,request:p};n(e,c,r),p=null}},p.onerror=function(){c(h("Network Error",t)),p=null},p.ontimeout=function(){c(h("timeout of "+t.timeout+"ms exceeded",t,"ECONNABORTED")),p=null},s.isStandardBrowserEnv()){var v=i(49),b=(t.withCredentials||a(t.url))&&t.xsrfCookieName?v.read(t.xsrfCookieName):void 0;b&&(d[t.xsrfHeaderName]=b)}if("setRequestHeader"in p&&s.forEach(d,function(t,e){void 0===u&&"content-type"===e.toLowerCase()?delete d[e]:p.setRequestHeader(e,t)}),t.withCredentials&&(p.withCredentials=!0),t.responseType)try{p.responseType=t.responseType}catch(e){if("json"!==t.responseType)throw e}"function"==typeof t.onDownloadProgress&&p.addEventListener("progress",t.onDownloadProgress),"function"==typeof t.onUploadProgress&&p.upload&&p.upload.addEventListener("progress",t.onUploadProgress),t.cancelToken&&t.cancelToken.promise.then(function(t){p&&(p.abort(),c(t),p=null)}),void 0===u&&(u=null),p.send(u)})}},function(t,e,i){"use strict";function s(t){this.message=t}s.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},s.prototype.__CANCEL__=!0,t.exports=s},function(t,e,i){"use strict";t.exports=function(t){return!(!t||!t.__CANCEL__)}},function(t,e,i){"use strict";var s=i(43);t.exports=function(t,e,i,n){var r=new Error(t);return s(r,e,i,n)}},function(t,e,i){"use strict";t.exports=function(t,e){return function(){for(var i=new Array(arguments.length),s=0;s<i.length;s++)i[s]=arguments[s];return t.apply(e,i)}}},function(t,e,i){"use strict";function s(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var n=function(){function t(t,e){for(var i=0;i<e.length;i++){var s=e[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(t,s.key,s)}}return function(e,i,s){return i&&t(e.prototype,i),s&&t(e,s),e}}(),r=function(){function t(e,i,n,r,o){s(this,t),this.game=e,this.scale=i||1,this.color=o,this.x=n,this.y=r,this.sprite=this.game.add.sprite(this.x,this.y,"bricks",this.color),this.sprite.inputEnabled=!0,this.sprite.scale.setTo(this.scale),this.emitter=this.game.add.emitter(0,0,6),this.emitter.makeParticles("bricks",this.color),this.emitter.minParticleScale=this.scale,this.emitter.maxParticleScale=this.scale,this.emitter.gravity=2e3*this.scale}return n(t,[{key:"tweenTo",value:function(t,e){this.game.add.tween(this.sprite).to({x:t,y:e},400,"Bounce",!0)}},{key:"addClickEvent",value:function(t,e){this.sprite.events.onInputDown.add(t,e)}},{key:"enableClickEvents",value:function(){this.sprite.inputEnabled=!0}},{key:"disableClickEvents",value:function(){this.sprite.inputEnabled=!1}},{key:"changePosition",value:function(t){var e=t.x,i=t.y;this.isEmpty()?(this.game.world.sendToBack(this.sprite),this.sprite.x=e||this.sprite.x,this.sprite.y=i||this.sprite.y):this.tweenTo(e,i),this.x=e,this.y=i}},{key:"runDestroyAnim",value:function(){this.game.world.bringToTop(this.emitter),this.emitter.x=this.x+this.sprite.width/2,this.emitter.y=this.y+this.sprite.width/2,this.emitter.start(!1,1e3,1,1)}},{key:"destroy",value:function(){this.runDestroyAnim(),this.sprite.destroy()}},{key:"isEmpty",value:function(){return 7===this.color}}]),t}();e.a=r},,,,,,,,,,,,,,function(t,e,i){"use strict";function s(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function r(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}Object.defineProperty(e,"__esModule",{value:!0});var o=i(79),a=(i.n(o),i(81)),h=(i.n(a),i(80)),l=i.n(h),c=i(60),u=i(5),d=u.a.SCREENWIDTH,p=u.a.SCREENHEIGHT;new(function(t){function e(t,i,r){s(this,e);var o=n(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t,i,r));return o.state.add("Preload",c.a,!1),o.state.add("Main",c.b,!1),o.state.start("Preload"),o}return r(e,t),e}(l.a.Game))(d,p,l.a.CANVAS)},,,,function(t,e,i){t.exports=i(38)},function(t,e,i){"use strict";function s(t){var e=new o(t),i=r(o.prototype.request,e);return n.extend(i,o.prototype,e),n.extend(i,e),i}var n=i(1),r=i(18),o=i(40),a=i(9),h=s(a);h.Axios=o,h.create=function(t){return s(n.merge(a,t))},h.Cancel=i(15),h.CancelToken=i(39),h.isCancel=i(16),h.all=function(t){return Promise.all(t)},h.spread=i(54),t.exports=h,t.exports.default=h},function(t,e,i){"use strict";function s(t){if("function"!=typeof t)throw new TypeError("executor must be a function.");var e;this.promise=new Promise(function(t){e=t});var i=this;t(function(t){i.reason||(i.reason=new n(t),e(i.reason))})}var n=i(15);s.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},s.source=function(){var t;return{token:new s(function(e){t=e}),cancel:t}},t.exports=s},function(t,e,i){"use strict";function s(t){this.defaults=t,this.interceptors={request:new o,response:new o}}var n=i(9),r=i(1),o=i(41),a=i(42),h=i(50),l=i(48);s.prototype.request=function(t){"string"==typeof t&&(t=r.merge({url:arguments[0]},arguments[1])),t=r.merge(n,this.defaults,{method:"get"},t),t.baseURL&&!h(t.url)&&(t.url=l(t.baseURL,t.url));var e=[a,void 0],i=Promise.resolve(t);for(this.interceptors.request.forEach(function(t){e.unshift(t.fulfilled,t.rejected)}),this.interceptors.response.forEach(function(t){e.push(t.fulfilled,t.rejected)});e.length;)i=i.then(e.shift(),e.shift());return i},r.forEach(["delete","get","head","options"],function(t){s.prototype[t]=function(e,i){return this.request(r.merge(i||{},{method:t,url:e}))}}),r.forEach(["post","put","patch"],function(t){s.prototype[t]=function(e,i,s){return this.request(r.merge(s||{},{method:t,url:e,data:i}))}}),t.exports=s},function(t,e,i){"use strict";function s(){this.handlers=[]}var n=i(1);s.prototype.use=function(t,e){return this.handlers.push({fulfilled:t,rejected:e}),this.handlers.length-1},s.prototype.eject=function(t){this.handlers[t]&&(this.handlers[t]=null)},s.prototype.forEach=function(t){n.forEach(this.handlers,function(e){null!==e&&t(e)})},t.exports=s},function(t,e,i){"use strict";function s(t){t.cancelToken&&t.cancelToken.throwIfRequested()}var n=i(1),r=i(45),o=i(16),a=i(9);t.exports=function(t){return s(t),t.headers=t.headers||{},t.data=r(t.data,t.headers,t.transformRequest),t.headers=n.merge(t.headers.common||{},t.headers[t.method]||{},t.headers||{}),n.forEach(["delete","get","head","post","put","patch","common"],function(e){delete t.headers[e]}),(t.adapter||a.adapter)(t).then(function(e){return s(t),e.data=r(e.data,e.headers,t.transformResponse),e},function(e){return o(e)||(s(t),e&&e.response&&(e.response.data=r(e.response.data,e.response.headers,t.transformResponse))),Promise.reject(e)})}},function(t,e,i){"use strict";t.exports=function(t,e,i,s){return t.config=e,i&&(t.code=i),t.response=s,t}},function(t,e,i){"use strict";var s=i(17);t.exports=function(t,e,i){var n=i.config.validateStatus;i.status&&n&&!n(i.status)?e(s("Request failed with status code "+i.status,i.config,null,i)):t(i)}},function(t,e,i){"use strict";var s=i(1);t.exports=function(t,e,i){return s.forEach(i,function(i){t=i(t,e)}),t}},function(t,e,i){"use strict";function s(){this.message="String contains an invalid character"}function n(t){for(var e,i,n=String(t),o="",a=0,h=r;n.charAt(0|a)||(h="=",a%1);o+=h.charAt(63&e>>8-a%1*8)){if((i=n.charCodeAt(a+=.75))>255)throw new s;e=e<<8|i}return o}var r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";s.prototype=new Error,s.prototype.code=5,s.prototype.name="InvalidCharacterError",t.exports=n},function(t,e,i){"use strict";function s(t){return encodeURIComponent(t).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var n=i(1);t.exports=function(t,e,i){if(!e)return t;var r;if(i)r=i(e);else if(n.isURLSearchParams(e))r=e.toString();else{var o=[];n.forEach(e,function(t,e){null!==t&&void 0!==t&&(n.isArray(t)&&(e+="[]"),n.isArray(t)||(t=[t]),n.forEach(t,function(t){n.isDate(t)?t=t.toISOString():n.isObject(t)&&(t=JSON.stringify(t)),o.push(s(e)+"="+s(t))}))}),r=o.join("&")}return r&&(t+=(-1===t.indexOf("?")?"?":"&")+r),t}},function(t,e,i){"use strict";t.exports=function(t,e){return e?t.replace(/\/+$/,"")+"/"+e.replace(/^\/+/,""):t}},function(t,e,i){"use strict";var s=i(1);t.exports=s.isStandardBrowserEnv()?function(){return{write:function(t,e,i,n,r,o){var a=[];a.push(t+"="+encodeURIComponent(e)),s.isNumber(i)&&a.push("expires="+new Date(i).toGMTString()),s.isString(n)&&a.push("path="+n),s.isString(r)&&a.push("domain="+r),!0===o&&a.push("secure"),document.cookie=a.join("; ")},read:function(t){var e=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove:function(t){this.write(t,"",Date.now()-864e5)}}}():function(){return{write:function(){},read:function(){return null},remove:function(){}}}()},function(t,e,i){"use strict";t.exports=function(t){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(t)}},function(t,e,i){"use strict";var s=i(1);t.exports=s.isStandardBrowserEnv()?function(){function t(t){var e=t;return i&&(n.setAttribute("href",e),e=n.href),n.setAttribute("href",e),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:"/"===n.pathname.charAt(0)?n.pathname:"/"+n.pathname}}var e,i=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");return e=t(window.location.href),function(i){var n=s.isString(i)?t(i):i;return n.protocol===e.protocol&&n.host===e.host}}():function(){return function(){return!0}}()},function(t,e,i){"use strict";var s=i(1);t.exports=function(t,e){s.forEach(t,function(i,s){s!==e&&s.toUpperCase()===e.toUpperCase()&&(t[e]=i,delete t[s])})}},function(t,e,i){"use strict";var s=i(1);t.exports=function(t){var e,i,n,r={};return t?(s.forEach(t.split("\n"),function(t){n=t.indexOf(":"),e=s.trim(t.substr(0,n)).toLowerCase(),i=s.trim(t.substr(n+1)),e&&(r[e]=r[e]?r[e]+", "+i:i)}),r):r}},function(t,e,i){"use strict";t.exports=function(t){return function(e){return t.apply(null,e)}}},function(t,e,i){"use strict";function s(t){function e(i,s,n){var r=n||[];return 0==s||t.boardRows[s][i].isEmpty()||(r.push(t.boardRows[s][i]),e(i,s-1,r)),r}var i=t.getBrickLocation(this),s=i.x,n=(i.y,e(s,t.boardRows.length-1)),r=n.length;t.deleteGroup(n),t.addScore(r)}function n(t){for(var e=t.getBrickLocation(this),i=(e.x,e.y),s=[],n=0;n<t.boardRows[i].length;n++)t.boardRows[i][n].isEmpty()||s.push(t.boardRows[i][n]);var r=s.length;t.deleteGroup(s),t.addScore(r)}function r(t){var e=t.getBrickLocation(this),i=e.x,s=e.y,n=[];n.push(t.boardRows[s][i]),i!==t.boardRows[s].length-1&&n.push(t.boardRows[s][i+1]),i!==t.boardRows[s].length-1&&s!==t.boardRows.length-1&&n.push(t.boardRows[s+1][i+1]),i!==t.boardRows[s].length-1&&0!==s&&n.push(t.boardRows[s-1][i+1]),0!==i&&n.push(t.boardRows[s][i-1]),0!==i&&0!==s&&n.push(t.boardRows[s-1][i-1]),0!==i&&s!==t.boardRows.length-1&&n.push(t.boardRows[s+1][i-1]),0!==s&&n.push(t.boardRows[s-1][i]),s!==t.boardRows.length-1&&n.push(t.boardRows[s+1][i]);for(var r=n.length-1;r>0;r--)n[r].isEmpty()&&n.splice(r,1);var o=n.length;t.deleteGroup(n),t.addScore(o)}function o(t){return a[t]}e.a=o;var a={8:s,9:n,10:r}},function(t,e,i){"use strict";function s(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var n=i(19),r=i(57),o=i(5),a=i(37),h=i.n(a),l=function(){function t(t,e){for(var i=0;i<e.length;i++){var s=e[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(t,s.key,s)}}return function(e,i,s){return i&&t(e.prototype,i),s&&t(e,s),e}}(),c=o.a.BRICKSIZE,u=function(){function t(e,i,n,r){s(this,t),this.game=e,this.boardRows=[],this.brickSize=c,this.brickScale=i,this.brickOffset=this.brickSize*this.brickScale,this.boardWidth=8*this.brickOffset,this.boardHeight=12*this.brickOffset,this.boardOffsetW=this.boardWidth/2,this.boardOffsetH=this.boardHeight/2,this.posX=n-this.boardOffsetW,this.posY=r-this.boardOffsetH,this.moves=0,this.numOfColors=5,this.playerScore=0,this.destroyBrickSound=this.game.add.audio("brickDestroy"),this.destroyBrickSound.volume=1.5,this.gameMusic=this.game.add.audio("gameMusic"),this.gameMusic.loop=!0,this.gameMusic.volume=.5,o.c||(this.background=this.makeBackground(),this.background.start(!1,5e3,250,0)),this.scoreBoard=this.game.add.text(this.posX,this.posY-100*this.brickScale,"Score: "+this.playerScore,{fill:"#fff",fontSize:60*this.brickScale}),this.settings={},this.settings.music="on",this.settings.sound="on",this.settingsIcon=this.game.add.sprite(this.boardWidth+this.posX-90*this.brickScale,this.posY-90*this.brickScale,"settingsIcon"),this.settingsIcon.width=75*this.brickScale,this.settingsIcon.height=75*this.brickScale,this.settingsIcon.inputEnabled=!0,this.settingsIcon.events.onInputDown.add(this.openSettingsModal,this),this.createBoard(),this.gameMusic.play()}return l(t,[{key:"createSettingsModal",value:function(){this.disableBoardInput();var t=this.game.add.group();t.destroyChildren=!0;var e=600*this.brickScale,i=800*this.brickScale,s=this.game.add.graphics(0,0),n=this.game.world.centerX-e/2,r=this.game.world.centerY-i/2;s.beginFill(3783567),s.drawRect(n,r,e,i),s.endFill(),s.beginFill(16777215),s.drawRect(n+15*this.brickScale,r+15*this.brickScale,e-30*this.brickScale,i-30*this.brickScale),s.endFill(),t.add(s);var o=this.game.add.text(n+e-75*this.brickScale,r+25*this.brickScale,"X",{fill:"#427a8b",fontSize:70*this.brickScale});t.add(o);var a=this.game.add.text(n+s.centerX-175*this.brickScale,r+s.centerY-155*this.brickScale,"Music",{fill:"#427a8b",fontSize:60*this.brickScale});t.add(a);var h=this.game.add.text(n+s.centerX-175*this.brickScale,r+s.centerY+100*this.brickScale,"Sound",{fill:"#427a8b",fontSize:60*this.brickScale});t.add(h);var l=this.game.add.text(n+s.centerX+75*this.brickScale,r+s.centerY-155*this.brickScale,""+this.settings.music,{fill:"#427a8b",fontSize:60*this.brickScale});t.add(l);var c=this.game.add.text(n+s.centerX+75*this.brickScale,r+s.centerY+100*this.brickScale,""+this.settings.sound,{fill:"#427a8b",fontSize:60*this.brickScale});t.add(c),l.inputEnabled=!0,l.events.onInputDown.add(this.toggleSetting.bind(this,"music")),c.inputEnabled=!0,c.events.onInputDown.add(this.toggleSetting.bind(this,"sound")),o.inputEnabled=!0,o.events.onInputDown.add(this.closeSettingsMenu.bind(this,t))}},{key:"toggleSetting",value:function(t,e){"on"===this.settings[t]?(this.settings[t]="off",e.text=this.settings[t],"music"===t&&this.gameMusic.stop()):"off"===this.settings[t]&&(this.settings[t]="on",e.text=this.settings[t],"music"===t&&this.gameMusic.play())}},{key:"openSettingsModal",value:function(){this.createSettingsModal()}},{key:"closeSettingsMenu",value:function(t){t.destroy(),this.enableBoardInput()}},{key:"makeBackground",value:function(){var t=this.game.add.emitter(this.game.world.centerX,-100,50);return t.width=this.game.world.width,t.minParticleScale=.25*this.brickScale,t.maxParticleScale=.8*this.brickScale,t.makeParticles("bricks",[0,1,2,3,4,5]),t.setYSpeed(50*this.brickScale,150*this.brickScale),t.setXSpeed(0,0),t.minRotation=0,t.maxRotation=0,t}},{key:"brickClickHandler",value:function(t){if(7!==t.frame){var e=this.getBrickLocation(t),i=e.x,s=e.y,n=this.findColorGroup(s,i,t.frame),r=n.length;if(this.deleteGroup(n),2===++this.moves)if(this.isGameOver())this.gameOver();else{var o=this.posX+this.brickOffset,a=this.posY+this.brickOffset;this.boardRows[0]=this.createColorRow(o,a),this.moves=0}this.dropColumns(),this.addScore(r)}}},{key:"powerUpClickHandler",value:function(t){var e=this.getBrickLocation(t),i=e.x,s=e.y;if(this.boardRows[s][i].applyEffect(this),2==++this.moves)if(this.isGameOver())this.gameOver();else{var n=this.posX+this.brickOffset,r=this.posY+this.brickOffset;this.boardRows[0]=this.createColorRow(n,r),this.moves=0}this.dropColumns()}},{key:"runScoreAnim",value:function(t){var e=this,i=this.game.add.text(this.game.input.x,this.game.input.y-50*this.brickScale,"+"+t,{fill:"#fff",fontSize:60*this.brickScale});this.game.world.bringToTop(i);var s=this.game.add.tween(i).to({y:i.y-50*this.brickScale},300,"Quad.easeOut",!0),n=function(){e.game.add.tween(i).to({alpha:0},400,"Quad.easeOut",!0).onComplete.add(function(){return i.destroy()})};s.onComplete.add(n)}},{key:"addScore",value:function(t){var e=Math.floor(t+t/1.5);this.runScoreAnim(e),this.playerScore+=e,this.updateScoreBoard()}},{key:"updateScoreBoard",value:function(){this.scoreBoard.text="Score: "+this.playerScore}},{key:"findColorGroup",value:function(t,e,i,s){var n=s||[],r=function(t){return n.includes(t)};return r(this.boardRows[t][e])||n.push(this.boardRows[t][e]),0!=e&&this.boardRows[t][e-1].color===i&&(r(this.boardRows[t][e-1])||(n.push(this.boardRows[t][e-1]),this.findColorGroup(t,e-1,i,n))),e!=this.boardRows[t].length-1&&this.boardRows[t][e+1].color===i&&(r(this.boardRows[t][e+1])||(n.push(this.boardRows[t][e+1]),this.findColorGroup(t,e+1,i,n))),0!=t&&this.boardRows[t-1][e].color===i&&(r(this.boardRows[t-1][e])||(n.push(this.boardRows[t-1][e]),this.findColorGroup(t-1,e,i,n))),t!=this.boardRows.length-1&&this.boardRows[t+1][e].color===i&&(r(this.boardRows[t+1][e])||(n.push(this.boardRows[t+1][e]),this.findColorGroup(t+1,e,i,n))),n}},{key:"createBoard",value:function(){this.createBoardBackground();for(var t=this.posX+this.brickOffset,e=this.posY+this.brickOffset,i=0;i<10;i++){var s=this.brickOffset*i;i<4?this.boardRows.push(this.createColorRow(t,e+s,7)):this.boardRows.push(this.createColorRow(t,e+s))}}},{key:"renderBoard",value:function(){for(var t=0;t<this.boardRows.length;t++)for(var e=0;e<this.boardRows[t].length;e++){var i=this.posX+this.brickOffset+this.brickOffset*e,s=this.posY+this.brickOffset+this.brickOffset*t;this.boardRows[t][e].changePosition({x:i,y:s})}}},{key:"createBoardBackground",value:function(){for(var t=0;t<12;t++)for(var e=0;e<8;e++){var i=this.brickOffset*e,s=this.brickOffset*t,r=6;e>0&&e<7&&t>0&&t<11&&(r=7),new n.a(this.game,this.brickScale,this.posX+i,this.posY+s,r)}}},{key:"createEmptyBrick",value:function(t,e){var i=this.getBrickLocation(this.boardRows[t][e]),s=i.x,r=i.y;return new n.a(this.game,this.brickScale,s,r,7)}},{key:"createColorRow",value:function(t,e,i){for(var s=[],o=void 0,a=0;a<6;a++){var h=void 0;Math.floor(100*Math.random())<96?(o=i||Math.floor(Math.random()*this.numOfColors),h=new n.a(this.game,this.brickScale,t+this.brickOffset*a,e,o),h.addClickEvent(this.brickClickHandler,this)):(o=i||Math.floor(3*Math.random())+8,h=new r.a(this.game,this.brickScale,t+this.brickOffset*a,e,o),h.addClickEvent(this.powerUpClickHandler,this)),s.push(h)}return s}},{key:"dropColumns",value:function(){for(var t=[[],[],[],[],[],[]],e=0;e<t.length;e++){for(var i=0;i<10;i++)t[e].push(this.boardRows[i][e]);this.moveEmptyTop(t[e])}for(var s=0;s<t.length;s++)for(var n=0;n<t[s].length;n++)this.boardRows[n][s]=t[s][n];this.renderBoard()}},{key:"moveEmptyTop",value:function(t){for(var e=0;e<t.length;e++)if(t[e].isEmpty()){var i=t.splice(e,1)[0];t.unshift(i)}}},{key:"getBrickLocation",value:function(t){return{x:(t.x-this.posX)/this.brickOffset-1,y:(t.y-this.posY)/this.brickOffset-1}}},{key:"deleteBrick",value:function(t,e){var i=this.createEmptyBrick(t,e);this.boardRows[t][e].destroy(),this.boardRows[t].splice(e,1,i)}},{key:"deleteGroup",value:function(t){for(var e=0;e<t.length;e++){var i=this.getBrickLocation(t[e]),s=i.x,n=i.y;this.deleteBrick(n,s)}"on"===this.settings.sound&&this.destroyBrickSound.play()}},{key:"isGameOver",value:function(){for(var t=!1,e=0;e<this.boardRows[0].length;e++)if(!this.boardRows[0][e].isEmpty()){t=!0;break}return t}},{key:"disableBoardInput",value:function(){this.boardRows.map(function(t){t.map(function(t){t.disableClickEvents()})})}},{key:"enableBoardInput",value:function(){this.boardRows.map(function(t){t.map(function(t){t.enableClickEvents()})})}},{key:"gameOver",value:function(){this.disableBoardInput(),this.scoreBoard.text="Game Over\nFinal Score: "+this.playerScore,h.a.post("/user/score/new",{score:this.playerScore}).then(function(t){alert("Thanks for playing!"),window.location.replace("/profile")}).catch(function(t){console.log(t)})}}]),t}();e.a=u},function(t,e,i){"use strict";function s(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function r(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}var o=i(19),a=i(55),h=function(){function t(t,e){for(var i=0;i<e.length;i++){var s=e[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(t,s.key,s)}}return function(e,i,s){return i&&t(e.prototype,i),s&&t(e,s),e}}(),l=function(t){function e(t,r,o,h,l){s(this,e);var c=n(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t,r,o,h,l));return c.effect=i.i(a.a)(c.color),c}return r(e,t),h(e,[{key:"applyEffect",value:function(t){this.effect(t)}}]),e}(o.a);e.a=l},function(t,e,i){"use strict";function s(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function r(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}var o=i(5),a=i(56),h=function(){function t(t,e){for(var i=0;i<e.length;i++){var s=e[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(t,s.key,s)}}return function(e,i,s){return i&&t(e.prototype,i),s&&t(e,s),e}}(),l=(o.a.SCREENWIDTH,o.a.SCREENHEIGHT,o.a.SCALERATIO),c=function(t){function e(){return s(this,e),n(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return r(e,t),h(e,[{key:"create",value:function(){this.game.scale.fullScreenScaleMode=Phaser.ScaleManager.SHOW_ALL,this.game.scale.scaleMode=Phaser.ScaleManager.SHOW_ALL,this.game.scale.refresh(),this.game.forceSingleUpdate=!0,this.myBoard=new a.a(this.game,l,this.game.world.centerX,this.game.world.centerY)}}]),e}(Phaser.State);e.a=c},function(t,e,i){"use strict";function s(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function r(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}var o=i(5),a=i(84),h=i.n(a),l=i(82),c=i.n(l),u=i(83),d=i.n(u),p=i(85),f=i.n(p),g=function(){function t(t,e){for(var i=0;i<e.length;i++){var s=e[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(t,s.key,s)}}return function(e,i,s){return i&&t(e.prototype,i),s&&t(e,s),e}}(),m=function(t){function e(){return s(this,e),n(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return r(e,t),g(e,[{key:"preload",value:function(){var t=this;this.load.onLoadComplete.addOnce(function(){return t.ready=!0}),this.loadResources()}},{key:"create",value:function(){this.stage.backgroundColor=o.b.DARKBLUE,this.game.add.text(this.game.world.centerX,this.game.world.centerY,"Loading ...",{fill:"#fff",align:"center",fontSize:50*o.a.SCALERATIO}).anchor.set(.5)}},{key:"loadResources",value:function(){this.game.load.spritesheet("bricks",h.a,o.a.BRICKSIZE,o.a.BRICKSIZE,11),this.game.load.image("settingsIcon",f.a),this.game.load.audio("brickDestroy",c.a),this.game.load.audio("gameMusic",d.a)}},{key:"update",value:function(){this.ready&&this.game.state.start("Main")}}]),e}(Phaser.State);e.a=m},function(t,e,i){"use strict";var s=i(58),n=i(59);i.d(e,"b",function(){return s.a}),i.d(e,"a",function(){return n.a})},,,function(t,e,i){"use strict";function s(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===t[e-2]?2:"="===t[e-1]?1:0}function n(t){return 3*t.length/4-s(t)}function r(t){var e,i,n,r,o,a,h=t.length;o=s(t),a=new u(3*h/4-o),n=o>0?h-4:h;var l=0;for(e=0,i=0;e<n;e+=4,i+=3)r=c[t.charCodeAt(e)]<<18|c[t.charCodeAt(e+1)]<<12|c[t.charCodeAt(e+2)]<<6|c[t.charCodeAt(e+3)],a[l++]=r>>16&255,a[l++]=r>>8&255,a[l++]=255&r;return 2===o?(r=c[t.charCodeAt(e)]<<2|c[t.charCodeAt(e+1)]>>4,a[l++]=255&r):1===o&&(r=c[t.charCodeAt(e)]<<10|c[t.charCodeAt(e+1)]<<4|c[t.charCodeAt(e+2)]>>2,a[l++]=r>>8&255,a[l++]=255&r),a}function o(t){return l[t>>18&63]+l[t>>12&63]+l[t>>6&63]+l[63&t]}function a(t,e,i){for(var s,n=[],r=e;r<i;r+=3)s=(t[r]<<16)+(t[r+1]<<8)+t[r+2],n.push(o(s));return n.join("")}function h(t){for(var e,i=t.length,s=i%3,n="",r=[],o=0,h=i-s;o<h;o+=16383)r.push(a(t,o,o+16383>h?h:o+16383));return 1===s?(e=t[i-1],n+=l[e>>2],n+=l[e<<4&63],n+="=="):2===s&&(e=(t[i-2]<<8)+t[i-1],n+=l[e>>10],n+=l[e>>4&63],n+=l[e<<2&63],n+="="),r.push(n),r.join("")}e.byteLength=n,e.toByteArray=r,e.fromByteArray=h;for(var l=[],c=[],u="undefined"!=typeof Uint8Array?Uint8Array:Array,d="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",p=0,f=d.length;p<f;++p)l[p]=d[p],c[d.charCodeAt(p)]=p;c["-".charCodeAt(0)]=62,c["_".charCodeAt(0)]=63},,function(t,e,i){"use strict";(function(t){function s(){return r.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function n(t,e){if(s()<e)throw new RangeError("Invalid typed array length");return r.TYPED_ARRAY_SUPPORT?(t=new Uint8Array(e),t.__proto__=r.prototype):(null===t&&(t=new r(e)),t.length=e),t}function r(t,e,i){if(!(r.TYPED_ARRAY_SUPPORT||this instanceof r))return new r(t,e,i);if("number"==typeof t){if("string"==typeof e)throw new Error("If encoding is specified then the first argument must be a string");return l(this,t)}return o(this,t,e,i)}function o(t,e,i,s){if("number"==typeof e)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer?d(t,e,i,s):"string"==typeof e?c(t,e,i):p(t,e)}function a(t){if("number"!=typeof t)throw new TypeError('"size" argument must be a number');if(t<0)throw new RangeError('"size" argument must not be negative')}function h(t,e,i,s){return a(e),e<=0?n(t,e):void 0!==i?"string"==typeof s?n(t,e).fill(i,s):n(t,e).fill(i):n(t,e)}function l(t,e){if(a(e),t=n(t,e<0?0:0|f(e)),!r.TYPED_ARRAY_SUPPORT)for(var i=0;i<e;++i)t[i]=0;return t}function c(t,e,i){if("string"==typeof i&&""!==i||(i="utf8"),!r.isEncoding(i))throw new TypeError('"encoding" must be a valid string encoding');var s=0|m(e,i);t=n(t,s);var o=t.write(e,i);return o!==s&&(t=t.slice(0,o)),t}function u(t,e){var i=e.length<0?0:0|f(e.length);t=n(t,i);for(var s=0;s<i;s+=1)t[s]=255&e[s];return t}function d(t,e,i,s){if(e.byteLength,i<0||e.byteLength<i)throw new RangeError("'offset' is out of bounds");if(e.byteLength<i+(s||0))throw new RangeError("'length' is out of bounds");return e=void 0===i&&void 0===s?new Uint8Array(e):void 0===s?new Uint8Array(e,i):new Uint8Array(e,i,s),r.TYPED_ARRAY_SUPPORT?(t=e,t.__proto__=r.prototype):t=u(t,e),t}function p(t,e){if(r.isBuffer(e)){var i=0|f(e.length);return t=n(t,i),0===t.length?t:(e.copy(t,0,0,i),t)}if(e){if("undefined"!=typeof ArrayBuffer&&e.buffer instanceof ArrayBuffer||"length"in e)return"number"!=typeof e.length||K(e.length)?n(t,0):u(t,e);if("Buffer"===e.type&&Z(e.data))return u(t,e.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}function f(t){if(t>=s())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s().toString(16)+" bytes");return 0|t}function g(t){return+t!=t&&(t=0),r.alloc(+t)}function m(t,e){if(r.isBuffer(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var i=t.length;if(0===i)return 0;for(var s=!1;;)switch(e){case"ascii":case"latin1":case"binary":return i;case"utf8":case"utf-8":case void 0:return V(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*i;case"hex":return i>>>1;case"base64":return Y(t).length;default:if(s)return V(t).length;e=(""+e).toLowerCase(),s=!0}}function y(t,e,i){var s=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===i||i>this.length)&&(i=this.length),i<=0)return"";if(i>>>=0,e>>>=0,i<=e)return"";for(t||(t="utf8");;)switch(t){case"hex":return B(this,e,i);case"utf8":case"utf-8":return E(this,e,i);case"ascii":return M(this,e,i);case"latin1":case"binary":return R(this,e,i);case"base64":return A(this,e,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return L(this,e,i);default:if(s)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),s=!0}}function v(t,e,i){var s=t[e];t[e]=t[i],t[i]=s}function b(t,e,i,s,n){if(0===t.length)return-1;if("string"==typeof i?(s=i,i=0):i>2147483647?i=2147483647:i<-2147483648&&(i=-2147483648),i=+i,isNaN(i)&&(i=n?0:t.length-1),i<0&&(i=t.length+i),i>=t.length){if(n)return-1;i=t.length-1}else if(i<0){if(!n)return-1;i=0}if("string"==typeof e&&(e=r.from(e,s)),r.isBuffer(e))return 0===e.length?-1:x(t,e,i,s,n);if("number"==typeof e)return e&=255,r.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?n?Uint8Array.prototype.indexOf.call(t,e,i):Uint8Array.prototype.lastIndexOf.call(t,e,i):x(t,[e],i,s,n);throw new TypeError("val must be string, number or Buffer")}function x(t,e,i,s,n){function r(t,e){return 1===o?t[e]:t.readUInt16BE(e*o)}var o=1,a=t.length,h=e.length;if(void 0!==s&&("ucs2"===(s=String(s).toLowerCase())||"ucs-2"===s||"utf16le"===s||"utf-16le"===s)){if(t.length<2||e.length<2)return-1;o=2,a/=2,h/=2,i/=2}var l;if(n){var c=-1;for(l=i;l<a;l++)if(r(t,l)===r(e,-1===c?0:l-c)){if(-1===c&&(c=l),l-c+1===h)return c*o}else-1!==c&&(l-=l-c),c=-1}else for(i+h>a&&(i=a-h),l=i;l>=0;l--){for(var u=!0,d=0;d<h;d++)if(r(t,l+d)!==r(e,d)){u=!1;break}if(u)return l}return-1}function w(t,e,i,s){i=Number(i)||0;var n=t.length-i;s?(s=Number(s))>n&&(s=n):s=n;var r=e.length;if(r%2!=0)throw new TypeError("Invalid hex string");s>r/2&&(s=r/2);for(var o=0;o<s;++o){var a=parseInt(e.substr(2*o,2),16);if(isNaN(a))return o;t[i+o]=a}return o}function _(t,e,i,s){return z(V(e,t.length-i),t,i,s)}function P(t,e,i,s){return z(q(e),t,i,s)}function T(t,e,i,s){return P(t,e,i,s)}function C(t,e,i,s){return z(Y(e),t,i,s)}function S(t,e,i,s){return z(H(e,t.length-i),t,i,s)}function A(t,e,i){return 0===e&&i===t.length?J.fromByteArray(t):J.fromByteArray(t.slice(e,i))}function E(t,e,i){i=Math.min(t.length,i);for(var s=[],n=e;n<i;){var r=t[n],o=null,a=r>239?4:r>223?3:r>191?2:1;if(n+a<=i){var h,l,c,u;switch(a){case 1:r<128&&(o=r);break;case 2:h=t[n+1],128==(192&h)&&(u=(31&r)<<6|63&h)>127&&(o=u);break;case 3:h=t[n+1],l=t[n+2],128==(192&h)&&128==(192&l)&&(u=(15&r)<<12|(63&h)<<6|63&l)>2047&&(u<55296||u>57343)&&(o=u);break;case 4:h=t[n+1],l=t[n+2],c=t[n+3],128==(192&h)&&128==(192&l)&&128==(192&c)&&(u=(15&r)<<18|(63&h)<<12|(63&l)<<6|63&c)>65535&&u<1114112&&(o=u)}}null===o?(o=65533,a=1):o>65535&&(o-=65536,s.push(o>>>10&1023|55296),o=56320|1023&o),s.push(o),n+=a}return I(s)}function I(t){var e=t.length;if(e<=$)return String.fromCharCode.apply(String,t);for(var i="",s=0;s<e;)i+=String.fromCharCode.apply(String,t.slice(s,s+=$));return i}function M(t,e,i){var s="";i=Math.min(t.length,i);for(var n=e;n<i;++n)s+=String.fromCharCode(127&t[n]);return s}function R(t,e,i){var s="";i=Math.min(t.length,i);for(var n=e;n<i;++n)s+=String.fromCharCode(t[n]);return s}function B(t,e,i){var s=t.length;(!e||e<0)&&(e=0),(!i||i<0||i>s)&&(i=s);for(var n="",r=e;r<i;++r)n+=j(t[r]);return n}function L(t,e,i){for(var s=t.slice(e,i),n="",r=0;r<s.length;r+=2)n+=String.fromCharCode(s[r]+256*s[r+1]);return n}function k(t,e,i){if(t%1!=0||t<0)throw new RangeError("offset is not uint");if(t+e>i)throw new RangeError("Trying to access beyond buffer length")}function O(t,e,i,s,n,o){if(!r.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>n||e<o)throw new RangeError('"value" argument is out of bounds');if(i+s>t.length)throw new RangeError("Index out of range")}function F(t,e,i,s){e<0&&(e=65535+e+1);for(var n=0,r=Math.min(t.length-i,2);n<r;++n)t[i+n]=(e&255<<8*(s?n:1-n))>>>8*(s?n:1-n)}function D(t,e,i,s){e<0&&(e=4294967295+e+1);for(var n=0,r=Math.min(t.length-i,4);n<r;++n)t[i+n]=e>>>8*(s?n:3-n)&255}function U(t,e,i,s,n,r){if(i+s>t.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("Index out of range")}function G(t,e,i,s,n){return n||U(t,e,i,4,3.4028234663852886e38,-3.4028234663852886e38),Q.write(t,e,i,s,23,4),i+4}function N(t,e,i,s,n){return n||U(t,e,i,8,1.7976931348623157e308,-1.7976931348623157e308),Q.write(t,e,i,s,52,8),i+8}function X(t){if(t=W(t).replace(tt,""),t.length<2)return"";for(;t.length%4!=0;)t+="=";return t}function W(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function j(t){return t<16?"0"+t.toString(16):t.toString(16)}function V(t,e){e=e||1/0;for(var i,s=t.length,n=null,r=[],o=0;o<s;++o){if((i=t.charCodeAt(o))>55295&&i<57344){if(!n){if(i>56319){(e-=3)>-1&&r.push(239,191,189);continue}if(o+1===s){(e-=3)>-1&&r.push(239,191,189);continue}n=i;continue}if(i<56320){(e-=3)>-1&&r.push(239,191,189),n=i;continue}i=65536+(n-55296<<10|i-56320)}else n&&(e-=3)>-1&&r.push(239,191,189);if(n=null,i<128){if((e-=1)<0)break;r.push(i)}else if(i<2048){if((e-=2)<0)break;r.push(i>>6|192,63&i|128)}else if(i<65536){if((e-=3)<0)break;r.push(i>>12|224,i>>6&63|128,63&i|128)}else{if(!(i<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;r.push(i>>18|240,i>>12&63|128,i>>6&63|128,63&i|128)}}return r}function q(t){for(var e=[],i=0;i<t.length;++i)e.push(255&t.charCodeAt(i));return e}function H(t,e){for(var i,s,n,r=[],o=0;o<t.length&&!((e-=2)<0);++o)i=t.charCodeAt(o),s=i>>8,n=i%256,r.push(n),r.push(s);return r}function Y(t){return J.toByteArray(X(t))}function z(t,e,i,s){for(var n=0;n<s&&!(n+i>=e.length||n>=t.length);++n)e[n+i]=t[n];return n}function K(t){return t!==t}/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <[email protected]> <http://feross.org>
* @license MIT
*/
var J=i(63),Q=i(87),Z=i(66);e.Buffer=r,e.SlowBuffer=g,e.INSPECT_MAX_BYTES=50,r.TYPED_ARRAY_SUPPORT=void 0!==t.TYPED_ARRAY_SUPPORT?t.TYPED_ARRAY_SUPPORT:function(){try{var t=new Uint8Array(1);return t.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===t.foo()&&"function"==typeof t.subarray&&0===t.subarray(1,1).byteLength}catch(t){return!1}}(),e.kMaxLength=s(),r.poolSize=8192,r._augment=function(t){return t.__proto__=r.prototype,t},r.from=function(t,e,i){return o(null,t,e,i)},r.TYPED_ARRAY_SUPPORT&&(r.prototype.__proto__=Uint8Array.prototype,r.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&r[Symbol.species]===r&&Object.defineProperty(r,Symbol.species,{value:null,configurable:!0})),r.alloc=function(t,e,i){return h(null,t,e,i)},r.allocUnsafe=function(t){return l(null,t)},r.allocUnsafeSlow=function(t){return l(null,t)},r.isBuffer=function(t){return!(null==t||!t._isBuffer)},r.compare=function(t,e){if(!r.isBuffer(t)||!r.isBuffer(e))throw new TypeError("Arguments must be Buffers");if(t===e)return 0;for(var i=t.length,s=e.length,n=0,o=Math.min(i,s);n<o;++n)if(t[n]!==e[n]){i=t[n],s=e[n];break}return i<s?-1:s<i?1:0},r.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},r.concat=function(t,e){if(!Z(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return r.alloc(0);var i;if(void 0===e)for(e=0,i=0;i<t.length;++i)e+=t[i].length;var s=r.allocUnsafe(e),n=0;for(i=0;i<t.length;++i){var o=t[i];if(!r.isBuffer(o))throw new TypeError('"list" argument must be an Array of Buffers');o.copy(s,n),n+=o.length}return s},r.byteLength=m,r.prototype._isBuffer=!0,r.prototype.swap16=function(){var t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var e=0;e<t;e+=2)v(this,e,e+1);return this},r.prototype.swap32=function(){var t=this.length;if(t%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var e=0;e<t;e+=4)v(this,e,e+3),v(this,e+1,e+2);return this},r.prototype.swap64=function(){var t=this.length;if(t%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var e=0;e<t;e+=8)v(this,e,e+7),v(this,e+1,e+6),v(this,e+2,e+5),v(this,e+3,e+4);return this},r.prototype.toString=function(){var t=0|this.length;return 0===t?"":0===arguments.length?E(this,0,t):y.apply(this,arguments)},r.prototype.equals=function(t){if(!r.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===r.compare(this,t)},r.prototype.inspect=function(){var t="",i=e.INSPECT_MAX_BYTES;return this.length>0&&(t=this.toString("hex",0,i).match(/.{2}/g).join(" "),this.length>i&&(t+=" ... ")),"<Buffer "+t+">"},r.prototype.compare=function(t,e,i,s,n){if(!r.isBuffer(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===i&&(i=t?t.length:0),void 0===s&&(s=0),void 0===n&&(n=this.length),e<0||i>t.length||s<0||n>this.length)throw new RangeError("out of range index");if(s>=n&&e>=i)return 0;if(s>=n)return-1;if(e>=i)return 1;if(e>>>=0,i>>>=0,s>>>=0,n>>>=0,this===t)return 0;for(var o=n-s,a=i-e,h=Math.min(o,a),l=this.slice(s,n),c=t.slice(e,i),u=0;u<h;++u)if(l[u]!==c[u]){o=l[u],a=c[u];break}return o<a?-1:a<o?1:0},r.prototype.includes=function(t,e,i){return-1!==this.indexOf(t,e,i)},r.prototype.indexOf=function(t,e,i){return b(this,t,e,i,!0)},r.prototype.lastIndexOf=function(t,e,i){return b(this,t,e,i,!1)},r.prototype.write=function(t,e,i,s){if(void 0===e)s="utf8",i=this.length,e=0;else if(void 0===i&&"string"==typeof e)s=e,i=this.length,e=0;else{if(!isFinite(e))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");e|=0,isFinite(i)?(i|=0,void 0===s&&(s="utf8")):(s=i,i=void 0)}var n=this.length-e;if((void 0===i||i>n)&&(i=n),t.length>0&&(i<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");s||(s="utf8");for(var r=!1;;)switch(s){case"hex":return w(this,t,e,i);case"utf8":case"utf-8":return _(this,t,e,i);case"ascii":return P(this,t,e,i);case"latin1":case"binary":return T(this,t,e,i);case"base64":return C(this,t,e,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,t,e,i);default:if(r)throw new TypeError("Unknown encoding: "+s);s=(""+s).toLowerCase(),r=!0}},r.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var $=4096;r.prototype.slice=function(t,e){var i=this.length;t=~~t,e=void 0===e?i:~~e,t<0?(t+=i)<0&&(t=0):t>i&&(t=i),e<0?(e+=i)<0&&(e=0):e>i&&(e=i),e<t&&(e=t);var s;if(r.TYPED_ARRAY_SUPPORT)s=this.subarray(t,e),s.__proto__=r.prototype;else{var n=e-t;s=new r(n,void 0);for(var o=0;o<n;++o)s[o]=this[o+t]}return s},r.prototype.readUIntLE=function(t,e,i){t|=0,e|=0,i||k(t,e,this.length);for(var s=this[t],n=1,r=0;++r<e&&(n*=256);)s+=this[t+r]*n;return s},r.prototype.readUIntBE=function(t,e,i){t|=0,e|=0,i||k(t,e,this.length);for(var s=this[t+--e],n=1;e>0&&(n*=256);)s+=this[t+--e]*n;return s},r.prototype.readUInt8=function(t,e){return e||k(t,1,this.length),this[t]},r.prototype.readUInt16LE=function(t,e){return e||k(t,2,this.length),this[t]|this[t+1]<<8},r.prototype.readUInt16BE=function(t,e){return e||k(t,2,this.length),this[t]<<8|this[t+1]},r.prototype.readUInt32LE=function(t,e){return e||k(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},r.prototype.readUInt32BE=function(t,e){return e||k(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},r.prototype.readIntLE=function(t,e,i){t|=0,e|=0,i||k(t,e,this.length);for(var s=this[t],n=1,r=0;++r<e&&(n*=256);)s+=this[t+r]*n;return n*=128,s>=n&&(s-=Math.pow(2,8*e)),s},r.prototype.readIntBE=function(t,e,i){t|=0,e|=0,i||k(t,e,this.length);for(var s=e,n=1,r=this[t+--s];s>0&&(n*=256);)r+=this[t+--s]*n;return n*=128,r>=n&&(r-=Math.pow(2,8*e)),r},r.prototype.readInt8=function(t,e){return e||k(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},r.prototype.readInt16LE=function(t,e){e||k(t,2,this.length);var i=this[t]|this[t+1]<<8;return 32768&i?4294901760|i:i},r.prototype.readInt16BE=function(t,e){e||k(t,2,this.length);var i=this[t+1]|this[t]<<8;return 32768&i?4294901760|i:i},r.prototype.readInt32LE=function(t,e){return e||k(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},r.prototype.readInt32BE=function(t,e){return e||k(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},r.prototype.readFloatLE=function(t,e){return e||k(t,4,this.length),Q.read(this,t,!0,23,4)},r.prototype.readFloatBE=function(t,e){return e||k(t,4,this.length),Q.read(this,t,!1,23,4)},r.prototype.readDoubleLE=function(t,e){return e||k(t,8,this.length),Q.read(this,t,!0,52,8)},r.prototype.readDoubleBE=function(t,e){return e||k(t,8,this.length),Q.read(this,t,!1,52,8)},r.prototype.writeUIntLE=function(t,e,i,s){if(t=+t,e|=0,i|=0,!s){O(this,t,e,i,Math.pow(2,8*i)-1,0)}var n=1,r=0;for(this[e]=255&t;++r<i&&(n*=256);)this[e+r]=t/n&255;return e+i},r.prototype.writeUIntBE=function(t,e,i,s){if(t=+t,e|=0,i|=0,!s){O(this,t,e,i,Math.pow(2,8*i)-1,0)}var n=i-1,r=1;for(this[e+n]=255&t;--n>=0&&(r*=256);)this[e+n]=t/r&255;return e+i},r.prototype.writeUInt8=function(t,e,i){return t=+t,e|=0,i||O(this,t,e,1,255,0),r.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},r.prototype.writeUInt16LE=function(t,e,i){return t=+t,e|=0,i||O(this,t,e,2,65535,0),r.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):F(this,t,e,!0),e+2},r.prototype.writeUInt16BE=function(t,e,i){return t=+t,e|=0,i||O(this,t,e,2,65535,0),r.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):F(this,t,e,!1),e+2},r.prototype.writeUInt32LE=function(t,e,i){return t=+t,e|=0,i||O(this,t,e,4,4294967295,0),r.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):D(this,t,e,!0),e+4},r.prototype.writeUInt32BE=function(t,e,i){return t=+t,e|=0,i||O(this,t,e,4,4294967295,0),r.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):D(this,t,e,!1),e+4},r.prototype.writeIntLE=function(t,e,i,s){if(t=+t,e|=0,!s){var n=Math.pow(2,8*i-1);O(this,t,e,i,n-1,-n)}var r=0,o=1,a=0;for(this[e]=255&t;++r<i&&(o*=256);)t<0&&0===a&&0!==this[e+r-1]&&(a=1),this[e+r]=(t/o>>0)-a&255;return e+i},r.prototype.writeIntBE=function(t,e,i,s){if(t=+t,e|=0,!s){var n=Math.pow(2,8*i-1);O(this,t,e,i,n-1,-n)}var r=i-1,o=1,a=0;for(this[e+r]=255&t;--r>=0&&(o*=256);)t<0&&0===a&&0!==this[e+r+1]&&(a=1),this[e+r]=(t/o>>0)-a&255;return e+i},r.prototype.writeInt8=function(t,e,i){return t=+t,e|=0,i||O(this,t,e,1,127,-128),r.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[e]=255&t,e+1},r.prototype.writeInt16LE=function(t,e,i){return t=+t,e|=0,i||O(this,t,e,2,32767,-32768),r.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):F(this,t,e,!0),e+2},r.prototype.writeInt16BE=function(t,e,i){return t=+t,e|=0,i||O(this,t,e,2,32767,-32768),r.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):F(this,t,e,!1),e+2},r.prototype.writeInt32LE=function(t,e,i){return t=+t,e|=0,i||O(this,t,e,4,2147483647,-2147483648),r.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):D(this,t,e,!0),e+4},r.prototype.writeInt32BE=function(t,e,i){return t=+t,e|=0,i||O(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),r.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):D(this,t,e,!1),e+4},r.prototype.writeFloatLE=function(t,e,i){return G(this,t,e,!0,i)},r.prototype.writeFloatBE=function(t,e,i){return G(this,t,e,!1,i)},r.prototype.writeDoubleLE=function(t,e,i){return N(this,t,e,!0,i)},r.prototype.writeDoubleBE=function(t,e,i){return N(this,t,e,!1,i)},r.prototype.copy=function(t,e,i,s){if(i||(i=0),s||0===s||(s=this.length),e>=t.length&&(e=t.length),e||(e=0),s>0&&s<i&&(s=i),s===i)return 0;if(0===t.length||0===this.length)return 0;if(e<0)throw new RangeError("targetStart out of bounds");if(i<0||i>=this.length)throw new RangeError("sourceStart out of bounds");if(s<0)throw new RangeError("sourceEnd out of bounds");s>this.length&&(s=this.length),t.length-e<s-i&&(s=t.length-e+i);var n,o=s-i;if(this===t&&i<e&&e<s)for(n=o-1;n>=0;--n)t[n+e]=this[n+i];else if(o<1e3||!r.TYPED_ARRAY_SUPPORT)for(n=0;n<o;++n)t[n+e]=this[n+i];else Uint8Array.prototype.set.call(t,this.subarray(i,i+o),e);return o},r.prototype.fill=function(t,e,i,s){if("string"==typeof t){if("string"==typeof e?(s=e,e=0,i=this.length):"string"==typeof i&&(s=i,i=this.length),1===t.length){var n=t.charCodeAt(0);n<256&&(t=n)}if(void 0!==s&&"string"!=typeof s)throw new TypeError("encoding must be a string");if("string"==typeof s&&!r.isEncoding(s))throw new TypeError("Unknown encoding: "+s)}else"number"==typeof t&&(t&=255);if(e<0||this.length<e||this.length<i)throw new RangeError("Out of range index");if(i<=e)return this;e>>>=0,i=void 0===i?this.length:i>>>0,t||(t=0);var o;if("number"==typeof t)for(o=e;o<i;++o)this[o]=t;else{var a=r.isBuffer(t)?t:V(new r(t,s).toString()),h=a.length;for(o=0;o<i-e;++o)this[o+e]=a[o%h]}return this};var tt=/[^+\/0-9A-Za-z-_]/g}).call(e,i(0))},function(t,e){var i={}.toString;t.exports=Array.isArray||function(t){return"[object Array]"==i.call(t)}},,,,,,,,,,,,,function(t,e,i){(function(e){t.exports=e.PIXI=i(92)}).call(e,i(0))},function(t,e,i){(function(e){t.exports=e.Phaser=i(91)}).call(e,i(0))},function(t,e,i){(function(e){t.exports=e.p2=i(90)}).call(e,i(0))},function(t,e,i){t.exports=i.p+"js/game/src/assets/sounds/brick_destroy.wav"},function(t,e,i){t.exports=i.p+"js/game/src/assets/sounds/game_music.wav"},function(t,e,i){t.exports=i.p+"js/game/src/assets/sprites/bricksScaled720X240.png"},function(t,e,i){t.exports=i.p+"js/game/src/assets/sprites/settings-50.png"},,function(t,e){e.read=function(t,e,i,s,n){var r,o,a=8*n-s-1,h=(1<<a)-1,l=h>>1,c=-7,u=i?n-1:0,d=i?-1:1,p=t[e+u];for(u+=d,r=p&(1<<-c)-1,p>>=-c,c+=a;c>0;r=256*r+t[e+u],u+=d,c-=8);for(o=r&(1<<-c)-1,r>>=-c,c+=s;c>0;o=256*o+t[e+u],u+=d,c-=8);if(0===r)r=1-l;else{if(r===h)return o?NaN:1/0*(p?-1:1);o+=Math.pow(2,s),r-=l}return(p?-1:1)*o*Math.pow(2,r-s)},e.write=function(t,e,i,s,n,r){var o,a,h,l=8*r-n-1,c=(1<<l)-1,u=c>>1,d=23===n?Math.pow(2,-24)-Math.pow(2,-77):0,p=s?0:r-1,f=s?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=c):(o=Math.floor(Math.log(e)/Math.LN2),e*(h=Math.pow(2,-o))<1&&(o--,h*=2),e+=o+u>=1?d/h:d*Math.pow(2,1-u),e*h>=2&&(o++,h/=2),o+u>=c?(a=0,o=c):o+u>=1?(a=(e*h-1)*Math.pow(2,n),o+=u):(a=e*Math.pow(2,u-1)*Math.pow(2,n),o=0));n>=8;t[i+p]=255&a,p+=f,a/=256,n-=8);for(o=o<<n|a,l+=n;l>0;t[i+p]=255&o,p+=f,o/=256,l-=8);t[i+p-f]|=128*g}},,,function(t,e,i){var s,s;!function(e){t.exports=e()}(function(){return function t(e,i,n){function r(a,h){if(!i[a]){if(!e[a]){var l="function"==typeof s&&s;if(!h&&l)return s(a,!0);if(o)return s(a,!0);throw new Error("Cannot find module '"+a+"'")}var c=i[a]={exports:{}};e[a][0].call(c.exports,function(t){var i=e[a][1][t];return r(i||t)},c,c.exports,t,e,i,n)}return i[a].exports}for(var o="function"==typeof s&&s,a=0;a<n.length;a++)r(n[a]);return r}({1:[function(t,e,i){function s(){}var n=t("./Scalar");e.exports=s,s.lineInt=function(t,e,i){i=i||0;var s,r,o,a,h,l,c,u=[0,0];return s=t[1][1]-t[0][1],r=t[0][0]-t[1][0],o=s*t[0][0]+r*t[0][1],a=e[1][1]-e[0][1],h=e[0][0]-e[1][0],l=a*e[0][0]+h*e[0][1],c=s*h-a*r,n.eq(c,0,i)||(u[0]=(h*o-r*l)/c,u[1]=(s*l-a*o)/c),u},s.segmentsIntersect=function(t,e,i,s){var n=e[0]-t[0],r=e[1]-t[1],o=s[0]-i[0],a=s[1]-i[1];if(o*r-a*n==0)return!1;var h=(n*(i[1]-t[1])+r*(t[0]-i[0]))/(o*r-a*n),l=(o*(t[1]-i[1])+a*(i[0]-t[0]))/(a*n-o*r);return h>=0&&h<=1&&l>=0&&l<=1}},{"./Scalar":4}],2:[function(t,e,i){function s(){}e.exports=s,s.area=function(t,e,i){return(e[0]-t[0])*(i[1]-t[1])-(i[0]-t[0])*(e[1]-t[1])},s.left=function(t,e,i){return s.area(t,e,i)>0},s.leftOn=function(t,e,i){return s.area(t,e,i)>=0},s.right=function(t,e,i){return s.area(t,e,i)<0},s.rightOn=function(t,e,i){return s.area(t,e,i)<=0};var n=[],r=[];s.collinear=function(t,e,i,o){if(o){var a=n,h=r;a[0]=e[0]-t[0],a[1]=e[1]-t[1],h[0]=i[0]-e[0],h[1]=i[1]-e[1];var l=a[0]*h[0]+a[1]*h[1],c=Math.sqrt(a[0]*a[0]+a[1]*a[1]),u=Math.sqrt(h[0]*h[0]+h[1]*h[1]);return Math.acos(l/(c*u))<o}return 0==s.area(t,e,i)},s.sqdist=function(t,e){var i=e[0]-t[0],s=e[1]-t[1];return i*i+s*s}},{}],3:[function(t,e,i){function s(){this.vertices=[]}function n(t,e,i,s,n){n=n||0;var r=e[1]-t[1],o=t[0]-e[0],h=r*t[0]+o*t[1],l=s[1]-i[1],c=i[0]-s[0],u=l*i[0]+c*i[1],d=r*c-l*o;return a.eq(d,0,n)?[0,0]:[(c*h-o*u)/d,(r*u-l*h)/d]}var r=t("./Line"),o=t("./Point"),a=t("./Scalar");e.exports=s,s.prototype.at=function(t){var e=this.vertices,i=e.length;return e[t<0?t%i+i:t%i]},s.prototype.first=function(){return this.vertices[0]},s.prototype.last=function(){return this.vertices[this.vertices.length-1]},s.prototype.clear=function(){this.vertices.length=0},s.prototype.append=function(t,e,i){if(void 0===e)throw new Error("From is not given!");if(void 0===i)throw new Error("To is not given!");if(i-1<e)throw new Error("lol1");if(i>t.vertices.length)throw new Error("lol2");if(e<0)throw new Error("lol3");for(var s=e;s<i;s++)this.vertices.push(t.vertices[s])},s.prototype.makeCCW=function(){for(var t=0,e=this.vertices,i=1;i<this.vertices.length;++i)(e[i][1]<e[t][1]||e[i][1]==e[t][1]&&e[i][0]>e[t][0])&&(t=i);o.left(this.at(t-1),this.at(t),this.at(t+1))||this.reverse()},s.prototype.reverse=function(){for(var t=[],e=0,i=this.vertices.length;e!==i;e++)t.push(this.vertices.pop());this.vertices=t},s.prototype.isReflex=function(t){return o.right(this.at(t-1),this.at(t),this.at(t+1))};var h=[],l=[];s.prototype.canSee=function(t,e){var i,s,n=h,a=l;if(o.leftOn(this.at(t+1),this.at(t),this.at(e))&&o.rightOn(this.at(t-1),this.at(t),this.at(e)))return!1;s=o.sqdist(this.at(t),this.at(e));for(var c=0;c!==this.vertices.length;++c)if((c+1)%this.vertices.length!==t&&c!==t&&o.leftOn(this.at(t),this.at(e),this.at(c+1))&&o.rightOn(this.at(t),this.at(e),this.at(c))&&(n[0]=this.at(t),n[1]=this.at(e),a[0]=this.at(c),a[1]=this.at(c+1),i=r.lineInt(n,a),o.sqdist(this.at(t),i)<s))return!1;return!0},s.prototype.copy=function(t,e,i){var n=i||new s;if(n.clear(),t<e)for(var r=t;r<=e;r++)n.vertices.push(this.vertices[r]);else{for(var r=0;r<=e;r++)n.vertices.push(this.vertices[r]);for(var r=t;r<this.vertices.length;r++)n.vertices.push(this.vertices[r])}return n},s.prototype.getCutEdges=function(){for(var t=[],e=[],i=[],n=new s,r=Number.MAX_VALUE,o=0;o<this.vertices.length;++o)if(this.isReflex(o))for(var a=0;a<this.vertices.length;++a)if(this.canSee(o,a)){e=this.copy(o,a,n).getCutEdges(),i=this.copy(a,o,n).getCutEdges();for(var h=0;h<i.length;h++)e.push(i[h]);e.length<r&&(t=e,r=e.length,t.push([this.at(o),this.at(a)]))}return t},s.prototype.decomp=function(){var t=this.getCutEdges();return t.length>0?this.slice(t):[this]},s.prototype.slice=function(t){if(0==t.length)return[this];if(t instanceof Array&&t.length&&t[0]instanceof Array&&2==t[0].length&&t[0][0]instanceof Array){for(var e=[this],i=0;i<t.length;i++)for(var s=t[i],n=0;n<e.length;n++){var r=e[n],o=r.slice(s);if(o){e.splice(n,1),e.push(o[0],o[1]);break}}return e}var s=t,i=this.vertices.indexOf(s[0]),n=this.vertices.indexOf(s[1]);return-1!=i&&-1!=n&&[this.copy(i,n),this.copy(n,i)]},s.prototype.isSimple=function(){for(var t=this.vertices,e=0;e<t.length-1;e++)for(var i=0;i<e-1;i++)if(r.segmentsIntersect(t[e],t[e+1],t[i],t[i+1]))return!1;for(var e=1;e<t.length-2;e++)if(r.segmentsIntersect(t[0],t[t.length-1],t[e],t[e+1]))return!1;return!0},s.prototype.quickDecomp=function(t,e,i,r,a,h){a=a||100,h=h||0,r=r||25,t=void 0!==t?t:[],e=e||[],i=i||[];var l=[0,0],c=[0,0],u=[0,0],d=0,p=0,f=0,g=0,m=0,y=0,v=0,b=new s,x=new s,w=this,_=this.vertices;if(_.length<3)return t;if(++h>a)return console.warn("quickDecomp: max level ("+a+") reached."),t;for(var P=0;P<this.vertices.length;++P)if(w.isReflex(P)){e.push(w.vertices[P]),d=p=Number.MAX_VALUE;for(var T=0;T<this.vertices.length;++T)o.left(w.at(P-1),w.at(P),w.at(T))&&o.rightOn(w.at(P-1),w.at(P),w.at(T-1))&&(u=n(w.at(P-1),w.at(P),w.at(T),w.at(T-1)),o.right(w.at(P+1),w.at(P),u)&&(f=o.sqdist(w.vertices[P],u))<p&&(p=f,c=u,y=T)),o.left(w.at(P+1),w.at(P),w.at(T+1))&&o.rightOn(w.at(P+1),w.at(P),w.at(T))&&(u=n(w.at(P+1),w.at(P),w.at(T),w.at(T+1)),o.left(w.at(P-1),w.at(P),u)&&(f=o.sqdist(w.vertices[P],u))<d&&(d=f,l=u,m=T));if(y==(m+1)%this.vertices.length)u[0]=(c[0]+l[0])/2,u[1]=(c[1]+l[1])/2,i.push(u),P<m?(b.append(w,P,m+1),b.vertices.push(u),x.vertices.push(u),0!=y&&x.append(w,y,w.vertices.length),x.append(w,0,P+1)):(0!=P&&b.append(w,P,w.vertices.length),b.append(w,0,m+1),b.vertices.push(u),x.vertices.push(u),x.append(w,y,P+1));else{if(y>m&&(m+=this.vertices.length),g=Number.MAX_VALUE,m<y)return t;for(var T=y;T<=m;++T)o.leftOn(w.at(P-1),w.at(P),w.at(T))&&o.rightOn(w.at(P+1),w.at(P),w.at(T))&&(f=o.sqdist(w.at(P),w.at(T)))<g&&(g=f,v=T%this.vertices.length);P<v?(b.append(w,P,v+1),0!=v&&x.append(w,v,_.length),x.append(w,0,P+1)):(0!=P&&b.append(w,P,_.length),b.append(w,0,v+1),x.append(w,v,P+1))}return b.vertices.length<x.vertices.length?(b.quickDecomp(t,e,i,r,a,h),x.quickDecomp(t,e,i,r,a,h)):(x.quickDecomp(t,e,i,r,a,h),b.quickDecomp(t,e,i,r,a,h)),t}return t.push(this),t},s.prototype.removeCollinearPoints=function(t){for(var e=0,i=this.vertices.length-1;this.vertices.length>3&&i>=0;--i)o.collinear(this.at(i-1),this.at(i),this.at(i+1),t)&&(this.vertices.splice(i%this.vertices.length,1),i--,e++);return e}},{"./Line":1,"./Point":2,"./Scalar":4}],4:[function(t,e,i){function s(){}e.exports=s,s.eq=function(t,e,i){return i=i||0,Math.abs(t-e)<i}},{}],5:[function(t,e,i){e.exports={Polygon:t("./Polygon"),Point:t("./Point")}},{"./Point":2,"./Polygon":3}],6:[function(t,e,i){e.exports={name:"p2",version:"0.7.0",description:"A JavaScript 2D physics engine.",author:"Stefan Hedman <[email protected]> (http://steffe.se)",keywords:["p2.js","p2","physics","engine","2d"],main:"./src/p2.js",engines:{node:"*"},repository:{type:"git",url:"https://github.com/schteppe/p2.js.git"},bugs:{url:"https://github.com/schteppe/p2.js/issues"},licenses:[{type:"MIT"}],devDependencies:{grunt:"^0.4.5","grunt-contrib-jshint":"^0.11.2","grunt-contrib-nodeunit":"^0.4.1","grunt-contrib-uglify":"~0.4.0","grunt-contrib-watch":"~0.5.0","grunt-browserify":"~2.0.1","grunt-contrib-concat":"^0.4.0"},dependencies:{"poly-decomp":"0.1.0"}}},{}],7:[function(t,e,i){function s(t){this.lowerBound=n.create(),t&&t.lowerBound&&n.copy(this.lowerBound,t.lowerBound),this.upperBound=n.create(),t&&t.upperBound&&n.copy(this.upperBound,t.upperBound)}var n=t("../math/vec2");t("../utils/Utils");e.exports=s;var r=n.create();s.prototype.setFromPoints=function(t,e,i,s){var o=this.lowerBound,a=this.upperBound;"number"!=typeof i&&(i=0),0!==i?n.rotate(o,t[0],i):n.copy(o,t[0]),n.copy(a,o);for(var h=Math.cos(i),l=Math.sin(i),c=1;c<t.length;c++){var u=t[c];if(0!==i){var d=u[0],p=u[1];r[0]=h*d-l*p,r[1]=l*d+h*p,u=r}for(var f=0;f<2;f++)u[f]>a[f]&&(a[f]=u[f]),u[f]<o[f]&&(o[f]=u[f])}e&&(n.add(this.lowerBound,this.lowerBound,e),n.add(this.upperBound,this.upperBound,e)),s&&(this.lowerBound[0]-=s,this.lowerBound[1]-=s,this.upperBound[0]+=s,this.upperBound[1]+=s)},s.prototype.copy=function(t){n.copy(this.lowerBound,t.lowerBound),n.copy(this.upperBound,t.upperBound)},s.prototype.extend=function(t){for(var e=2;e--;){var i=t.lowerBound[e];this.lowerBound[e]>i&&(this.lowerBound[e]=i);var s=t.upperBound[e];this.upperBound[e]<s&&(this.upperBound[e]=s)}},s.prototype.overlaps=function(t){var e=this.lowerBound,i=this.upperBound,s=t.lowerBound,n=t.upperBound;return(s[0]<=i[0]&&i[0]<=n[0]||e[0]<=n[0]&&n[0]<=i[0])&&(s[1]<=i[1]&&i[1]<=n[1]||e[1]<=n[1]&&n[1]<=i[1])},s.prototype.containsPoint=function(t){var e=this.lowerBound,i=this.upperBound;return e[0]<=t[0]&&t[0]<=i[0]&&e[1]<=t[1]&&t[1]<=i[1]},s.prototype.overlapsRay=function(t){var e=1/t.direction[0],i=1/t.direction[1],s=(this.lowerBound[0]-t.from[0])*e,n=(this.upperBound[0]-t.from[0])*e,r=(this.lowerBound[1]-t.from[1])*i,o=(this.upperBound[1]-t.from[1])*i,a=Math.max(Math.max(Math.min(s,n),Math.min(r,o))),h=Math.min(Math.min(Math.max(s,n),Math.max(r,o)));return h<0?-1:a>h?-1:a}},{"../math/vec2":30,"../utils/Utils":57}],8:[function(t,e,i){function s(t){this.type=t,this.result=[],this.world=null,this.boundingVolumeType=s.AABB}var n=t("../math/vec2"),r=t("../objects/Body");e.exports=s,s.AABB=1,s.BOUNDING_CIRCLE=2,s.prototype.setWorld=function(t){this.world=t},s.prototype.getCollisionPairs=function(t){};var o=n.create();s.boundingRadiusCheck=function(t,e){n.sub(o,t.position,e.position);var i=n.squaredLength(o),s=t.boundingRadius+e.boundingRadius;return i<=s*s},s.aabbCheck=function(t,e){return t.getAABB().overlaps(e.getAABB())},s.prototype.boundingVolumeCheck=function(t,e){var i;switch(this.boundingVolumeType){case s.BOUNDING_CIRCLE:i=s.boundingRadiusCheck(t,e);break;case s.AABB:i=s.aabbCheck(t,e);break;default:throw new Error("Bounding volume type not recognized: "+this.boundingVolumeType)}return i},s.canCollide=function(t,e){var i=r.KINEMATIC,s=r.STATIC;return(t.type!==s||e.type!==s)&&(!(t.type===i&&e.type===s||t.type===s&&e.type===i)&&((t.type!==i||e.type!==i)&&((t.sleepState!==r.SLEEPING||e.sleepState!==r.SLEEPING)&&!(t.sleepState===r.SLEEPING&&e.type===s||e.sleepState===r.SLEEPING&&t.type===s))))},s.NAIVE=1,s.SAP=2},{"../math/vec2":30,"../objects/Body":31}],9:[function(t,e,i){function s(){n.call(this,n.NAIVE)}var n=(t("../shapes/Circle"),t("../shapes/Plane"),t("../shapes/Shape"),t("../shapes/Particle"),t("../collision/Broadphase"));t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.getCollisionPairs=function(t){var e=t.bodies,i=this.result;i.length=0;for(var s=0,r=e.length;s!==r;s++)for(var o=e[s],a=0;a<s;a++){var h=e[a];n.canCollide(o,h)&&this.boundingVolumeCheck(o,h)&&i.push(o,h)}return i},s.prototype.aabbQuery=function(t,e,i){i=i||[];for(var s=t.bodies,n=0;n<s.length;n++){var r=s[n];r.aabbNeedsUpdate&&r.updateAABB(),r.aabb.overlaps(e)&&i.push(r)}return i}},{"../collision/Broadphase":8,"../math/vec2":30,"../shapes/Circle":39,"../shapes/Particle":43,"../shapes/Plane":44,"../shapes/Shape":45}],10:[function(t,e,i){function s(){this.contactEquations=[],this.frictionEquations=[],this.enableFriction=!0,this.enabledEquations=!0,this.slipForce=10,this.frictionCoefficient=.3,this.surfaceVelocity=0,this.contactEquationPool=new c({size:32}),this.frictionEquationPool=new u({size:64}),this.restitution=0,this.stiffness=p.DEFAULT_STIFFNESS,this.relaxation=p.DEFAULT_RELAXATION,this.frictionStiffness=p.DEFAULT_STIFFNESS,this.frictionRelaxation=p.DEFAULT_RELAXATION,this.enableFrictionReduction=!0,this.collidingBodiesLastStep=new d,this.contactSkinSize=.01}function n(t,e){o.set(t.vertices[0],.5*-e.length,-e.radius),o.set(t.vertices[1],.5*e.length,-e.radius),o.set(t.vertices[2],.5*e.length,e.radius),o.set(t.vertices[3],.5*-e.length,e.radius)}function r(t,e,i,s){for(var n=q,r=H,l=Y,c=z,u=t,d=e.vertices,p=null,f=0;f!==d.length+1;f++){var g=d[f%d.length],m=d[(f+1)%d.length];o.rotate(n,g,s),o.rotate(r,m,s),h(n,n,i),h(r,r,i),a(l,n,u),a(c,r,u);var y=o.crossLength(l,c);if(null===p&&(p=y),y*p<=0)return!1;p=y}return!0}var o=t("../math/vec2"),a=o.sub,h=o.add,l=o.dot,c=(t("../utils/Utils"),t("../utils/ContactEquationPool")),u=t("../utils/FrictionEquationPool"),d=t("../utils/TupleDictionary"),p=t("../equations/Equation"),f=(t("../equations/ContactEquation"),t("../equations/FrictionEquation"),t("../shapes/Circle")),g=t("../shapes/Convex"),m=t("../shapes/Shape"),y=(t("../objects/Body"),t("../shapes/Box"));e.exports=s;var v=o.fromValues(0,1),b=o.fromValues(0,0),x=o.fromValues(0,0),w=o.fromValues(0,0),_=o.fromValues(0,0),P=o.fromValues(0,0),T=o.fromValues(0,0),C=o.fromValues(0,0),S=o.fromValues(0,0),A=o.fromValues(0,0),E=o.fromValues(0,0),I=o.fromValues(0,0),M=o.fromValues(0,0),R=o.fromValues(0,0),B=o.fromValues(0,0),L=o.fromValues(0,0),k=o.fromValues(0,0),O=o.fromValues(0,0),F=o.fromValues(0,0),D=[],U=o.create(),G=o.create();s.prototype.bodiesOverlap=function(t,e){for(var i=U,s=G,n=0,r=t.shapes.length;n!==r;n++){var o=t.shapes[n];t.toWorldFrame(i,o.position);for(var a=0,h=e.shapes.length;a!==h;a++){var l=e.shapes[a];if(e.toWorldFrame(s,l.position),this[o.type|l.type](t,o,i,o.angle+t.angle,e,l,s,l.angle+e.angle,!0))return!0}}return!1},s.prototype.collidedLastStep=function(t,e){var i=0|t.id,s=0|e.id;return!!this.collidingBodiesLastStep.get(i,s)},s.prototype.reset=function(){this.collidingBodiesLastStep.reset();for(var t=this.contactEquations,e=t.length;e--;){var i=t[e],s=i.bodyA.id,n=i.bodyB.id;this.collidingBodiesLastStep.set(s,n,!0)}for(var r=this.contactEquations,o=this.frictionEquations,a=0;a<r.length;a++)this.contactEquationPool.release(r[a]);for(var a=0;a<o.length;a++)this.frictionEquationPool.release(o[a]);this.contactEquations.length=this.frictionEquations.length=0},s.prototype.createContactEquation=function(t,e,i,s){var n=this.contactEquationPool.get();return n.bodyA=t,n.bodyB=e,n.shapeA=i,n.shapeB=s,n.restitution=this.restitution,n.firstImpact=!this.collidedLastStep(t,e),n.stiffness=this.stiffness,n.relaxation=this.relaxation,n.needsUpdate=!0,n.enabled=this.enabledEquations,n.offset=this.contactSkinSize,n},s.prototype.createFrictionEquation=function(t,e,i,s){var n=this.frictionEquationPool.get();return n.bodyA=t,n.bodyB=e,n.shapeA=i,n.shapeB=s,n.setSlipForce(this.slipForce),n.frictionCoefficient=this.frictionCoefficient,n.relativeVelocity=this.surfaceVelocity,n.enabled=this.enabledEquations,n.needsUpdate=!0,n.stiffness=this.frictionStiffness,n.relaxation=this.frictionRelaxation,n.contactEquations.length=0,n},s.prototype.createFrictionFromContact=function(t){var e=this.createFrictionEquation(t.bodyA,t.bodyB,t.shapeA,t.shapeB);return o.copy(e.contactPointA,t.contactPointA),o.copy(e.contactPointB,t.contactPointB),o.rotate90cw(e.t,t.normalA),e.contactEquations.push(t),e},s.prototype.createFrictionFromAverage=function(t){var e=this.contactEquations[this.contactEquations.length-1],i=this.createFrictionEquation(e.bodyA,e.bodyB,e.shapeA,e.shapeB),s=e.bodyA;e.bodyB;o.set(i.contactPointA,0,0),o.set(i.contactPointB,0,0),o.set(i.t,0,0);for(var n=0;n!==t;n++)e=this.contactEquations[this.contactEquations.length-1-n],e.bodyA===s?(o.add(i.t,i.t,e.normalA),o.add(i.contactPointA,i.contactPointA,e.contactPointA),o.add(i.contactPointB,i.contactPointB,e.contactPointB)):(o.sub(i.t,i.t,e.normalA),o.add(i.contactPointA,i.contactPointA,e.contactPointB),o.add(i.contactPointB,i.contactPointB,e.contactPointA)),i.contactEquations.push(e);var r=1/t;return o.scale(i.contactPointA,i.contactPointA,r),o.scale(i.contactPointB,i.contactPointB,r),o.normalize(i.t,i.t),o.rotate90cw(i.t,i.t),i},s.prototype[m.LINE|m.CONVEX]=s.prototype.convexLine=function(t,e,i,s,n,r,o,a,h){return!h&&0},s.prototype[m.LINE|m.BOX]=s.prototype.lineBox=function(t,e,i,s,n,r,o,a,h){return!h&&0};var N=new y({width:1,height:1}),X=o.create();s.prototype[m.CAPSULE|m.CONVEX]=s.prototype[m.CAPSULE|m.BOX]=s.prototype.convexCapsule=function(t,e,i,s,r,a,h,l,c){var u=X;o.set(u,a.length/2,0),o.rotate(u,u,l),o.add(u,u,h);var d=this.circleConvex(r,a,u,l,t,e,i,s,c,a.radius);o.set(u,-a.length/2,0),o.rotate(u,u,l),o.add(u,u,h);var p=this.circleConvex(r,a,u,l,t,e,i,s,c,a.radius);if(c&&(d||p))return!0;var f=N;return n(f,a),this.convexConvex(t,e,i,s,r,f,h,l,c)+d+p},s.prototype[m.CAPSULE|m.LINE]=s.prototype.lineCapsule=function(t,e,i,s,n,r,o,a,h){return!h&&0};var W=o.create(),j=o.create(),V=new y({width:1,height:1});s.prototype[m.CAPSULE|m.CAPSULE]=s.prototype.capsuleCapsule=function(t,e,i,s,r,a,h,l,c){for(var u,d=W,p=j,f=0,g=0;g<2;g++){o.set(d,(0===g?-1:1)*e.length/2,0),o.rotate(d,d,s),o.add(d,d,i);for(var m=0;m<2;m++){o.set(p,(0===m?-1:1)*a.length/2,0),o.rotate(p,p,l),o.add(p,p,h),this.enableFrictionReduction&&(u=this.enableFriction,this.enableFriction=!1);var y=this.circleCircle(t,e,d,s,r,a,p,l,c,e.radius,a.radius);if(this.enableFrictionReduction&&(this.enableFriction=u),c&&y)return!0;f+=y}}this.enableFrictionReduction&&(u=this.enableFriction,this.enableFriction=!1);var v=V;n(v,e);var b=this.convexCapsule(t,v,i,s,r,a,h,l,c);if(this.enableFrictionReduction&&(this.enableFriction=u),c&&b)return!0;if(f+=b,this.enableFrictionReduction){var u=this.enableFriction;this.enableFriction=!1}n(v,a);var x=this.convexCapsule(r,v,h,l,t,e,i,s,c);return this.enableFrictionReduction&&(this.enableFriction=u),!(!c||!x)||(f+=x,this.enableFrictionReduction&&f&&this.enableFriction&&this.frictionEquations.push(this.createFrictionFromAverage(f)),f)},s.prototype[m.LINE|m.LINE]=s.prototype.lineLine=function(t,e,i,s,n,r,o,a,h){return!h&&0},s.prototype[m.PLANE|m.LINE]=s.prototype.planeLine=function(t,e,i,s,n,r,c,u,d){var p=b,f=x,g=w,m=_,y=P,E=T,I=C,M=S,R=A,B=D,L=0;o.set(p,-r.length/2,0),o.set(f,r.length/2,0),o.rotate(g,p,u),o.rotate(m,f,u),h(g,g,c),h(m,m,c),o.copy(p,g),o.copy(f,m),a(y,f,p),o.normalize(E,y),o.rotate90cw(R,E),o.rotate(M,v,s),B[0]=p,B[1]=f;for(var k=0;k<B.length;k++){var O=B[k];a(I,O,i);var F=l(I,M);if(F<0){if(d)return!0;var U=this.createContactEquation(t,n,e,r);L++,o.copy(U.normalA,M),o.normalize(U.normalA,U.normalA),o.scale(I,M,F),a(U.contactPointA,O,I),a(U.contactPointA,U.contactPointA,t.position),a(U.contactPointB,O,c),h(U.contactPointB,U.contactPointB,c),a(U.contactPointB,U.contactPointB,n.position),this.contactEquations.push(U),this.enableFrictionReduction||this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(U))}}return!d&&(this.enableFrictionReduction||L&&this.enableFriction&&this.frictionEquations.push(this.createFrictionFromAverage(L)),L)},s.prototype[m.PARTICLE|m.CAPSULE]=s.prototype.particleCapsule=function(t,e,i,s,n,r,o,a,h){return this.circleLine(t,e,i,s,n,r,o,a,h,r.radius,0)},s.prototype[m.CIRCLE|m.LINE]=s.prototype.circleLine=function(t,e,i,s,n,r,c,u,d,p,f){var p=p||0,f=void 0!==f?f:e.radius,g=b,m=x,y=w,v=_,L=P,k=T,O=C,F=S,U=A,G=E,N=I,X=M,W=R,j=B,V=D;o.set(F,-r.length/2,0),o.set(U,r.length/2,0),o.rotate(G,F,u),o.rotate(N,U,u),h(G,G,c),h(N,N,c),o.copy(F,G),o.copy(U,N),a(k,U,F),o.normalize(O,k),o.rotate90cw(L,O),a(X,i,F);var q=l(X,L);a(v,F,c),a(W,i,c);var H=f+p;if(Math.abs(q)<H){o.scale(g,L,q),a(y,i,g),o.scale(m,L,l(L,W)),o.normalize(m,m),o.scale(m,m,p),h(y,y,m);var Y=l(O,y),z=l(O,F),K=l(O,U);if(Y>z&&Y<K){if(d)return!0;var J=this.createContactEquation(t,n,e,r);return o.scale(J.normalA,g,-1),o.normalize(J.normalA,J.normalA),o.scale(J.contactPointA,J.normalA,f),h(J.contactPointA,J.contactPointA,i),a(J.contactPointA,J.contactPointA,t.position),a(J.contactPointB,y,c),h(J.contactPointB,J.contactPointB,c),a(J.contactPointB,J.contactPointB,n.position),this.contactEquations.push(J),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(J)),1}}V[0]=F,V[1]=U;for(var Q=0;Q<V.length;Q++){var Z=V[Q];if(a(X,Z,i),o.squaredLength(X)<Math.pow(H,2)){if(d)return!0;var J=this.createContactEquation(t,n,e,r);return o.copy(J.normalA,X),o.normalize(J.normalA,J.normalA),o.scale(J.contactPointA,J.normalA,f),h(J.contactPointA,J.contactPointA,i),a(J.contactPointA,J.contactPointA,t.position),a(J.contactPointB,Z,c),o.scale(j,J.normalA,-p),h(J.contactPointB,J.contactPointB,j),h(J.contactPointB,J.contactPointB,c),a(J.contactPointB,J.contactPointB,n.position),this.contactEquations.push(J),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(J)),1}}return 0},s.prototype[m.CIRCLE|m.CAPSULE]=s.prototype.circleCapsule=function(t,e,i,s,n,r,o,a,h){return this.circleLine(t,e,i,s,n,r,o,a,h,r.radius)},s.prototype[m.CIRCLE|m.CONVEX]=s.prototype[m.CIRCLE|m.BOX]=s.prototype.circleConvex=function(t,e,i,s,n,l,c,u,d,p){for(var p="number"==typeof p?p:e.radius,f=b,g=x,m=w,y=_,v=P,T=E,C=I,S=R,A=B,M=L,O=k,F=!1,D=Number.MAX_VALUE,U=l.vertices,G=0;G!==U.length+1;G++){var N=U[G%U.length],X=U[(G+1)%U.length];if(o.rotate(f,N,u),o.rotate(g,X,u),h(f,f,c),h(g,g,c),a(m,g,f),o.normalize(y,m),o.rotate90cw(v,y),o.scale(A,v,-e.radius),h(A,A,i),r(A,l,c,u)){o.sub(M,f,A);var W=Math.abs(o.dot(M,v));W<D&&(o.copy(O,A),D=W,o.scale(S,v,W),o.add(S,S,A),F=!0)}}if(F){if(d)return!0;var j=this.createContactEquation(t,n,e,l);return o.sub(j.normalA,O,i),o.normalize(j.normalA,j.normalA),o.scale(j.contactPointA,j.normalA,p),h(j.contactPointA,j.contactPointA,i),a(j.contactPointA,j.contactPointA,t.position),a(j.contactPointB,S,c),h(j.contactPointB,j.contactPointB,c),a(j.contactPointB,j.contactPointB,n.position),this.contactEquations.push(j),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(j)),1}if(p>0)for(var G=0;G<U.length;G++){var V=U[G];if(o.rotate(C,V,u),h(C,C,c),a(T,C,i),o.squaredLength(T)<Math.pow(p,2)){if(d)return!0;var j=this.createContactEquation(t,n,e,l);return o.copy(j.normalA,T),o.normalize(j.normalA,j.normalA),o.scale(j.contactPointA,j.normalA,p),h(j.contactPointA,j.contactPointA,i),a(j.contactPointA,j.contactPointA,t.position),a(j.contactPointB,C,c),h(j.contactPointB,j.contactPointB,c),a(j.contactPointB,j.contactPointB,n.position),this.contactEquations.push(j),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(j)),1}}return 0};var q=o.create(),H=o.create(),Y=o.create(),z=o.create();s.prototype[m.PARTICLE|m.CONVEX]=s.prototype[m.PARTICLE|m.BOX]=s.prototype.particleConvex=function(t,e,i,s,n,c,u,d,p){var f=b,g=x,m=w,y=_,v=P,S=T,A=C,I=E,M=R,B=O,L=F,k=Number.MAX_VALUE,D=!1,U=c.vertices;if(!r(i,c,u,d))return 0;if(p)return!0;for(var G=0;G!==U.length+1;G++){var N=U[G%U.length],X=U[(G+1)%U.length];o.rotate(f,N,d),o.rotate(g,X,d),h(f,f,u),h(g,g,u),a(m,g,f),o.normalize(y,m),o.rotate90cw(v,y),a(I,i,f);l(I,v);a(S,f,u),a(A,i,u),o.sub(B,f,i);var W=Math.abs(o.dot(B,v));W<k&&(k=W,o.scale(M,v,W),o.add(M,M,i),o.copy(L,v),D=!0)}if(D){var j=this.createContactEquation(t,n,e,c);return o.scale(j.normalA,L,-1),o.normalize(j.normalA,j.normalA),o.set(j.contactPointA,0,0),h(j.contactPointA,j.contactPointA,i),a(j.contactPointA,j.contactPointA,t.position),a(j.contactPointB,M,u),h(j.contactPointB,j.contactPointB,u),a(j.contactPointB,j.contactPointB,n.position),this.contactEquations.push(j),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(j)),1}return 0},s.prototype[m.CIRCLE]=s.prototype.circleCircle=function(t,e,i,s,n,r,l,c,u,d,p){var f=b,d=d||e.radius,p=p||r.radius;a(f,i,l);var g=d+p;if(o.squaredLength(f)>Math.pow(g,2))return 0;if(u)return!0;var m=this.createContactEquation(t,n,e,r);return a(m.normalA,l,i),o.normalize(m.normalA,m.normalA),o.scale(m.contactPointA,m.normalA,d),o.scale(m.contactPointB,m.normalA,-p),h(m.contactPointA,m.contactPointA,i),a(m.contactPointA,m.contactPointA,t.position),h(m.contactPointB,m.contactPointB,l),a(m.contactPointB,m.contactPointB,n.position),this.contactEquations.push(m),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(m)),1},s.prototype[m.PLANE|m.CONVEX]=s.prototype[m.PLANE|m.BOX]=s.prototype.planeConvex=function(t,e,i,s,n,r,c,u,d){var p=b,f=x,g=w,m=0;o.rotate(f,v,s);for(var y=0;y!==r.vertices.length;y++){var _=r.vertices[y];if(o.rotate(p,_,u),h(p,p,c),a(g,p,i),l(g,f)<=0){if(d)return!0;m++;var P=this.createContactEquation(t,n,e,r);a(g,p,i),o.copy(P.normalA,f);var T=l(g,P.normalA);o.scale(g,P.normalA,T),a(P.contactPointB,p,n.position),a(P.contactPointA,p,g),a(P.contactPointA,P.contactPointA,t.position),this.contactEquations.push(P),this.enableFrictionReduction||this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(P))}}return this.enableFrictionReduction&&this.enableFriction&&m&&this.frictionEquations.push(this.createFrictionFromAverage(m)),m},s.prototype[m.PARTICLE|m.PLANE]=s.prototype.particlePlane=function(t,e,i,s,n,r,h,c,u){var d=b,p=x;c=c||0,a(d,i,h),o.rotate(p,v,c);var f=l(d,p);if(f>0)return 0;if(u)return!0;var g=this.createContactEquation(n,t,r,e);return o.copy(g.normalA,p),o.scale(d,g.normalA,f),a(g.contactPointA,i,d),a(g.contactPointA,g.contactPointA,n.position),a(g.contactPointB,i,t.position),this.contactEquations.push(g),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(g)),1},s.prototype[m.CIRCLE|m.PARTICLE]=s.prototype.circleParticle=function(t,e,i,s,n,r,l,c,u){var d=b;if(a(d,l,i),o.squaredLength(d)>Math.pow(e.radius,2))return 0;if(u)return!0;var p=this.createContactEquation(t,n,e,r);return o.copy(p.normalA,d),o.normalize(p.normalA,p.normalA),o.scale(p.contactPointA,p.normalA,e.radius),h(p.contactPointA,p.contactPointA,i),a(p.contactPointA,p.contactPointA,t.position),a(p.contactPointB,l,n.position),this.contactEquations.push(p),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(p)),1};var K=new f({radius:1}),J=o.create(),Q=o.create();o.create();s.prototype[m.PLANE|m.CAPSULE]=s.prototype.planeCapsule=function(t,e,i,s,n,r,a,l,c){var u=J,d=Q,p=K;o.set(u,-r.length/2,0),o.rotate(u,u,l),h(u,u,a),o.set(d,r.length/2,0),o.rotate(d,d,l),h(d,d,a),p.radius=r.radius;var f;this.enableFrictionReduction&&(f=this.enableFriction,this.enableFriction=!1);var g=this.circlePlane(n,p,u,0,t,e,i,s,c),m=this.circlePlane(n,p,d,0,t,e,i,s,c);if(this.enableFrictionReduction&&(this.enableFriction=f),c)return g||m;var y=g+m;return this.enableFrictionReduction&&y&&this.frictionEquations.push(this.createFrictionFromAverage(y)),y},s.prototype[m.CIRCLE|m.PLANE]=s.prototype.circlePlane=function(t,e,i,s,n,r,c,u,d){var p=t,f=e,g=i,m=n,y=c,_=u;_=_||0;var P=b,T=x,C=w;a(P,g,y),o.rotate(T,v,_);var S=l(T,P);if(S>f.radius)return 0;if(d)return!0;var A=this.createContactEquation(m,p,r,e);return o.copy(A.normalA,T),o.scale(A.contactPointB,A.normalA,-f.radius),h(A.contactPointB,A.contactPointB,g),a(A.contactPointB,A.contactPointB,p.position),o.scale(C,A.normalA,S),a(A.contactPointA,P,C),h(A.contactPointA,A.contactPointA,y),a(A.contactPointA,A.contactPointA,m.position),this.contactEquations.push(A),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(A)),1},s.prototype[m.CONVEX]=s.prototype[m.CONVEX|m.BOX]=s.prototype[m.BOX]=s.prototype.convexConvex=function(t,e,i,n,r,c,u,d,p,f){var g=b,m=x,y=w,v=_,T=P,E=C,I=S,M=A,R=0,f="number"==typeof f?f:0;if(!s.findSeparatingAxis(e,i,n,c,u,d,g))return 0;a(I,u,i),l(g,I)>0&&o.scale(g,g,-1);var B=s.getClosestEdge(e,n,g,!0),L=s.getClosestEdge(c,d,g);if(-1===B||-1===L)return 0;for(var k=0;k<2;k++){var O=B,F=L,D=e,U=c,G=i,N=u,X=n,W=d,j=t,V=r;if(0===k){var q;q=O,O=F,F=q,q=D,D=U,U=q,q=G,G=N,N=q,q=X,X=W,W=q,q=j,j=V,V=q}for(var H=F;H<F+2;H++){var Y=U.vertices[(H+U.vertices.length)%U.vertices.length];o.rotate(m,Y,W),h(m,m,N);for(var z=0,K=O-1;K<O+2;K++){var J=D.vertices[(K+D.vertices.length)%D.vertices.length],Q=D.vertices[(K+1+D.vertices.length)%D.vertices.length];o.rotate(y,J,X),o.rotate(v,Q,X),h(y,y,G),h(v,v,G),a(T,v,y),o.rotate90cw(M,T),o.normalize(M,M),a(I,m,y);var Z=l(M,I);(K===O&&Z<=f||K!==O&&Z<=0)&&z++}if(z>=3){if(p)return!0;var $=this.createContactEquation(j,V,D,U);R++;var J=D.vertices[O%D.vertices.length],Q=D.vertices[(O+1)%D.vertices.length];o.rotate(y,J,X),o.rotate(v,Q,X),h(y,y,G),h(v,v,G),a(T,v,y),o.rotate90cw($.normalA,T),o.normalize($.normalA,$.normalA),a(I,m,y);var Z=l($.normalA,I);o.scale(E,$.normalA,Z),a($.contactPointA,m,G),a($.contactPointA,$.contactPointA,E),h($.contactPointA,$.contactPointA,G),a($.contactPointA,$.contactPointA,j.position),a($.contactPointB,m,N),h($.contactPointB,$.contactPointB,N),a($.contactPointB,$.contactPointB,V.position),this.contactEquations.push($),this.enableFrictionReduction||this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact($))}}}return this.enableFrictionReduction&&this.enableFriction&&R&&this.frictionEquations.push(this.createFrictionFromAverage(R)),R};var Z=o.fromValues(0,0);s.projectConvexOntoAxis=function(t,e,i,s,n){var r,a,h=null,c=null,u=Z;o.rotate(u,s,-i);for(var d=0;d<t.vertices.length;d++)r=t.vertices[d],a=l(r,u),(null===h||a>h)&&(h=a),(null===c||a<c)&&(c=a);if(c>h){var p=c;c=h,h=p}var f=l(e,s);o.set(n,c+f,h+f)};var $=o.fromValues(0,0),tt=o.fromValues(0,0),et=o.fromValues(0,0),it=o.fromValues(0,0),st=o.fromValues(0,0),nt=o.fromValues(0,0);s.findSeparatingAxis=function(t,e,i,n,r,h,l){var c=null,u=!1,d=!1,p=$,f=tt,g=et,m=it,v=st,b=nt;if(t instanceof y&&n instanceof y)for(var x=0;2!==x;x++){var w=t,_=i;1===x&&(w=n,_=h);for(var P=0;2!==P;P++){0===P?o.set(m,0,1):1===P&&o.set(m,1,0),0!==_&&o.rotate(m,m,_),s.projectConvexOntoAxis(t,e,i,m,v),s.projectConvexOntoAxis(n,r,h,m,b);var T=v,C=b;v[0]>b[0]&&(C=v,T=b,!0);var S=C[0]-T[1];u=S<=0,(null===c||S>c)&&(o.copy(l,m),c=S,d=u)}}else for(var x=0;2!==x;x++){var w=t,_=i;1===x&&(w=n,_=h);for(var P=0;P!==w.vertices.length;P++){o.rotate(f,w.vertices[P],_),o.rotate(g,w.vertices[(P+1)%w.vertices.length],_),a(p,g,f),o.rotate90cw(m,p),o.normalize(m,m),s.projectConvexOntoAxis(t,e,i,m,v),s.projectConvexOntoAxis(n,r,h,m,b);var T=v,C=b;v[0]>b[0]&&(C=v,T=b,!0);var S=C[0]-T[1];u=S<=0,(null===c||S>c)&&(o.copy(l,m),c=S,d=u)}}return d};var rt=o.fromValues(0,0),ot=o.fromValues(0,0),at=o.fromValues(0,0);s.getClosestEdge=function(t,e,i,s){var n=rt,r=ot,h=at;o.rotate(n,i,-e),s&&o.scale(n,n,-1);for(var c=-1,u=t.vertices.length,d=-1,p=0;p!==u;p++){a(r,t.vertices[(p+1)%u],t.vertices[p%u]),o.rotate90cw(h,r),o.normalize(h,h);var f=l(h,n);(-1===c||f>d)&&(c=p%u,d=f)}return c};var ht=o.create(),lt=o.create(),ct=o.create(),ut=o.create(),dt=o.create(),pt=o.create(),ft=o.create();s.prototype[m.CIRCLE|m.HEIGHTFIELD]=s.prototype.circleHeightfield=function(t,e,i,s,n,r,l,c,u,d){var p=r.heights,d=d||e.radius,f=r.elementWidth,g=lt,m=ht,y=dt,v=ft,b=pt,x=ct,w=ut,_=Math.floor((i[0]-d-l[0])/f),P=Math.ceil((i[0]+d-l[0])/f);_<0&&(_=0),P>=p.length&&(P=p.length-1);for(var T=p[_],C=p[P],S=_;S<P;S++)p[S]<C&&(C=p[S]),p[S]>T&&(T=p[S]);if(i[1]-d>T)return!u&&0;for(var A=!1,S=_;S<P;S++){o.set(x,S*f,p[S]),o.set(w,(S+1)*f,p[S+1]),o.add(x,x,l),o.add(w,w,l),o.sub(b,w,x),o.rotate(b,b,Math.PI/2),o.normalize(b,b),o.scale(m,b,-d),o.add(m,m,i),o.sub(g,m,x);var E=o.dot(g,b);if(m[0]>=x[0]&&m[0]<w[0]&&E<=0){if(u)return!0;A=!0,o.scale(g,b,-E),o.add(y,m,g),o.copy(v,b);var I=this.createContactEquation(n,t,r,e);o.copy(I.normalA,v),o.scale(I.contactPointB,I.normalA,-d),h(I.contactPointB,I.contactPointB,i),a(I.contactPointB,I.contactPointB,t.position),o.copy(I.contactPointA,y),o.sub(I.contactPointA,I.contactPointA,n.position),this.contactEquations.push(I),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(I))}}if(A=!1,d>0)for(var S=_;S<=P;S++)if(o.set(x,S*f,p[S]),o.add(x,x,l),o.sub(g,i,x),o.squaredLength(g)<Math.pow(d,2)){if(u)return!0;A=!0;var I=this.createContactEquation(n,t,r,e);o.copy(I.normalA,g),o.normalize(I.normalA,I.normalA),o.scale(I.contactPointB,I.normalA,-d),h(I.contactPointB,I.contactPointB,i),a(I.contactPointB,I.contactPointB,t.position),a(I.contactPointA,x,l),h(I.contactPointA,I.contactPointA,l),a(I.contactPointA,I.contactPointA,n.position),this.contactEquations.push(I),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(I))}return A?1:0};var gt=o.create(),mt=o.create(),yt=o.create(),vt=new g({vertices:[o.create(),o.create(),o.create(),o.create()]});s.prototype[m.BOX|m.HEIGHTFIELD]=s.prototype[m.CONVEX|m.HEIGHTFIELD]=s.prototype.convexHeightfield=function(t,e,i,s,n,r,a,h,l){var c=r.heights,u=r.elementWidth,d=gt,p=mt,f=yt,g=vt,m=Math.floor((t.aabb.lowerBound[0]-a[0])/u),y=Math.ceil((t.aabb.upperBound[0]-a[0])/u);m<0&&(m=0),y>=c.length&&(y=c.length-1);for(var v=c[m],b=c[y],x=m;x<y;x++)c[x]<b&&(b=c[x]),c[x]>v&&(v=c[x]);if(t.aabb.lowerBound[1]>v)return!l&&0;for(var w=0,x=m;x<y;x++){o.set(d,x*u,c[x]),o.set(p,(x+1)*u,c[x+1]),o.add(d,d,a),o.add(p,p,a);o.set(f,.5*(p[0]+d[0]),.5*(p[1]+d[1]-100)),o.sub(g.vertices[0],p,f),o.sub(g.vertices[1],d,f),o.copy(g.vertices[2],g.vertices[1]),o.copy(g.vertices[3],g.vertices[0]),g.vertices[2][1]-=100,g.vertices[3][1]-=100,w+=this.convexConvex(t,e,i,s,n,g,f,0,l)}return w}},{"../equations/ContactEquation":21,"../equations/Equation":22,"../equations/FrictionEquation":23,"../math/vec2":30,"../objects/Body":31,"../shapes/Box":37,"../shapes/Circle":39,"../shapes/Convex":40,"../shapes/Shape":45,"../utils/ContactEquationPool":48,"../utils/FrictionEquationPool":49,"../utils/TupleDictionary":56,"../utils/Utils":57}],11:[function(t,e,i){function s(t){t=t||{},this.from=t.from?r.fromValues(t.from[0],t.from[1]):r.create(),this.to=t.to?r.fromValues(t.to[0],t.to[1]):r.create(),this.checkCollisionResponse=void 0===t.checkCollisionResponse||t.checkCollisionResponse,this.skipBackfaces=!!t.skipBackfaces,this.collisionMask=void 0!==t.collisionMask?t.collisionMask:-1,this.collisionGroup=void 0!==t.collisionGroup?t.collisionGroup:-1,this.mode=void 0!==t.mode?t.mode:s.ANY,this.callback=t.callback||function(t){},this.direction=r.create(),this.length=1,this.update()}function n(t,e,i){r.sub(a,i,t);var s=r.dot(a,e);return r.scale(h,e,s),r.add(h,h,t),r.squaredDistance(i,h)}e.exports=s;var r=t("../math/vec2");t("../collision/RaycastResult"),t("../shapes/Shape"),t("../collision/AABB");s.prototype.constructor=s,s.CLOSEST=1,s.ANY=2,s.ALL=4,s.prototype.update=function(){var t=this.direction;r.sub(t,this.to,this.from),this.length=r.length(t),r.normalize(t,t)},s.prototype.intersectBodies=function(t,e){for(var i=0,s=e.length;!t.shouldStop(this)&&i<s;i++){var n=e[i],r=n.getAABB();(r.overlapsRay(this)>=0||r.containsPoint(this.from))&&this.intersectBody(t,n)}};var o=r.create();s.prototype.intersectBody=function(t,e){var i=this.checkCollisionResponse;if(!i||e.collisionResponse)for(var s=o,n=0,a=e.shapes.length;n<a;n++){var h=e.shapes[n];if((!i||h.collisionResponse)&&(0!=(this.collisionGroup&h.collisionMask)&&0!=(h.collisionGroup&this.collisionMask))){r.rotate(s,h.position,e.angle),r.add(s,s,e.position);var l=h.angle+e.angle;if(this.intersectShape(t,h,l,s,e),t.shouldStop(this))break}}},s.prototype.intersectShape=function(t,e,i,s,r){n(this.from,this.direction,s)>e.boundingRadius*e.boundingRadius||(this._currentBody=r,this._currentShape=e,e.raycast(t,this,s,i),this._currentBody=this._currentShape=null)},s.prototype.getAABB=function(t){var e=this.to,i=this.from;r.set(t.lowerBound,Math.min(e[0],i[0]),Math.min(e[1],i[1])),r.set(t.upperBound,Math.max(e[0],i[0]),Math.max(e[1],i[1]))};r.create();s.prototype.reportIntersection=function(t,e,i,n){var o=(this.from,this.to,this._currentShape),a=this._currentBody;if(!(this.skipBackfaces&&r.dot(i,this.direction)>0))switch(this.mode){case s.ALL:t.set(i,o,a,e,n),this.callback(t);break;case s.CLOSEST:(e<t.fraction||!t.hasHit())&&t.set(i,o,a,e,n);break;case s.ANY:t.set(i,o,a,e,n)}};var a=r.create(),h=r.create()},{"../collision/AABB":7,"../collision/RaycastResult":12,"../math/vec2":30,"../shapes/Shape":45}],12:[function(t,e,i){function s(){this.normal=n.create(),this.shape=null,this.body=null,this.faceIndex=-1,this.fraction=-1,this.isStopped=!1}var n=t("../math/vec2"),r=t("../collision/Ray");e.exports=s,s.prototype.reset=function(){n.set(this.normal,0,0),this.shape=null,this.body=null,this.faceIndex=-1,this.fraction=-1,this.isStopped=!1},s.prototype.getHitDistance=function(t){return n.distance(t.from,t.to)*this.fraction},s.prototype.hasHit=function(){return-1!==this.fraction},s.prototype.getHitPoint=function(t,e){n.lerp(t,e.from,e.to,this.fraction)},s.prototype.stop=function(){this.isStopped=!0},s.prototype.shouldStop=function(t){return this.isStopped||-1!==this.fraction&&t.mode===r.ANY},s.prototype.set=function(t,e,i,s,r){n.copy(this.normal,t),this.shape=e,this.body=i,this.fraction=s,this.faceIndex=r}},{"../collision/Ray":11,"../math/vec2":30}],13:[function(t,e,i){function s(){r.call(this,r.SAP),this.axisList=[],this.axisIndex=0;var t=this;this._addBodyHandler=function(e){t.axisList.push(e.body)},this._removeBodyHandler=function(e){var i=t.axisList.indexOf(e.body);-1!==i&&t.axisList.splice(i,1)}}var n=t("../utils/Utils"),r=t("../collision/Broadphase");e.exports=s,s.prototype=new r,s.prototype.constructor=s,s.prototype.setWorld=function(t){this.axisList.length=0,n.appendArray(this.axisList,t.bodies),t.off("addBody",this._addBodyHandler).off("removeBody",this._removeBodyHandler),t.on("addBody",this._addBodyHandler).on("removeBody",this._removeBodyHandler),this.world=t},s.sortAxisList=function(t,e){e|=0;for(var i=1,s=t.length;i<s;i++){for(var n=t[i],r=i-1;r>=0&&!(t[r].aabb.lowerBound[e]<=n.aabb.lowerBound[e]);r--)t[r+1]=t[r];t[r+1]=n}return t},s.prototype.sortList=function(){var t=this.axisList,e=this.axisIndex;s.sortAxisList(t,e)},s.prototype.getCollisionPairs=function(t){var e=this.axisList,i=this.result,s=this.axisIndex;i.length=0;for(var n=e.length;n--;){var o=e[n];o.aabbNeedsUpdate&&o.updateAABB()}this.sortList();for(var a=0,h=0|e.length;a!==h;a++)for(var l=e[a],c=a+1;c<h;c++){var u=e[c],d=u.aabb.lowerBound[s]<=l.aabb.upperBound[s];if(!d)break;r.canCollide(l,u)&&this.boundingVolumeCheck(l,u)&&i.push(l,u)}return i},s.prototype.aabbQuery=function(t,e,i){i=i||[],this.sortList();var s=this.axisIndex,n="x";1===s&&(n="y"),2===s&&(n="z");for(var r=this.axisList,o=(e.lowerBound[n],e.upperBound[n],0);o<r.length;o++){var a=r[o];a.aabbNeedsUpdate&&a.updateAABB(),a.aabb.overlaps(e)&&i.push(a)}return i}},{"../collision/Broadphase":8,"../utils/Utils":57}],14:[function(t,e,i){function s(t,e,i,s){this.type=i,s=n.defaults(s,{collideConnected:!0,wakeUpBodies:!0}),this.equations=[],this.bodyA=t,this.bodyB=e,this.collideConnected=s.collideConnected,s.wakeUpBodies&&(t&&t.wakeUp(),e&&e.wakeUp())}e.exports=s;var n=t("../utils/Utils");s.prototype.update=function(){throw new Error("method update() not implmemented in this Constraint subclass!")},s.DISTANCE=1,s.GEAR=2,s.LOCK=3,s.PRISMATIC=4,s.REVOLUTE=5,s.prototype.setStiffness=function(t){for(var e=this.equations,i=0;i!==e.length;i++){var s=e[i];s.stiffness=t,s.needsUpdate=!0}},s.prototype.setRelaxation=function(t){for(var e=this.equations,i=0;i!==e.length;i++){var s=e[i];s.relaxation=t,s.needsUpdate=!0}}},{"../utils/Utils":57}],15:[function(t,e,i){function s(t,e,i){i=a.defaults(i,{localAnchorA:[0,0],localAnchorB:[0,0]}),n.call(this,t,e,n.DISTANCE,i),this.localAnchorA=o.fromValues(i.localAnchorA[0],i.localAnchorA[1]),this.localAnchorB=o.fromValues(i.localAnchorB[0],i.localAnchorB[1]);var s=this.localAnchorA,h=this.localAnchorB;if(this.distance=0,"number"==typeof i.distance)this.distance=i.distance;else{var l=o.create(),c=o.create(),u=o.create();o.rotate(l,s,t.angle),o.rotate(c,h,e.angle),o.add(u,e.position,c),o.sub(u,u,l),o.sub(u,u,t.position),this.distance=o.length(u)}var d;d=void 0===i.maxForce?Number.MAX_VALUE:i.maxForce;var p=new r(t,e,-d,d);this.equations=[p],this.maxForce=d;var u=o.create(),f=o.create(),g=o.create(),m=this;p.computeGq=function(){var t=this.bodyA,e=this.bodyB,i=t.position,n=e.position;return o.rotate(f,s,t.angle),o.rotate(g,h,e.angle),o.add(u,n,g),o.sub(u,u,f),o.sub(u,u,i),o.length(u)-m.distance},this.setMaxForce(d),this.upperLimitEnabled=!1,this.upperLimit=1,this.lowerLimitEnabled=!1,this.lowerLimit=0,this.position=0}var n=t("./Constraint"),r=t("../equations/Equation"),o=t("../math/vec2"),a=t("../utils/Utils");e.exports=s,s.prototype=new n,s.prototype.constructor=s;var h=o.create(),l=o.create(),c=o.create();s.prototype.update=function(){var t=this.equations[0],e=this.bodyA,i=this.bodyB,s=(this.distance,e.position),n=i.position,r=this.equations[0],a=t.G;o.rotate(l,this.localAnchorA,e.angle),o.rotate(c,this.localAnchorB,i.angle),o.add(h,n,c),o.sub(h,h,l),o.sub(h,h,s),this.position=o.length(h);var u=!1;if(this.upperLimitEnabled&&this.position>this.upperLimit&&(r.maxForce=0,r.minForce=-this.maxForce,this.distance=this.upperLimit,u=!0),this.lowerLimitEnabled&&this.position<this.lowerLimit&&(r.maxForce=this.maxForce,r.minForce=0,this.distance=this.lowerLimit,u=!0),(this.lowerLimitEnabled||this.upperLimitEnabled)&&!u)return void(r.enabled=!1);r.enabled=!0,o.normalize(h,h);var d=o.crossLength(l,h),p=o.crossLength(c,h);a[0]=-h[0],a[1]=-h[1],a[2]=-d,a[3]=h[0],a[4]=h[1],a[5]=p},s.prototype.setMaxForce=function(t){var e=this.equations[0];e.minForce=-t,e.maxForce=t},s.prototype.getMaxForce=function(){return this.equations[0].maxForce}},{"../equations/Equation":22,"../math/vec2":30,"../utils/Utils":57,"./Constraint":14}],16:[function(t,e,i){function s(t,e,i){i=i||{},n.call(this,t,e,n.GEAR,i),this.ratio=void 0!==i.ratio?i.ratio:1,this.angle=void 0!==i.angle?i.angle:e.angle-this.ratio*t.angle,i.angle=this.angle,i.ratio=this.ratio,this.equations=[new r(t,e,i)],void 0!==i.maxTorque&&this.setMaxTorque(i.maxTorque)}var n=t("./Constraint"),r=(t("../equations/Equation"),t("../equations/AngleLockEquation"));t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.update=function(){var t=this.equations[0];t.ratio!==this.ratio&&t.setRatio(this.ratio),t.angle=this.angle},s.prototype.setMaxTorque=function(t){this.equations[0].setMaxTorque(t)},s.prototype.getMaxTorque=function(t){return this.equations[0].maxForce}},{"../equations/AngleLockEquation":20,"../equations/Equation":22,"../math/vec2":30,"./Constraint":14}],17:[function(t,e,i){function s(t,e,i){i=i||{},n.call(this,t,e,n.LOCK,i);var s=void 0===i.maxForce?Number.MAX_VALUE:i.maxForce,a=(i.localAngleB,new o(t,e,-s,s)),h=new o(t,e,-s,s),l=new o(t,e,-s,s),c=r.create(),u=r.create(),d=this;a.computeGq=function(){return r.rotate(c,d.localOffsetB,t.angle),r.sub(u,e.position,t.position),r.sub(u,u,c),u[0]},h.computeGq=function(){return r.rotate(c,d.localOffsetB,t.angle),r.sub(u,e.position,t.position),r.sub(u,u,c),u[1]};var p=r.create(),f=r.create();l.computeGq=function(){return r.rotate(p,d.localOffsetB,e.angle-d.localAngleB),r.scale(p,p,-1),r.sub(u,t.position,e.position),r.add(u,u,p),r.rotate(f,p,-Math.PI/2),r.normalize(f,f),r.dot(u,f)},this.localOffsetB=r.create(),i.localOffsetB?r.copy(this.localOffsetB,i.localOffsetB):(r.sub(this.localOffsetB,e.position,t.position),r.rotate(this.localOffsetB,this.localOffsetB,-t.angle)),this.localAngleB=0,"number"==typeof i.localAngleB?this.localAngleB=i.localAngleB:this.localAngleB=e.angle-t.angle,this.equations.push(a,h,l),this.setMaxForce(s)}var n=t("./Constraint"),r=t("../math/vec2"),o=t("../equations/Equation");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.setMaxForce=function(t){for(var e=this.equations,i=0;i<this.equations.length;i++)e[i].maxForce=t,e[i].minForce=-t},s.prototype.getMaxForce=function(){return this.equations[0].maxForce};var a=r.create(),h=r.create(),l=r.create(),c=r.fromValues(1,0),u=r.fromValues(0,1);s.prototype.update=function(){var t=this.equations[0],e=this.equations[1],i=this.equations[2],s=this.bodyA,n=this.bodyB;r.rotate(a,this.localOffsetB,s.angle),r.rotate(h,this.localOffsetB,n.angle-this.localAngleB),r.scale(h,h,-1),r.rotate(l,h,Math.PI/2),r.normalize(l,l),t.G[0]=-1,t.G[1]=0,t.G[2]=-r.crossLength(a,c),t.G[3]=1,e.G[0]=0,e.G[1]=-1,e.G[2]=-r.crossLength(a,u),e.G[4]=1,i.G[0]=-l[0],i.G[1]=-l[1],i.G[3]=l[0],i.G[4]=l[1],i.G[5]=r.crossLength(h,l)}},{"../equations/Equation":22,"../math/vec2":30,"./Constraint":14}],18:[function(t,e,i){function s(t,e,i){i=i||{},n.call(this,t,e,n.PRISMATIC,i);var s=a.fromValues(0,0),l=a.fromValues(1,0),c=a.fromValues(0,0);i.localAnchorA&&a.copy(s,i.localAnchorA),i.localAxisA&&a.copy(l,i.localAxisA),i.localAnchorB&&a.copy(c,i.localAnchorB),this.localAnchorA=s,this.localAnchorB=c,this.localAxisA=l;var u=this.maxForce=void 0!==i.maxForce?i.maxForce:Number.MAX_VALUE,d=new o(t,e,-u,u),p=new a.create,f=new a.create,g=new a.create,m=new a.create;if(d.computeGq=function(){return a.dot(g,m)},d.updateJacobian=function(){var i=this.G,n=t.position,r=e.position;a.rotate(p,s,t.angle),a.rotate(f,c,e.angle),a.add(g,r,f),a.sub(g,g,n),a.sub(g,g,p),a.rotate(m,l,t.angle+Math.PI/2),i[0]=-m[0],i[1]=-m[1],i[2]=-a.crossLength(p,m)+a.crossLength(m,g),i[3]=m[0],i[4]=m[1],i[5]=a.crossLength(f,m)},this.equations.push(d),!i.disableRotationalLock){var y=new h(t,e,-u,u);this.equations.push(y)}this.position=0,this.velocity=0,this.lowerLimitEnabled=void 0!==i.lowerLimit,this.upperLimitEnabled=void 0!==i.upperLimit,this.lowerLimit=void 0!==i.lowerLimit?i.lowerLimit:0,this.upperLimit=void 0!==i.upperLimit?i.upperLimit:1,this.upperLimitEquation=new r(t,e),this.lowerLimitEquation=new r(t,e),this.upperLimitEquation.minForce=this.lowerLimitEquation.minForce=0,this.upperLimitEquation.maxForce=this.lowerLimitEquation.maxForce=u,this.motorEquation=new o(t,e),this.motorEnabled=!1,this.motorSpeed=0;var v=this,b=this.motorEquation;b.computeGW;b.computeGq=function(){return 0},b.computeGW=function(){var t=this.G,e=this.bodyA,i=this.bodyB,s=e.velocity,n=i.velocity,r=e.angularVelocity,o=i.angularVelocity;return this.gmult(t,s,r,n,o)+v.motorSpeed}}var n=t("./Constraint"),r=t("../equations/ContactEquation"),o=t("../equations/Equation"),a=t("../math/vec2"),h=t("../equations/RotationalLockEquation");e.exports=s,s.prototype=new n,s.prototype.constructor=s;var l=a.create(),c=a.create(),u=a.create(),d=a.create(),p=a.create(),f=a.create();s.prototype.update=function(){var t=this.equations,e=t[0],i=this.upperLimit,s=this.lowerLimit,n=this.upperLimitEquation,r=this.lowerLimitEquation,o=this.bodyA,h=this.bodyB,g=this.localAxisA,m=this.localAnchorA,y=this.localAnchorB;e.updateJacobian(),a.rotate(l,g,o.angle),a.rotate(d,m,o.angle),a.add(c,d,o.position),a.rotate(p,y,h.angle),a.add(u,p,h.position);var v=this.position=a.dot(u,l)-a.dot(c,l);if(this.motorEnabled){var b=this.motorEquation.G;b[0]=l[0],b[1]=l[1],b[2]=a.crossLength(l,p),b[3]=-l[0],b[4]=-l[1],b[5]=-a.crossLength(l,d)}if(this.upperLimitEnabled&&v>i)a.scale(n.normalA,l,-1),a.sub(n.contactPointA,c,o.position),a.sub(n.contactPointB,u,h.position),a.scale(f,l,i),a.add(n.contactPointA,n.contactPointA,f),-1===t.indexOf(n)&&t.push(n);else{var x=t.indexOf(n);-1!==x&&t.splice(x,1)}if(this.lowerLimitEnabled&&v<s)a.scale(r.normalA,l,1),a.sub(r.contactPointA,c,o.position),a.sub(r.contactPointB,u,h.position),a.scale(f,l,s),a.sub(r.contactPointB,r.contactPointB,f),-1===t.indexOf(r)&&t.push(r);else{var x=t.indexOf(r);-1!==x&&t.splice(x,1)}},s.prototype.enableMotor=function(){this.motorEnabled||(this.equations.push(this.motorEquation),this.motorEnabled=!0)},s.prototype.disableMotor=function(){if(this.motorEnabled){var t=this.equations.indexOf(this.motorEquation);this.equations.splice(t,1),this.motorEnabled=!1}},s.prototype.setLimits=function(t,e){"number"==typeof t?(this.lowerLimit=t,this.lowerLimitEnabled=!0):(this.lowerLimit=t,this.lowerLimitEnabled=!1),"number"==typeof e?(this.upperLimit=e,this.upperLimitEnabled=!0):(this.upperLimit=e,this.upperLimitEnabled=!1)}},{"../equations/ContactEquation":21,"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../math/vec2":30,"./Constraint":14}],19:[function(t,e,i){function s(t,e,i){i=i||{},n.call(this,t,e,n.REVOLUTE,i);var s=this.maxForce=void 0!==i.maxForce?i.maxForce:Number.MAX_VALUE;this.pivotA=h.create(),this.pivotB=h.create(),i.worldPivot?(h.sub(this.pivotA,i.worldPivot,t.position),h.sub(this.pivotB,i.worldPivot,e.position),h.rotate(this.pivotA,this.pivotA,-t.angle),h.rotate(this.pivotB,this.pivotB,-e.angle)):(h.copy(this.pivotA,i.localPivotA),h.copy(this.pivotB,i.localPivotB));var f=this.equations=[new r(t,e,-s,s),new r(t,e,-s,s)],g=f[0],m=f[1],y=this;g.computeGq=function(){return h.rotate(l,y.pivotA,t.angle),h.rotate(c,y.pivotB,e.angle),h.add(p,e.position,c),h.sub(p,p,t.position),h.sub(p,p,l),h.dot(p,u)},m.computeGq=function(){return h.rotate(l,y.pivotA,t.angle),h.rotate(c,y.pivotB,e.angle),h.add(p,e.position,c),h.sub(p,p,t.position),h.sub(p,p,l),h.dot(p,d)},m.minForce=g.minForce=-s,m.maxForce=g.maxForce=s,this.motorEquation=new o(t,e),this.motorEnabled=!1,this.angle=0,this.lowerLimitEnabled=!1,this.upperLimitEnabled=!1,this.lowerLimit=0,this.upperLimit=0,this.upperLimitEquation=new a(t,e),this.lowerLimitEquation=new a(t,e),this.upperLimitEquation.minForce=0,this.lowerLimitEquation.maxForce=0}var n=t("./Constraint"),r=t("../equations/Equation"),o=t("../equations/RotationalVelocityEquation"),a=t("../equations/RotationalLockEquation"),h=t("../math/vec2");e.exports=s;var l=h.create(),c=h.create(),u=h.fromValues(1,0),d=h.fromValues(0,1),p=h.create();s.prototype=new n,s.prototype.constructor=s,s.prototype.setLimits=function(t,e){"number"==typeof t?(this.lowerLimit=t,this.lowerLimitEnabled=!0):(this.lowerLimit=t,this.lowerLimitEnabled=!1),"number"==typeof e?(this.upperLimit=e,this.upperLimitEnabled=!0):(this.upperLimit=e,this.upperLimitEnabled=!1)},s.prototype.update=function(){var t=this.bodyA,e=this.bodyB,i=this.pivotA,s=this.pivotB,n=this.equations,r=(n[0],n[1],n[0]),o=n[1],a=this.upperLimit,p=this.lowerLimit,f=this.upperLimitEquation,g=this.lowerLimitEquation,m=this.angle=e.angle-t.angle;if(this.upperLimitEnabled&&m>a)f.angle=a,-1===n.indexOf(f)&&n.push(f);else{var y=n.indexOf(f);-1!==y&&n.splice(y,1)}if(this.lowerLimitEnabled&&m<p)g.angle=p,-1===n.indexOf(g)&&n.push(g);else{var y=n.indexOf(g);-1!==y&&n.splice(y,1)}h.rotate(l,i,t.angle),h.rotate(c,s,e.angle),r.G[0]=-1,r.G[1]=0,r.G[2]=-h.crossLength(l,u),r.G[3]=1,r.G[4]=0,r.G[5]=h.crossLength(c,u),o.G[0]=0,o.G[1]=-1,o.G[2]=-h.crossLength(l,d),o.G[3]=0,o.G[4]=1,o.G[5]=h.crossLength(c,d)},s.prototype.enableMotor=function(){this.motorEnabled||(this.equations.push(this.motorEquation),this.motorEnabled=!0)},s.prototype.disableMotor=function(){if(this.motorEnabled){var t=this.equations.indexOf(this.motorEquation);this.equations.splice(t,1),this.motorEnabled=!1}},s.prototype.motorIsEnabled=function(){return!!this.motorEnabled},s.prototype.setMotorSpeed=function(t){if(this.motorEnabled){var e=this.equations.indexOf(this.motorEquation);this.equations[e].relativeVelocity=t}},s.prototype.getMotorSpeed=function(){return!!this.motorEnabled&&this.motorEquation.relativeVelocity}},{"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../equations/RotationalVelocityEquation":25,"../math/vec2":30,"./Constraint":14}],20:[function(t,e,i){function s(t,e,i){i=i||{},n.call(this,t,e,-Number.MAX_VALUE,Number.MAX_VALUE),this.angle=i.angle||0,this.ratio="number"==typeof i.ratio?i.ratio:1,this.setRatio(this.ratio)}var n=t("./Equation");t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.computeGq=function(){return this.ratio*this.bodyA.angle-this.bodyB.angle+this.angle},s.prototype.setRatio=function(t){var e=this.G;e[2]=t,e[5]=-1,this.ratio=t},s.prototype.setMaxTorque=function(t){this.maxForce=t,this.minForce=-t}},{"../math/vec2":30,"./Equation":22}],21:[function(t,e,i){function s(t,e){n.call(this,t,e,0,Number.MAX_VALUE),this.contactPointA=r.create(),this.penetrationVec=r.create(),this.contactPointB=r.create(),this.normalA=r.create(),this.restitution=0,this.firstImpact=!1,this.shapeA=null,this.shapeB=null}var n=t("./Equation"),r=t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.computeB=function(t,e,i){var s=this.bodyA,n=this.bodyB,o=this.contactPointA,a=this.contactPointB,h=s.position,l=n.position,c=this.penetrationVec,u=this.normalA,d=this.G,p=r.crossLength(o,u),f=r.crossLength(a,u);d[0]=-u[0],d[1]=-u[1],d[2]=-p,d[3]=u[0],d[4]=u[1],d[5]=f,r.add(c,l,a),r.sub(c,c,h),r.sub(c,c,o);var g,m;return this.firstImpact&&0!==this.restitution?(m=0,g=1/e*(1+this.restitution)*this.computeGW()):(m=r.dot(u,c)+this.offset,g=this.computeGW()),-m*t-g*e-i*this.computeGiMf()}},{"../math/vec2":30,"./Equation":22}],22:[function(t,e,i){function s(t,e,i,n){this.minForce=void 0===i?-Number.MAX_VALUE:i,this.maxForce=void 0===n?Number.MAX_VALUE:n,this.bodyA=t,this.bodyB=e,this.stiffness=s.DEFAULT_STIFFNESS,this.relaxation=s.DEFAULT_RELAXATION,this.G=new r.ARRAY_TYPE(6);for(var o=0;o<6;o++)this.G[o]=0;this.offset=0,this.a=0,this.b=0,this.epsilon=0,this.timeStep=1/60,this.needsUpdate=!0,this.multiplier=0,this.relativeVelocity=0,this.enabled=!0}e.exports=s;var n=t("../math/vec2"),r=t("../utils/Utils");t("../objects/Body");s.prototype.constructor=s,s.DEFAULT_STIFFNESS=1e6,s.DEFAULT_RELAXATION=4,s.prototype.update=function(){var t=this.stiffness,e=this.relaxation,i=this.timeStep;this.a=4/(i*(1+4*e)),this.b=4*e/(1+4*e),this.epsilon=4/(i*i*t*(1+4*e)),this.needsUpdate=!1},s.prototype.gmult=function(t,e,i,s,n){return t[0]*e[0]+t[1]*e[1]+t[2]*i+t[3]*s[0]+t[4]*s[1]+t[5]*n},s.prototype.computeB=function(t,e,i){var s=this.computeGW();return-this.computeGq()*t-s*e-this.computeGiMf()*i};var o=n.create(),a=n.create();s.prototype.computeGq=function(){var t=this.G,e=this.bodyA,i=this.bodyB,s=(e.position,i.position,e.angle),n=i.angle;return this.gmult(t,o,s,a,n)+this.offset},s.prototype.computeGW=function(){var t=this.G,e=this.bodyA,i=this.bodyB,s=e.velocity,n=i.velocity,r=e.angularVelocity,o=i.angularVelocity;return this.gmult(t,s,r,n,o)+this.relativeVelocity},s.prototype.computeGWlambda=function(){var t=this.G,e=this.bodyA,i=this.bodyB,s=e.vlambda,n=i.vlambda,r=e.wlambda,o=i.wlambda;return this.gmult(t,s,r,n,o)};var h=n.create(),l=n.create();s.prototype.computeGiMf=function(){var t=this.bodyA,e=this.bodyB,i=t.force,s=t.angularForce,r=e.force,o=e.angularForce,a=t.invMassSolve,c=e.invMassSolve,u=t.invInertiaSolve,d=e.invInertiaSolve,p=this.G;return n.scale(h,i,a),n.multiply(h,t.massMultiplier,h),n.scale(l,r,c),n.multiply(l,e.massMultiplier,l),this.gmult(p,h,s*u,l,o*d)},s.prototype.computeGiMGt=function(){var t=this.bodyA,e=this.bodyB,i=t.invMassSolve,s=e.invMassSolve,n=t.invInertiaSolve,r=e.invInertiaSolve,o=this.G;return o[0]*o[0]*i*t.massMultiplier[0]+o[1]*o[1]*i*t.massMultiplier[1]+o[2]*o[2]*n+o[3]*o[3]*s*e.massMultiplier[0]+o[4]*o[4]*s*e.massMultiplier[1]+o[5]*o[5]*r};var c=n.create(),u=n.create(),d=n.create();n.create(),n.create(),n.create();s.prototype.addToWlambda=function(t){var e=this.bodyA,i=this.bodyB,s=c,r=u,o=d,a=e.invMassSolve,h=i.invMassSolve,l=e.invInertiaSolve,p=i.invInertiaSolve,f=this.G;r[0]=f[0],r[1]=f[1],o[0]=f[3],o[1]=f[4],n.scale(s,r,a*t),n.multiply(s,s,e.massMultiplier),n.add(e.vlambda,e.vlambda,s),e.wlambda+=l*f[2]*t,n.scale(s,o,h*t),n.multiply(s,s,i.massMultiplier),n.add(i.vlambda,i.vlambda,s),i.wlambda+=p*f[5]*t},s.prototype.computeInvC=function(t){return 1/(this.computeGiMGt()+t)}},{"../math/vec2":30,"../objects/Body":31,"../utils/Utils":57}],23:[function(t,e,i){function s(t,e,i){r.call(this,t,e,-i,i),this.contactPointA=n.create(),this.contactPointB=n.create(),this.t=n.create(),this.contactEquations=[],this.shapeA=null,this.shapeB=null,this.frictionCoefficient=.3}var n=t("../math/vec2"),r=t("./Equation");t("../utils/Utils");e.exports=s,s.prototype=new r,s.prototype.constructor=s,s.prototype.setSlipForce=function(t){this.maxForce=t,this.minForce=-t},s.prototype.getSlipForce=function(){return this.maxForce},s.prototype.computeB=function(t,e,i){var s=(this.bodyA,this.bodyB,this.contactPointA),r=this.contactPointB,o=this.t,a=this.G;return a[0]=-o[0],a[1]=-o[1],a[2]=-n.crossLength(s,o),a[3]=o[0],a[4]=o[1],a[5]=n.crossLength(r,o),-this.computeGW()*e-i*this.computeGiMf()}},{"../math/vec2":30,"../utils/Utils":57,"./Equation":22}],24:[function(t,e,i){function s(t,e,i){i=i||{},n.call(this,t,e,-Number.MAX_VALUE,Number.MAX_VALUE),this.angle=i.angle||0;var s=this.G;s[2]=1,s[5]=-1}var n=t("./Equation"),r=t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s;var o=r.create(),a=r.create(),h=r.fromValues(1,0),l=r.fromValues(0,1);s.prototype.computeGq=function(){return r.rotate(o,h,this.bodyA.angle+this.angle),r.rotate(a,l,this.bodyB.angle),r.dot(o,a)}},{"../math/vec2":30,"./Equation":22}],25:[function(t,e,i){function s(t,e){n.call(this,t,e,-Number.MAX_VALUE,Number.MAX_VALUE),this.relativeVelocity=1,this.ratio=1}var n=t("./Equation");t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.computeB=function(t,e,i){var s=this.G;s[2]=-1,s[5]=this.ratio;var n=this.computeGiMf();return-this.computeGW()*e-i*n}},{"../math/vec2":30,"./Equation":22}],26:[function(t,e,i){var s=function(){};e.exports=s,s.prototype={constructor:s,on:function(t,e,i){e.context=i||this,void 0===this._listeners&&(this._listeners={});var s=this._listeners;return void 0===s[t]&&(s[t]=[]),-1===s[t].indexOf(e)&&s[t].push(e),this},has:function(t,e){if(void 0===this._listeners)return!1;var i=this._listeners;if(e){if(void 0!==i[t]&&-1!==i[t].indexOf(e))return!0}else if(void 0!==i[t])return!0;return!1},off:function(t,e){if(void 0===this._listeners)return this;var i=this._listeners,s=i[t].indexOf(e);return-1!==s&&i[t].splice(s,1),this},emit:function(t){if(void 0===this._listeners)return this;var e=this._listeners,i=e[t.type];if(void 0!==i){t.target=this;for(var s=0,n=i.length;s<n;s++){var r=i[s];r.call(r.context,t)}}return this}}},{}],27:[function(t,e,i){function s(t,e,i){if(i=i||{},!(t instanceof n&&e instanceof n))throw new Error("First two arguments must be Material instances.");this.id=s.idCounter++,this.materialA=t,this.materialB=e,this.friction=void 0!==i.friction?Number(i.friction):.3,this.restitution=void 0!==i.restitution?Number(i.restitution):0,this.stiffness=void 0!==i.stiffness?Number(i.stiffness):r.DEFAULT_STIFFNESS,this.relaxation=void 0!==i.relaxation?Number(i.relaxation):r.DEFAULT_RELAXATION,this.frictionStiffness=void 0!==i.frictionStiffness?Number(i.frictionStiffness):r.DEFAULT_STIFFNESS,this.frictionRelaxation=void 0!==i.frictionRelaxation?Number(i.frictionRelaxation):r.DEFAULT_RELAXATION,this.surfaceVelocity=void 0!==i.surfaceVelocity?Number(i.surfaceVelocity):0,this.contactSkinSize=.005}var n=t("./Material"),r=t("../equations/Equation");e.exports=s,s.idCounter=0},{"../equations/Equation":22,"./Material":28}],28:[function(t,e,i){function s(t){this.id=t||s.idCounter++}e.exports=s,s.idCounter=0},{}],29:[function(t,e,i){var s={};s.GetArea=function(t){if(t.length<6)return 0;for(var e=t.length-2,i=0,s=0;s<e;s+=2)i+=(t[s+2]-t[s])*(t[s+1]+t[s+3]);return.5*-(i+=(t[0]-t[e])*(t[e+1]+t[1]))},s.Triangulate=function(t){var e=t.length>>1;if(e<3)return[];for(var i=[],n=[],r=0;r<e;r++)n.push(r);for(var r=0,o=e;o>3;){var a=n[(r+0)%o],h=n[(r+1)%o],l=n[(r+2)%o],c=t[2*a],u=t[2*a+1],d=t[2*h],p=t[2*h+1],f=t[2*l],g=t[2*l+1],m=!1;if(s._convex(c,u,d,p,f,g)){m=!0;for(var y=0;y<o;y++){var v=n[y];if(v!=a&&v!=h&&v!=l&&s._PointInTriangle(t[2*v],t[2*v+1],c,u,d,p,f,g)){m=!1;break}}}if(m)i.push(a,h,l),n.splice((r+1)%o,1),o--,r=0;else if(r++>3*o)break}return i.push(n[0],n[1],n[2]),i},s._PointInTriangle=function(t,e,i,s,n,r,o,a){var h=o-i,l=a-s,c=n-i,u=r-s,d=t-i,p=e-s,f=h*h+l*l,g=h*c+l*u,m=h*d+l*p,y=c*c+u*u,v=c*d+u*p,b=1/(f*y-g*g),x=(y*m-g*v)*b,w=(f*v-g*m)*b;return x>=0&&w>=0&&x+w<1},s._convex=function(t,e,i,s,n,r){return(e-s)*(n-i)+(i-t)*(r-s)>=0},e.exports=s},{}],30:[function(t,e,i){var s=e.exports={},n=t("../utils/Utils");s.crossLength=function(t,e){return t[0]*e[1]-t[1]*e[0]},s.crossVZ=function(t,e,i){return s.rotate(t,e,-Math.PI/2),s.scale(t,t,i),t},s.crossZV=function(t,e,i){return s.rotate(t,i,Math.PI/2),s.scale(t,t,e),t},s.rotate=function(t,e,i){if(0!==i){var s=Math.cos(i),n=Math.sin(i),r=e[0],o=e[1];t[0]=s*r-n*o,t[1]=n*r+s*o}else t[0]=e[0],t[1]=e[1]},s.rotate90cw=function(t,e){var i=e[0],s=e[1];t[0]=s,t[1]=-i},s.toLocalFrame=function(t,e,i,n){s.copy(t,e),s.sub(t,t,i),s.rotate(t,t,-n)},s.toGlobalFrame=function(t,e,i,n){s.copy(t,e),s.rotate(t,t,n),s.add(t,t,i)},s.vectorToLocalFrame=function(t,e,i){s.rotate(t,e,-i)},s.vectorToGlobalFrame=function(t,e,i){s.rotate(t,e,i)},s.centroid=function(t,e,i,n){return s.add(t,e,i),s.add(t,t,n),s.scale(t,t,1/3),t},s.create=function(){var t=new n.ARRAY_TYPE(2);return t[0]=0,t[1]=0,t},s.clone=function(t){var e=new n.ARRAY_TYPE(2);return e[0]=t[0],e[1]=t[1],e},s.fromValues=function(t,e){var i=new n.ARRAY_TYPE(2);return i[0]=t,i[1]=e,i},s.copy=function(t,e){return t[0]=e[0],t[1]=e[1],t},s.set=function(t,e,i){return t[0]=e,t[1]=i,t},s.add=function(t,e,i){return t[0]=e[0]+i[0],t[1]=e[1]+i[1],t},s.subtract=function(t,e,i){return t[0]=e[0]-i[0],t[1]=e[1]-i[1],t},s.sub=s.subtract,s.multiply=function(t,e,i){return t[0]=e[0]*i[0],t[1]=e[1]*i[1],t},s.mul=s.multiply,s.divide=function(t,e,i){return t[0]=e[0]/i[0],t[1]=e[1]/i[1],t},s.div=s.divide,s.scale=function(t,e,i){return t[0]=e[0]*i,t[1]=e[1]*i,t},s.distance=function(t,e){var i=e[0]-t[0],s=e[1]-t[1];return Math.sqrt(i*i+s*s)},s.dist=s.distance,s.squaredDistance=function(t,e){var i=e[0]-t[0],s=e[1]-t[1];return i*i+s*s},s.sqrDist=s.squaredDistance,s.length=function(t){var e=t[0],i=t[1];return Math.sqrt(e*e+i*i)},s.len=s.length,s.squaredLength=function(t){var e=t[0],i=t[1];return e*e+i*i},s.sqrLen=s.squaredLength,s.negate=function(t,e){return t[0]=-e[0],t[1]=-e[1],t},s.normalize=function(t,e){var i=e[0],s=e[1],n=i*i+s*s;return n>0&&(n=1/Math.sqrt(n),t[0]=e[0]*n,t[1]=e[1]*n),t},s.dot=function(t,e){return t[0]*e[0]+t[1]*e[1]},s.str=function(t){return"vec2("+t[0]+", "+t[1]+")"},s.lerp=function(t,e,i,s){var n=e[0],r=e[1];return t[0]=n+s*(i[0]-n),t[1]=r+s*(i[1]-r),t},s.reflect=function(t,e,i){var s=e[0]*i[0]+e[1]*i[1];t[0]=e[0]-2*i[0]*s,t[1]=e[1]-2*i[1]*s},s.getLineSegmentsIntersection=function(t,e,i,n,r){var o=s.getLineSegmentsIntersectionFraction(e,i,n,r);return!(o<0)&&(t[0]=e[0]+o*(i[0]-e[0]),t[1]=e[1]+o*(i[1]-e[1]),!0)},s.getLineSegmentsIntersectionFraction=function(t,e,i,s){var n,r,o=e[0]-t[0],a=e[1]-t[1],h=s[0]-i[0],l=s[1]-i[1];return n=(-a*(t[0]-i[0])+o*(t[1]-i[1]))/(-h*a+o*l),r=(h*(t[1]-i[1])-l*(t[0]-i[0]))/(-h*a+o*l),n>=0&&n<=1&&r>=0&&r<=1?r:-1}},{"../utils/Utils":57}],31:[function(t,e,i){function s(t){t=t||{},c.call(this),this.id=t.id||++s._idCounter,this.world=null,this.shapes=[],this.mass=t.mass||0,this.invMass=0,this.inertia=0,this.invInertia=0,this.invMassSolve=0,this.invInertiaSolve=0,this.fixedRotation=!!t.fixedRotation,this.fixedX=!!t.fixedX,this.fixedY=!!t.fixedY,this.massMultiplier=n.create(),this.position=n.fromValues(0,0),t.position&&n.copy(this.position,t.position),this.interpolatedPosition=n.fromValues(0,0),this.interpolatedAngle=0,this.previousPosition=n.fromValues(0,0),this.previousAngle=0,this.velocity=n.fromValues(0,0),t.velocity&&n.copy(this.velocity,t.velocity),this.vlambda=n.fromValues(0,0),this.wlambda=0,this.angle=t.angle||0,this.angularVelocity=t.angularVelocity||0,this.force=n.create(),t.force&&n.copy(this.force,t.force),this.angularForce=t.angularForce||0,this.damping="number"==typeof t.damping?t.damping:.1,this.angularDamping="number"==typeof t.angularDamping?t.angularDamping:.1,this.type=s.STATIC,void 0!==t.type?this.type=t.type:t.mass?this.type=s.DYNAMIC:this.type=s.STATIC,this.boundingRadius=0,this.aabb=new l,this.aabbNeedsUpdate=!0,this.allowSleep=void 0===t.allowSleep||t.allowSleep,this.wantsToSleep=!1,this.sleepState=s.AWAKE,this.sleepSpeedLimit=void 0!==t.sleepSpeedLimit?t.sleepSpeedLimit:.2,this.sleepTimeLimit=void 0!==t.sleepTimeLimit?t.sleepTimeLimit:1,this.gravityScale=void 0!==t.gravityScale?t.gravityScale:1,this.collisionResponse=void 0===t.collisionResponse||t.collisionResponse,this.idleTime=0,this.timeLastSleepy=0,this.ccdSpeedThreshold=void 0!==t.ccdSpeedThreshold?t.ccdSpeedThreshold:-1,this.ccdIterations=void 0!==t.ccdIterations?t.ccdIterations:10,this.concavePath=null,this._wakeUpAfterNarrowphase=!1,this.updateMassProperties()}var n=t("../math/vec2"),r=t("poly-decomp"),o=t("../shapes/Convex"),a=t("../collision/RaycastResult"),h=t("../collision/Ray"),l=t("../collision/AABB"),c=t("../events/EventEmitter");e.exports=s,s.prototype=new c,s.prototype.constructor=s,s._idCounter=0,s.prototype.updateSolveMassProperties=function(){this.sleepState===s.SLEEPING||this.type===s.KINEMATIC?(this.invMassSolve=0,this.invInertiaSolve=0):(this.invMassSolve=this.invMass,this.invInertiaSolve=this.invInertia)},s.prototype.setDensity=function(t){var e=this.getArea();this.mass=e*t,this.updateMassProperties()},s.prototype.getArea=function(){for(var t=0,e=0;e<this.shapes.length;e++)t+=this.shapes[e].area;return t},s.prototype.getAABB=function(){return this.aabbNeedsUpdate&&this.updateAABB(),this.aabb};var u=new l,d=n.create();s.prototype.updateAABB=function(){for(var t=this.shapes,e=t.length,i=d,s=this.angle,r=0;r!==e;r++){var o=t[r],a=o.angle+s;n.rotate(i,o.position,s),n.add(i,i,this.position),o.computeAABB(u,i,a),0===r?this.aabb.copy(u):this.aabb.extend(u)}this.aabbNeedsUpdate=!1},s.prototype.updateBoundingRadius=function(){for(var t=this.shapes,e=t.length,i=0,s=0;s!==e;s++){var r=t[s],o=n.length(r.position),a=r.boundingRadius;o+a>i&&(i=o+a)}this.boundingRadius=i},s.prototype.addShape=function(t,e,i){if(t.body)throw new Error("A shape can only be added to one body.");t.body=this,e?n.copy(t.position,e):n.set(t.position,0,0),t.angle=i||0,this.shapes.push(t),this.updateMassProperties(),this.updateBoundingRadius(),this.aabbNeedsUpdate=!0},s.prototype.removeShape=function(t){var e=this.shapes.indexOf(t);return-1!==e&&(this.shapes.splice(e,1),this.aabbNeedsUpdate=!0,t.body=null,!0)},s.prototype.updateMassProperties=function(){if(this.type===s.STATIC||this.type===s.KINEMATIC)this.mass=Number.MAX_VALUE,this.invMass=0,this.inertia=Number.MAX_VALUE,this.invInertia=0;else{var t=this.shapes,e=t.length,i=this.mass/e,r=0;if(this.fixedRotation)this.inertia=Number.MAX_VALUE,this.invInertia=0;else{for(var o=0;o<e;o++){var a=t[o],h=n.squaredLength(a.position);r+=a.computeMomentOfInertia(i)+i*h}this.inertia=r,this.invInertia=r>0?1/r:0}this.invMass=1/this.mass,n.set(this.massMultiplier,this.fixedX?0:1,this.fixedY?0:1)}};n.create();s.prototype.applyForce=function(t,e){if(n.add(this.force,this.force,t),e){var i=n.crossLength(e,t);this.angularForce+=i}};var p=n.create(),f=n.create(),g=n.create();s.prototype.applyForceLocal=function(t,e){e=e||g;var i=p,s=f;this.vectorToWorldFrame(i,t),this.vectorToWorldFrame(s,e),this.applyForce(i,s)};var m=n.create();s.prototype.applyImpulse=function(t,e){if(this.type===s.DYNAMIC){var i=m;if(n.scale(i,t,this.invMass),n.multiply(i,this.massMultiplier,i),n.add(this.velocity,i,this.velocity),e){var r=n.crossLength(e,t);r*=this.invInertia,this.angularVelocity+=r}}};var y=n.create(),v=n.create(),b=n.create();s.prototype.applyImpulseLocal=function(t,e){e=e||b;var i=y,s=v;this.vectorToWorldFrame(i,t),this.vectorToWorldFrame(s,e),this.applyImpulse(i,s)},s.prototype.toLocalFrame=function(t,e){n.toLocalFrame(t,e,this.position,this.angle)},s.prototype.toWorldFrame=function(t,e){n.toGlobalFrame(t,e,this.position,this.angle)},s.prototype.vectorToLocalFrame=function(t,e){n.vectorToLocalFrame(t,e,this.angle)},s.prototype.vectorToWorldFrame=function(t,e){n.vectorToGlobalFrame(t,e,this.angle)},s.prototype.fromPolygon=function(t,e){e=e||{};for(var i=this.shapes.length;i>=0;--i)this.removeShape(this.shapes[i]);var s=new r.Polygon;if(s.vertices=t,s.makeCCW(),"number"==typeof e.removeCollinearPoints&&s.removeCollinearPoints(e.removeCollinearPoints),void 0===e.skipSimpleCheck&&!s.isSimple())return!1;this.concavePath=s.vertices.slice(0);for(var i=0;i<this.concavePath.length;i++){var a=[0,0];n.copy(a,this.concavePath[i]),this.concavePath[i]=a}var h;h=e.optimalDecomp?s.decomp():s.quickDecomp();for(var l=n.create(),i=0;i!==h.length;i++){for(var c=new o({vertices:h[i].vertices}),u=0;u!==c.vertices.length;u++){var a=c.vertices[u];n.sub(a,a,c.centerOfMass)}n.scale(l,c.centerOfMass,1),c.updateTriangles(),c.updateCenterOfMass(),c.updateBoundingRadius(),this.addShape(c,l)}return this.adjustCenterOfMass(),this.aabbNeedsUpdate=!0,!0};var x=(n.fromValues(0,0),n.fromValues(0,0)),w=n.fromValues(0,0),_=n.fromValues(0,0);s.prototype.adjustCenterOfMass=function(){var t=x,e=w,i=_,s=0;n.set(e,0,0);for(var r=0;r!==this.shapes.length;r++){var o=this.shapes[r];n.scale(t,o.position,o.area),n.add(e,e,t),s+=o.area}n.scale(i,e,1/s);for(var r=0;r!==this.shapes.length;r++){var o=this.shapes[r];n.sub(o.position,o.position,i)}n.add(this.position,this.position,i);for(var r=0;this.concavePath&&r<this.concavePath.length;r++)n.sub(this.concavePath[r],this.concavePath[r],i);this.updateMassProperties(),this.updateBoundingRadius()},s.prototype.setZeroForce=function(){n.set(this.force,0,0),this.angularForce=0},s.prototype.resetConstraintVelocity=function(){var t=this,e=t.vlambda;n.set(e,0,0),t.wlambda=0},s.prototype.addConstraintVelocity=function(){var t=this,e=t.velocity;n.add(e,e,t.vlambda),t.angularVelocity+=t.wlambda},s.prototype.applyDamping=function(t){if(this.type===s.DYNAMIC){var e=this.velocity;n.scale(e,e,Math.pow(1-this.damping,t)),this.angularVelocity*=Math.pow(1-this.angularDamping,t)}},s.prototype.wakeUp=function(){var t=this.sleepState;this.sleepState=s.AWAKE,this.idleTime=0,t!==s.AWAKE&&this.emit(s.wakeUpEvent)},s.prototype.sleep=function(){this.sleepState=s.SLEEPING,this.angularVelocity=0,this.angularForce=0,n.set(this.velocity,0,0),n.set(this.force,0,0),this.emit(s.sleepEvent)},s.prototype.sleepTick=function(t,e,i){if(this.allowSleep&&this.type!==s.SLEEPING){this.wantsToSleep=!1;this.sleepState;n.squaredLength(this.velocity)+Math.pow(this.angularVelocity,2)>=Math.pow(this.sleepSpeedLimit,2)?(this.idleTime=0,this.sleepState=s.AWAKE):(this.idleTime+=i,this.sleepState=s.SLEEPY),this.idleTime>this.sleepTimeLimit&&(e?this.wantsToSleep=!0:this.sleep())}},s.prototype.overlaps=function(t){return this.world.overlapKeeper.bodiesAreOverlapping(this,t)};var P=n.create(),T=n.create();s.prototype.integrate=function(t){var e=this.invMass,i=this.force,s=this.position,r=this.velocity;n.copy(this.previousPosition,this.position),this.previousAngle=this.angle,this.fixedRotation||(this.angularVelocity+=this.angularForce*this.invInertia*t),n.scale(P,i,t*e),n.multiply(P,this.massMultiplier,P),n.add(r,P,r),this.integrateToTimeOfImpact(t)||(n.scale(T,r,t),n.add(s,s,T),this.fixedRotation||(this.angle+=this.angularVelocity*t)),this.aabbNeedsUpdate=!0};var C=new a,S=new h({mode:h.ALL}),A=n.create(),E=n.create(),I=n.create(),M=n.create();s.prototype.integrateToTimeOfImpact=function(t){if(this.ccdSpeedThreshold<0||n.squaredLength(this.velocity)<Math.pow(this.ccdSpeedThreshold,2))return!1;n.normalize(A,this.velocity),n.scale(E,this.velocity,t),n.add(E,E,this.position),n.sub(I,E,this.position);var e,i=this.angularVelocity*t,s=n.length(I),r=1,o=this;if(C.reset(),S.callback=function(t){t.body!==o&&(e=t.body,t.getHitPoint(E,S),n.sub(I,E,o.position),r=n.length(I)/s,t.stop())},n.copy(S.from,this.position),n.copy(S.to,E),S.update(),this.world.raycast(C,S),!e)return!1;var a=this.angle;n.copy(M,this.position);for(var h=0,l=0,c=0,u=r;u>=l&&h<this.ccdIterations;){h++,c=(u-l)/2,n.scale(T,I,r),n.add(this.position,M,T),this.angle=a+i*r,this.updateAABB();this.aabb.overlaps(e.aabb)&&this.world.narrowphase.bodiesOverlap(this,e)?l=c:u=c}return r=c,n.copy(this.position,M),this.angle=a,n.scale(T,I,r),n.add(this.position,this.position,T),this.fixedRotation||(this.angle+=i*r),!0},s.prototype.getVelocityAtPoint=function(t,e){return n.crossVZ(t,e,this.angularVelocity),n.subtract(t,this.velocity,t),t},s.sleepyEvent={type:"sleepy"},s.sleepEvent={type:"sleep"},s.wakeUpEvent={type:"wakeup"},s.DYNAMIC=1,s.STATIC=2,s.KINEMATIC=4,s.AWAKE=0,s.SLEEPY=1,s.SLEEPING=2},{"../collision/AABB":7,"../collision/Ray":11,"../collision/RaycastResult":12,"../events/EventEmitter":26,"../math/vec2":30,"../shapes/Convex":40,"poly-decomp":5}],32:[function(t,e,i){function s(t,e,i){i=i||{},r.call(this,t,e,i),this.localAnchorA=n.fromValues(0,0),this.localAnchorB=n.fromValues(0,0),i.localAnchorA&&n.copy(this.localAnchorA,i.localAnchorA),i.localAnchorB&&n.copy(this.localAnchorB,i.localAnchorB),i.worldAnchorA&&this.setWorldAnchorA(i.worldAnchorA),i.worldAnchorB&&this.setWorldAnchorB(i.worldAnchorB);var s=n.create(),o=n.create();this.getWorldAnchorA(s),this.getWorldAnchorB(o);var a=n.distance(s,o);this.restLength="number"==typeof i.restLength?i.restLength:a}var n=t("../math/vec2"),r=t("./Spring");t("../utils/Utils");e.exports=s,s.prototype=new r,s.prototype.constructor=s,s.prototype.setWorldAnchorA=function(t){this.bodyA.toLocalFrame(this.localAnchorA,t)},s.prototype.setWorldAnchorB=function(t){this.bodyB.toLocalFrame(this.localAnchorB,t)},s.prototype.getWorldAnchorA=function(t){this.bodyA.toWorldFrame(t,this.localAnchorA)},s.prototype.getWorldAnchorB=function(t){this.bodyB.toWorldFrame(t,this.localAnchorB)};var o=n.create(),a=n.create(),h=n.create(),l=n.create(),c=n.create(),u=n.create(),d=n.create(),p=n.create(),f=n.create();s.prototype.applyForce=function(){var t=this.stiffness,e=this.damping,i=this.restLength,s=this.bodyA,r=this.bodyB,g=o,m=a,y=h,v=l,b=f,x=c,w=u,_=d,P=p;this.getWorldAnchorA(x),this.getWorldAnchorB(w),n.sub(_,x,s.position),n.sub(P,w,r.position),n.sub(g,w,x);var T=n.len(g);n.normalize(m,g),n.sub(y,r.velocity,s.velocity),n.crossZV(b,r.angularVelocity,P),n.add(y,y,b),n.crossZV(b,s.angularVelocity,_),n.sub(y,y,b),n.scale(v,m,-t*(T-i)-e*n.dot(y,m)),n.sub(s.force,s.force,v),n.add(r.force,r.force,v);var C=n.crossLength(_,v),S=n.crossLength(P,v);s.angularForce-=C,r.angularForce+=S}},{"../math/vec2":30,"../utils/Utils":57,"./Spring":34}],33:[function(t,e,i){function s(t,e,i){i=i||{},n.call(this,t,e,i),this.restAngle="number"==typeof i.restAngle?i.restAngle:e.angle-t.angle}var n=(t("../math/vec2"),t("./Spring"));e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.applyForce=function(){var t=this.stiffness,e=this.damping,i=this.restAngle,s=this.bodyA,n=this.bodyB,r=n.angle-s.angle,o=n.angularVelocity-s.angularVelocity,a=-t*(r-i)-e*o*0;s.angularForce-=a,n.angularForce+=a}},{"../math/vec2":30,"./Spring":34}],34:[function(t,e,i){function s(t,e,i){i=n.defaults(i,{stiffness:100,damping:1}),this.stiffness=i.stiffness,this.damping=i.damping,this.bodyA=t,this.bodyB=e}var n=(t("../math/vec2"),t("../utils/Utils"));e.exports=s,s.prototype.applyForce=function(){}},{"../math/vec2":30,"../utils/Utils":57}],35:[function(t,e,i){function s(t,e){e=e||{},this.chassisBody=t,this.wheels=[],this.groundBody=new h({mass:0}),this.world=null;var i=this;this.preStepCallback=function(){i.update()}}function n(t,e){e=e||{},this.vehicle=t,this.forwardEquation=new a(t.chassisBody,t.groundBody),this.sideEquation=new a(t.chassisBody,t.groundBody),this.steerValue=0,this.engineForce=0,this.setSideFriction(void 0!==e.sideFriction?e.sideFriction:5),this.localForwardVector=r.fromValues(0,1),e.localForwardVector&&r.copy(this.localForwardVector,e.localForwardVector),this.localPosition=r.fromValues(0,0),e.localPosition&&r.copy(this.localPosition,e.localPosition),o.apply(this,t.chassisBody,t.groundBody),this.equations.push(this.forwardEquation,this.sideEquation),this.setBrakeForce(0)}var r=t("../math/vec2"),o=(t("../utils/Utils"),t("../constraints/Constraint")),a=t("../equations/FrictionEquation"),h=t("../objects/Body");e.exports=s,s.prototype.addToWorld=function(t){this.world=t,t.addBody(this.groundBody),t.on("preStep",this.preStepCallback);for(var e=0;e<this.wheels.length;e++){var i=this.wheels[e];t.addConstraint(i)}},s.prototype.removeFromWorld=function(){var t=this.world;t.removeBody(this.groundBody),t.off("preStep",this.preStepCallback);for(var e=0;e<this.wheels.length;e++){var i=this.wheels[e];t.removeConstraint(i)}this.world=null},s.prototype.addWheel=function(t){var e=new n(this,t);return this.wheels.push(e),e},s.prototype.update=function(){for(var t=0;t<this.wheels.length;t++)this.wheels[t].update()},n.prototype=new o,n.prototype.setBrakeForce=function(t){this.forwardEquation.setSlipForce(t)},n.prototype.setSideFriction=function(t){this.sideEquation.setSlipForce(t)};var l=r.create(),c=r.create();n.prototype.getSpeed=function(){return this.vehicle.chassisBody.vectorToWorldFrame(c,this.localForwardVector),this.vehicle.chassisBody.getVelocityAtPoint(l,c),r.dot(l,c)};var u=r.create();n.prototype.update=function(){this.vehicle.chassisBody.vectorToWorldFrame(this.forwardEquation.t,this.localForwardVector),r.rotate(this.sideEquation.t,this.localForwardVector,Math.PI/2),this.vehicle.chassisBody.vectorToWorldFrame(this.sideEquation.t,this.sideEquation.t),r.rotate(this.forwardEquation.t,this.forwardEquation.t,this.steerValue),r.rotate(this.sideEquation.t,this.sideEquation.t,this.steerValue),this.vehicle.chassisBody.toWorldFrame(this.forwardEquation.contactPointB,this.localPosition),r.copy(this.sideEquation.contactPointB,this.forwardEquation.contactPointB),this.vehicle.chassisBody.vectorToWorldFrame(this.forwardEquation.contactPointA,this.localPosition),r.copy(this.sideEquation.contactPointA,this.forwardEquation.contactPointA),r.normalize(u,this.forwardEquation.t),r.scale(u,u,this.engineForce),this.vehicle.chassisBody.applyForce(u,this.forwardEquation.contactPointA)}},{"../constraints/Constraint":14,"../equations/FrictionEquation":23,"../math/vec2":30,"../objects/Body":31,"../utils/Utils":57}],36:[function(t,e,i){var s=e.exports={AABB:t("./collision/AABB"),AngleLockEquation:t("./equations/AngleLockEquation"),Body:t("./objects/Body"),Broadphase:t("./collision/Broadphase"),Capsule:t("./shapes/Capsule"),Circle:t("./shapes/Circle"),Constraint:t("./constraints/Constraint"),ContactEquation:t("./equations/ContactEquation"),ContactEquationPool:t("./utils/ContactEquationPool"),ContactMaterial:t("./material/ContactMaterial"),Convex:t("./shapes/Convex"),DistanceConstraint:t("./constraints/DistanceConstraint"),Equation:t("./equations/Equation"),EventEmitter:t("./events/EventEmitter"),FrictionEquation:t("./equations/FrictionEquation"),FrictionEquationPool:t("./utils/FrictionEquationPool"),GearConstraint:t("./constraints/GearConstraint"),GSSolver:t("./solver/GSSolver"),Heightfield:t("./shapes/Heightfield"),Line:t("./shapes/Line"),LockConstraint:t("./constraints/LockConstraint"),Material:t("./material/Material"),Narrowphase:t("./collision/Narrowphase"),NaiveBroadphase:t("./collision/NaiveBroadphase"),Particle:t("./shapes/Particle"),Plane:t("./shapes/Plane"),Pool:t("./utils/Pool"),RevoluteConstraint:t("./constraints/RevoluteConstraint"),PrismaticConstraint:t("./constraints/PrismaticConstraint"),Ray:t("./collision/Ray"),RaycastResult:t("./collision/RaycastResult"),Box:t("./shapes/Box"),RotationalVelocityEquation:t("./equations/RotationalVelocityEquation"),SAPBroadphase:t("./collision/SAPBroadphase"),Shape:t("./shapes/Shape"),Solver:t("./solver/Solver"),Spring:t("./objects/Spring"),TopDownVehicle:t("./objects/TopDownVehicle"),LinearSpring:t("./objects/LinearSpring"),RotationalSpring:t("./objects/RotationalSpring"),Utils:t("./utils/Utils"),World:t("./world/World"),vec2:t("./math/vec2"),version:t("../package.json").version};Object.defineProperty(s,"Rectangle",{get:function(){return console.warn("The Rectangle class has been renamed to Box."),this.Box}})},{"../package.json":6,"./collision/AABB":7,"./collision/Broadphase":8,"./collision/NaiveBroadphase":9,"./collision/Narrowphase":10,"./collision/Ray":11,"./collision/RaycastResult":12,"./collision/SAPBroadphase":13,"./constraints/Constraint":14,"./constraints/DistanceConstraint":15,"./constraints/GearConstraint":16,"./constraints/LockConstraint":17,"./constraints/PrismaticConstraint":18,"./constraints/RevoluteConstraint":19,"./equations/AngleLockEquation":20,"./equations/ContactEquation":21,"./equations/Equation":22,"./equations/FrictionEquation":23,"./equations/RotationalVelocityEquation":25,"./events/EventEmitter":26,"./material/ContactMaterial":27,"./material/Material":28,"./math/vec2":30,"./objects/Body":31,"./objects/LinearSpring":32,"./objects/RotationalSpring":33,"./objects/Spring":34,"./objects/TopDownVehicle":35,"./shapes/Box":37,"./shapes/Capsule":38,"./shapes/Circle":39,"./shapes/Convex":40,"./shapes/Heightfield":41,"./shapes/Line":42,"./shapes/Particle":43,"./shapes/Plane":44,"./shapes/Shape":45,"./solver/GSSolver":46,"./solver/Solver":47,"./utils/ContactEquationPool":48,"./utils/FrictionEquationPool":49,"./utils/Pool":55,"./utils/Utils":57,"./world/World":61}],37:[function(t,e,i){function s(t){"number"==typeof arguments[0]&&"number"==typeof arguments[1]&&(t={width:arguments[0],height:arguments[1]},console.warn("The Rectangle has been renamed to Box and its constructor signature has changed. Please use the following format: new Box({ width: 1, height: 1, ... })")),t=t||{};var e=this.width=t.width||1,i=this.height=t.height||1,s=[n.fromValues(-e/2,-i/2),n.fromValues(e/2,-i/2),n.fromValues(e/2,i/2),n.fromValues(-e/2,i/2)],a=[n.fromValues(1,0),n.fromValues(0,1)];t.vertices=s,t.axes=a,t.type=r.BOX,o.call(this,t)}var n=t("../math/vec2"),r=t("./Shape"),o=t("./Convex");e.exports=s,s.prototype=new o,s.prototype.constructor=s,s.prototype.computeMomentOfInertia=function(t){var e=this.width,i=this.height;return t*(i*i+e*e)/12},s.prototype.updateBoundingRadius=function(){var t=this.width,e=this.height;this.boundingRadius=Math.sqrt(t*t+e*e)/2};n.create(),n.create(),n.create(),n.create();s.prototype.computeAABB=function(t,e,i){t.setFromPoints(this.vertices,e,i,0)},s.prototype.updateArea=function(){this.area=this.width*this.height}},{"../math/vec2":30,"./Convex":40,"./Shape":45}],38:[function(t,e,i){function s(t){"number"==typeof arguments[0]&&"number"==typeof arguments[1]&&(t={length:arguments[0],radius:arguments[1]},console.warn("The Capsule constructor signature has changed. Please use the following format: new Capsule({ radius: 1, length: 1 })")),t=t||{},this.length=t.length||1,this.radius=t.radius||1,t.type=n.CAPSULE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.computeMomentOfInertia=function(t){var e=this.radius,i=this.length+e,s=2*e;return t*(s*s+i*i)/12},s.prototype.updateBoundingRadius=function(){this.boundingRadius=this.radius+this.length/2},s.prototype.updateArea=function(){this.area=Math.PI*this.radius*this.radius+2*this.radius*this.length};var o=r.create();s.prototype.computeAABB=function(t,e,i){var s=this.radius;r.set(o,this.length/2,0),0!==i&&r.rotate(o,o,i),r.set(t.upperBound,Math.max(o[0]+s,-o[0]+s),Math.max(o[1]+s,-o[1]+s)),r.set(t.lowerBound,Math.min(o[0]-s,-o[0]-s),Math.min(o[1]-s,-o[1]-s)),r.add(t.lowerBound,t.lowerBound,e),r.add(t.upperBound,t.upperBound,e)};var a=r.create(),h=r.create(),l=r.create(),c=r.create(),u=r.fromValues(0,1);s.prototype.raycast=function(t,e,i,s){for(var n=e.from,o=e.to,d=(e.direction,a),p=h,f=l,g=c,m=this.length/2,y=0;y<2;y++){var v=this.radius*(2*y-1);r.set(f,-m,v),r.set(g,m,v),r.toGlobalFrame(f,f,i,s),r.toGlobalFrame(g,g,i,s);var b=r.getLineSegmentsIntersectionFraction(n,o,f,g);if(b>=0&&(r.rotate(p,u,s),r.scale(p,p,2*y-1),e.reportIntersection(t,b,p,-1),t.shouldStop(e)))return}for(var x=Math.pow(this.radius,2)+Math.pow(m,2),y=0;y<2;y++){r.set(f,m*(2*y-1),0),r.toGlobalFrame(f,f,i,s);var w=Math.pow(o[0]-n[0],2)+Math.pow(o[1]-n[1],2),_=2*((o[0]-n[0])*(n[0]-f[0])+(o[1]-n[1])*(n[1]-f[1])),P=Math.pow(n[0]-f[0],2)+Math.pow(n[1]-f[1],2)-Math.pow(this.radius,2),b=Math.pow(_,2)-4*w*P;if(!(b<0))if(0===b){if(r.lerp(d,n,o,b),r.squaredDistance(d,i)>x&&(r.sub(p,d,f),r.normalize(p,p),e.reportIntersection(t,b,p,-1),t.shouldStop(e)))return}else{var T=Math.sqrt(b),C=1/(2*w),S=(-_-T)*C,A=(-_+T)*C;if(S>=0&&S<=1&&(r.lerp(d,n,o,S),r.squaredDistance(d,i)>x&&(r.sub(p,d,f),r.normalize(p,p),e.reportIntersection(t,S,p,-1),t.shouldStop(e))))return;if(A>=0&&A<=1&&(r.lerp(d,n,o,A),r.squaredDistance(d,i)>x&&(r.sub(p,d,f),r.normalize(p,p),e.reportIntersection(t,A,p,-1),t.shouldStop(e))))return}}}},{"../math/vec2":30,"./Shape":45}],39:[function(t,e,i){function s(t){"number"==typeof arguments[0]&&(t={radius:arguments[0]},console.warn("The Circle constructor signature has changed. Please use the following format: new Circle({ radius: 1 })")),t=t||{},this.radius=t.radius||1,t.type=n.CIRCLE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.computeMomentOfInertia=function(t){var e=this.radius;return t*e*e/2},s.prototype.updateBoundingRadius=function(){this.boundingRadius=this.radius},s.prototype.updateArea=function(){this.area=Math.PI*this.radius*this.radius},s.prototype.computeAABB=function(t,e,i){var s=this.radius;r.set(t.upperBound,s,s),r.set(t.lowerBound,-s,-s),e&&(r.add(t.lowerBound,t.lowerBound,e),r.add(t.upperBound,t.upperBound,e))};var o=r.create(),a=r.create();s.prototype.raycast=function(t,e,i,s){var n=e.from,h=e.to,l=this.radius,c=Math.pow(h[0]-n[0],2)+Math.pow(h[1]-n[1],2),u=2*((h[0]-n[0])*(n[0]-i[0])+(h[1]-n[1])*(n[1]-i[1])),d=Math.pow(n[0]-i[0],2)+Math.pow(n[1]-i[1],2)-Math.pow(l,2),p=Math.pow(u,2)-4*c*d,f=o,g=a;if(!(p<0))if(0===p)r.lerp(f,n,h,p),r.sub(g,f,i),r.normalize(g,g),e.reportIntersection(t,p,g,-1);else{var m=Math.sqrt(p),y=1/(2*c),v=(-u-m)*y,b=(-u+m)*y;if(v>=0&&v<=1&&(r.lerp(f,n,h,v),r.sub(g,f,i),r.normalize(g,g),e.reportIntersection(t,v,g,-1),t.shouldStop(e)))return;b>=0&&b<=1&&(r.lerp(f,n,h,b),r.sub(g,f,i),r.normalize(g,g),e.reportIntersection(t,b,g,-1))}}},{"../math/vec2":30,"./Shape":45}],40:[function(t,e,i){function s(t){Array.isArray(arguments[0])&&(t={vertices:arguments[0],axes:arguments[1]},console.warn("The Convex constructor signature has changed. Please use the following format: new Convex({ vertices: [...], ... })")),t=t||{},this.vertices=[];for(var e=void 0!==t.vertices?t.vertices:[],i=0;i<e.length;i++){var s=r.create();r.copy(s,e[i]),this.vertices.push(s)}if(this.axes=[],t.axes)for(var i=0;i<t.axes.length;i++){var o=r.create();r.copy(o,t.axes[i]),this.axes.push(o)}else for(var i=0;i<this.vertices.length;i++){var a=this.vertices[i],h=this.vertices[(i+1)%this.vertices.length],l=r.create();r.sub(l,h,a),r.rotate90cw(l,l),r.normalize(l,l),this.axes.push(l)}if(this.centerOfMass=r.fromValues(0,0),this.triangles=[],this.vertices.length&&(this.updateTriangles(),this.updateCenterOfMass()),this.boundingRadius=0,t.type=n.CONVEX,n.call(this,t),this.updateBoundingRadius(),this.updateArea(),this.area<0)throw new Error("Convex vertices must be given in conter-clockwise winding.")}var n=t("./Shape"),r=t("../math/vec2"),o=t("../math/polyk");t("poly-decomp");e.exports=s,s.prototype=new n,s.prototype.constructor=s;var a=r.create(),h=r.create();s.prototype.projectOntoLocalAxis=function(t,e){for(var i,s,n=null,o=null,t=a,h=0;h<this.vertices.length;h++)i=this.vertices[h],s=r.dot(i,t),(null===n||s>n)&&(n=s),(null===o||s<o)&&(o=s);if(o>n){var l=o;o=n,n=l}r.set(e,o,n)},s.prototype.projectOntoWorldAxis=function(t,e,i,s){var n=h;this.projectOntoLocalAxis(t,s),0!==i?r.rotate(n,t,i):n=t;var o=r.dot(e,n);r.set(s,s[0]+o,s[1]+o)},s.prototype.updateTriangles=function(){this.triangles.length=0;for(var t=[],e=0;e<this.vertices.length;e++){var i=this.vertices[e];t.push(i[0],i[1])}for(var s=o.Triangulate(t),e=0;e<s.length;e+=3){var n=s[e],r=s[e+1],a=s[e+2];this.triangles.push([n,r,a])}};var l=r.create(),c=r.create(),u=r.create(),d=r.create(),p=r.create();r.create(),r.create(),r.create(),r.create();s.prototype.updateCenterOfMass=function(){var t=this.triangles,e=this.vertices,i=this.centerOfMass,n=l,o=u,a=d,h=p,f=c;r.set(i,0,0);for(var g=0,m=0;m!==t.length;m++){var y=t[m],o=e[y[0]],a=e[y[1]],h=e[y[2]];r.centroid(n,o,a,h);var v=s.triangleArea(o,a,h);g+=v,r.scale(f,n,v),r.add(i,i,f)}r.scale(i,i,1/g)},s.prototype.computeMomentOfInertia=function(t){for(var e=0,i=0,s=this.vertices.length,n=s-1,o=0;o<s;n=o,o++){var a=this.vertices[n],h=this.vertices[o],l=Math.abs(r.crossLength(a,h));e+=l*(r.dot(h,h)+r.dot(h,a)+r.dot(a,a)),i+=l}return t/6*(e/i)},s.prototype.updateBoundingRadius=function(){for(var t=this.vertices,e=0,i=0;i!==t.length;i++){var s=r.squaredLength(t[i]);s>e&&(e=s)}this.boundingRadius=Math.sqrt(e)},s.triangleArea=function(t,e,i){return.5*((e[0]-t[0])*(i[1]-t[1])-(i[0]-t[0])*(e[1]-t[1]))},s.prototype.updateArea=function(){this.updateTriangles(),this.area=0;for(var t=this.triangles,e=this.vertices,i=0;i!==t.length;i++){var n=t[i],r=e[n[0]],o=e[n[1]],a=e[n[2]],h=s.triangleArea(r,o,a);this.area+=h}},s.prototype.computeAABB=function(t,e,i){t.setFromPoints(this.vertices,e,i,0)};var f=r.create(),g=r.create(),m=r.create();s.prototype.raycast=function(t,e,i,s){var n=f,o=g,a=m,h=this.vertices;r.toLocalFrame(n,e.from,i,s),r.toLocalFrame(o,e.to,i,s);for(var l=h.length,c=0;c<l&&!t.shouldStop(e);c++){var u=h[c],d=h[(c+1)%l],p=r.getLineSegmentsIntersectionFraction(n,o,u,d);p>=0&&(r.sub(a,d,u),r.rotate(a,a,-Math.PI/2+s),r.normalize(a,a),e.reportIntersection(t,p,a,c))}}},{"../math/polyk":29,"../math/vec2":30,"./Shape":45,"poly-decomp":5}],41:[function(t,e,i){function s(t){if(Array.isArray(arguments[0])){if(t={heights:arguments[0]},"object"==typeof arguments[1])for(var e in arguments[1])t[e]=arguments[1][e];console.warn("The Heightfield constructor signature has changed. Please use the following format: new Heightfield({ heights: [...], ... })")}t=t||{},this.heights=t.heights?t.heights.slice(0):[],this.maxValue=t.maxValue||null,this.minValue=t.minValue||null,this.elementWidth=t.elementWidth||.1,void 0!==t.maxValue&&void 0!==t.minValue||this.updateMaxMinValues(),t.type=n.HEIGHTFIELD,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");t("../utils/Utils");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.updateMaxMinValues=function(){for(var t=this.heights,e=t[0],i=t[0],s=0;s!==t.length;s++){var n=t[s];n>e&&(e=n),n<i&&(i=n)}this.maxValue=e,this.minValue=i},s.prototype.computeMomentOfInertia=function(t){return Number.MAX_VALUE},s.prototype.updateBoundingRadius=function(){this.boundingRadius=Number.MAX_VALUE},s.prototype.updateArea=function(){for(var t=this.heights,e=0,i=0;i<t.length-1;i++)e+=(t[i]+t[i+1])/2*this.elementWidth;this.area=e};var o=[r.create(),r.create(),r.create(),r.create()];s.prototype.computeAABB=function(t,e,i){r.set(o[0],0,this.maxValue),r.set(o[1],this.elementWidth*this.heights.length,this.maxValue),r.set(o[2],this.elementWidth*this.heights.length,this.minValue),r.set(o[3],0,this.minValue),t.setFromPoints(o,e,i)},s.prototype.getLineSegment=function(t,e,i){var s=this.heights,n=this.elementWidth;r.set(t,i*n,s[i]),r.set(e,(i+1)*n,s[i+1])},s.prototype.getSegmentIndex=function(t){return Math.floor(t[0]/this.elementWidth)},s.prototype.getClampedSegmentIndex=function(t){var e=this.getSegmentIndex(t);return e=Math.min(this.heights.length,Math.max(e,0))};var a=(r.create(),r.create()),h=r.create(),l=r.create(),c=r.create(),u=r.create();r.fromValues(0,1);s.prototype.raycast=function(t,e,i,s){var n=e.from,o=e.to,d=(e.direction,a),p=h,f=l,g=c,m=u;r.toLocalFrame(g,n,i,s),r.toLocalFrame(m,o,i,s);var y=this.getClampedSegmentIndex(g),v=this.getClampedSegmentIndex(m);if(y>v){var b=y;y=v,v=b}for(var x=0;x<this.heights.length-1;x++){this.getLineSegment(p,f,x);var w=r.getLineSegmentsIntersectionFraction(g,m,p,f);if(w>=0&&(r.sub(d,f,p),r.rotate(d,d,s+Math.PI/2),r.normalize(d,d),e.reportIntersection(t,w,d,-1),t.shouldStop(e)))return}}},{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],42:[function(t,e,i){function s(t){"number"==typeof arguments[0]&&(t={length:arguments[0]},console.warn("The Line constructor signature has changed. Please use the following format: new Line({ length: 1, ... })")),t=t||{},this.length=t.length||1,t.type=n.LINE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.computeMomentOfInertia=function(t){return t*Math.pow(this.length,2)/12},s.prototype.updateBoundingRadius=function(){this.boundingRadius=this.length/2};var o=[r.create(),r.create()];s.prototype.computeAABB=function(t,e,i){var s=this.length/2;r.set(o[0],-s,0),r.set(o[1],s,0),t.setFromPoints(o,e,i,0)};var a=(r.create(),r.create()),h=r.create(),l=r.create(),c=r.fromValues(0,1);s.prototype.raycast=function(t,e,i,s){var n=e.from,o=e.to,u=h,d=l,p=this.length/2;r.set(u,-p,0),r.set(d,p,0),r.toGlobalFrame(u,u,i,s),r.toGlobalFrame(d,d,i,s);var f=r.getLineSegmentsIntersectionFraction(u,d,n,o);if(f>=0){var g=a;r.rotate(g,c,s),e.reportIntersection(t,f,g,-1)}}},{"../math/vec2":30,"./Shape":45}],43:[function(t,e,i){function s(t){t=t||{},t.type=n.PARTICLE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.computeMomentOfInertia=function(t){return 0},s.prototype.updateBoundingRadius=function(){this.boundingRadius=0},s.prototype.computeAABB=function(t,e,i){r.copy(t.lowerBound,e),r.copy(t.upperBound,e)}},{"../math/vec2":30,"./Shape":45}],44:[function(t,e,i){function s(t){t=t||{},t.type=n.PLANE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");t("../utils/Utils");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.computeMomentOfInertia=function(t){return 0},s.prototype.updateBoundingRadius=function(){this.boundingRadius=Number.MAX_VALUE},s.prototype.computeAABB=function(t,e,i){var s=i%(2*Math.PI),n=r.set,o=Number.MAX_VALUE,a=t.lowerBound,h=t.upperBound;0===s?(n(a,-o,-o),n(h,o,0)):s===Math.PI/2?(n(a,0,-o),n(h,o,o)):s===Math.PI?(n(a,-o,0),n(h,o,o)):s===3*Math.PI/2?(n(a,-o,-o),n(h,0,o)):(n(a,-o,-o),n(h,o,o)),r.add(a,a,e),r.add(h,h,e)},s.prototype.updateArea=function(){this.area=Number.MAX_VALUE};var o=r.create(),a=(r.create(),r.create(),r.create()),h=r.create();s.prototype.raycast=function(t,e,i,s){var n=e.from,l=e.to,c=e.direction,u=o,d=a,p=h;r.set(d,0,1),r.rotate(d,d,s),r.sub(p,n,i);var f=r.dot(p,d);if(r.sub(p,l,i),!(f*r.dot(p,d)>0||r.squaredDistance(n,l)<f*f)){var g=r.dot(d,c);r.sub(u,n,i);var m=-r.dot(d,u)/g/e.length;e.reportIntersection(t,m,d,-1)}}},{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],45:[function(t,e,i){function s(t){t=t||{},this.body=null,this.position=n.fromValues(0,0),t.position&&n.copy(this.position,t.position),this.angle=t.angle||0,this.type=t.type||0,this.id=s.idCounter++,this.boundingRadius=0,this.collisionGroup=void 0!==t.collisionGroup?t.collisionGroup:1,this.collisionResponse=void 0===t.collisionResponse||t.collisionResponse,this.collisionMask=void 0!==t.collisionMask?t.collisionMask:1,this.material=t.material||null,this.area=0,this.sensor=void 0!==t.sensor&&t.sensor,this.type&&this.updateBoundingRadius(),this.updateArea()}e.exports=s;var n=t("../math/vec2");s.idCounter=0,s.CIRCLE=1,s.PARTICLE=2,s.PLANE=4,s.CONVEX=8,s.LINE=16,s.BOX=32,Object.defineProperty(s,"RECTANGLE",{get:function(){return console.warn("Shape.RECTANGLE is deprecated, use Shape.BOX instead."),s.BOX}}),s.CAPSULE=64,s.HEIGHTFIELD=128,s.prototype.computeMomentOfInertia=function(t){},s.prototype.updateBoundingRadius=function(){},s.prototype.updateArea=function(){},s.prototype.computeAABB=function(t,e,i){},s.prototype.raycast=function(t,e,i,s){}},{"../math/vec2":30}],46:[function(t,e,i){function s(t){o.call(this,t,o.GS),t=t||{},this.iterations=t.iterations||10,this.tolerance=t.tolerance||1e-7,this.arrayStep=30,this.lambda=new a.ARRAY_TYPE(this.arrayStep),this.Bs=new a.ARRAY_TYPE(this.arrayStep),this.invCs=new a.ARRAY_TYPE(this.arrayStep),this.useZeroRHS=!1,this.frictionIterations=0,this.usedIterations=0}function n(t){for(var e=t.length;e--;)t[e]=0}var r=t("../math/vec2"),o=t("./Solver"),a=t("../utils/Utils"),h=t("../equations/FrictionEquation");e.exports=s,s.prototype=new o,s.prototype.constructor=s,s.prototype.solve=function(t,e){this.sortEquations();var i=0,o=this.iterations,l=this.frictionIterations,c=this.equations,u=c.length,d=Math.pow(this.tolerance*u,2),p=e.bodies,f=e.bodies.length,g=(r.add,r.set,this.useZeroRHS),m=this.lambda;if(this.usedIterations=0,u)for(var y=0;y!==f;y++){var v=p[y];v.updateSolveMassProperties()}m.length<u&&(m=this.lambda=new a.ARRAY_TYPE(u+this.arrayStep),this.Bs=new a.ARRAY_TYPE(u+this.arrayStep),this.invCs=new a.ARRAY_TYPE(u+this.arrayStep)),n(m);for(var b=this.invCs,x=this.Bs,m=this.lambda,y=0;y!==c.length;y++){var w=c[y];(w.timeStep!==t||w.needsUpdate)&&(w.timeStep=t,w.update()),x[y]=w.computeB(w.a,w.b,t),b[y]=w.computeInvC(w.epsilon)}var w,_,y,P;if(0!==u){for(y=0;y!==f;y++){var v=p[y];v.resetConstraintVelocity()}if(l){for(i=0;i!==l;i++){for(_=0,P=0;P!==u;P++){w=c[P];var T=s.iterateEquation(P,w,w.epsilon,x,b,m,g,t,i);_+=Math.abs(T)}if(this.usedIterations++,_*_<=d)break}for(s.updateMultipliers(c,m,1/t),P=0;P!==u;P++){var C=c[P];if(C instanceof h){for(var S=0,A=0;A!==C.contactEquations.length;A++)S+=C.contactEquations[A].multiplier;S*=C.frictionCoefficient/C.contactEquations.length,C.maxForce=S,C.minForce=-S}}}for(i=0;i!==o;i++){for(_=0,P=0;P!==u;P++){w=c[P];var T=s.iterateEquation(P,w,w.epsilon,x,b,m,g,t,i);_+=Math.abs(T)}if(this.usedIterations++,_*_<=d)break}for(y=0;y!==f;y++)p[y].addConstraintVelocity();s.updateMultipliers(c,m,1/t)}},s.updateMultipliers=function(t,e,i){for(var s=t.length;s--;)t[s].multiplier=e[s]*i},s.iterateEquation=function(t,e,i,s,n,r,o,a,h){var l=s[t],c=n[t],u=r[t],d=e.computeGWlambda(),p=e.maxForce,f=e.minForce;o&&(l=0);var g=c*(l-d-i*u),m=u+g;return m<f*a?g=f*a-u:m>p*a&&(g=p*a-u),r[t]+=g,e.addToWlambda(g),g}},{"../equations/FrictionEquation":23,"../math/vec2":30,"../utils/Utils":57,"./Solver":47}],47:[function(t,e,i){function s(t,e){t=t||{},n.call(this),this.type=e,this.equations=[],this.equationSortFunction=t.equationSortFunction||!1}var n=(t("../utils/Utils"),t("../events/EventEmitter"));e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.solve=function(t,e){throw new Error("Solver.solve should be implemented by subclasses!")};var r={bodies:[]};s.prototype.solveIsland=function(t,e){this.removeAllEquations(),e.equations.length&&(this.addEquations(e.equations),r.bodies.length=0,e.getBodies(r.bodies),r.bodies.length&&this.solve(t,r))},s.prototype.sortEquations=function(){this.equationSortFunction&&this.equations.sort(this.equationSortFunction)},s.prototype.addEquation=function(t){t.enabled&&this.equations.push(t)},s.prototype.addEquations=function(t){for(var e=0,i=t.length;e!==i;e++){var s=t[e];s.enabled&&this.equations.push(s)}},s.prototype.removeEquation=function(t){var e=this.equations.indexOf(t);-1!==e&&this.equations.splice(e,1)},s.prototype.removeAllEquations=function(){this.equations.length=0},s.GS=1,s.ISLAND=2},{"../events/EventEmitter":26,"../utils/Utils":57}],48:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../equations/ContactEquation"),r=t("./Pool");e.exports=s,s.prototype=new r,s.prototype.constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.bodyA=t.bodyB=null,this}},{"../equations/ContactEquation":21,"./Pool":55}],49:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../equations/FrictionEquation"),r=t("./Pool");e.exports=s,s.prototype=new r,s.prototype.constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.bodyA=t.bodyB=null,this}},{"../equations/FrictionEquation":23,"./Pool":55}],50:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../world/IslandNode"),r=t("./Pool");e.exports=s,s.prototype=new r,s.prototype.constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.reset(),this}},{"../world/IslandNode":60,"./Pool":55}],51:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../world/Island"),r=t("./Pool");e.exports=s,s.prototype=new r,s.prototype.constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.reset(),this}},{"../world/Island":58,"./Pool":55}],52:[function(t,e,i){function s(){this.overlappingShapesLastState=new n,this.overlappingShapesCurrentState=new n,this.recordPool=new r({size:16}),this.tmpDict=new n,this.tmpArray1=[]}var n=t("./TupleDictionary"),r=(t("./OverlapKeeperRecord"),t("./OverlapKeeperRecordPool"));t("./Utils");e.exports=s,s.prototype.tick=function(){for(var t=this.overlappingShapesLastState,e=this.overlappingShapesCurrentState,i=t.keys.length;i--;){var s=t.keys[i],n=t.getByKey(s);e.getByKey(s);n&&this.recordPool.release(n)}t.reset(),t.copy(e),e.reset()},s.prototype.setOverlapping=function(t,e,i,s){var n=(this.overlappingShapesLastState,this.overlappingShapesCurrentState);if(!n.get(e.id,s.id)){var r=this.recordPool.get();r.set(t,e,i,s),n.set(e.id,s.id,r)}},s.prototype.getNewOverlaps=function(t){return this.getDiff(this.overlappingShapesLastState,this.overlappingShapesCurrentState,t)},s.prototype.getEndOverlaps=function(t){return this.getDiff(this.overlappingShapesCurrentState,this.overlappingShapesLastState,t)},s.prototype.bodiesAreOverlapping=function(t,e){for(var i=this.overlappingShapesCurrentState,s=i.keys.length;s--;){var n=i.keys[s],r=i.data[n];if(r.bodyA===t&&r.bodyB===e||r.bodyA===e&&r.bodyB===t)return!0}return!1},s.prototype.getDiff=function(t,e,i){var i=i||[],s=t,n=e;i.length=0;for(var r=n.keys.length;r--;){var o=n.keys[r],a=n.data[o];if(!a)throw new Error("Key "+o+" had no data!");s.data[o]||i.push(a)}return i},s.prototype.isNewOverlap=function(t,e){var i=0|t.id,s=0|e.id,n=this.overlappingShapesLastState,r=this.overlappingShapesCurrentState;return!n.get(i,s)&&!!r.get(i,s)},s.prototype.getNewBodyOverlaps=function(t){this.tmpArray1.length=0;var e=this.getNewOverlaps(this.tmpArray1);return this.getBodyDiff(e,t)},s.prototype.getEndBodyOverlaps=function(t){this.tmpArray1.length=0;var e=this.getEndOverlaps(this.tmpArray1);return this.getBodyDiff(e,t)},s.prototype.getBodyDiff=function(t,e){e=e||[];for(var i=this.tmpDict,s=t.length;s--;){var n=t[s];i.set(0|n.bodyA.id,0|n.bodyB.id,n)}for(s=i.keys.length;s--;){var n=i.getByKey(i.keys[s]);n&&e.push(n.bodyA,n.bodyB)}return i.reset(),e}},{"./OverlapKeeperRecord":53,"./OverlapKeeperRecordPool":54,"./TupleDictionary":56,"./Utils":57}],53:[function(t,e,i){function s(t,e,i,s){this.shapeA=e,this.shapeB=s,this.bodyA=t,this.bodyB=i}e.exports=s,s.prototype.set=function(t,e,i,n){s.call(this,t,e,i,n)}},{}],54:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("./OverlapKeeperRecord"),r=t("./Pool");e.exports=s,s.prototype=new r,s.prototype.constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.bodyA=t.bodyB=t.shapeA=t.shapeB=null,this}},{"./OverlapKeeperRecord":53,"./Pool":55}],55:[function(t,e,i){function s(t){t=t||{},this.objects=[],void 0!==t.size&&this.resize(t.size)}e.exports=s,s.prototype.resize=function(t){for(var e=this.objects;e.length>t;)e.pop();for(;e.length<t;)e.push(this.create());return this},s.prototype.get=function(){var t=this.objects;return t.length?t.pop():this.create()},s.prototype.release=function(t){return this.destroy(t),this.objects.push(t),this}},{}],56:[function(t,e,i){function s(){this.data={},this.keys=[]}var n=t("./Utils");e.exports=s,s.prototype.getKey=function(t,e){return t|=0,e|=0,(0|t)==(0|e)?-1:0|((0|t)>(0|e)?t<<16|65535&e:e<<16|65535&t)},s.prototype.getByKey=function(t){return t|=0,this.data[t]},s.prototype.get=function(t,e){return this.data[this.getKey(t,e)]},s.prototype.set=function(t,e,i){if(!i)throw new Error("No data!");var s=this.getKey(t,e);return this.data[s]||this.keys.push(s),this.data[s]=i,s},s.prototype.reset=function(){for(var t=this.data,e=this.keys,i=e.length;i--;)delete t[e[i]];e.length=0},s.prototype.copy=function(t){this.reset(),n.appendArray(this.keys,t.keys);for(var e=t.keys.length;e--;){var i=t.keys[e];this.data[i]=t.data[i]}}},{"./Utils":57}],57:[function(t,e,i){function s(){}e.exports=s,s.appendArray=function(t,e){if(e.length<15e4)t.push.apply(t,e);else for(var i=0,s=e.length;i!==s;++i)t.push(e[i])},s.splice=function(t,e,i){i=i||1;for(var s=e,n=t.length-i;s<n;s++)t[s]=t[s+i];t.length=n},"undefined"!=typeof P2_ARRAY_TYPE?s.ARRAY_TYPE=P2_ARRAY_TYPE:"undefined"!=typeof Float32Array?s.ARRAY_TYPE=Float32Array:s.ARRAY_TYPE=Array,s.extend=function(t,e){for(var i in e)t[i]=e[i]},s.defaults=function(t,e){t=t||{};for(var i in e)i in t||(t[i]=e[i]);return t}},{}],58:[function(t,e,i){function s(){this.equations=[],this.bodies=[]}var n=t("../objects/Body");e.exports=s,s.prototype.reset=function(){this.equations.length=this.bodies.length=0};var r=[];s.prototype.getBodies=function(t){var e=t||[],i=this.equations;r.length=0;for(var s=0;s!==i.length;s++){var n=i[s];-1===r.indexOf(n.bodyA.id)&&(e.push(n.bodyA),r.push(n.bodyA.id)),-1===r.indexOf(n.bodyB.id)&&(e.push(n.bodyB),r.push(n.bodyB.id))}return e},s.prototype.wantsToSleep=function(){for(var t=0;t<this.bodies.length;t++){var e=this.bodies[t];if(e.type===n.DYNAMIC&&!e.wantsToSleep)return!1}return!0},s.prototype.sleep=function(){for(var t=0;t<this.bodies.length;t++){this.bodies[t].sleep()}return!0}},{"../objects/Body":31}],59:[function(t,e,i){function s(t){this.nodePool=new n({size:16}),this.islandPool=new r({size:8}),this.equations=[],this.islands=[],this.nodes=[],this.queue=[]}var n=(t("../math/vec2"),t("./Island"),t("./IslandNode"),t("./../utils/IslandNodePool")),r=t("./../utils/IslandPool"),o=t("../objects/Body");e.exports=s,s.getUnvisitedNode=function(t){for(var e=t.length,i=0;i!==e;i++){var s=t[i];if(!s.visited&&s.body.type===o.DYNAMIC)return s}return!1},s.prototype.visit=function(t,e,i){e.push(t.body);for(var s=t.equations.length,n=0;n!==s;n++){var r=t.equations[n];-1===i.indexOf(r)&&i.push(r)}},s.prototype.bfs=function(t,e,i){var n=this.queue;for(n.length=0,n.push(t),t.visited=!0,this.visit(t,e,i);n.length;)for(var r,a=n.pop();r=s.getUnvisitedNode(a.neighbors);)r.visited=!0,this.visit(r,e,i),r.body.type===o.DYNAMIC&&n.push(r)},s.prototype.split=function(t){for(var e=t.bodies,i=this.nodes,n=this.equations;i.length;)this.nodePool.release(i.pop());for(var r=0;r!==e.length;r++){var o=this.nodePool.get();o.body=e[r],i.push(o)}for(var a=0;a!==n.length;a++){var h=n[a],r=e.indexOf(h.bodyA),l=e.indexOf(h.bodyB),c=i[r],u=i[l];c.neighbors.push(u),u.neighbors.push(c),c.equations.push(h),u.equations.push(h)}for(var d=this.islands,r=0;r<d.length;r++)this.islandPool.release(d[r]);d.length=0;for(var p;p=s.getUnvisitedNode(i);){var f=this.islandPool.get();this.bfs(p,f.bodies,f.equations),d.push(f)}return d}},{"../math/vec2":30,"../objects/Body":31,"./../utils/IslandNodePool":50,"./../utils/IslandPool":51,"./Island":58,"./IslandNode":60}],60:[function(t,e,i){function s(t){this.body=t,this.neighbors=[],this.equations=[],this.visited=!1}e.exports=s,s.prototype.reset=function(){this.equations.length=0,this.neighbors.length=0,this.visited=!1,this.body=null}},{}],61:[function(t,e,i){function s(t){u.apply(this),t=t||{},this.springs=[],this.bodies=[],this.disabledBodyCollisionPairs=[],this.solver=t.solver||new n,this.narrowphase=new y(this),this.islandManager=new x,this.gravity=r.fromValues(0,-9.78),t.gravity&&r.copy(this.gravity,t.gravity),this.frictionGravity=r.length(this.gravity)||10,this.useWorldGravityAsFrictionGravity=!0,this.useFrictionGravityOnZeroGravity=!0,this.broadphase=t.broadphase||new m,this.broadphase.setWorld(this),this.constraints=[],this.defaultMaterial=new p,this.defaultContactMaterial=new f(this.defaultMaterial,this.defaultMaterial),this.lastTimeStep=1/60,this.applySpringForces=!0,this.applyDamping=!0,this.applyGravity=!0,this.solveConstraints=!0,this.contactMaterials=[],this.time=0,this.accumulator=0,this.stepping=!1,this.bodiesToBeRemoved=[],this.islandSplit=void 0===t.islandSplit||!!t.islandSplit,this.emitImpactEvent=!0,this._constraintIdCounter=0,this._bodyIdCounter=0,this.postStepEvent={type:"postStep"},this.addBodyEvent={type:"addBody",body:null},this.removeBodyEvent={type:"removeBody",body:null},this.addSpringEvent={type:"addSpring",spring:null},this.impactEvent={type:"impact",bodyA:null,bodyB:null,shapeA:null,shapeB:null,contactEquation:null},this.postBroadphaseEvent={type:"postBroadphase",pairs:null},this.sleepMode=s.NO_SLEEPING,this.beginContactEvent={type:"beginContact",shapeA:null,shapeB:null,bodyA:null,bodyB:null,contactEquations:[]},this.endContactEvent={type:"endContact",shapeA:null,shapeB:null,bodyA:null,bodyB:null},this.preSolveEvent={type:"preSolve",contactEquations:null,frictionEquations:null},this.overlappingShapesLastState={keys:[]},this.overlappingShapesCurrentState={keys:[]},this.overlapKeeper=new b}var n=t("../solver/GSSolver"),r=(t("../solver/Solver"),t("../collision/Ray"),t("../math/vec2")),o=t("../shapes/Circle"),a=t("../shapes/Convex"),h=(t("../shapes/Line"),t("../shapes/Plane")),l=t("../shapes/Capsule"),c=t("../shapes/Particle"),u=t("../events/EventEmitter"),d=t("../objects/Body"),p=(t("../shapes/Shape"),t("../objects/LinearSpring"),t("../material/Material")),f=t("../material/ContactMaterial"),g=(t("../constraints/DistanceConstraint"),t("../constraints/Constraint"),t("../constraints/LockConstraint"),t("../constraints/RevoluteConstraint"),t("../constraints/PrismaticConstraint"),t("../constraints/GearConstraint"),t("../../package.json"),t("../collision/Broadphase"),t("../collision/AABB")),m=t("../collision/SAPBroadphase"),y=t("../collision/Narrowphase"),v=t("../utils/Utils"),b=t("../utils/OverlapKeeper"),x=t("./IslandManager");t("../objects/RotationalSpring");e.exports=s,s.prototype=new Object(u.prototype),s.prototype.constructor=s,s.NO_SLEEPING=1,s.BODY_SLEEPING=2,s.ISLAND_SLEEPING=4,s.prototype.addConstraint=function(t){this.constraints.push(t)},s.prototype.addContactMaterial=function(t){this.contactMaterials.push(t)},s.prototype.removeContactMaterial=function(t){var e=this.contactMaterials.indexOf(t);-1!==e&&v.splice(this.contactMaterials,e,1)},s.prototype.getContactMaterial=function(t,e){for(var i=this.contactMaterials,s=0,n=i.length;s!==n;s++){var r=i[s];if(r.materialA.id===t.id&&r.materialB.id===e.id||r.materialA.id===e.id&&r.materialB.id===t.id)return r}return!1},s.prototype.removeConstraint=function(t){var e=this.constraints.indexOf(t);-1!==e&&v.splice(this.constraints,e,1)};var w=(r.create(),r.create(),r.create(),r.create(),r.create(),r.create(),r.create()),_=r.fromValues(0,0),P=r.fromValues(0,0);r.fromValues(0,0),r.fromValues(0,0);s.prototype.step=function(t,e,i){if(i=i||10,0===(e=e||0))this.internalStep(t),this.time+=t;else{this.accumulator+=e;for(var s=0;this.accumulator>=t&&s<i;)this.internalStep(t),this.time+=t,this.accumulator-=t,s++;for(var n=this.accumulator%t/t,o=0;o!==this.bodies.length;o++){var a=this.bodies[o];r.lerp(a.interpolatedPosition,a.previousPosition,a.position,n),a.interpolatedAngle=a.previousAngle+n*(a.angle-a.previousAngle)}}};var T=[];s.prototype.internalStep=function(t){this.stepping=!0;var e=this.springs.length,i=this.springs,n=this.bodies,o=this.gravity,a=this.solver,h=this.bodies.length,l=this.broadphase,c=this.narrowphase,u=this.constraints,p=w,f=(r.scale,r.add),g=(r.rotate,this.islandManager);if(this.overlapKeeper.tick(),this.lastTimeStep=t,this.useWorldGravityAsFrictionGravity){var m=r.length(this.gravity);0===m&&this.useFrictionGravityOnZeroGravity||(this.frictionGravity=m)}if(this.applyGravity)for(var y=0;y!==h;y++){var b=n[y],x=b.force;b.type===d.DYNAMIC&&b.sleepState!==d.SLEEPING&&(r.scale(p,o,b.mass*b.gravityScale),f(x,x,p))}if(this.applySpringForces)for(var y=0;y!==e;y++){var _=i[y];_.applyForce()}if(this.applyDamping)for(var y=0;y!==h;y++){var b=n[y];b.type===d.DYNAMIC&&b.applyDamping(t)}for(var P=l.getCollisionPairs(this),C=this.disabledBodyCollisionPairs,y=C.length-2;y>=0;y-=2)for(var S=P.length-2;S>=0;S-=2)(C[y]===P[S]&&C[y+1]===P[S+1]||C[y+1]===P[S]&&C[y]===P[S+1])&&P.splice(S,2);var A=u.length;for(y=0;y!==A;y++){var E=u[y];if(!E.collideConnected)for(var S=P.length-2;S>=0;S-=2)(E.bodyA===P[S]&&E.bodyB===P[S+1]||E.bodyB===P[S]&&E.bodyA===P[S+1])&&P.splice(S,2)}this.postBroadphaseEvent.pairs=P,this.emit(this.postBroadphaseEvent),this.postBroadphaseEvent.pairs=null,c.reset(this);for(var y=0,I=P.length;y!==I;y+=2)for(var M=P[y],R=P[y+1],B=0,L=M.shapes.length;B!==L;B++)for(var k=M.shapes[B],O=k.position,F=k.angle,D=0,U=R.shapes.length;D!==U;D++){var G=R.shapes[D],N=G.position,X=G.angle,W=this.defaultContactMaterial;if(k.material&&G.material){var j=this.getContactMaterial(k.material,G.material);j&&(W=j)}this.runNarrowphase(c,M,k,O,F,R,G,N,X,W,this.frictionGravity)}for(var y=0;y!==h;y++){var V=n[y];V._wakeUpAfterNarrowphase&&(V.wakeUp(),V._wakeUpAfterNarrowphase=!1)}if(this.has("endContact")){this.overlapKeeper.getEndOverlaps(T);for(var q=this.endContactEvent,D=T.length;D--;){var H=T[D];q.shapeA=H.shapeA,q.shapeB=H.shapeB,q.bodyA=H.bodyA,q.bodyB=H.bodyB,this.emit(q)}T.length=0}var Y=this.preSolveEvent;Y.contactEquations=c.contactEquations,Y.frictionEquations=c.frictionEquations,this.emit(Y),Y.contactEquations=Y.frictionEquations=null;var A=u.length;for(y=0;y!==A;y++)u[y].update();if(c.contactEquations.length||c.frictionEquations.length||A)if(this.islandSplit){for(g.equations.length=0,v.appendArray(g.equations,c.contactEquations),v.appendArray(g.equations,c.frictionEquations),y=0;y!==A;y++)v.appendArray(g.equations,u[y].equations);g.split(this);for(var y=0;y!==g.islands.length;y++){var z=g.islands[y];z.equations.length&&a.solveIsland(t,z)}}else{for(a.addEquations(c.contactEquations),a.addEquations(c.frictionEquations),y=0;y!==A;y++)a.addEquations(u[y].equations);this.solveConstraints&&a.solve(t,this),a.removeAllEquations()}for(var y=0;y!==h;y++){var V=n[y];V.integrate(t)}for(var y=0;y!==h;y++)n[y].setZeroForce();if(this.emitImpactEvent&&this.has("impact"))for(var K=this.impactEvent,y=0;y!==c.contactEquations.length;y++){var J=c.contactEquations[y];J.firstImpact&&(K.bodyA=J.bodyA,K.bodyB=J.bodyB,K.shapeA=J.shapeA,K.shapeB=J.shapeB,K.contactEquation=J,this.emit(K))}if(this.sleepMode===s.BODY_SLEEPING)for(y=0;y!==h;y++)n[y].sleepTick(this.time,!1,t);else if(this.sleepMode===s.ISLAND_SLEEPING&&this.islandSplit){for(y=0;y!==h;y++)n[y].sleepTick(this.time,!0,t);for(var y=0;y<this.islandManager.islands.length;y++){var z=this.islandManager.islands[y];z.wantsToSleep()&&z.sleep()}}this.stepping=!1;for(var Q=this.bodiesToBeRemoved,y=0;y!==Q.length;y++)this.removeBody(Q[y]);Q.length=0,this.emit(this.postStepEvent)},s.prototype.runNarrowphase=function(t,e,i,s,n,o,a,h,l,c,u){if(0!=(i.collisionGroup&a.collisionMask)&&0!=(a.collisionGroup&i.collisionMask)){r.rotate(_,s,e.angle),r.rotate(P,h,o.angle),r.add(_,_,e.position),r.add(P,P,o.position);var p=n+e.angle,f=l+o.angle;t.enableFriction=c.friction>0,t.frictionCoefficient=c.friction;var g;g=e.type===d.STATIC||e.type===d.KINEMATIC?o.mass:o.type===d.STATIC||o.type===d.KINEMATIC?e.mass:e.mass*o.mass/(e.mass+o.mass),t.slipForce=c.friction*u*g,t.restitution=c.restitution,t.surfaceVelocity=c.surfaceVelocity,t.frictionStiffness=c.frictionStiffness,t.frictionRelaxation=c.frictionRelaxation,t.stiffness=c.stiffness,t.relaxation=c.relaxation,t.contactSkinSize=c.contactSkinSize,t.enabledEquations=e.collisionResponse&&o.collisionResponse&&i.collisionResponse&&a.collisionResponse;var m=t[i.type|a.type],y=0;if(m){var v=i.sensor||a.sensor,b=t.frictionEquations.length;y=i.type<a.type?m.call(t,e,i,_,p,o,a,P,f,v):m.call(t,o,a,P,f,e,i,_,p,v);var x=t.frictionEquations.length-b;if(y){if(e.allowSleep&&e.type===d.DYNAMIC&&e.sleepState===d.SLEEPING&&o.sleepState===d.AWAKE&&o.type!==d.STATIC){r.squaredLength(o.velocity)+Math.pow(o.angularVelocity,2)>=2*Math.pow(o.sleepSpeedLimit,2)&&(e._wakeUpAfterNarrowphase=!0)}if(o.allowSleep&&o.type===d.DYNAMIC&&o.sleepState===d.SLEEPING&&e.sleepState===d.AWAKE&&e.type!==d.STATIC){r.squaredLength(e.velocity)+Math.pow(e.angularVelocity,2)>=2*Math.pow(e.sleepSpeedLimit,2)&&(o._wakeUpAfterNarrowphase=!0)}if(this.overlapKeeper.setOverlapping(e,i,o,a),this.has("beginContact")&&this.overlapKeeper.isNewOverlap(i,a)){var w=this.beginContactEvent;if(w.shapeA=i,w.shapeB=a,w.bodyA=e,w.bodyB=o,w.contactEquations.length=0,"number"==typeof y)for(var T=t.contactEquations.length-y;T<t.contactEquations.length;T++)w.contactEquations.push(t.contactEquations[T]);this.emit(w)}if("number"==typeof y&&x>1)for(var T=t.frictionEquations.length-x;T<t.frictionEquations.length;T++){var C=t.frictionEquations[T];C.setSlipForce(C.getSlipForce()/x)}}}}},s.prototype.addSpring=function(t){this.springs.push(t);var e=this.addSpringEvent;e.spring=t,this.emit(e),e.spring=null},s.prototype.removeSpring=function(t){var e=this.springs.indexOf(t);-1!==e&&v.splice(this.springs,e,1)},s.prototype.addBody=function(t){if(-1===this.bodies.indexOf(t)){this.bodies.push(t),t.world=this;var e=this.addBodyEvent;e.body=t,this.emit(e),e.body=null}},s.prototype.removeBody=function(t){if(this.stepping)this.bodiesToBeRemoved.push(t);else{t.world=null;var e=this.bodies.indexOf(t);-1!==e&&(v.splice(this.bodies,e,1),this.removeBodyEvent.body=t,t.resetConstraintVelocity(),this.emit(this.removeBodyEvent),this.removeBodyEvent.body=null)}},s.prototype.getBodyById=function(t){for(var e=this.bodies,i=0;i<e.length;i++){var s=e[i];if(s.id===t)return s}return!1},s.prototype.disableBodyCollision=function(t,e){this.disabledBodyCollisionPairs.push(t,e)},s.prototype.enableBodyCollision=function(t,e){for(var i=this.disabledBodyCollisionPairs,s=0;s<i.length;s+=2)if(i[s]===t&&i[s+1]===e||i[s+1]===t&&i[s]===e)return void i.splice(s,2)},s.prototype.clear=function(){this.time=0,this.solver&&this.solver.equations.length&&this.solver.removeAllEquations();for(var t=this.constraints,e=t.length-1;e>=0;e--)this.removeConstraint(t[e]);for(var i=this.bodies,e=i.length-1;e>=0;e--)this.removeBody(i[e]);for(var n=this.springs,e=n.length-1;e>=0;e--)this.removeSpring(n[e]);for(var r=this.contactMaterials,e=r.length-1;e>=0;e--)this.removeContactMaterial(r[e]);s.apply(this)};var C=r.create(),S=(r.fromValues(0,0),r.fromValues(0,0));s.prototype.hitTest=function(t,e,i){i=i||0;var s=new d({position:t}),n=new c,u=t,p=C,f=S;s.addShape(n);for(var g=this.narrowphase,m=[],y=0,v=e.length;y!==v;y++)for(var b=e[y],x=0,w=b.shapes.length;x!==w;x++){var _=b.shapes[x];r.rotate(p,_.position,b.angle),r.add(p,p,b.position);var P=_.angle+b.angle;(_ instanceof o&&g.circleParticle(b,_,p,P,s,n,u,0,!0)||_ instanceof a&&g.particleConvex(s,n,u,0,b,_,p,P,!0)||_ instanceof h&&g.particlePlane(s,n,u,0,b,_,p,P,!0)||_ instanceof l&&g.particleCapsule(s,n,u,0,b,_,p,P,!0)||_ instanceof c&&r.squaredLength(r.sub(f,p,t))<i*i)&&m.push(b)}return m},s.prototype.setGlobalStiffness=function(t){for(var e=this.constraints,i=0;i!==e.length;i++)for(var s=e[i],n=0;n!==s.equations.length;n++){var r=s.equations[n];r.stiffness=t,r.needsUpdate=!0}for(var o=this.contactMaterials,i=0;i!==o.length;i++){var s=o[i];s.stiffness=s.frictionStiffness=t}var s=this.defaultContactMaterial;s.stiffness=s.frictionStiffness=t},s.prototype.setGlobalRelaxation=function(t){for(var e=0;e!==this.constraints.length;e++)for(var i=this.constraints[e],s=0;s!==i.equations.length;s++){var n=i.equations[s];n.relaxation=t,n.needsUpdate=!0}for(var e=0;e!==this.contactMaterials.length;e++){var i=this.contactMaterials[e];i.relaxation=i.frictionRelaxation=t}var i=this.defaultContactMaterial;i.relaxation=i.frictionRelaxation=t};var A=new g,E=[];s.prototype.raycast=function(t,e){return e.getAABB(A),this.broadphase.aabbQuery(this,A,E),e.intersectBodies(t,E),E.length=0,t.hasHit()}},{"../../package.json":6,"../collision/AABB":7,"../collision/Broadphase":8,"../collision/Narrowphase":10,"../collision/Ray":11,"../collision/SAPBroadphase":13,"../constraints/Constraint":14,"../constraints/DistanceConstraint":15,"../constraints/GearConstraint":16,"../constraints/LockConstraint":17,"../constraints/PrismaticConstraint":18,"../constraints/RevoluteConstraint":19,"../events/EventEmitter":26,"../material/ContactMaterial":27,"../material/Material":28,"../math/vec2":30,"../objects/Body":31,"../objects/LinearSpring":32,"../objects/RotationalSpring":33,"../shapes/Capsule":38,"../shapes/Circle":39,"../shapes/Convex":40,"../shapes/Line":42,"../shapes/Particle":43,"../shapes/Plane":44,"../shapes/Shape":45,"../solver/GSSolver":46,"../solver/Solver":47,"../utils/OverlapKeeper":52,"../utils/Utils":57,"./IslandManager":59}]},{},[36])(36)})},function(t,e,i){(function(i){/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*
* @overview
*
* Phaser - http://phaser.io
*
* v2.6.2 "Kore Springs" - Built: Fri Aug 26 2016 01:03:19
*
* By Richard Davey http://www.photonstorm.com @photonstorm
*
* Phaser is a fun, free and fast 2D game framework for making HTML5 games
* for desktop and mobile web browsers, supporting Canvas and WebGL rendering.
*
* Phaser uses Pixi.js for rendering, created by Mat Groves http://matgroves.com @Doormat23
* Phaser uses p2.js for full-body physics, created by Stefan Hedman https://github.com/schteppe/p2.js @schteppe
* Phaser contains a port of N+ Physics, converted by Richard Davey, original by http://www.metanetsoftware.com
*
* Many thanks to Adam Saltsman (@ADAMATOMIC) for releasing Flixel, from which both Phaser and my love of framework development originate.
*
* Follow development at http://phaser.io and on our forum
*
* "If you want your children to be intelligent, read them fairy tales."
* "If you want them to be more intelligent, read them more fairy tales."
* -- Albert Einstein
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
(function(){function s(t,e){this._scaleFactor=t,this._deltaMode=e,this.originalEvent=null}var n=n||{VERSION:"2.6.2",GAMES:[],AUTO:0,CANVAS:1,WEBGL:2,HEADLESS:3,NONE:0,LEFT:1,RIGHT:2,UP:3,DOWN:4,SPRITE:0,BUTTON:1,IMAGE:2,GRAPHICS:3,TEXT:4,TILESPRITE:5,BITMAPTEXT:6,GROUP:7,RENDERTEXTURE:8,TILEMAP:9,TILEMAPLAYER:10,EMITTER:11,POLYGON:12,BITMAPDATA:13,CANVAS_FILTER:14,WEBGL_FILTER:15,ELLIPSE:16,SPRITEBATCH:17,RETROFONT:18,POINTER:19,ROPE:20,CIRCLE:21,RECTANGLE:22,LINE:23,MATRIX:24,POINT:25,ROUNDEDRECTANGLE:26,CREATURE:27,VIDEO:28,PENDING_ATLAS:-1,HORIZONTAL:0,VERTICAL:1,LANDSCAPE:0,PORTRAIT:1,ANGLE_UP:270,ANGLE_DOWN:90,ANGLE_LEFT:180,ANGLE_RIGHT:0,ANGLE_NORTH_EAST:315,ANGLE_NORTH_WEST:225,ANGLE_SOUTH_EAST:45,ANGLE_SOUTH_WEST:135,TOP_LEFT:0,TOP_CENTER:1,TOP_RIGHT:2,LEFT_TOP:3,LEFT_CENTER:4,LEFT_BOTTOM:5,CENTER:6,RIGHT_TOP:7,RIGHT_CENTER:8,RIGHT_BOTTOM:9,BOTTOM_LEFT:10,BOTTOM_CENTER:11,BOTTOM_RIGHT:12,blendModes:{NORMAL:0,ADD:1,MULTIPLY:2,SCREEN:3,OVERLAY:4,DARKEN:5,LIGHTEN:6,COLOR_DODGE:7,COLOR_BURN:8,HARD_LIGHT:9,SOFT_LIGHT:10,DIFFERENCE:11,EXCLUSION:12,HUE:13,SATURATION:14,COLOR:15,LUMINOSITY:16},scaleModes:{DEFAULT:0,LINEAR:0,NEAREST:1},PIXI:PIXI||{}};if(/**
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
Math.trunc||(Math.trunc=function(t){return t<0?Math.ceil(t):Math.floor(t)}),Function.prototype.bind||(Function.prototype.bind=function(){var t=Array.prototype.slice;return function(e){function i(){var r=n.concat(t.call(arguments));s.apply(this instanceof i?this:e,r)}var s=this,n=t.call(arguments,1);if("function"!=typeof s)throw new TypeError;return i.prototype=function t(e){if(e&&(t.prototype=e),!(this instanceof t))return new t}(s.prototype),i}}()),Array.isArray||(Array.isArray=function(t){return"[object Array]"===Object.prototype.toString.call(t)}),Array.prototype.forEach||(Array.prototype.forEach=function(t){"use strict";if(void 0===this||null===this)throw new TypeError;var e=Object(this),i=e.length>>>0;if("function"!=typeof t)throw new TypeError;for(var s=arguments.length>=2?arguments[1]:void 0,n=0;n<i;n++)n in e&&t.call(s,e[n],n,e)}),"function"!=typeof window.Uint32Array&&"object"!=typeof window.Uint32Array){var r=function(t){var e=new Array;window[t]=function(t){if("number"==typeof t){Array.call(this,t),this.length=t;for(var e=0;e<this.length;e++)this[e]=0}else{Array.call(this,t.length),this.length=t.length;for(var e=0;e<this.length;e++)this[e]=t[e]}},window[t].prototype=e,window[t].constructor=window[t]};r("Uint32Array"),r("Int16Array")}window.console||(window.console={},window.console.log=window.console.assert=function(){},window.console.warn=window.console.assert=function(){}),/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Utils={reverseString:function(t){return t.split("").reverse().join("")},getProperty:function(t,e){for(var i=e.split("."),s=i.pop(),n=i.length,r=1,o=i[0];r<n&&(t=t[o]);)o=i[r],r++;return t?t[s]:null},setProperty:function(t,e,i){for(var s=e.split("."),n=s.pop(),r=s.length,o=1,a=s[0];o<r&&(t=t[a]);)a=s[o],o++;return t&&(t[n]=i),t},chanceRoll:function(t){return void 0===t&&(t=50),t>0&&100*Math.random()<=t},randomChoice:function(t,e){return Math.random()<.5?t:e},parseDimension:function(t,e){var i=0,s=0;return"string"==typeof t?"%"===t.substr(-1)?(i=parseInt(t,10)/100,s=0===e?window.innerWidth*i:window.innerHeight*i):s=parseInt(t,10):s=t,s},pad:function(t,e,i,s){if(void 0===e)var e=0;if(void 0===i)var i=" ";if(void 0===s)var s=3;t=t.toString();var n=0;if(e+1>=t.length)switch(s){case 1:t=new Array(e+1-t.length).join(i)+t;break;case 3:var r=Math.ceil((n=e-t.length)/2),o=n-r;t=new Array(o+1).join(i)+t+new Array(r+1).join(i);break;default:t+=new Array(e+1-t.length).join(i)}return t},isPlainObject:function(t){if("object"!=typeof t||t.nodeType||t===t.window)return!1;try{if(t.constructor&&!{}.hasOwnProperty.call(t.constructor.prototype,"isPrototypeOf"))return!1}catch(t){return!1}return!0},extend:function(){var t,e,i,s,r,o,a=arguments[0]||{},h=1,l=arguments.length,c=!1;for("boolean"==typeof a&&(c=a,a=arguments[1]||{},h=2),l===h&&(a=this,--h);h<l;h++)if(null!=(t=arguments[h]))for(e in t)i=a[e],s=t[e],a!==s&&(c&&s&&(n.Utils.isPlainObject(s)||(r=Array.isArray(s)))?(r?(r=!1,o=i&&Array.isArray(i)?i:[]):o=i&&n.Utils.isPlainObject(i)?i:{},a[e]=n.Utils.extend(c,o,s)):void 0!==s&&(a[e]=s));return a},mixinPrototype:function(t,e,i){void 0===i&&(i=!1);for(var s=Object.keys(e),n=0;n<s.length;n++){var r=s[n],o=e[r];!i&&r in t||(!o||"function"!=typeof o.get&&"function"!=typeof o.set?t[r]=o:"function"==typeof o.clone?t[r]=o.clone():Object.defineProperty(t,r,o))}},mixin:function(t,e){if(!t||"object"!=typeof t)return e;for(var i in t){var s=t[i];if(!s.childNodes&&!s.cloneNode){var r=typeof t[i];t[i]&&"object"===r?typeof e[i]===r?e[i]=n.Utils.mixin(t[i],e[i]):e[i]=n.Utils.mixin(t[i],new s.constructor):e[i]=t[i]}}return e}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Circle=function(t,e,i){t=t||0,e=e||0,i=i||0,this.x=t,this.y=e,this._diameter=i,this._radius=0,i>0&&(this._radius=.5*i),this.type=n.CIRCLE},n.Circle.prototype={circumference:function(){return Math.PI*this._radius*2},random:function(t){void 0===t&&(t=new n.Point);var e=2*Math.PI*Math.random(),i=Math.random()+Math.random(),s=i>1?2-i:i,r=s*Math.cos(e),o=s*Math.sin(e);return t.x=this.x+r*this.radius,t.y=this.y+o*this.radius,t},getBounds:function(){return new n.Rectangle(this.x-this.radius,this.y-this.radius,this.diameter,this.diameter)},setTo:function(t,e,i){return this.x=t,this.y=e,this._diameter=i,this._radius=.5*i,this},copyFrom:function(t){return this.setTo(t.x,t.y,t.diameter)},copyTo:function(t){return t.x=this.x,t.y=this.y,t.diameter=this._diameter,t},distance:function(t,e){var i=n.Math.distance(this.x,this.y,t.x,t.y);return e?Math.round(i):i},clone:function(t){return void 0===t||null===t?t=new n.Circle(this.x,this.y,this.diameter):t.setTo(this.x,this.y,this.diameter),t},contains:function(t,e){return n.Circle.contains(this,t,e)},circumferencePoint:function(t,e,i){return n.Circle.circumferencePoint(this,t,e,i)},offset:function(t,e){return this.x+=t,this.y+=e,this},offsetPoint:function(t){return this.offset(t.x,t.y)},toString:function(){return"[{Phaser.Circle (x="+this.x+" y="+this.y+" diameter="+this.diameter+" radius="+this.radius+")}]"}},n.Circle.prototype.constructor=n.Circle,Object.defineProperty(n.Circle.prototype,"diameter",{get:function(){return this._diameter},set:function(t){t>0&&(this._diameter=t,this._radius=.5*t)}}),Object.defineProperty(n.Circle.prototype,"radius",{get:function(){return this._radius},set:function(t){t>0&&(this._radius=t,this._diameter=2*t)}}),Object.defineProperty(n.Circle.prototype,"left",{get:function(){return this.x-this._radius},set:function(t){t>this.x?(this._radius=0,this._diameter=0):this.radius=this.x-t}}),Object.defineProperty(n.Circle.prototype,"right",{get:function(){return this.x+this._radius},set:function(t){t<this.x?(this._radius=0,this._diameter=0):this.radius=t-this.x}}),Object.defineProperty(n.Circle.prototype,"top",{get:function(){return this.y-this._radius},set:function(t){t>this.y?(this._radius=0,this._diameter=0):this.radius=this.y-t}}),Object.defineProperty(n.Circle.prototype,"bottom",{get:function(){return this.y+this._radius},set:function(t){t<this.y?(this._radius=0,this._diameter=0):this.radius=t-this.y}}),Object.defineProperty(n.Circle.prototype,"area",{get:function(){return this._radius>0?Math.PI*this._radius*this._radius:0}}),Object.defineProperty(n.Circle.prototype,"empty",{get:function(){return 0===this._diameter},set:function(t){!0===t&&this.setTo(0,0,0)}}),n.Circle.contains=function(t,e,i){if(t.radius>0&&e>=t.left&&e<=t.right&&i>=t.top&&i<=t.bottom){return(t.x-e)*(t.x-e)+(t.y-i)*(t.y-i)<=t.radius*t.radius}return!1},n.Circle.equals=function(t,e){return t.x===e.x&&t.y===e.y&&t.diameter===e.diameter},n.Circle.intersects=function(t,e){return n.Math.distance(t.x,t.y,e.x,e.y)<=t.radius+e.radius},n.Circle.circumferencePoint=function(t,e,i,s){return void 0===i&&(i=!1),void 0===s&&(s=new n.Point),!0===i&&(e=n.Math.degToRad(e)),s.x=t.x+t.radius*Math.cos(e),s.y=t.y+t.radius*Math.sin(e),s},n.Circle.intersectsRectangle=function(t,e){var i=Math.abs(t.x-e.x-e.halfWidth);if(i>e.halfWidth+t.radius)return!1;var s=Math.abs(t.y-e.y-e.halfHeight);if(s>e.halfHeight+t.radius)return!1;if(i<=e.halfWidth||s<=e.halfHeight)return!0;var n=i-e.halfWidth,r=s-e.halfHeight;return n*n+r*r<=t.radius*t.radius},PIXI.Circle=n.Circle,/**
* @author Richard Davey <[email protected]>
* @author Chad Engler <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Ellipse=function(t,e,i,s){t=t||0,e=e||0,i=i||0,s=s||0,this.x=t,this.y=e,this.width=i,this.height=s,this.type=n.ELLIPSE},n.Ellipse.prototype={setTo:function(t,e,i,s){return this.x=t,this.y=e,this.width=i,this.height=s,this},getBounds:function(){return new n.Rectangle(this.x-this.width,this.y-this.height,this.width,this.height)},copyFrom:function(t){return this.setTo(t.x,t.y,t.width,t.height)},copyTo:function(t){return t.x=this.x,t.y=this.y,t.width=this.width,t.height=this.height,t},clone:function(t){return void 0===t||null===t?t=new n.Ellipse(this.x,this.y,this.width,this.height):t.setTo(this.x,this.y,this.width,this.height),t},contains:function(t,e){return n.Ellipse.contains(this,t,e)},random:function(t){void 0===t&&(t=new n.Point);var e=Math.random()*Math.PI*2,i=Math.random();return t.x=Math.sqrt(i)*Math.cos(e),t.y=Math.sqrt(i)*Math.sin(e),t.x=this.x+t.x*this.width/2,t.y=this.y+t.y*this.height/2,t},toString:function(){return"[{Phaser.Ellipse (x="+this.x+" y="+this.y+" width="+this.width+" height="+this.height+")}]"}},n.Ellipse.prototype.constructor=n.Ellipse,Object.defineProperty(n.Ellipse.prototype,"left",{get:function(){return this.x},set:function(t){this.x=t}}),Object.defineProperty(n.Ellipse.prototype,"right",{get:function(){return this.x+this.width},set:function(t){t<this.x?this.width=0:this.width=t-this.x}}),Object.defineProperty(n.Ellipse.prototype,"top",{get:function(){return this.y},set:function(t){this.y=t}}),Object.defineProperty(n.Ellipse.prototype,"bottom",{get:function(){return this.y+this.height},set:function(t){t<this.y?this.height=0:this.height=t-this.y}}),Object.defineProperty(n.Ellipse.prototype,"empty",{get:function(){return 0===this.width||0===this.height},set:function(t){!0===t&&this.setTo(0,0,0,0)}}),n.Ellipse.contains=function(t,e,i){if(t.width<=0||t.height<=0)return!1;var s=(e-t.x)/t.width-.5,n=(i-t.y)/t.height-.5;return s*=s,n*=n,s+n<.25},PIXI.Ellipse=n.Ellipse,/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Line=function(t,e,i,s){t=t||0,e=e||0,i=i||0,s=s||0,this.start=new n.Point(t,e),this.end=new n.Point(i,s),this.type=n.LINE},n.Line.prototype={setTo:function(t,e,i,s){return this.start.setTo(t,e),this.end.setTo(i,s),this},fromSprite:function(t,e,i){return void 0===i&&(i=!1),i?this.setTo(t.center.x,t.center.y,e.center.x,e.center.y):this.setTo(t.x,t.y,e.x,e.y)},fromAngle:function(t,e,i,s){return this.start.setTo(t,e),this.end.setTo(t+Math.cos(i)*s,e+Math.sin(i)*s),this},rotate:function(t,e){var i=(this.start.x+this.end.x)/2,s=(this.start.y+this.end.y)/2;return this.start.rotate(i,s,t,e),this.end.rotate(i,s,t,e),this},rotateAround:function(t,e,i,s){return this.start.rotate(t,e,i,s),this.end.rotate(t,e,i,s),this},intersects:function(t,e,i){return n.Line.intersectsPoints(this.start,this.end,t.start,t.end,e,i)},reflect:function(t){return n.Line.reflect(this,t)},midPoint:function(t){return void 0===t&&(t=new n.Point),t.x=(this.start.x+this.end.x)/2,t.y=(this.start.y+this.end.y)/2,t},centerOn:function(t,e){var i=(this.start.x+this.end.x)/2,s=(this.start.y+this.end.y)/2,n=t-i,r=e-s;this.start.add(n,r),this.end.add(n,r)},pointOnLine:function(t,e){return(t-this.start.x)*(this.end.y-this.start.y)==(this.end.x-this.start.x)*(e-this.start.y)},pointOnSegment:function(t,e){var i=Math.min(this.start.x,this.end.x),s=Math.max(this.start.x,this.end.x),n=Math.min(this.start.y,this.end.y),r=Math.max(this.start.y,this.end.y);return this.pointOnLine(t,e)&&t>=i&&t<=s&&e>=n&&e<=r},random:function(t){void 0===t&&(t=new n.Point);var e=Math.random();return t.x=this.start.x+e*(this.end.x-this.start.x),t.y=this.start.y+e*(this.end.y-this.start.y),t},coordinatesOnLine:function(t,e){void 0===t&&(t=1),void 0===e&&(e=[]);var i=Math.round(this.start.x),s=Math.round(this.start.y),n=Math.round(this.end.x),r=Math.round(this.end.y),o=Math.abs(n-i),a=Math.abs(r-s),h=i<n?1:-1,l=s<r?1:-1,c=o-a;e.push([i,s]);for(var u=1;i!==n||s!==r;){var d=c<<1;d>-a&&(c-=a,i+=h),d<o&&(c+=o,s+=l),u%t==0&&e.push([i,s]),u++}return e},clone:function(t){return void 0===t||null===t?t=new n.Line(this.start.x,this.start.y,this.end.x,this.end.y):t.setTo(this.start.x,this.start.y,this.end.x,this.end.y),t}},Object.defineProperty(n.Line.prototype,"length",{get:function(){return Math.sqrt((this.end.x-this.start.x)*(this.end.x-this.start.x)+(this.end.y-this.start.y)*(this.end.y-this.start.y))}}),Object.defineProperty(n.Line.prototype,"angle",{get:function(){return Math.atan2(this.end.y-this.start.y,this.end.x-this.start.x)}}),Object.defineProperty(n.Line.prototype,"slope",{get:function(){return(this.end.y-this.start.y)/(this.end.x-this.start.x)}}),Object.defineProperty(n.Line.prototype,"perpSlope",{get:function(){return-(this.end.x-this.start.x)/(this.end.y-this.start.y)}}),Object.defineProperty(n.Line.prototype,"x",{get:function(){return Math.min(this.start.x,this.end.x)}}),Object.defineProperty(n.Line.prototype,"y",{get:function(){return Math.min(this.start.y,this.end.y)}}),Object.defineProperty(n.Line.prototype,"left",{get:function(){return Math.min(this.start.x,this.end.x)}}),Object.defineProperty(n.Line.prototype,"right",{get:function(){return Math.max(this.start.x,this.end.x)}}),Object.defineProperty(n.Line.prototype,"top",{get:function(){return Math.min(this.start.y,this.end.y)}}),Object.defineProperty(n.Line.prototype,"bottom",{get:function(){return Math.max(this.start.y,this.end.y)}}),Object.defineProperty(n.Line.prototype,"width",{get:function(){return Math.abs(this.start.x-this.end.x)}}),Object.defineProperty(n.Line.prototype,"height",{get:function(){return Math.abs(this.start.y-this.end.y)}}),Object.defineProperty(n.Line.prototype,"normalX",{get:function(){return Math.cos(this.angle-1.5707963267948966)}}),Object.defineProperty(n.Line.prototype,"normalY",{get:function(){return Math.sin(this.angle-1.5707963267948966)}}),Object.defineProperty(n.Line.prototype,"normalAngle",{get:function(){return n.Math.wrap(this.angle-1.5707963267948966,-Math.PI,Math.PI)}}),n.Line.intersectsPoints=function(t,e,i,s,r,o){void 0===r&&(r=!0),void 0===o&&(o=new n.Point);var a=e.y-t.y,h=s.y-i.y,l=t.x-e.x,c=i.x-s.x,u=e.x*t.y-t.x*e.y,d=s.x*i.y-i.x*s.y,p=a*c-h*l;if(0===p)return null;if(o.x=(l*d-c*u)/p,o.y=(h*u-a*d)/p,r){var f=(s.y-i.y)*(e.x-t.x)-(s.x-i.x)*(e.y-t.y),g=((s.x-i.x)*(t.y-i.y)-(s.y-i.y)*(t.x-i.x))/f,m=((e.x-t.x)*(t.y-i.y)-(e.y-t.y)*(t.x-i.x))/f;return g>=0&&g<=1&&m>=0&&m<=1?o:null}return o},n.Line.intersects=function(t,e,i,s){return n.Line.intersectsPoints(t.start,t.end,e.start,e.end,i,s)},n.Line.intersectsRectangle=function(t,e){if(!n.Rectangle.intersects(t,e))return!1;var i=t.start.x,s=t.start.y,r=t.end.x,o=t.end.y,a=e.x,h=e.y,l=e.right,c=e.bottom,u=0;if(i>=a&&i<=l&&s>=h&&s<=c||r>=a&&r<=l&&o>=h&&o<=c)return!0;if(i<a&&r>=a){if((u=s+(o-s)*(a-i)/(r-i))>h&&u<=c)return!0}else if(i>l&&r<=l&&(u=s+(o-s)*(l-i)/(r-i))>=h&&u<=c)return!0;if(s<h&&o>=h){if((u=i+(r-i)*(h-s)/(o-s))>=a&&u<=l)return!0}else if(s>c&&o<=c&&(u=i+(r-i)*(c-s)/(o-s))>=a&&u<=l)return!0;return!1},n.Line.reflect=function(t,e){return 2*e.normalAngle-3.141592653589793-t.angle},/**
* @author Mat Groves http://matgroves.com/ @Doormat23
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Matrix=function(t,e,i,s,r,o){void 0!==t&&null!==t||(t=1),void 0!==e&&null!==e||(e=0),void 0!==i&&null!==i||(i=0),void 0!==s&&null!==s||(s=1),void 0!==r&&null!==r||(r=0),void 0!==o&&null!==o||(o=0),this.a=t,this.b=e,this.c=i,this.d=s,this.tx=r,this.ty=o,this.type=n.MATRIX},n.Matrix.prototype={fromArray:function(t){return this.setTo(t[0],t[1],t[3],t[4],t[2],t[5])},setTo:function(t,e,i,s,n,r){return this.a=t,this.b=e,this.c=i,this.d=s,this.tx=n,this.ty=r,this},clone:function(t){return void 0===t||null===t?t=new n.Matrix(this.a,this.b,this.c,this.d,this.tx,this.ty):(t.a=this.a,t.b=this.b,t.c=this.c,t.d=this.d,t.tx=this.tx,t.ty=this.ty),t},copyTo:function(t){return t.copyFrom(this),t},copyFrom:function(t){return this.a=t.a,this.b=t.b,this.c=t.c,this.d=t.d,this.tx=t.tx,this.ty=t.ty,this},toArray:function(t,e){return void 0===e&&(e=new PIXI.Float32Array(9)),t?(e[0]=this.a,e[1]=this.b,e[2]=0,e[3]=this.c,e[4]=this.d,e[5]=0,e[6]=this.tx,e[7]=this.ty,e[8]=1):(e[0]=this.a,e[1]=this.c,e[2]=this.tx,e[3]=this.b,e[4]=this.d,e[5]=this.ty,e[6]=0,e[7]=0,e[8]=1),e},apply:function(t,e){return void 0===e&&(e=new n.Point),e.x=this.a*t.x+this.c*t.y+this.tx,e.y=this.b*t.x+this.d*t.y+this.ty,e},applyInverse:function(t,e){void 0===e&&(e=new n.Point);var i=1/(this.a*this.d+this.c*-this.b),s=t.x,r=t.y;return e.x=this.d*i*s+-this.c*i*r+(this.ty*this.c-this.tx*this.d)*i,e.y=this.a*i*r+-this.b*i*s+(-this.ty*this.a+this.tx*this.b)*i,e},translate:function(t,e){return this.tx+=t,this.ty+=e,this},scale:function(t,e){return this.a*=t,this.d*=e,this.c*=t,this.b*=e,this.tx*=t,this.ty*=e,this},rotate:function(t){var e=Math.cos(t),i=Math.sin(t),s=this.a,n=this.c,r=this.tx;return this.a=s*e-this.b*i,this.b=s*i+this.b*e,this.c=n*e-this.d*i,this.d=n*i+this.d*e,this.tx=r*e-this.ty*i,this.ty=r*i+this.ty*e,this},append:function(t){var e=this.a,i=this.b,s=this.c,n=this.d;return this.a=t.a*e+t.b*s,this.b=t.a*i+t.b*n,this.c=t.c*e+t.d*s,this.d=t.c*i+t.d*n,this.tx=t.tx*e+t.ty*s+this.tx,this.ty=t.tx*i+t.ty*n+this.ty,this},identity:function(){return this.setTo(1,0,0,1,0,0)}},n.identityMatrix=new n.Matrix,PIXI.Matrix=n.Matrix,PIXI.identityMatrix=n.identityMatrix,/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Point=function(t,e){t=t||0,e=e||0,this.x=t,this.y=e,this.type=n.POINT},n.Point.prototype={copyFrom:function(t){return this.setTo(t.x,t.y)},invert:function(){return this.setTo(this.y,this.x)},setTo:function(t,e){return this.x=t||0,this.y=e||(0!==e?this.x:0),this},set:function(t,e){return this.x=t||0,this.y=e||(0!==e?this.x:0),this},add:function(t,e){return this.x+=t,this.y+=e,this},subtract:function(t,e){return this.x-=t,this.y-=e,this},multiply:function(t,e){return this.x*=t,this.y*=e,this},divide:function(t,e){return this.x/=t,this.y/=e,this},clampX:function(t,e){return this.x=n.Math.clamp(this.x,t,e),this},clampY:function(t,e){return this.y=n.Math.clamp(this.y,t,e),this},clamp:function(t,e){return this.x=n.Math.clamp(this.x,t,e),this.y=n.Math.clamp(this.y,t,e),this},clone:function(t){return void 0===t||null===t?t=new n.Point(this.x,this.y):t.setTo(this.x,this.y),t},copyTo:function(t){return t.x=this.x,t.y=this.y,t},distance:function(t,e){return n.Point.distance(this,t,e)},equals:function(t){return t.x===this.x&&t.y===this.y},angle:function(t,e){return void 0===e&&(e=!1),e?n.Math.radToDeg(Math.atan2(t.y-this.y,t.x-this.x)):Math.atan2(t.y-this.y,t.x-this.x)},rotate:function(t,e,i,s,r){return n.Point.rotate(this,t,e,i,s,r)},getMagnitude:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},getMagnitudeSq:function(){return this.x*this.x+this.y*this.y},setMagnitude:function(t){return this.normalize().multiply(t,t)},normalize:function(){if(!this.isZero()){var t=this.getMagnitude();this.x/=t,this.y/=t}return this},isZero:function(){return 0===this.x&&0===this.y},dot:function(t){return this.x*t.x+this.y*t.y},cross:function(t){return this.x*t.y-this.y*t.x},perp:function(){return this.setTo(-this.y,this.x)},rperp:function(){return this.setTo(this.y,-this.x)},normalRightHand:function(){return this.setTo(-1*this.y,this.x)},floor:function(){return this.setTo(Math.floor(this.x),Math.floor(this.y))},ceil:function(){return this.setTo(Math.ceil(this.x),Math.ceil(this.y))},toString:function(){return"[{Point (x="+this.x+" y="+this.y+")}]"}},n.Point.prototype.constructor=n.Point,n.Point.add=function(t,e,i){return void 0===i&&(i=new n.Point),i.x=t.x+e.x,i.y=t.y+e.y,i},n.Point.subtract=function(t,e,i){return void 0===i&&(i=new n.Point),i.x=t.x-e.x,i.y=t.y-e.y,i},n.Point.multiply=function(t,e,i){return void 0===i&&(i=new n.Point),i.x=t.x*e.x,i.y=t.y*e.y,i},n.Point.divide=function(t,e,i){return void 0===i&&(i=new n.Point),i.x=t.x/e.x,i.y=t.y/e.y,i},n.Point.equals=function(t,e){return t.x===e.x&&t.y===e.y},n.Point.angle=function(t,e){return Math.atan2(t.y-e.y,t.x-e.x)},n.Point.negative=function(t,e){return void 0===e&&(e=new n.Point),e.setTo(-t.x,-t.y)},n.Point.multiplyAdd=function(t,e,i,s){return void 0===s&&(s=new n.Point),s.setTo(t.x+e.x*i,t.y+e.y*i)},n.Point.interpolate=function(t,e,i,s){return void 0===s&&(s=new n.Point),s.setTo(t.x+(e.x-t.x)*i,t.y+(e.y-t.y)*i)},n.Point.perp=function(t,e){return void 0===e&&(e=new n.Point),e.setTo(-t.y,t.x)},n.Point.rperp=function(t,e){return void 0===e&&(e=new n.Point),e.setTo(t.y,-t.x)},n.Point.distance=function(t,e,i){var s=n.Math.distance(t.x,t.y,e.x,e.y);return i?Math.round(s):s},n.Point.project=function(t,e,i){void 0===i&&(i=new n.Point);var s=t.dot(e)/e.getMagnitudeSq();return 0!==s&&i.setTo(s*e.x,s*e.y),i},n.Point.projectUnit=function(t,e,i){void 0===i&&(i=new n.Point);var s=t.dot(e);return 0!==s&&i.setTo(s*e.x,s*e.y),i},n.Point.normalRightHand=function(t,e){return void 0===e&&(e=new n.Point),e.setTo(-1*t.y,t.x)},n.Point.normalize=function(t,e){void 0===e&&(e=new n.Point);var i=t.getMagnitude();return 0!==i&&e.setTo(t.x/i,t.y/i),e},n.Point.rotate=function(t,e,i,s,r,o){if(r&&(s=n.Math.degToRad(s)),void 0===o){t.subtract(e,i);var a=Math.sin(s),h=Math.cos(s),l=h*t.x-a*t.y,c=a*t.x+h*t.y;t.x=l+e,t.y=c+i}else{var u=s+Math.atan2(t.y-i,t.x-e);t.x=e+o*Math.cos(u),t.y=i+o*Math.sin(u)}return t},n.Point.centroid=function(t,e){if(void 0===e&&(e=new n.Point),"[object Array]"!==Object.prototype.toString.call(t))throw new Error("Phaser.Point. Parameter 'points' must be an array");var i=t.length;if(i<1)throw new Error("Phaser.Point. Parameter 'points' array must not be empty");if(1===i)return e.copyFrom(t[0]),e;for(var s=0;s<i;s++)n.Point.add(e,t[s],e);return e.divide(i,i),e},n.Point.parse=function(t,e,i){e=e||"x",i=i||"y";var s=new n.Point;return t[e]&&(s.x=parseInt(t[e],10)),t[i]&&(s.y=parseInt(t[i],10)),s},PIXI.Point=n.Point,/**
* @author Richard Davey <[email protected]>
* @author Adrien Brault <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Polygon=function(){this.area=0,this._points=[],arguments.length>0&&this.setTo.apply(this,arguments),this.closed=!0,this.flattened=!1,this.type=n.POLYGON},n.Polygon.prototype={toNumberArray:function(t){void 0===t&&(t=[]);for(var e=0;e<this._points.length;e++)"number"==typeof this._points[e]?(t.push(this._points[e]),t.push(this._points[e+1]),e++):(t.push(this._points[e].x),t.push(this._points[e].y));return t},flatten:function(){return this._points=this.toNumberArray(),this.flattened=!0,this},clone:function(t){var e=this._points.slice();return void 0===t||null===t?t=new n.Polygon(e):t.setTo(e),t},contains:function(t,e){var i=!1;if(this.flattened)for(var s=-2,n=this._points.length-2;(s+=2)<this._points.length;n=s){var r=this._points[s],o=this._points[s+1],a=this._points[n],h=this._points[n+1];(o<=e&&e<h||h<=e&&e<o)&&t<(a-r)*(e-o)/(h-o)+r&&(i=!i)}else for(var s=-1,n=this._points.length-1;++s<this._points.length;n=s){var r=this._points[s].x,o=this._points[s].y,a=this._points[n].x,h=this._points[n].y;(o<=e&&e<h||h<=e&&e<o)&&t<(a-r)*(e-o)/(h-o)+r&&(i=!i)}return i},setTo:function(t){if(this.area=0,this._points=[],arguments.length>0){Array.isArray(t)||(t=Array.prototype.slice.call(arguments));for(var e=Number.MAX_VALUE,i=0,s=t.length;i<s;i++){if("number"==typeof t[i]){var n=new PIXI.Point(t[i],t[i+1]);i++}else if(Array.isArray(t[i]))var n=new PIXI.Point(t[i][0],t[i][1]);else var n=new PIXI.Point(t[i].x,t[i].y);this._points.push(n),n.y<e&&(e=n.y)}this.calculateArea(e)}return this},calculateArea:function(t){for(var e,i,s,n,r=0,o=this._points.length;r<o;r++)e=this._points[r],i=r===o-1?this._points[0]:this._points[r+1],s=(e.y-t+(i.y-t))/2,n=e.x-i.x,this.area+=s*n;return this.area}},n.Polygon.prototype.constructor=n.Polygon,Object.defineProperty(n.Polygon.prototype,"points",{get:function(){return this._points},set:function(t){null!=t?this.setTo(t):this.setTo()}}),PIXI.Polygon=n.Polygon,/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Rectangle=function(t,e,i,s){t=t||0,e=e||0,i=i||0,s=s||0,this.x=t,this.y=e,this.width=i,this.height=s,this.type=n.RECTANGLE},n.Rectangle.prototype={offset:function(t,e){return this.x+=t,this.y+=e,this},offsetPoint:function(t){return this.offset(t.x,t.y)},setTo:function(t,e,i,s){return this.x=t,this.y=e,this.width=i,this.height=s,this},scale:function(t,e){return void 0===e&&(e=t),this.width*=t,this.height*=e,this},centerOn:function(t,e){return this.centerX=t,this.centerY=e,this},floor:function(){this.x=Math.floor(this.x),this.y=Math.floor(this.y)},floorAll:function(){this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.width=Math.floor(this.width),this.height=Math.floor(this.height)},ceil:function(){this.x=Math.ceil(this.x),this.y=Math.ceil(this.y)},ceilAll:function(){this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.width=Math.ceil(this.width),this.height=Math.ceil(this.height)},copyFrom:function(t){return this.setTo(t.x,t.y,t.width,t.height)},copyTo:function(t){return t.x=this.x,t.y=this.y,t.width=this.width,t.height=this.height,t},inflate:function(t,e){return n.Rectangle.inflate(this,t,e)},size:function(t){return n.Rectangle.size(this,t)},resize:function(t,e){return this.width=t,this.height=e,this},clone:function(t){return n.Rectangle.clone(this,t)},contains:function(t,e){return n.Rectangle.contains(this,t,e)},containsRect:function(t){return n.Rectangle.containsRect(t,this)},equals:function(t){return n.Rectangle.equals(this,t)},intersection:function(t,e){return n.Rectangle.intersection(this,t,e)},intersects:function(t){return n.Rectangle.intersects(this,t)},intersectsRaw:function(t,e,i,s,r){return n.Rectangle.intersectsRaw(this,t,e,i,s,r)},union:function(t,e){return n.Rectangle.union(this,t,e)},random:function(t){return void 0===t&&(t=new n.Point),t.x=this.randomX,t.y=this.randomY,t},getPoint:function(t,e){switch(void 0===e&&(e=new n.Point),t){default:case n.TOP_LEFT:return e.set(this.x,this.y);case n.TOP_CENTER:return e.set(this.centerX,this.y);case n.TOP_RIGHT:return e.set(this.right,this.y);case n.LEFT_CENTER:return e.set(this.x,this.centerY);case n.CENTER:return e.set(this.centerX,this.centerY);case n.RIGHT_CENTER:return e.set(this.right,this.centerY);case n.BOTTOM_LEFT:return e.set(this.x,this.bottom);case n.BOTTOM_CENTER:return e.set(this.centerX,this.bottom);case n.BOTTOM_RIGHT:return e.set(this.right,this.bottom)}},toString:function(){return"[{Rectangle (x="+this.x+" y="+this.y+" width="+this.width+" height="+this.height+" empty="+this.empty+")}]"}},Object.defineProperty(n.Rectangle.prototype,"halfWidth",{get:function(){return Math.round(this.width/2)}}),Object.defineProperty(n.Rectangle.prototype,"halfHeight",{get:function(){return Math.round(this.height/2)}}),Object.defineProperty(n.Rectangle.prototype,"bottom",{get:function(){return this.y+this.height},set:function(t){t<=this.y?this.height=0:this.height=t-this.y}}),Object.defineProperty(n.Rectangle.prototype,"bottomLeft",{get:function(){return new n.Point(this.x,this.bottom)},set:function(t){this.x=t.x,this.bottom=t.y}}),Object.defineProperty(n.Rectangle.prototype,"bottomRight",{get:function(){return new n.Point(this.right,this.bottom)},set:function(t){this.right=t.x,this.bottom=t.y}}),Object.defineProperty(n.Rectangle.prototype,"left",{get:function(){return this.x},set:function(t){t>=this.right?this.width=0:this.width=this.right-t,this.x=t}}),Object.defineProperty(n.Rectangle.prototype,"right",{get:function(){return this.x+this.width},set:function(t){t<=this.x?this.width=0:this.width=t-this.x}}),Object.defineProperty(n.Rectangle.prototype,"volume",{get:function(){return this.width*this.height}}),Object.defineProperty(n.Rectangle.prototype,"perimeter",{get:function(){return 2*this.width+2*this.height}}),Object.defineProperty(n.Rectangle.prototype,"centerX",{get:function(){return this.x+this.halfWidth},set:function(t){this.x=t-this.halfWidth}}),Object.defineProperty(n.Rectangle.prototype,"centerY",{get:function(){return this.y+this.halfHeight},set:function(t){this.y=t-this.halfHeight}}),Object.defineProperty(n.Rectangle.prototype,"randomX",{get:function(){return this.x+Math.random()*this.width}}),Object.defineProperty(n.Rectangle.prototype,"randomY",{get:function(){return this.y+Math.random()*this.height}}),Object.defineProperty(n.Rectangle.prototype,"top",{get:function(){return this.y},set:function(t){t>=this.bottom?(this.height=0,this.y=t):this.height=this.bottom-t}}),Object.defineProperty(n.Rectangle.prototype,"topLeft",{get:function(){return new n.Point(this.x,this.y)},set:function(t){this.x=t.x,this.y=t.y}}),Object.defineProperty(n.Rectangle.prototype,"topRight",{get:function(){return new n.Point(this.x+this.width,this.y)},set:function(t){this.right=t.x,this.y=t.y}}),Object.defineProperty(n.Rectangle.prototype,"empty",{get:function(){return!this.width||!this.height},set:function(t){!0===t&&this.setTo(0,0,0,0)}}),n.Rectangle.prototype.constructor=n.Rectangle,n.Rectangle.inflate=function(t,e,i){return t.x-=e,t.width+=2*e,t.y-=i,t.height+=2*i,t},n.Rectangle.inflatePoint=function(t,e){return n.Rectangle.inflate(t,e.x,e.y)},n.Rectangle.size=function(t,e){return void 0===e||null===e?e=new n.Point(t.width,t.height):e.setTo(t.width,t.height),e},n.Rectangle.clone=function(t,e){return void 0===e||null===e?e=new n.Rectangle(t.x,t.y,t.width,t.height):e.setTo(t.x,t.y,t.width,t.height),e},n.Rectangle.contains=function(t,e,i){return!(t.width<=0||t.height<=0)&&(e>=t.x&&e<t.right&&i>=t.y&&i<t.bottom)},n.Rectangle.containsRaw=function(t,e,i,s,n,r){return n>=t&&n<t+i&&r>=e&&r<e+s},n.Rectangle.containsPoint=function(t,e){return n.Rectangle.contains(t,e.x,e.y)},n.Rectangle.containsRect=function(t,e){return!(t.volume>e.volume)&&(t.x>=e.x&&t.y>=e.y&&t.right<e.right&&t.bottom<e.bottom)},n.Rectangle.equals=function(t,e){return t.x===e.x&&t.y===e.y&&t.width===e.width&&t.height===e.height},n.Rectangle.sameDimensions=function(t,e){return t.width===e.width&&t.height===e.height},n.Rectangle.intersection=function(t,e,i){return void 0===i&&(i=new n.Rectangle),n.Rectangle.intersects(t,e)&&(i.x=Math.max(t.x,e.x),i.y=Math.max(t.y,e.y),i.width=Math.min(t.right,e.right)-i.x,i.height=Math.min(t.bottom,e.bottom)-i.y),i},n.Rectangle.intersects=function(t,e){return!(t.width<=0||t.height<=0||e.width<=0||e.height<=0)&&!(t.right<e.x||t.bottom<e.y||t.x>e.right||t.y>e.bottom)},n.Rectangle.intersectsRaw=function(t,e,i,s,n,r){return void 0===r&&(r=0),!(e>t.right+r||i<t.left-r||s>t.bottom+r||n<t.top-r)},n.Rectangle.union=function(t,e,i){return void 0===i&&(i=new n.Rectangle),i.setTo(Math.min(t.x,e.x),Math.min(t.y,e.y),Math.max(t.right,e.right)-Math.min(t.left,e.left),Math.max(t.bottom,e.bottom)-Math.min(t.top,e.top))},n.Rectangle.aabb=function(t,e){void 0===e&&(e=new n.Rectangle);var i=Number.NEGATIVE_INFINITY,s=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY,o=Number.POSITIVE_INFINITY;return t.forEach(function(t){t.x>i&&(i=t.x),t.x<s&&(s=t.x),t.y>r&&(r=t.y),t.y<o&&(o=t.y)}),e.setTo(s,o,i-s,r-o),e},PIXI.Rectangle=n.Rectangle,PIXI.EmptyRectangle=new n.Rectangle(0,0,0,0),/**
* @author Mat Groves http://matgroves.com/
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.RoundedRectangle=function(t,e,i,s,r){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===s&&(s=0),void 0===r&&(r=20),this.x=t,this.y=e,this.width=i,this.height=s,this.radius=r||20,this.type=n.ROUNDEDRECTANGLE},n.RoundedRectangle.prototype={clone:function(){return new n.RoundedRectangle(this.x,this.y,this.width,this.height,this.radius)},contains:function(t,e){if(this.width<=0||this.height<=0)return!1;var i=this.x;if(t>=i&&t<=i+this.width){var s=this.y;if(e>=s&&e<=s+this.height)return!0}return!1}},n.RoundedRectangle.prototype.constructor=n.RoundedRectangle,PIXI.RoundedRectangle=n.RoundedRectangle,/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Camera=function(t,e,i,s,r,o){this.game=t,this.world=t.world,this.id=0,this.view=new n.Rectangle(i,s,r,o),this.bounds=new n.Rectangle(i,s,r,o),this.deadzone=null,this.visible=!0,this.roundPx=!0,this.atLimit={x:!1,y:!1},this.target=null,this.displayObject=null,this.scale=null,this.totalInView=0,this.lerp=new n.Point(1,1),this.onShakeComplete=new n.Signal,this.onFlashComplete=new n.Signal,this.onFadeComplete=new n.Signal,this.fx=null,this._targetPosition=new n.Point,this._edge=0,this._position=new n.Point,this._shake={intensity:0,duration:0,horizontal:!1,vertical:!1,shakeBounds:!0,x:0,y:0},this._fxDuration=0,this._fxType=0},n.Camera.FOLLOW_LOCKON=0,n.Camera.FOLLOW_PLATFORMER=1,n.Camera.FOLLOW_TOPDOWN=2,n.Camera.FOLLOW_TOPDOWN_TIGHT=3,n.Camera.SHAKE_BOTH=4,n.Camera.SHAKE_HORIZONTAL=5,n.Camera.SHAKE_VERTICAL=6,n.Camera.ENABLE_FX=!0,n.Camera.prototype={boot:function(){this.displayObject=this.game.world,this.scale=this.game.world.scale,this.game.camera=this,n.Graphics&&n.Camera.ENABLE_FX&&(this.fx=new n.Graphics(this.game),this.game.stage.addChild(this.fx))},preUpdate:function(){this.totalInView=0},follow:function(t,e,i,s){void 0===e&&(e=n.Camera.FOLLOW_LOCKON),void 0===i&&(i=1),void 0===s&&(s=1),this.target=t,this.lerp.set(i,s);var r;switch(e){case n.Camera.FOLLOW_PLATFORMER:var o=this.width/8,a=this.height/3;this.deadzone=new n.Rectangle((this.width-o)/2,(this.height-a)/2-.25*a,o,a);break;case n.Camera.FOLLOW_TOPDOWN:r=Math.max(this.width,this.height)/4,this.deadzone=new n.Rectangle((this.width-r)/2,(this.height-r)/2,r,r);break;case n.Camera.FOLLOW_TOPDOWN_TIGHT:r=Math.max(this.width,this.height)/8,this.deadzone=new n.Rectangle((this.width-r)/2,(this.height-r)/2,r,r);break;case n.Camera.FOLLOW_LOCKON:default:this.deadzone=null}},unfollow:function(){this.target=null},focusOn:function(t){this.setPosition(Math.round(t.x-this.view.halfWidth),Math.round(t.y-this.view.halfHeight))},focusOnXY:function(t,e){this.setPosition(Math.round(t-this.view.halfWidth),Math.round(e-this.view.halfHeight))},shake:function(t,e,i,s,r){return void 0===t&&(t=.05),void 0===e&&(e=500),void 0===i&&(i=!0),void 0===s&&(s=n.Camera.SHAKE_BOTH),void 0===r&&(r=!0),!(!i&&this._shake.duration>0)&&(this._shake.intensity=t,this._shake.duration=e,this._shake.shakeBounds=r,this._shake.x=0,this._shake.y=0,this._shake.horizontal=s===n.Camera.SHAKE_BOTH||s===n.Camera.SHAKE_HORIZONTAL,this._shake.vertical=s===n.Camera.SHAKE_BOTH||s===n.Camera.SHAKE_VERTICAL,!0)},flash:function(t,e,i){return void 0===t&&(t=16777215),void 0===e&&(e=500),void 0===i&&(i=!1),!(!this.fx||!i&&this._fxDuration>0)&&(this.fx.clear(),this.fx.beginFill(t),this.fx.drawRect(0,0,this.width,this.height),this.fx.endFill(),this.fx.alpha=1,this._fxDuration=e,this._fxType=0,!0)},fade:function(t,e,i){return void 0===t&&(t=0),void 0===e&&(e=500),void 0===i&&(i=!1),!(!this.fx||!i&&this._fxDuration>0)&&(this.fx.clear(),this.fx.beginFill(t),this.fx.drawRect(0,0,this.width,this.height),this.fx.endFill(),this.fx.alpha=0,this._fxDuration=e,this._fxType=1,!0)},update:function(){this._fxDuration>0&&this.updateFX(),this._shake.duration>0&&this.updateShake(),this.bounds&&this.checkBounds(),this.roundPx&&(this.view.floor(),this._shake.x=Math.floor(this._shake.x),this._shake.y=Math.floor(this._shake.y)),this.displayObject.position.x=-this.view.x,this.displayObject.position.y=-this.view.y},updateFX:function(){0===this._fxType?(this.fx.alpha-=this.game.time.elapsedMS/this._fxDuration,this.fx.alpha<=0&&(this._fxDuration=0,this.fx.alpha=0,this.onFlashComplete.dispatch())):(this.fx.alpha+=this.game.time.elapsedMS/this._fxDuration,this.fx.alpha>=1&&(this._fxDuration=0,this.fx.alpha=1,this.onFadeComplete.dispatch()))},updateShake:function(){this._shake.duration-=this.game.time.elapsedMS,this._shake.duration<=0?(this.onShakeComplete.dispatch(),this._shake.x=0,this._shake.y=0):(this._shake.horizontal&&(this._shake.x=this.game.rnd.frac()*this._shake.intensity*this.view.width*2-this._shake.intensity*this.view.width),this._shake.vertical&&(this._shake.y=this.game.rnd.frac()*this._shake.intensity*this.view.height*2-this._shake.intensity*this.view.height))},updateTarget:function(){this._targetPosition.x=this.view.x+this.target.worldPosition.x,this._targetPosition.y=this.view.y+this.target.worldPosition.y,this.deadzone?(this._edge=this._targetPosition.x-this.view.x,this._edge<this.deadzone.left?this.view.x=this.game.math.linear(this.view.x,this._targetPosition.x-this.deadzone.left,this.lerp.x):this._edge>this.deadzone.right&&(this.view.x=this.game.math.linear(this.view.x,this._targetPosition.x-this.deadzone.right,this.lerp.x)),this._edge=this._targetPosition.y-this.view.y,this._edge<this.deadzone.top?this.view.y=this.game.math.linear(this.view.y,this._targetPosition.y-this.deadzone.top,this.lerp.y):this._edge>this.deadzone.bottom&&(this.view.y=this.game.math.linear(this.view.y,this._targetPosition.y-this.deadzone.bottom,this.lerp.y))):(this.view.x=this.game.math.linear(this.view.x,this._targetPosition.x-this.view.halfWidth,this.lerp.x),this.view.y=this.game.math.linear(this.view.y,this._targetPosition.y-this.view.halfHeight,this.lerp.y)),this.bounds&&this.checkBounds(),this.roundPx&&this.view.floor(),this.displayObject.position.x=-this.view.x,this.displayObject.position.y=-this.view.y},setBoundsToWorld:function(){this.bounds&&this.bounds.copyFrom(this.game.world.bounds)},checkBounds:function(){this.atLimit.x=!1,this.atLimit.y=!1;var t=this.view.x+this._shake.x,e=this.view.right+this._shake.x,i=this.view.y+this._shake.y,s=this.view.bottom+this._shake.y;t<=this.bounds.x*this.scale.x&&(this.atLimit.x=!0,this.view.x=this.bounds.x*this.scale.x,this._shake.shakeBounds||(this._shake.x=0)),e>=this.bounds.right*this.scale.x&&(this.atLimit.x=!0,this.view.x=this.bounds.right*this.scale.x-this.width,this._shake.shakeBounds||(this._shake.x=0)),i<=this.bounds.top*this.scale.y&&(this.atLimit.y=!0,this.view.y=this.bounds.top*this.scale.y,this._shake.shakeBounds||(this._shake.y=0)),s>=this.bounds.bottom*this.scale.y&&(this.atLimit.y=!0,this.view.y=this.bounds.bottom*this.scale.y-this.height,this._shake.shakeBounds||(this._shake.y=0))},setPosition:function(t,e){this.view.x=t,this.view.y=e,this.bounds&&this.checkBounds()},setSize:function(t,e){this.view.width=t,this.view.height=e},reset:function(){this.target=null,this.view.x=0,this.view.y=0,this._shake.duration=0,this.resetFX()},resetFX:function(){this.fx.clear(),this.fx.alpha=0,this._fxDuration=0}},n.Camera.prototype.constructor=n.Camera,Object.defineProperty(n.Camera.prototype,"x",{get:function(){return this.view.x},set:function(t){this.view.x=t,this.bounds&&this.checkBounds()}}),Object.defineProperty(n.Camera.prototype,"y",{get:function(){return this.view.y},set:function(t){this.view.y=t,this.bounds&&this.checkBounds()}}),Object.defineProperty(n.Camera.prototype,"position",{get:function(){return this._position.set(this.view.x,this.view.y),this._position},set:function(t){void 0!==t.x&&(this.view.x=t.x),void 0!==t.y&&(this.view.y=t.y),this.bounds&&this.checkBounds()}}),Object.defineProperty(n.Camera.prototype,"width",{get:function(){return this.view.width},set:function(t){this.view.width=t}}),Object.defineProperty(n.Camera.prototype,"height",{get:function(){return this.view.height},set:function(t){this.view.height=t}}),Object.defineProperty(n.Camera.prototype,"shakeIntensity",{get:function(){return this._shake.intensity},set:function(t){this._shake.intensity=t}}),/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.State=function(){this.game=null,this.key="",this.add=null,this.make=null,this.camera=null,this.cache=null,this.input=null,this.load=null,this.math=null,this.sound=null,this.scale=null,this.stage=null,this.state=null,this.time=null,this.tweens=null,this.world=null,this.particles=null,this.physics=null,this.rnd=null},n.State.prototype={init:function(){},preload:function(){},loadUpdate:function(){},loadRender:function(){},create:function(){},update:function(){},preRender:function(){},render:function(){},resize:function(){},paused:function(){},resumed:function(){},pauseUpdate:function(){},shutdown:function(){}},n.State.prototype.constructor=n.State,/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.StateManager=function(t,e){this.game=t,this.states={},this._pendingState=null,void 0!==e&&null!==e&&(this._pendingState=e),this._clearWorld=!1,this._clearCache=!1,this._created=!1,this._args=[],this.current="",this.onStateChange=new n.Signal,this.onInitCallback=null,this.onPreloadCallback=null,this.onCreateCallback=null,this.onUpdateCallback=null,this.onRenderCallback=null,this.onResizeCallback=null,this.onPreRenderCallback=null,this.onLoadUpdateCallback=null,this.onLoadRenderCallback=null,this.onPausedCallback=null,this.onResumedCallback=null,this.onPauseUpdateCallback=null,this.onShutDownCallback=null},n.StateManager.prototype={boot:function(){this.game.onPause.add(this.pause,this),this.game.onResume.add(this.resume,this),null!==this._pendingState&&"string"!=typeof this._pendingState&&this.add("default",this._pendingState,!0)},add:function(t,e,i){void 0===i&&(i=!1);var s;return e instanceof n.State?s=e:"object"==typeof e?(s=e,s.game=this.game):"function"==typeof e&&(s=new e(this.game)),this.states[t]=s,i&&(this.game.isBooted?this.start(t):this._pendingState=t),s},remove:function(t){this.current===t&&(this.callbackContext=null,this.onInitCallback=null,this.onShutDownCallback=null,this.onPreloadCallback=null,this.onLoadRenderCallback=null,this.onLoadUpdateCallback=null,this.onCreateCallback=null,this.onUpdateCallback=null,this.onPreRenderCallback=null,this.onRenderCallback=null,this.onResizeCallback=null,this.onPausedCallback=null,this.onResumedCallback=null,this.onPauseUpdateCallback=null),delete this.states[t]},start:function(t,e,i){void 0===e&&(e=!0),void 0===i&&(i=!1),this.checkState(t)&&(this._pendingState=t,this._clearWorld=e,this._clearCache=i,arguments.length>3&&(this._args=Array.prototype.splice.call(arguments,3)))},restart:function(t,e){void 0===t&&(t=!0),void 0===e&&(e=!1),this._pendingState=this.current,this._clearWorld=t,this._clearCache=e,arguments.length>2&&(this._args=Array.prototype.slice.call(arguments,2))},dummy:function(){},preUpdate:function(){if(this._pendingState&&this.game.isBooted){var t=this.current;if(this.clearCurrentState(),this.setCurrentState(this._pendingState),this.onStateChange.dispatch(this.current,t),this.current!==this._pendingState)return;this._pendingState=null,this.onPreloadCallback?(this.game.load.reset(!0),this.onPreloadCallback.call(this.callbackContext,this.game),0===this.game.load.totalQueuedFiles()&&0===this.game.load.totalQueuedPacks()?this.loadComplete():this.game.load.start()):this.loadComplete()}},clearCurrentState:function(){this.current&&(this.onShutDownCallback&&this.onShutDownCallback.call(this.callbackContext,this.game),this.game.tweens.removeAll(),this.game.camera.reset(),this.game.input.reset(!0),this.game.physics.clear(),this.game.time.removeAll(),this.game.scale.reset(this._clearWorld),this.game.debug&&this.game.debug.reset(),this._clearWorld&&(this.game.world.shutdown(),this._clearCache&&this.game.cache.destroy()))},checkState:function(t){return this.states[t]?!!(this.states[t].preload||this.states[t].create||this.states[t].update||this.states[t].render)||(console.warn("Invalid Phaser State object given. Must contain at least a one of the required functions: preload, create, update or render"),!1):(console.warn("Phaser.StateManager - No state found with the key: "+t),!1)},link:function(t){this.states[t].game=this.game,this.states[t].add=this.game.add,this.states[t].make=this.game.make,this.states[t].camera=this.game.camera,this.states[t].cache=this.game.cache,this.states[t].input=this.game.input,this.states[t].load=this.game.load,this.states[t].math=this.game.math,this.states[t].sound=this.game.sound,this.states[t].scale=this.game.scale,this.states[t].state=this,this.states[t].stage=this.game.stage,this.states[t].time=this.game.time,this.states[t].tweens=this.game.tweens,this.states[t].world=this.game.world,this.states[t].particles=this.game.particles,this.states[t].rnd=this.game.rnd,this.states[t].physics=this.game.physics,this.states[t].key=t},unlink:function(t){this.states[t]&&(this.states[t].game=null,this.states[t].add=null,this.states[t].make=null,this.states[t].camera=null,this.states[t].cache=null,this.states[t].input=null,this.states[t].load=null,this.states[t].math=null,this.states[t].sound=null,this.states[t].scale=null,this.states[t].state=null,this.states[t].stage=null,this.states[t].time=null,this.states[t].tweens=null,this.states[t].world=null,this.states[t].particles=null,this.states[t].rnd=null,this.states[t].physics=null)},setCurrentState:function(t){this.callbackContext=this.states[t],this.link(t),this.onInitCallback=this.states[t].init||this.dummy,this.onPreloadCallback=this.states[t].preload||null,this.onLoadRenderCallback=this.states[t].loadRender||null,this.onLoadUpdateCallback=this.states[t].loadUpdate||null,this.onCreateCallback=this.states[t].create||null,this.onUpdateCallback=this.states[t].update||null,this.onPreRenderCallback=this.states[t].preRender||null,this.onRenderCallback=this.states[t].render||null,this.onResizeCallback=this.states[t].resize||null,this.onPausedCallback=this.states[t].paused||null,this.onResumedCallback=this.states[t].resumed||null,this.onPauseUpdateCallback=this.states[t].pauseUpdate||null,this.onShutDownCallback=this.states[t].shutdown||this.dummy,""!==this.current&&this.game.physics.reset(),this.current=t,this._created=!1,this.onInitCallback.apply(this.callbackContext,this._args),t===this._pendingState&&(this._args=[]),this.game._kickstart=!0},getCurrentState:function(){return this.states[this.current]},loadComplete:function(){!1===this._created&&this.onLoadUpdateCallback&&this.onLoadUpdateCallback.call(this.callbackContext,this.game),!1===this._created&&this.onCreateCallback?(this._created=!0,this.onCreateCallback.call(this.callbackContext,this.game)):this._created=!0},pause:function(){this._created&&this.onPausedCallback&&this.onPausedCallback.call(this.callbackContext,this.game)},resume:function(){this._created&&this.onResumedCallback&&this.onResumedCallback.call(this.callbackContext,this.game)},update:function(){this._created?this.onUpdateCallback&&this.onUpdateCallback.call(this.callbackContext,this.game):this.onLoadUpdateCallback&&this.onLoadUpdateCallback.call(this.callbackContext,this.game)},pauseUpdate:function(){this._created?this.onPauseUpdateCallback&&this.onPauseUpdateCallback.call(this.callbackContext,this.game):this.onLoadUpdateCallback&&this.onLoadUpdateCallback.call(this.callbackContext,this.game)},preRender:function(t){this._created&&this.onPreRenderCallback&&this.onPreRenderCallback.call(this.callbackContext,this.game,t)},resize:function(t,e){this.onResizeCallback&&this.onResizeCallback.call(this.callbackContext,t,e)},render:function(){this._created?this.onRenderCallback&&(this.game.renderType===n.CANVAS?(this.game.context.save(),this.game.context.setTransform(1,0,0,1,0,0),this.onRenderCallback.call(this.callbackContext,this.game),this.game.context.restore()):this.onRenderCallback.call(this.callbackContext,this.game)):this.onLoadRenderCallback&&this.onLoadRenderCallback.call(this.callbackContext,this.game)},destroy:function(){this._clearWorld=!0,this._clearCache=!0,this.clearCurrentState(),this.callbackContext=null,this.onInitCallback=null,this.onShutDownCallback=null,this.onPreloadCallback=null,this.onLoadRenderCallback=null,this.onLoadUpdateCallback=null,this.onCreateCallback=null,this.onUpdateCallback=null,this.onRenderCallback=null,this.onPausedCallback=null,this.onResumedCallback=null,this.onPauseUpdateCallback=null,this.game=null,this.states={},this._pendingState=null,this.current=""}},n.StateManager.prototype.constructor=n.StateManager,Object.defineProperty(n.StateManager.prototype,"created",{get:function(){return this._created}}),/**
* @author Miller Medeiros http://millermedeiros.github.com/js-signals/
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Signal=function(){},n.Signal.prototype={_bindings:null,_prevParams:null,memorize:!1,_shouldPropagate:!0,active:!0,_boundDispatch:!1,validateListener:function(t,e){if("function"!=typeof t)throw new Error("Phaser.Signal: listener is a required param of {fn}() and should be a Function.".replace("{fn}",e))},_registerListener:function(t,e,i,s,r){var o,a=this._indexOfListener(t,i);if(-1!==a){if(o=this._bindings[a],o.isOnce()!==e)throw new Error("You cannot add"+(e?"":"Once")+"() then add"+(e?"Once":"")+"() the same listener without removing the relationship first.")}else o=new n.SignalBinding(this,t,e,i,s,r),this._addBinding(o);return this.memorize&&this._prevParams&&o.execute(this._prevParams),o},_addBinding:function(t){this._bindings||(this._bindings=[]);var e=this._bindings.length;do{e--}while(this._bindings[e]&&t._priority<=this._bindings[e]._priority);this._bindings.splice(e+1,0,t)},_indexOfListener:function(t,e){if(!this._bindings)return-1;void 0===e&&(e=null);for(var i,s=this._bindings.length;s--;)if(i=this._bindings[s],i._listener===t&&i.context===e)return s;return-1},has:function(t,e){return-1!==this._indexOfListener(t,e)},add:function(t,e,i){this.validateListener(t,"add");var s=[];if(arguments.length>3)for(var n=3;n<arguments.length;n++)s.push(arguments[n]);return this._registerListener(t,!1,e,i,s)},addOnce:function(t,e,i){this.validateListener(t,"addOnce");var s=[];if(arguments.length>3)for(var n=3;n<arguments.length;n++)s.push(arguments[n]);return this._registerListener(t,!0,e,i,s)},remove:function(t,e){this.validateListener(t,"remove");var i=this._indexOfListener(t,e);return-1!==i&&(this._bindings[i]._destroy(),this._bindings.splice(i,1)),t},removeAll:function(t){if(void 0===t&&(t=null),this._bindings){for(var e=this._bindings.length;e--;)t?this._bindings[e].context===t&&(this._bindings[e]._destroy(),this._bindings.splice(e,1)):this._bindings[e]._destroy();t||(this._bindings.length=0)}},getNumListeners:function(){return this._bindings?this._bindings.length:0},halt:function(){this._shouldPropagate=!1},dispatch:function(){if(this.active&&this._bindings){var t,e=Array.prototype.slice.call(arguments),i=this._bindings.length;if(this.memorize&&(this._prevParams=e),i){t=this._bindings.slice(),this._shouldPropagate=!0;do{i--}while(t[i]&&this._shouldPropagate&&!1!==t[i].execute(e))}}},forget:function(){this._prevParams&&(this._prevParams=null)},dispose:function(){this.removeAll(),this._bindings=null,this._prevParams&&(this._prevParams=null)},toString:function(){return"[Phaser.Signal active:"+this.active+" numListeners:"+this.getNumListeners()+"]"}},Object.defineProperty(n.Signal.prototype,"boundDispatch",{get:function(){var t=this;return this._boundDispatch||(this._boundDispatch=function(){return t.dispatch.apply(t,arguments)})}}),n.Signal.prototype.constructor=n.Signal,/**
* @author Miller Medeiros http://millermedeiros.github.com/js-signals/
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.SignalBinding=function(t,e,i,s,n,r){this._listener=e,i&&(this._isOnce=!0),null!=s&&(this.context=s),this._signal=t,n&&(this._priority=n),r&&r.length&&(this._args=r)},n.SignalBinding.prototype={context:null,_isOnce:!1,_priority:0,_args:null,callCount:0,active:!0,params:null,execute:function(t){var e,i;return this.active&&this._listener&&(i=this.params?this.params.concat(t):t,this._args&&(i=i.concat(this._args)),e=this._listener.apply(this.context,i),this.callCount++,this._isOnce&&this.detach()),e},detach:function(){return this.isBound()?this._signal.remove(this._listener,this.context):null},isBound:function(){return!!this._signal&&!!this._listener},isOnce:function(){return this._isOnce},getListener:function(){return this._listener},getSignal:function(){return this._signal},_destroy:function(){delete this._signal,delete this._listener,delete this.context},toString:function(){return"[Phaser.SignalBinding isOnce:"+this._isOnce+", isBound:"+this.isBound()+", active:"+this.active+"]"}},n.SignalBinding.prototype.constructor=n.SignalBinding,/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Filter=function(t,e,i){this.game=t,this.type=n.WEBGL_FILTER,this.passes=[this],this.shaders=[],this.dirty=!0,this.padding=0,this.prevPoint=new n.Point;var s=new Date;if(this.uniforms={resolution:{type:"2f",value:{x:256,y:256}},time:{type:"1f",value:0},mouse:{type:"2f",value:{x:0,y:0}},date:{type:"4fv",value:[s.getFullYear(),s.getMonth(),s.getDate(),60*s.getHours()*60+60*s.getMinutes()+s.getSeconds()]},sampleRate:{type:"1f",value:44100},iChannel0:{type:"sampler2D",value:null,textureData:{repeat:!0}},iChannel1:{type:"sampler2D",value:null,textureData:{repeat:!0}},iChannel2:{type:"sampler2D",value:null,textureData:{repeat:!0}},iChannel3:{type:"sampler2D",value:null,textureData:{repeat:!0}}},e)for(var r in e)this.uniforms[r]=e[r];this.fragmentSrc=i||""},n.Filter.prototype={init:function(){},setResolution:function(t,e){this.uniforms.resolution.value.x=t,this.uniforms.resolution.value.y=e},update:function(t){if(void 0!==t){var e=t.x/this.game.width,i=1-t.y/this.game.height;e===this.prevPoint.x&&i===this.prevPoint.y||(this.uniforms.mouse.value.x=e.toFixed(2),this.uniforms.mouse.value.y=i.toFixed(2),this.prevPoint.set(e,i))}this.uniforms.time.value=this.game.time.totalElapsedSeconds()},addToWorld:function(t,e,i,s,n,r){void 0===n&&(n=0),void 0===r&&(r=0),void 0!==i&&null!==i?this.width=i:i=this.width,void 0!==s&&null!==s?this.height=s:s=this.height;var o=this.game.add.image(t,e,"__default");return o.width=i,o.height=s,o.anchor.set(n,r),o.filters=[this],o},destroy:function(){this.game=null}},n.Filter.prototype.constructor=n.Filter,Object.defineProperty(n.Filter.prototype,"width",{get:function(){return this.uniforms.resolution.value.x},set:function(t){this.uniforms.resolution.value.x=t}}),Object.defineProperty(n.Filter.prototype,"height",{get:function(){return this.uniforms.resolution.value.y},set:function(t){this.uniforms.resolution.value.y=t}}),/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Plugin=function(t,e){void 0===e&&(e=null),this.game=t,this.parent=e,this.active=!1,this.visible=!1,this.hasPreUpdate=!1,this.hasUpdate=!1,this.hasPostUpdate=!1,this.hasRender=!1,this.hasPostRender=!1},n.Plugin.prototype={preUpdate:function(){},update:function(){},render:function(){},postRender:function(){},destroy:function(){this.game=null,this.parent=null,this.active=!1,this.visible=!1}},n.Plugin.prototype.constructor=n.Plugin,/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.PluginManager=function(t){this.game=t,this.plugins=[],this._len=0,this._i=0},n.PluginManager.prototype={add:function(t){var e=Array.prototype.slice.call(arguments,1),i=!1;return"function"==typeof t?t=new t(this.game,this):(t.game=this.game,t.parent=this),"function"==typeof t.preUpdate&&(t.hasPreUpdate=!0,i=!0),"function"==typeof t.update&&(t.hasUpdate=!0,i=!0),"function"==typeof t.postUpdate&&(t.hasPostUpdate=!0,i=!0),"function"==typeof t.render&&(t.hasRender=!0,i=!0),"function"==typeof t.postRender&&(t.hasPostRender=!0,i=!0),i?((t.hasPreUpdate||t.hasUpdate||t.hasPostUpdate)&&(t.active=!0),(t.hasRender||t.hasPostRender)&&(t.visible=!0),this._len=this.plugins.push(t),"function"==typeof t.init&&t.init.apply(t,e),t):null},remove:function(t,e){for(void 0===e&&(e=!0),this._i=this._len;this._i--;)if(this.plugins[this._i]===t)return e&&t.destroy(),this.plugins.splice(this._i,1),void this._len--},removeAll:function(){for(this._i=this._len;this._i--;)this.plugins[this._i].destroy();this.plugins.length=0,this._len=0},preUpdate:function(){for(this._i=this._len;this._i--;)this.plugins[this._i].active&&this.plugins[this._i].hasPreUpdate&&this.plugins[this._i].preUpdate()},update:function(){for(this._i=this._len;this._i--;)this.plugins[this._i].active&&this.plugins[this._i].hasUpdate&&this.plugins[this._i].update()},postUpdate:function(){for(this._i=this._len;this._i--;)this.plugins[this._i].active&&this.plugins[this._i].hasPostUpdate&&this.plugins[this._i].postUpdate()},render:function(){for(this._i=this._len;this._i--;)this.plugins[this._i].visible&&this.plugins[this._i].hasRender&&this.plugins[this._i].render()},postRender:function(){for(this._i=this._len;this._i--;)this.plugins[this._i].visible&&this.plugins[this._i].hasPostRender&&this.plugins[this._i].postRender()},destroy:function(){this.removeAll(),this.game=null}},n.PluginManager.prototype.constructor=n.PluginManager,/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Stage=function(t){this.game=t,PIXI.DisplayObjectContainer.call(this),this.name="_stage_root",this.disableVisibilityChange=!1,this.exists=!0,this.worldTransform=new PIXI.Matrix,this.stage=this,this.currentRenderOrderID=0,this._hiddenVar="hidden",this._onChange=null,this._bgColor={r:0,g:0,b:0,a:0,color:0,rgba:"#000000"},this.game.transparent||(this._bgColor.a=1),t.config&&this.parseConfig(t.config)},n.Stage.prototype=Object.create(PIXI.DisplayObjectContainer.prototype),n.Stage.prototype.constructor=n.Stage,n.Stage.prototype.parseConfig=function(t){t.disableVisibilityChange&&(this.disableVisibilityChange=t.disableVisibilityChange),t.backgroundColor&&this.setBackgroundColor(t.backgroundColor)},n.Stage.prototype.boot=function(){n.DOM.getOffset(this.game.canvas,this.offset),n.Canvas.setUserSelect(this.game.canvas,"none"),n.Canvas.setTouchAction(this.game.canvas,"none"),this.checkVisibility()},n.Stage.prototype.preUpdate=function(){this.currentRenderOrderID=0;for(var t=0;t<this.children.length;t++)this.children[t].preUpdate()},n.Stage.prototype.update=function(){for(var t=this.children.length;t--;)this.children[t].update()},n.Stage.prototype.postUpdate=function(){this.game.camera.update(),this.game.camera.target&&(this.game.camera.target.postUpdate(),this.updateTransform(),this.game.camera.updateTarget());for(var t=0;t<this.children.length;t++)this.children[t].postUpdate();this.updateTransform()},n.Stage.prototype.updateTransform=function(){this.worldAlpha=1;for(var t=0;t<this.children.length;t++)this.children[t].updateTransform()},n.Stage.prototype.checkVisibility=function(){void 0!==document.hidden?this._hiddenVar="visibilitychange":void 0!==document.webkitHidden?this._hiddenVar="webkitvisibilitychange":void 0!==document.mozHidden?this._hiddenVar="mozvisibilitychange":void 0!==document.msHidden?this._hiddenVar="msvisibilitychange":this._hiddenVar=null;var t=this;this._onChange=function(e){return t.visibilityChange(e)},this._hiddenVar&&document.addEventListener(this._hiddenVar,this._onChange,!1),window.onblur=this._onChange,window.onfocus=this._onChange,window.onpagehide=this._onChange,window.onpageshow=this._onChange,this.game.device.cocoonJSApp&&(CocoonJS.App.onSuspended.addEventListener(function(){n.Stage.prototype.visibilityChange.call(t,{type:"pause"})}),CocoonJS.App.onActivated.addEventListener(function(){n.Stage.prototype.visibilityChange.call(t,{type:"resume"})}))},n.Stage.prototype.visibilityChange=function(t){if("pagehide"===t.type||"blur"===t.type||"pageshow"===t.type||"focus"===t.type)return void("pagehide"===t.type||"blur"===t.type?this.game.focusLoss(t):"pageshow"!==t.type&&"focus"!==t.type||this.game.focusGain(t));this.disableVisibilityChange||(document.hidden||document.mozHidden||document.msHidden||document.webkitHidden||"pause"===t.type?this.game.gamePaused(t):this.game.gameResumed(t))},n.Stage.prototype.setBackgroundColor=function(t){this.game.transparent||(n.Color.valueToColor(t,this._bgColor),n.Color.updateColor(this._bgColor),this._bgColor.r/=255,this._bgColor.g/=255,this._bgColor.b/=255,this._bgColor.a=1)},n.Stage.prototype.destroy=function(){this._hiddenVar&&document.removeEventListener(this._hiddenVar,this._onChange,!1),window.onpagehide=null,window.onpageshow=null,window.onblur=null,window.onfocus=null},Object.defineProperty(n.Stage.prototype,"backgroundColor",{get:function(){return this._bgColor.color},set:function(t){this.setBackgroundColor(t)}}),Object.defineProperty(n.Stage.prototype,"smoothed",{get:function(){return PIXI.scaleModes.DEFAULT===PIXI.scaleModes.LINEAR},set:function(t){PIXI.scaleModes.DEFAULT=t?PIXI.scaleModes.LINEAR:PIXI.scaleModes.NEAREST}}),/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Group=function(t,e,i,s,r,o){void 0===s&&(s=!1),void 0===r&&(r=!1),void 0===o&&(o=n.Physics.ARCADE),this.game=t,void 0===e&&(e=t.world),this.name=i||"group",this.z=0,PIXI.DisplayObjectContainer.call(this),s?(this.game.stage.addChild(this),this.z=this.game.stage.children.length):e&&(e.addChild(this),this.z=e.children.length),this.type=n.GROUP,this.physicsType=n.GROUP,this.alive=!0,this.exists=!0,this.ignoreDestroy=!1,this.pendingDestroy=!1,this.classType=n.Sprite,this.cursor=null,this.inputEnableChildren=!1,this.onChildInputDown=new n.Signal,this.onChildInputUp=new n.Signal,this.onChildInputOver=new n.Signal,this.onChildInputOut=new n.Signal,this.enableBody=r,this.enableBodyDebug=!1,this.physicsBodyType=o,this.physicsSortDirection=null,this.onDestroy=new n.Signal,this.cursorIndex=0,this.fixedToCamera=!1,this.cameraOffset=new n.Point,this.hash=[],this._sortProperty="z"},n.Group.prototype=Object.create(PIXI.DisplayObjectContainer.prototype),n.Group.prototype.constructor=n.Group,n.Group.RETURN_NONE=0,n.Group.RETURN_TOTAL=1,n.Group.RETURN_CHILD=2,n.Group.RETURN_ALL=3,n.Group.SORT_ASCENDING=-1,n.Group.SORT_DESCENDING=1,n.Group.prototype.add=function(t,e,i){return void 0===e&&(e=!1),t.parent===this?t:(t.body&&t.parent&&t.parent.hash&&t.parent.removeFromHash(t),void 0===i?(t.z=this.children.length,this.addChild(t)):(this.addChildAt(t,i),this.updateZ()),this.enableBody&&t.hasOwnProperty("body")&&null===t.body?this.game.physics.enable(t,this.physicsBodyType):t.body&&this.addToHash(t),!this.inputEnableChildren||t.input&&!t.inputEnabled||(t.inputEnabled=!0),!e&&t.events&&t.events.onAddedToGroup$dispatch(t,this),null===this.cursor&&(this.cursor=t),t)},n.Group.prototype.addAt=function(t,e,i){this.add(t,i,e)},n.Group.prototype.addToHash=function(t){if(t.parent===this){if(-1===this.hash.indexOf(t))return this.hash.push(t),!0}return!1},n.Group.prototype.removeFromHash=function(t){if(t){var e=this.hash.indexOf(t);if(-1!==e)return this.hash.splice(e,1),!0}return!1},n.Group.prototype.addMultiple=function(t,e){if(t instanceof n.Group)t.moveAll(this,e);else if(Array.isArray(t))for(var i=0;i<t.length;i++)this.add(t[i],e);return t},n.Group.prototype.getAt=function(t){return t<0||t>=this.children.length?-1:this.getChildAt(t)},n.Group.prototype.create=function(t,e,i,s,n,r){void 0===n&&(n=!0);var o=new this.classType(this.game,t,e,i,s);return o.exists=n,o.visible=n,o.alive=n,this.add(o,!1,r)},n.Group.prototype.createMultiple=function(t,e,i,s){void 0===i&&(i=0),void 0===s&&(s=!1),Array.isArray(e)||(e=[e]),Array.isArray(i)||(i=[i]);var n=this,r=[];return e.forEach(function(e){i.forEach(function(i){for(var o=0;o<t;o++)r.push(n.create(0,0,e,i,s))})}),r},n.Group.prototype.updateZ=function(){for(var t=this.children.length;t--;)this.children[t].z=t},n.Group.prototype.align=function(t,e,i,s,r,o){if(void 0===r&&(r=n.TOP_LEFT),void 0===o&&(o=0),0===this.children.length||o>this.children.length||-1===t&&-1===e)return!1;for(var a=new n.Rectangle(0,0,i,s),h=t*i,l=e*s,c=o;c<this.children.length;c++){var u=this.children[c];if(u.alignIn)if(u.alignIn(a,r),-1===t)a.y+=s,a.y===l&&(a.x+=i,a.y=0);else if(-1===e)a.x+=i,a.x===h&&(a.x=0,a.y+=s);else if(a.x+=i,a.x===h&&(a.x=0,a.y+=s,a.y===l))return!0}return!0};n.Group.prototype.resetCursor=function(t){if(void 0===t&&(t=0),t>this.children.length-1&&(t=0),this.cursor)return this.cursorIndex=t,this.cursor=this.children[this.cursorIndex],this.cursor},n.Group.prototype.next=function(){if(this.cursor)return this.cursorIndex>=this.children.length-1?this.cursorIndex=0:this.cursorIndex++,this.cursor=this.children[this.cursorIndex],this.cursor},n.Group.prototype.previous=function(){if(this.cursor)return 0===this.cursorIndex?this.cursorIndex=this.children.length-1:this.cursorIndex--,this.cursor=this.children[this.cursorIndex],this.cursor},n.Group.prototype.swap=function(t,e){this.swapChildren(t,e),this.updateZ()},n.Group.prototype.bringToTop=function(t){return t.parent===this&&this.getIndex(t)<this.children.length&&(this.remove(t,!1,!0),this.add(t,!0)),t},n.Group.prototype.sendToBack=function(t){return t.parent===this&&this.getIndex(t)>0&&(this.remove(t,!1,!0),this.addAt(t,0,!0)),t},n.Group.prototype.moveUp=function(t){if(t.parent===this&&this.getIndex(t)<this.children.length-1){var e=this.getIndex(t),i=this.getAt(e+1);i&&this.swap(t,i)}return t},n.Group.prototype.moveDown=function(t){if(t.parent===this&&this.getIndex(t)>0){var e=this.getIndex(t),i=this.getAt(e-1);i&&this.swap(t,i)}return t},n.Group.prototype.xy=function(t,e,i){if(t<0||t>this.children.length)return-1;this.getChildAt(t).x=e,this.getChildAt(t).y=i},n.Group.prototype.reverse=function(){this.children.reverse(),this.updateZ()},n.Group.prototype.getIndex=function(t){return this.children.indexOf(t)},n.Group.prototype.getByName=function(t){for(var e=0;e<this.children.length;e++)if(this.children[e].name===t)return this.children[e];return null},n.Group.prototype.replace=function(t,e){var i=this.getIndex(t);if(-1!==i)return e.parent&&(e.parent instanceof n.Group?e.parent.remove(e):e.parent.removeChild(e)),this.remove(t),this.addAt(e,i),t},n.Group.prototype.hasProperty=function(t,e){var i=e.length;return 1===i&&e[0]in t||(2===i&&e[0]in t&&e[1]in t[e[0]]||(3===i&&e[0]in t&&e[1]in t[e[0]]&&e[2]in t[e[0]][e[1]]||4===i&&e[0]in t&&e[1]in t[e[0]]&&e[2]in t[e[0]][e[1]]&&e[3]in t[e[0]][e[1]][e[2]]))},n.Group.prototype.setProperty=function(t,e,i,s,n){if(void 0===n&&(n=!1),s=s||0,!this.hasProperty(t,e)&&(!n||s>0))return!1;var r=e.length;return 1===r?0===s?t[e[0]]=i:1===s?t[e[0]]+=i:2===s?t[e[0]]-=i:3===s?t[e[0]]*=i:4===s&&(t[e[0]]/=i):2===r?0===s?t[e[0]][e[1]]=i:1===s?t[e[0]][e[1]]+=i:2===s?t[e[0]][e[1]]-=i:3===s?t[e[0]][e[1]]*=i:4===s&&(t[e[0]][e[1]]/=i):3===r?0===s?t[e[0]][e[1]][e[2]]=i:1===s?t[e[0]][e[1]][e[2]]+=i:2===s?t[e[0]][e[1]][e[2]]-=i:3===s?t[e[0]][e[1]][e[2]]*=i:4===s&&(t[e[0]][e[1]][e[2]]/=i):4===r&&(0===s?t[e[0]][e[1]][e[2]][e[3]]=i:1===s?t[e[0]][e[1]][e[2]][e[3]]+=i:2===s?t[e[0]][e[1]][e[2]][e[3]]-=i:3===s?t[e[0]][e[1]][e[2]][e[3]]*=i:4===s&&(t[e[0]][e[1]][e[2]][e[3]]/=i)),!0},n.Group.prototype.checkProperty=function(t,e,i,s){return void 0===s&&(s=!1),!(!n.Utils.getProperty(t,e)&&s)&&n.Utils.getProperty(t,e)===i},n.Group.prototype.set=function(t,e,i,s,n,r,o){if(void 0===o&&(o=!1),e=e.split("."),void 0===s&&(s=!1),void 0===n&&(n=!1),(!1===s||s&&t.alive)&&(!1===n||n&&t.visible))return this.setProperty(t,e,i,r,o)},n.Group.prototype.setAll=function(t,e,i,s,n,r){void 0===i&&(i=!1),void 0===s&&(s=!1),void 0===r&&(r=!1),t=t.split("."),n=n||0;for(var o=0;o<this.children.length;o++)(!i||i&&this.children[o].alive)&&(!s||s&&this.children[o].visible)&&this.setProperty(this.children[o],t,e,n,r)},n.Group.prototype.setAllChildren=function(t,e,i,s,r,o){void 0===i&&(i=!1),void 0===s&&(s=!1),void 0===o&&(o=!1),r=r||0;for(var a=0;a<this.children.length;a++)(!i||i&&this.children[a].alive)&&(!s||s&&this.children[a].visible)&&(this.children[a]instanceof n.Group?this.children[a].setAllChildren(t,e,i,s,r,o):this.setProperty(this.children[a],t.split("."),e,r,o))},n.Group.prototype.checkAll=function(t,e,i,s,n){void 0===i&&(i=!1),void 0===s&&(s=!1),void 0===n&&(n=!1);for(var r=0;r<this.children.length;r++)if((!i||i&&this.children[r].alive)&&(!s||s&&this.children[r].visible)&&!this.checkProperty(this.children[r],t,e,n))return!1;return!0},n.Group.prototype.addAll=function(t,e,i,s){this.setAll(t,e,i,s,1)},n.Group.prototype.subAll=function(t,e,i,s){this.setAll(t,e,i,s,2)},n.Group.prototype.multiplyAll=function(t,e,i,s){this.setAll(t,e,i,s,3)},n.Group.prototype.divideAll=function(t,e,i,s){this.setAll(t,e,i,s,4)},n.Group.prototype.callAllExists=function(t,e){var i;if(arguments.length>2){i=[];for(var s=2;s<arguments.length;s++)i.push(arguments[s])}for(var s=0;s<this.children.length;s++)this.children[s].exists===e&&this.children[s][t]&&this.children[s][t].apply(this.children[s],i)},n.Group.prototype.callbackFromArray=function(t,e,i){if(1===i){if(t[e[0]])return t[e[0]]}else if(2===i){if(t[e[0]][e[1]])return t[e[0]][e[1]]}else if(3===i){if(t[e[0]][e[1]][e[2]])return t[e[0]][e[1]][e[2]]}else if(4===i){if(t[e[0]][e[1]][e[2]][e[3]])return t[e[0]][e[1]][e[2]][e[3]]}else if(t[e])return t[e];return!1},n.Group.prototype.callAll=function(t,e){if(void 0!==t){t=t.split(".");var i=t.length;if(void 0===e||null===e||""===e)e=null;else if("string"==typeof e){e=e.split(".");var s=e.length}var n;if(arguments.length>2){n=[];for(var r=2;r<arguments.length;r++)n.push(arguments[r])}for(var o=null,a=null,r=0;r<this.children.length;r++)o=this.callbackFromArray(this.children[r],t,i),e&&o?(a=this.callbackFromArray(this.children[r],e,s),o&&o.apply(a,n)):o&&o.apply(this.children[r],n)}},n.Group.prototype.preUpdate=function(){if(this.pendingDestroy)return this.destroy(),!1;if(!this.exists||!this.parent.exists)return this.renderOrderID=-1,!1;for(var t=0;t<this.children.length;t++)this.children[t].preUpdate();return!0},n.Group.prototype.update=function(){for(var t=this.children.length;t--;)this.children[t].update()},n.Group.prototype.postUpdate=function(){this.fixedToCamera&&(this.x=this.game.camera.view.x+this.cameraOffset.x,this.y=this.game.camera.view.y+this.cameraOffset.y);for(var t=0;t<this.children.length;t++)this.children[t].postUpdate()},n.Group.prototype.filter=function(t,e){for(var i=-1,s=this.children.length,r=[];++i<s;){var o=this.children[i];(!e||e&&o.exists)&&t(o,i,this.children)&&r.push(o)}return new n.ArraySet(r)},n.Group.prototype.forEach=function(t,e,i){if(void 0===i&&(i=!1),arguments.length<=3)for(var s=0;s<this.children.length;s++)(!i||i&&this.children[s].exists)&&t.call(e,this.children[s]);else{for(var n=[null],s=3;s<arguments.length;s++)n.push(arguments[s]);for(var s=0;s<this.children.length;s++)(!i||i&&this.children[s].exists)&&(n[0]=this.children[s],t.apply(e,n))}},n.Group.prototype.forEachExists=function(t,e){var i;if(arguments.length>2){i=[null];for(var s=2;s<arguments.length;s++)i.push(arguments[s])}this.iterate("exists",!0,n.Group.RETURN_TOTAL,t,e,i)},n.Group.prototype.forEachAlive=function(t,e){var i;if(arguments.length>2){i=[null];for(var s=2;s<arguments.length;s++)i.push(arguments[s])}this.iterate("alive",!0,n.Group.RETURN_TOTAL,t,e,i)},n.Group.prototype.forEachDead=function(t,e){var i;if(arguments.length>2){i=[null];for(var s=2;s<arguments.length;s++)i.push(arguments[s])}this.iterate("alive",!1,n.Group.RETURN_TOTAL,t,e,i)},n.Group.prototype.sort=function(t,e){this.children.length<2||(void 0===t&&(t="z"),void 0===e&&(e=n.Group.SORT_ASCENDING),this._sortProperty=t,e===n.Group.SORT_ASCENDING?this.children.sort(this.ascendingSortHandler.bind(this)):this.children.sort(this.descendingSortHandler.bind(this)),this.updateZ())},n.Group.prototype.customSort=function(t,e){this.children.length<2||(this.children.sort(t.bind(e)),this.updateZ())},n.Group.prototype.ascendingSortHandler=function(t,e){return t[this._sortProperty]<e[this._sortProperty]?-1:t[this._sortProperty]>e[this._sortProperty]?1:t.z<e.z?-1:1},n.Group.prototype.descendingSortHandler=function(t,e){return t[this._sortProperty]<e[this._sortProperty]?1:t[this._sortProperty]>e[this._sortProperty]?-1:0},n.Group.prototype.iterate=function(t,e,i,s,r,o){if(0===this.children.length){if(i===n.Group.RETURN_TOTAL)return 0;if(i===n.Group.RETURN_ALL)return[]}var a=0;if(i===n.Group.RETURN_ALL)var h=[];for(var l=0;l<this.children.length;l++)if(this.children[l][t]===e){if(a++,s&&(o?(o[0]=this.children[l],s.apply(r,o)):s.call(r,this.children[l])),i===n.Group.RETURN_CHILD)return this.children[l];i===n.Group.RETURN_ALL&&h.push(this.children[l])}return i===n.Group.RETURN_TOTAL?a:i===n.Group.RETURN_ALL?h:null},n.Group.prototype.getFirstExists=function(t,e,i,s,r,o){void 0===e&&(e=!1),"boolean"!=typeof t&&(t=!0);var a=this.iterate("exists",t,n.Group.RETURN_CHILD);return null===a&&e?this.create(i,s,r,o):this.resetChild(a,i,s,r,o)},n.Group.prototype.getFirstAlive=function(t,e,i,s,r){void 0===t&&(t=!1);var o=this.iterate("alive",!0,n.Group.RETURN_CHILD);return null===o&&t?this.create(e,i,s,r):this.resetChild(o,e,i,s,r)},n.Group.prototype.getFirstDead=function(t,e,i,s,r){void 0===t&&(t=!1);var o=this.iterate("alive",!1,n.Group.RETURN_CHILD);return null===o&&t?this.create(e,i,s,r):this.resetChild(o,e,i,s,r)},n.Group.prototype.resetChild=function(t,e,i,s,n){return null===t?null:(void 0===e&&(e=null),void 0===i&&(i=null),null!==e&&null!==i&&t.reset(e,i),void 0!==s&&t.loadTexture(s,n),t)},n.Group.prototype.getTop=function(){if(this.children.length>0)return this.children[this.children.length-1]},n.Group.prototype.getBottom=function(){if(this.children.length>0)return this.children[0]},n.Group.prototype.getClosestTo=function(t,e,i){for(var s=Number.MAX_VALUE,r=0,o=null,a=0;a<this.children.length;a++){var h=this.children[a];h.exists&&(r=Math.abs(n.Point.distance(t,h)))<s&&(!e||e.call(i,h,r))&&(s=r,o=h)}return o},n.Group.prototype.getFurthestFrom=function(t,e,i){for(var s=0,r=0,o=null,a=0;a<this.children.length;a++){var h=this.children[a];h.exists&&(r=Math.abs(n.Point.distance(t,h)))>s&&(!e||e.call(i,h,r))&&(s=r,o=h)}return o},n.Group.prototype.countLiving=function(){return this.iterate("alive",!0,n.Group.RETURN_TOTAL)},n.Group.prototype.countDead=function(){return this.iterate("alive",!1,n.Group.RETURN_TOTAL)},n.Group.prototype.getRandom=function(t,e){return void 0===t&&(t=0),void 0===e&&(e=this.children.length),0===e?null:n.ArrayUtils.getRandomItem(this.children,t,e)},n.Group.prototype.getRandomExists=function(t,e){var i=this.getAll("exists",!0,t,e);return this.game.rnd.pick(i)},n.Group.prototype.getAll=function(t,e,i,s){void 0===i&&(i=0),void 0===s&&(s=this.children.length);for(var n=[],r=i;r<s;r++){var o=this.children[r];t&&o[t]===e&&n.push(o)}return n},n.Group.prototype.remove=function(t,e,i){if(void 0===e&&(e=!1),void 0===i&&(i=!1),0===this.children.length||-1===this.children.indexOf(t))return!1;i||!t.events||t.destroyPhase||t.events.onRemovedFromGroup$dispatch(t,this);var s=this.removeChild(t);return this.removeFromHash(t),this.updateZ(),this.cursor===t&&this.next(),e&&s&&s.destroy(!0),!0},n.Group.prototype.moveAll=function(t,e){if(void 0===e&&(e=!1),this.children.length>0&&t instanceof n.Group){do{t.add(this.children[0],e)}while(this.children.length>0);this.hash=[],this.cursor=null}return t},n.Group.prototype.removeAll=function(t,e,i){if(void 0===t&&(t=!1),void 0===e&&(e=!1),void 0===i&&(i=!1),0!==this.children.length){do{!e&&this.children[0].events&&this.children[0].events.onRemovedFromGroup$dispatch(this.children[0],this);var s=this.removeChild(this.children[0]);this.removeFromHash(s),t&&s&&s.destroy(!0,i)}while(this.children.length>0);this.hash=[],this.cursor=null}},n.Group.prototype.removeBetween=function(t,e,i,s){if(void 0===e&&(e=this.children.length-1),void 0===i&&(i=!1),void 0===s&&(s=!1),0!==this.children.length){if(t>e||t<0||e>this.children.length)return!1;for(var n=e;n>=t;){!s&&this.children[n].events&&this.children[n].events.onRemovedFromGroup$dispatch(this.children[n],this);var r=this.removeChild(this.children[n]);this.removeFromHash(r),i&&r&&r.destroy(!0),this.cursor===this.children[n]&&(this.cursor=null),n--}this.updateZ()}},n.Group.prototype.destroy=function(t,e){null===this.game||this.ignoreDestroy||(void 0===t&&(t=!0),void 0===e&&(e=!1),this.onDestroy.dispatch(this,t,e),this.removeAll(t),this.cursor=null,this.filters=null,this.pendingDestroy=!1,e||(this.parent&&this.parent.removeChild(this),this.game=null,this.exists=!1))},Object.defineProperty(n.Group.prototype,"total",{get:function(){return this.iterate("exists",!0,n.Group.RETURN_TOTAL)}}),Object.defineProperty(n.Group.prototype,"length",{get:function(){return this.children.length}}),Object.defineProperty(n.Group.prototype,"angle",{get:function(){return n.Math.radToDeg(this.rotation)},set:function(t){this.rotation=n.Math.degToRad(t)}}),Object.defineProperty(n.Group.prototype,"centerX",{get:function(){return this.getBounds(this.parent).centerX},set:function(t){var e=this.getBounds(this.parent),i=this.x-e.x;this.x=t+i-e.halfWidth}}),Object.defineProperty(n.Group.prototype,"centerY",{get:function(){return this.getBounds(this.parent).centerY},set:function(t){var e=this.getBounds(this.parent),i=this.y-e.y;this.y=t+i-e.halfHeight}}),Object.defineProperty(n.Group.prototype,"left",{get:function(){return this.getBounds(this.parent).left},set:function(t){var e=this.getBounds(this.parent),i=this.x-e.x;this.x=t+i}}),Object.defineProperty(n.Group.prototype,"right",{get:function(){return this.getBounds(this.parent).right},set:function(t){var e=this.getBounds(this.parent),i=this.x-e.x;this.x=t+i-e.width}}),Object.defineProperty(n.Group.prototype,"top",{get:function(){return this.getBounds(this.parent).top},set:function(t){var e=this.getBounds(this.parent),i=this.y-e.y;this.y=t+i}}),Object.defineProperty(n.Group.prototype,"bottom",{get:function(){return this.getBounds(this.parent).bottom},set:function(t){var e=this.getBounds(this.parent),i=this.y-e.y;this.y=t+i-e.height}}),/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.World=function(t){n.Group.call(this,t,null,"__world",!1),this.bounds=new n.Rectangle(0,0,t.width,t.height),this.camera=null,this._definedSize=!1,this._width=t.width,this._height=t.height,this.game.state.onStateChange.add(this.stateChange,this)},n.World.prototype=Object.create(n.Group.prototype),n.World.prototype.constructor=n.World,n.World.prototype.boot=function(){this.camera=new n.Camera(this.game,0,0,0,this.game.width,this.game.height),this.game.stage.addChild(this),this.camera.boot()},n.World.prototype.stateChange=function(){this.x=0,this.y=0,this.camera.reset()},n.World.prototype.setBounds=function(t,e,i,s){this._definedSize=!0,this._width=i,this._height=s,this.bounds.setTo(t,e,i,s),this.x=t,this.y=e,this.camera.bounds&&this.camera.bounds.setTo(t,e,Math.max(i,this.game.width),Math.max(s,this.game.height)),this.game.physics.setBoundsToWorld()},n.World.prototype.resize=function(t,e){this._definedSize&&(t<this._width&&(t=this._width),e<this._height&&(e=this._height)),this.bounds.width=t,this.bounds.height=e,this.game.camera.setBoundsToWorld(),this.game.physics.setBoundsToWorld()},n.World.prototype.shutdown=function(){this.destroy(!0,!0)},n.World.prototype.wrap=function(t,e,i,s,n){void 0===e&&(e=0),void 0===i&&(i=!1),void 0===s&&(s=!0),void 0===n&&(n=!0),i?(t.getBounds(),s&&(t.x+t._currentBounds.width<this.bounds.x?t.x=this.bounds.right:t.x>this.bounds.right&&(t.x=this.bounds.left)),n&&(t.y+t._currentBounds.height<this.bounds.top?t.y=this.bounds.bottom:t.y>this.bounds.bottom&&(t.y=this.bounds.top))):(s&&t.x+e<this.bounds.x?t.x=this.bounds.right+e:s&&t.x-e>this.bounds.right&&(t.x=this.bounds.left-e),n&&t.y+e<this.bounds.top?t.y=this.bounds.bottom+e:n&&t.y-e>this.bounds.bottom&&(t.y=this.bounds.top-e))},Object.defineProperty(n.World.prototype,"width",{get:function(){return this.bounds.width},set:function(t){t<this.game.width&&(t=this.game.width),this.bounds.width=t,this._width=t,this._definedSize=!0}}),Object.defineProperty(n.World.prototype,"height",{get:function(){return this.bounds.height},set:function(t){t<this.game.height&&(t=this.game.height),this.bounds.height=t,this._height=t,this._definedSize=!0}}),Object.defineProperty(n.World.prototype,"centerX",{get:function(){return this.bounds.halfWidth+this.bounds.x}}),Object.defineProperty(n.World.prototype,"centerY",{get:function(){return this.bounds.halfHeight+this.bounds.y}}),Object.defineProperty(n.World.prototype,"randomX",{get:function(){return this.bounds.x<0?this.game.rnd.between(this.bounds.x,this.bounds.width-Math.abs(this.bounds.x)):this.game.rnd.between(this.bounds.x,this.bounds.width)}}),Object.defineProperty(n.World.prototype,"randomY",{get:function(){return this.bounds.y<0?this.game.rnd.between(this.bounds.y,this.bounds.height-Math.abs(this.bounds.y)):this.game.rnd.between(this.bounds.y,this.bounds.height)}}),/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Game=function(t,e,i,s,r,o,a,h){return this.id=n.GAMES.push(this)-1,this.config=null,this.physicsConfig=h,this.parent="",this.width=800,this.height=600,this.resolution=1,this._width=800,this._height=600,this.transparent=!1,this.antialias=!0,this.preserveDrawingBuffer=!1,this.clearBeforeRender=!0,this.renderer=null,this.renderType=n.AUTO,this.state=null,this.isBooted=!1,this.isRunning=!1,this.raf=null,this.add=null,this.make=null,this.cache=null,this.input=null,this.load=null,this.math=null,this.net=null,this.scale=null,this.sound=null,this.stage=null,this.time=null,this.tweens=null,this.world=null,this.physics=null,this.plugins=null,this.rnd=null,this.device=n.Device,this.camera=null,this.canvas=null,this.context=null,this.debug=null,this.particles=null,this.create=null,this.lockRender=!1,this.stepping=!1,this.pendingStep=!1,this.stepCount=0,this.onPause=null,this.onResume=null,this.onBlur=null,this.onFocus=null,this._paused=!1,this._codePaused=!1,this.currentUpdateID=0,this.updatesThisFrame=1,this._deltaTime=0,this._lastCount=0,this._spiraling=0,this._kickstart=!0,this.fpsProblemNotifier=new n.Signal,this.forceSingleUpdate=!0,this._nextFpsNotification=0,1===arguments.length&&"object"==typeof arguments[0]?this.parseConfig(arguments[0]):(this.config={enableDebug:!0},void 0!==t&&(this._width=t),void 0!==e&&(this._height=e),void 0!==i&&(this.renderType=i),void 0!==s&&(this.parent=s),void 0!==o&&(this.transparent=o),void 0!==a&&(this.antialias=a),this.rnd=new n.RandomDataGenerator([(Date.now()*Math.random()).toString()]),this.state=new n.StateManager(this,r)),this.device.whenReady(this.boot,this),this},n.Game.prototype={parseConfig:function(t){this.config=t,void 0===t.enableDebug&&(this.config.enableDebug=!0),t.width&&(this._width=t.width),t.height&&(this._height=t.height),t.renderer&&(this.renderType=t.renderer),t.parent&&(this.parent=t.parent),void 0!==t.transparent&&(this.transparent=t.transparent),void 0!==t.antialias&&(this.antialias=t.antialias),t.resolution&&(this.resolution=t.resolution),void 0!==t.preserveDrawingBuffer&&(this.preserveDrawingBuffer=t.preserveDrawingBuffer),t.physicsConfig&&(this.physicsConfig=t.physicsConfig);var e=[(Date.now()*Math.random()).toString()];t.seed&&(e=t.seed),this.rnd=new n.RandomDataGenerator(e);var i=null;t.state&&(i=t.state),this.state=new n.StateManager(this,i)},boot:function(){this.isBooted||(this.onPause=new n.Signal,this.onResume=new n.Signal,this.onBlur=new n.Signal,this.onFocus=new n.Signal,this.isBooted=!0,PIXI.game=this,this.math=n.Math,this.scale=new n.ScaleManager(this,this._width,this._height),this.stage=new n.Stage(this),this.setUpRenderer(),this.world=new n.World(this),this.add=new n.GameObjectFactory(this),this.make=new n.GameObjectCreator(this),this.cache=new n.Cache(this),this.load=new n.Loader(this),this.time=new n.Time(this),this.tweens=new n.TweenManager(this),this.input=new n.Input(this),this.sound=new n.SoundManager(this),this.physics=new n.Physics(this,this.physicsConfig),this.particles=new n.Particles(this),this.create=new n.Create(this),this.plugins=new n.PluginManager(this),this.net=new n.Net(this),this.time.boot(),this.stage.boot(),this.world.boot(),this.scale.boot(),this.input.boot(),this.sound.boot(),this.state.boot(),this.config.enableDebug?(this.debug=new n.Utils.Debug(this),this.debug.boot()):this.debug={preUpdate:function(){},update:function(){},reset:function(){}},this.showDebugHeader(),this.isRunning=!0,this.config&&this.config.forceSetTimeOut?this.raf=new n.RequestAnimationFrame(this,this.config.forceSetTimeOut):this.raf=new n.RequestAnimationFrame(this,!1),this._kickstart=!0,window.focus&&(!window.PhaserGlobal||window.PhaserGlobal&&!window.PhaserGlobal.stopFocus)&&window.focus(),this.raf.start())},showDebugHeader:function(){if(!window.PhaserGlobal||!window.PhaserGlobal.hideBanner){var t=n.VERSION,e="Canvas",i="HTML Audio",s=1;if(this.renderType===n.WEBGL?(e="WebGL",s++):this.renderType===n.HEADLESS&&(e="Headless"),this.device.webAudio&&(i="WebAudio",s++),this.device.chrome){for(var r=["%c %c %c Phaser v"+t+" | Pixi.js | "+e+" | "+i+" %c %c %c http://phaser.io %c♥%c♥%c♥","background: #fb8cb3","background: #d44a52","color: #ffffff; background: #871905;","background: #d44a52","background: #fb8cb3","background: #ffffff"],o=0;o<3;o++)o<s?r.push("color: #ff2424; background: #fff"):r.push("color: #959595; background: #fff");console.log.apply(console,r)}else window.console&&console.log("Phaser v"+t+" | Pixi.js "+PIXI.VERSION+" | "+e+" | "+i+" | http://phaser.io")}},setUpRenderer:function(){if(this.config.canvas?this.canvas=this.config.canvas:this.canvas=n.Canvas.create(this,this.width,this.height,this.config.canvasID,!0),this.config.canvasStyle?this.canvas.style=this.config.canvasStyle:this.canvas.style["-webkit-full-screen"]="width: 100%; height: 100%",this.renderType===n.HEADLESS||this.renderType===n.CANVAS||this.renderType===n.AUTO&&!this.device.webGL){if(!this.device.canvas)throw new Error("Phaser.Game - Cannot create Canvas or WebGL context, aborting.");this.renderType=n.CANVAS,this.renderer=new PIXI.CanvasRenderer(this),this.context=this.renderer.context}else this.renderType=n.WEBGL,this.renderer=new PIXI.WebGLRenderer(this),this.context=null,this.canvas.addEventListener("webglcontextlost",this.contextLost.bind(this),!1),this.canvas.addEventListener("webglcontextrestored",this.contextRestored.bind(this),!1);this.device.cocoonJS&&(this.canvas.screencanvas=this.renderType===n.CANVAS),this.renderType!==n.HEADLESS&&(this.stage.smoothed=this.antialias,n.Canvas.addToDOM(this.canvas,this.parent,!1),n.Canvas.setTouchAction(this.canvas))},contextLost:function(t){t.preventDefault(),this.renderer.contextLost=!0},contextRestored:function(){this.renderer.initContext(),this.cache.clearGLTextures(),this.renderer.contextLost=!1},update:function(t){if(this.time.update(t),this._kickstart)return this.updateLogic(this.time.desiredFpsMult),this.updateRender(this.time.slowMotion*this.time.desiredFps),void(this._kickstart=!1);if(this._spiraling>1&&!this.forceSingleUpdate)this.time.time>this._nextFpsNotification&&(this._nextFpsNotification=this.time.time+1e4,this.fpsProblemNotifier.dispatch()),this._deltaTime=0,this._spiraling=0,this.updateRender(this.time.slowMotion*this.time.desiredFps);else{var e=1e3*this.time.slowMotion/this.time.desiredFps;this._deltaTime+=Math.max(Math.min(3*e,this.time.elapsed),0);var i=0;for(this.updatesThisFrame=Math.floor(this._deltaTime/e),this.forceSingleUpdate&&(this.updatesThisFrame=Math.min(1,this.updatesThisFrame));this._deltaTime>=e&&(this._deltaTime-=e,this.currentUpdateID=i,this.updateLogic(this.time.desiredFpsMult),i++,!this.forceSingleUpdate||1!==i);)this.time.refresh();i>this._lastCount?this._spiraling++:i<this._lastCount&&(this._spiraling=0),this._lastCount=i,this.updateRender(this._deltaTime/e)}},updateLogic:function(t){this._paused||this.pendingStep?(this.scale.pauseUpdate(),this.state.pauseUpdate(),this.debug.preUpdate()):(this.stepping&&(this.pendingStep=!0),this.scale.preUpdate(),this.debug.preUpdate(),this.camera.preUpdate(),this.physics.preUpdate(),this.state.preUpdate(t),this.plugins.preUpdate(t),this.stage.preUpdate(),this.state.update(),this.stage.update(),this.tweens.update(),this.sound.update(),this.input.update(),this.physics.update(),this.particles.update(),this.plugins.update(),this.stage.postUpdate(),this.plugins.postUpdate()),this.stage.updateTransform()},updateRender:function(t){this.lockRender||(this.state.preRender(t),this.renderType!==n.HEADLESS&&(this.renderer.render(this.stage),this.plugins.render(t),this.state.render(t)),this.plugins.postRender(t))},enableStep:function(){this.stepping=!0,this.pendingStep=!1,this.stepCount=0},disableStep:function(){this.stepping=!1,this.pendingStep=!1},step:function(){this.pendingStep=!1,this.stepCount++},destroy:function(){this.raf.stop(),this.state.destroy(),this.sound.destroy(),this.scale.destroy(),this.stage.destroy(),this.input.destroy(),this.physics.destroy(),this.plugins.destroy(),this.state=null,this.sound=null,this.scale=null,this.stage=null,this.input=null,this.physics=null,this.plugins=null,this.cache=null,this.load=null,this.time=null,this.world=null,this.isBooted=!1,this.renderer.destroy(!1),n.Canvas.removeFromDOM(this.canvas),PIXI.defaultRenderer=null,n.GAMES[this.id]=null},gamePaused:function(t){this._paused||(this._paused=!0,this.time.gamePaused(),this.sound.muteOnPause&&this.sound.setMute(),this.onPause.dispatch(t),this.device.cordova&&this.device.iOS&&(this.lockRender=!0))},gameResumed:function(t){this._paused&&!this._codePaused&&(this._paused=!1,this.time.gameResumed(),this.input.reset(),this.sound.muteOnPause&&this.sound.unsetMute(),this.onResume.dispatch(t),this.device.cordova&&this.device.iOS&&(this.lockRender=!1))},focusLoss:function(t){this.onBlur.dispatch(t),this.stage.disableVisibilityChange||this.gamePaused(t)},focusGain:function(t){this.onFocus.dispatch(t),this.stage.disableVisibilityChange||this.gameResumed(t)}},n.Game.prototype.constructor=n.Game,Object.defineProperty(n.Game.prototype,"paused",{get:function(){return this._paused},set:function(t){!0===t?(!1===this._paused&&(this._paused=!0,this.sound.setMute(),this.time.gamePaused(),this.onPause.dispatch(this)),this._codePaused=!0):(this._paused&&(this._paused=!1,this.input.reset(),this.sound.unsetMute(),this.time.gameResumed(),this.onResume.dispatch(this)),this._codePaused=!1)}}),/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Input=function(t){this.game=t,this.hitCanvas=null,this.hitContext=null,this.moveCallbacks=[],this.customCandidateHandler=null,this.customCandidateHandlerContext=null,this.pollRate=0,this.enabled=!0,this.multiInputOverride=n.Input.MOUSE_TOUCH_COMBINE,this.position=null,this.speed=null,this.circle=null,this.scale=null,this.maxPointers=-1,this.tapRate=200,this.doubleTapRate=300,this.holdRate=2e3,this.justPressedRate=200,this.justReleasedRate=200,this.recordPointerHistory=!1,this.recordRate=100,this.recordLimit=100,this.pointer1=null,this.pointer2=null,this.pointer3=null,this.pointer4=null,this.pointer5=null,this.pointer6=null,this.pointer7=null,this.pointer8=null,this.pointer9=null,this.pointer10=null,this.pointers=[],this.activePointer=null,this.mousePointer=null,this.mouse=null,this.keyboard=null,this.touch=null,this.mspointer=null,this.gamepad=null,this.resetLocked=!1,this.onDown=null,this.onUp=null,this.onTap=null,this.onHold=null,this.minPriorityID=0,this.interactiveItems=new n.ArraySet,this._localPoint=new n.Point,this._pollCounter=0,this._oldPosition=null,this._x=0,this._y=0},n.Input.MOUSE_OVERRIDES_TOUCH=0,n.Input.TOUCH_OVERRIDES_MOUSE=1,n.Input.MOUSE_TOUCH_COMBINE=2,n.Input.MAX_POINTERS=10,n.Input.prototype={boot:function(){this.mousePointer=new n.Pointer(this.game,0,n.PointerMode.CURSOR),this.addPointer(),this.addPointer(),this.mouse=new n.Mouse(this.game),this.touch=new n.Touch(this.game),this.mspointer=new n.MSPointer(this.game),n.Keyboard&&(this.keyboard=new n.Keyboard(this.game)),n.Gamepad&&(this.gamepad=new n.Gamepad(this.game)),this.onDown=new n.Signal,this.onUp=new n.Signal,this.onTap=new n.Signal,this.onHold=new n.Signal,this.scale=new n.Point(1,1),this.speed=new n.Point,this.position=new n.Point,this._oldPosition=new n.Point,this.circle=new n.Circle(0,0,44),this.activePointer=this.mousePointer,this.hitCanvas=PIXI.CanvasPool.create(this,1,1),this.hitContext=this.hitCanvas.getContext("2d"),this.mouse.start(),this.touch.start(),this.mspointer.start(),this.mousePointer.active=!0,this.keyboard&&this.keyboard.start();var t=this;this._onClickTrampoline=function(e){t.onClickTrampoline(e)},this.game.canvas.addEventListener("click",this._onClickTrampoline,!1)},destroy:function(){this.mouse.stop(),this.touch.stop(),this.mspointer.stop(),this.keyboard&&this.keyboard.stop(),this.gamepad&&this.gamepad.stop(),this.moveCallbacks=[],PIXI.CanvasPool.remove(this),this.game.canvas.removeEventListener("click",this._onClickTrampoline)},setInteractiveCandidateHandler:function(t,e){this.customCandidateHandler=t,this.customCandidateHandlerContext=e},addMoveCallback:function(t,e){this.moveCallbacks.push({callback:t,context:e})},deleteMoveCallback:function(t,e){for(var i=this.moveCallbacks.length;i--;)if(this.moveCallbacks[i].callback===t&&this.moveCallbacks[i].context===e)return void this.moveCallbacks.splice(i,1)},addPointer:function(){if(this.pointers.length>=n.Input.MAX_POINTERS)return console.warn("Phaser.Input.addPointer: Maximum limit of "+n.Input.MAX_POINTERS+" pointers reached."),null;var t=this.pointers.length+1,e=new n.Pointer(this.game,t,n.PointerMode.TOUCH);return this.pointers.push(e),this["pointer"+t]=e,e},update:function(){if(this.keyboard&&this.keyboard.update(),this.pollRate>0&&this._pollCounter<this.pollRate)return void this._pollCounter++;this.speed.x=this.position.x-this._oldPosition.x,this.speed.y=this.position.y-this._oldPosition.y,this._oldPosition.copyFrom(this.position),this.mousePointer.update(),this.gamepad&&this.gamepad.active&&this.gamepad.update();for(var t=0;t<this.pointers.length;t++)this.pointers[t].update();this._pollCounter=0},reset:function(t){if(this.game.isBooted&&!this.resetLocked){void 0===t&&(t=!1),this.mousePointer.reset(),this.keyboard&&this.keyboard.reset(t),this.gamepad&&this.gamepad.reset();for(var e=0;e<this.pointers.length;e++)this.pointers[e].reset();"none"!==this.game.canvas.style.cursor&&(this.game.canvas.style.cursor="inherit"),t&&(this.onDown.dispose(),this.onUp.dispose(),this.onTap.dispose(),this.onHold.dispose(),this.onDown=new n.Signal,this.onUp=new n.Signal,this.onTap=new n.Signal,this.onHold=new n.Signal,this.moveCallbacks=[]),this._pollCounter=0}},resetSpeed:function(t,e){this._oldPosition.setTo(t,e),this.speed.setTo(0,0)},startPointer:function(t){if(this.maxPointers>=0&&this.countActivePointers(this.maxPointers)>=this.maxPointers)return null;if(!this.pointer1.active)return this.pointer1.start(t);if(!this.pointer2.active)return this.pointer2.start(t);for(var e=2;e<this.pointers.length;e++){var i=this.pointers[e];if(!i.active)return i.start(t)}return null},updatePointer:function(t){if(this.pointer1.active&&this.pointer1.identifier===t.identifier)return this.pointer1.move(t);if(this.pointer2.active&&this.pointer2.identifier===t.identifier)return this.pointer2.move(t);for(var e=2;e<this.pointers.length;e++){var i=this.pointers[e];if(i.active&&i.identifier===t.identifier)return i.move(t)}return null},stopPointer:function(t){if(this.pointer1.active&&this.pointer1.identifier===t.identifier)return this.pointer1.stop(t);if(this.pointer2.active&&this.pointer2.identifier===t.identifier)return this.pointer2.stop(t);for(var e=2;e<this.pointers.length;e++){var i=this.pointers[e];if(i.active&&i.identifier===t.identifier)return i.stop(t)}return null},countActivePointers:function(t){void 0===t&&(t=this.pointers.length);for(var e=t,i=0;i<this.pointers.length&&e>0;i++){this.pointers[i].active&&e--}return t-e},getPointer:function(t){void 0===t&&(t=!1);for(var e=0;e<this.pointers.length;e++){var i=this.pointers[e];if(i.active===t)return i}return null},getPointerFromIdentifier:function(t){for(var e=0;e<this.pointers.length;e++){var i=this.pointers[e];if(i.identifier===t)return i}return null},getPointerFromId:function(t){for(var e=0;e<this.pointers.length;e++){var i=this.pointers[e];if(i.pointerId===t)return i}return null},getLocalPosition:function(t,e,i){void 0===i&&(i=new n.Point);var s=t.worldTransform,r=1/(s.a*s.d+s.c*-s.b);return i.setTo(s.d*r*e.x+-s.c*r*e.y+(s.ty*s.c-s.tx*s.d)*r,s.a*r*e.y+-s.b*r*e.x+(-s.ty*s.a+s.tx*s.b)*r)},hitTest:function(t,e,i){if(!t.worldVisible)return!1;if(this.getLocalPosition(t,e,this._localPoint),i.copyFrom(this._localPoint),t.hitArea&&t.hitArea.contains)return t.hitArea.contains(this._localPoint.x,this._localPoint.y);if(t instanceof n.TileSprite){var s=t.width,r=t.height,o=-s*t.anchor.x;if(this._localPoint.x>=o&&this._localPoint.x<o+s){var a=-r*t.anchor.y;if(this._localPoint.y>=a&&this._localPoint.y<a+r)return!0}}else if(t instanceof PIXI.Sprite){var s=t.texture.frame.width,r=t.texture.frame.height,o=-s*t.anchor.x;if(this._localPoint.x>=o&&this._localPoint.x<o+s){var a=-r*t.anchor.y;if(this._localPoint.y>=a&&this._localPoint.y<a+r)return!0}}else if(t instanceof n.Graphics)for(var h=0;h<t.graphicsData.length;h++){var l=t.graphicsData[h];if(l.fill&&(l.shape&&l.shape.contains(this._localPoint.x,this._localPoint.y)))return!0}for(var h=0;h<t.children.length;h++)if(this.hitTest(t.children[h],e,i))return!0;return!1},onClickTrampoline:function(){this.activePointer.processClickTrampolines()}},n.Input.prototype.constructor=n.Input,Object.defineProperty(n.Input.prototype,"x",{get:function(){return this._x},set:function(t){this._x=Math.floor(t)}}),Object.defineProperty(n.Input.prototype,"y",{get:function(){return this._y},set:function(t){this._y=Math.floor(t)}}),Object.defineProperty(n.Input.prototype,"pollLocked",{get:function(){return this.pollRate>0&&this._pollCounter<this.pollRate}}),Object.defineProperty(n.Input.prototype,"totalInactivePointers",{get:function(){return this.pointers.length-this.countActivePointers()}}),Object.defineProperty(n.Input.prototype,"totalActivePointers",{get:function(){return this.countActivePointers()}}),Object.defineProperty(n.Input.prototype,"worldX",{get:function(){return this.game.camera.view.x+this.x}}),Object.defineProperty(n.Input.prototype,"worldY",{get:function(){return this.game.camera.view.y+this.y}}),/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Mouse=function(t){this.game=t,this.input=t.input,this.callbackContext=this.game,this.mouseDownCallback=null,this.mouseUpCallback=null,this.mouseOutCallback=null,this.mouseOverCallback=null,this.mouseWheelCallback=null,this.capture=!1,this.button=-1,this.wheelDelta=0,this.enabled=!0,this.locked=!1,this.stopOnGameOut=!1,this.pointerLock=new n.Signal,this.event=null,this._onMouseDown=null,this._onMouseMove=null,this._onMouseUp=null,this._onMouseOut=null,this._onMouseOver=null,this._onMouseWheel=null,this._wheelEvent=null},n.Mouse.NO_BUTTON=-1,n.Mouse.LEFT_BUTTON=0,n.Mouse.MIDDLE_BUTTON=1,n.Mouse.RIGHT_BUTTON=2,n.Mouse.BACK_BUTTON=3,n.Mouse.FORWARD_BUTTON=4,n.Mouse.WHEEL_UP=1,n.Mouse.WHEEL_DOWN=-1,n.Mouse.prototype={start:function(){if((!this.game.device.android||!1!==this.game.device.chrome)&&null===this._onMouseDown){var t=this;this._onMouseDown=function(e){return t.onMouseDown(e)},this._onMouseMove=function(e){return t.onMouseMove(e)},this._onMouseUp=function(e){return t.onMouseUp(e)},this._onMouseUpGlobal=function(e){return t.onMouseUpGlobal(e)},this._onMouseOutGlobal=function(e){return t.onMouseOutGlobal(e)},this._onMouseOut=function(e){return t.onMouseOut(e)},this._onMouseOver=function(e){return t.onMouseOver(e)},this._onMouseWheel=function(e){return t.onMouseWheel(e)};var e=this.game.canvas;e.addEventListener("mousedown",this._onMouseDown,!0),e.addEventListener("mousemove",this._onMouseMove,!0),e.addEventListener("mouseup",this._onMouseUp,!0),this.game.device.cocoonJS||(window.addEventListener("mouseup",this._onMouseUpGlobal,!0),window.addEventListener("mouseout",this._onMouseOutGlobal,!0),e.addEventListener("mouseover",this._onMouseOver,!0),e.addEventListener("mouseout",this._onMouseOut,!0));var i=this.game.device.wheelEvent;i&&(e.addEventListener(i,this._onMouseWheel,!0),"mousewheel"===i?this._wheelEvent=new s(-.025,1):"DOMMouseScroll"===i&&(this._wheelEvent=new s(1,1)))}},onMouseDown:function(t){this.event=t,this.capture&&t.preventDefault(),this.mouseDownCallback&&this.mouseDownCallback.call(this.callbackContext,t),this.input.enabled&&this.enabled&&(t.identifier=0,this.input.mousePointer.start(t))},onMouseMove:function(t){this.event=t,this.capture&&t.preventDefault(),this.mouseMoveCallback&&this.mouseMoveCallback.call(this.callbackContext,t),this.input.enabled&&this.enabled&&(t.identifier=0,this.input.mousePointer.move(t))},onMouseUp:function(t){this.event=t,this.capture&&t.preventDefault(),this.mouseUpCallback&&this.mouseUpCallback.call(this.callbackContext,t),this.input.enabled&&this.enabled&&(t.identifier=0,this.input.mousePointer.stop(t))},onMouseUpGlobal:function(t){this.input.mousePointer.withinGame||(this.mouseUpCallback&&this.mouseUpCallback.call(this.callbackContext,t),t.identifier=0,this.input.mousePointer.stop(t))},onMouseOutGlobal:function(t){this.event=t,this.capture&&t.preventDefault(),this.input.mousePointer.withinGame=!1,this.input.enabled&&this.enabled&&(this.input.mousePointer.stop(t),this.input.mousePointer.leftButton.stop(t),this.input.mousePointer.rightButton.stop(t))},onMouseOut:function(t){this.event=t,this.capture&&t.preventDefault(),this.input.mousePointer.withinGame=!1,this.mouseOutCallback&&this.mouseOutCallback.call(this.callbackContext,t),this.input.enabled&&this.enabled&&this.stopOnGameOut&&(t.identifier=0,this.input.mousePointer.stop(t))},onMouseOver:function(t){this.event=t,this.capture&&t.preventDefault(),this.input.mousePointer.withinGame=!0,this.mouseOverCallback&&this.mouseOverCallback.call(this.callbackContext,t)},onMouseWheel:function(t){this._wheelEvent&&(t=this._wheelEvent.bindEvent(t)),this.event=t,this.capture&&t.preventDefault(),this.wheelDelta=n.Math.clamp(-t.deltaY,-1,1),this.mouseWheelCallback&&this.mouseWheelCallback.call(this.callbackContext,t)},requestPointerLock:function(){if(this.game.device.pointerLock){var t=this.game.canvas;t.requestPointerLock=t.requestPointerLock||t.mozRequestPointerLock||t.webkitRequestPointerLock,t.requestPointerLock();var e=this;this._pointerLockChange=function(t){return e.pointerLockChange(t)},document.addEventListener("pointerlockchange",this._pointerLockChange,!0),document.addEventListener("mozpointerlockchange",this._pointerLockChange,!0),document.addEventListener("webkitpointerlockchange",this._pointerLockChange,!0)}},pointerLockChange:function(t){var e=this.game.canvas;document.pointerLockElement===e||document.mozPointerLockElement===e||document.webkitPointerLockElement===e?(this.locked=!0,this.pointerLock.dispatch(!0,t)):(this.locked=!1,this.pointerLock.dispatch(!1,t))},releasePointerLock:function(){document.exitPointerLock=document.exitPointerLock||document.mozExitPointerLock||document.webkitExitPointerLock,document.exitPointerLock(),document.removeEventListener("pointerlockchange",this._pointerLockChange,!0),document.removeEventListener("mozpointerlockchange",this._pointerLockChange,!0),document.removeEventListener("webkitpointerlockchange",this._pointerLockChange,!0)},stop:function(){var t=this.game.canvas;t.removeEventListener("mousedown",this._onMouseDown,!0),t.removeEventListener("mousemove",this._onMouseMove,!0),t.removeEventListener("mouseup",this._onMouseUp,!0),t.removeEventListener("mouseover",this._onMouseOver,!0),t.removeEventListener("mouseout",this._onMouseOut,!0);var e=this.game.device.wheelEvent;e&&t.removeEventListener(e,this._onMouseWheel,!0),window.removeEventListener("mouseup",this._onMouseUpGlobal,!0),window.removeEventListener("mouseout",this._onMouseOutGlobal,!0),document.removeEventListener("pointerlockchange",this._pointerLockChange,!0),document.removeEventListener("mozpointerlockchange",this._pointerLockChange,!0),document.removeEventListener("webkitpointerlockchange",this._pointerLockChange,!0)}},n.Mouse.prototype.constructor=n.Mouse,s.prototype={},s.prototype.constructor=s,s.prototype.bindEvent=function(t){if(!s._stubsGenerated&&t){for(var e in t)e in s.prototype||Object.defineProperty(s.prototype,e,{get:function(t){return function(){var e=this.originalEvent[t];return"function"!=typeof e?e:e.bind(this.originalEvent)}}(e)});s._stubsGenerated=!0}return this.originalEvent=t,this},Object.defineProperties(s.prototype,{type:{value:"wheel"},deltaMode:{get:function(){return this._deltaMode}},deltaY:{get:function(){return this._scaleFactor*(this.originalEvent.wheelDelta||this.originalEvent.detail)||0}},deltaX:{get:function(){return this._scaleFactor*this.originalEvent.wheelDeltaX||0}},deltaZ:{value:0}}),/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.MSPointer=function(t){this.game=t,this.input=t.input,this.callbackContext=this.game,this.pointerDownCallback=null,this.pointerMoveCallback=null,this.pointerUpCallback=null,this.capture=!0,this.button=-1,this.event=null,this.enabled=!0,this._onMSPointerDown=null,this._onMSPointerMove=null,this._onMSPointerUp=null,this._onMSPointerUpGlobal=null,this._onMSPointerOut=null,this._onMSPointerOver=null},n.MSPointer.prototype={start:function(){if(null===this._onMSPointerDown){var t=this;if(this.game.device.mspointer){this._onMSPointerDown=function(e){return t.onPointerDown(e)},this._onMSPointerMove=function(e){return t.onPointerMove(e)},this._onMSPointerUp=function(e){return t.onPointerUp(e)},this._onMSPointerUpGlobal=function(e){return t.onPointerUpGlobal(e)},this._onMSPointerOut=function(e){return t.onPointerOut(e)},this._onMSPointerOver=function(e){return t.onPointerOver(e)};var e=this.game.canvas;e.addEventListener("MSPointerDown",this._onMSPointerDown,!1),e.addEventListener("MSPointerMove",this._onMSPointerMove,!1),e.addEventListener("MSPointerUp",this._onMSPointerUp,!1),e.addEventListener("pointerdown",this._onMSPointerDown,!1),e.addEventListener("pointermove",this._onMSPointerMove,!1),e.addEventListener("pointerup",this._onMSPointerUp,!1),e.style["-ms-content-zooming"]="none",e.style["-ms-touch-action"]="none",this.game.device.cocoonJS||(window.addEventListener("MSPointerUp",this._onMSPointerUpGlobal,!0),e.addEventListener("MSPointerOver",this._onMSPointerOver,!0),e.addEventListener("MSPointerOut",this._onMSPointerOut,!0),window.addEventListener("pointerup",this._onMSPointerUpGlobal,!0),e.addEventListener("pointerover",this._onMSPointerOver,!0),e.addEventListener("pointerout",this._onMSPointerOut,!0))}}},onPointerDown:function(t){this.event=t,this.capture&&t.preventDefault(),this.pointerDownCallback&&this.pointerDownCallback.call(this.callbackContext,t),this.input.enabled&&this.enabled&&(t.identifier=t.pointerId,"mouse"===t.pointerType||4===t.pointerType?this.input.mousePointer.start(t):this.input.startPointer(t))},onPointerMove:function(t){this.event=t,this.capture&&t.preventDefault(),this.pointerMoveCallback&&this.pointerMoveCallback.call(this.callbackContext,t),this.input.enabled&&this.enabled&&(t.identifier=t.pointerId,"mouse"===t.pointerType||4===t.pointerType?this.input.mousePointer.move(t):this.input.updatePointer(t))},onPointerUp:function(t){this.event=t,this.capture&&t.preventDefault(),this.pointerUpCallback&&this.pointerUpCallback.call(this.callbackContext,t),this.input.enabled&&this.enabled&&(t.identifier=t.pointerId,"mouse"===t.pointerType||4===t.pointerType?this.input.mousePointer.stop(t):this.input.stopPointer(t))},onPointerUpGlobal:function(t){if("mouse"!==t.pointerType&&4!==t.pointerType||this.input.mousePointer.withinGame){var e=this.input.getPointerFromIdentifier(t.identifier);e&&e.withinGame&&this.onPointerUp(t)}else this.onPointerUp(t)},onPointerOut:function(t){if(this.event=t,this.capture&&t.preventDefault(),"mouse"===t.pointerType||4===t.pointerType)this.input.mousePointer.withinGame=!1;else{var e=this.input.getPointerFromIdentifier(t.identifier);e&&(e.withinGame=!1)}this.input.mouse.mouseOutCallback&&this.input.mouse.mouseOutCallback.call(this.input.mouse.callbackContext,t),this.input.enabled&&this.enabled&&this.input.mouse.stopOnGameOut&&(t.identifier=0,e?e.stop(t):this.input.mousePointer.stop(t))},onPointerOver:function(t){if(this.event=t,this.capture&&t.preventDefault(),"mouse"===t.pointerType||4===t.pointerType)this.input.mousePointer.withinGame=!0;else{var e=this.input.getPointerFromIdentifier(t.identifier);e&&(e.withinGame=!0)}this.input.mouse.mouseOverCallback&&this.input.mouse.mouseOverCallback.call(this.input.mouse.callbackContext,t)},stop:function(){var t=this.game.canvas;t.removeEventListener("MSPointerDown",this._onMSPointerDown,!1),t.removeEventListener("MSPointerMove",this._onMSPointerMove,!1),t.removeEventListener("MSPointerUp",this._onMSPointerUp,!1),t.removeEventListener("pointerdown",this._onMSPointerDown,!1),t.removeEventListener("pointermove",this._onMSPointerMove,!1),t.removeEventListener("pointerup",this._onMSPointerUp,!1),window.removeEventListener("MSPointerUp",this._onMSPointerUpGlobal,!0),t.removeEventListener("MSPointerOver",this._onMSPointerOver,!0),t.removeEventListener("MSPointerOut",this._onMSPointerOut,!0),window.removeEventListener("pointerup",this._onMSPointerUpGlobal,!0),t.removeEventListener("pointerover",this._onMSPointerOver,!0),t.removeEventListener("pointerout",this._onMSPointerOut,!0)}},n.MSPointer.prototype.constructor=n.MSPointer,/**
* @author Richard Davey <[email protected]>
* @author @karlmacklin <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.DeviceButton=function(t,e){this.parent=t,this.game=t.game,this.event=null,this.isDown=!1,this.isUp=!0,this.timeDown=0,this.timeUp=0,this.repeats=0,this.altKey=!1,this.shiftKey=!1,this.ctrlKey=!1,this.value=0,this.buttonCode=e,this.onDown=new n.Signal,this.onUp=new n.Signal,this.onFloat=new n.Signal},n.DeviceButton.prototype={start:function(t,e){this.isDown||(this.isDown=!0,this.isUp=!1,this.timeDown=this.game.time.time,this.repeats=0,this.event=t,this.value=e,t&&(this.altKey=t.altKey,this.shiftKey=t.shiftKey,this.ctrlKey=t.ctrlKey),this.onDown.dispatch(this,e))},stop:function(t,e){this.isUp||(this.isDown=!1,this.isUp=!0,this.timeUp=this.game.time.time,this.event=t,this.value=e,t&&(this.altKey=t.altKey,this.shiftKey=t.shiftKey,this.ctrlKey=t.ctrlKey),this.onUp.dispatch(this,e))},padFloat:function(t){this.value=t,this.onFloat.dispatch(this,t)},justPressed:function(t){return t=t||250,this.isDown&&this.timeDown+t>this.game.time.time},justReleased:function(t){return t=t||250,this.isUp&&this.timeUp+t>this.game.time.time},reset:function(){this.isDown=!1,this.isUp=!0,this.timeDown=this.game.time.time,this.repeats=0,this.altKey=!1,this.shiftKey=!1,this.ctrlKey=!1},destroy:function(){this.onDown.dispose(),this.onUp.dispose(),this.onFloat.dispose(),this.parent=null,this.game=null}},n.DeviceButton.prototype.constructor=n.DeviceButton,Object.defineProperty(n.DeviceButton.prototype,"duration",{get:function(){return this.isUp?-1:this.game.time.time-this.timeDown}}),/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Pointer=function(t,e,i){this.game=t,this.id=e,this.type=n.POINTER,this.exists=!0,this.identifier=0,this.pointerId=null,this.pointerMode=i||n.PointerMode.CURSOR|n.PointerMode.CONTACT,this.target=null,this.button=null,this.leftButton=new n.DeviceButton(this,n.Pointer.LEFT_BUTTON),this.middleButton=new n.DeviceButton(this,n.Pointer.MIDDLE_BUTTON),this.rightButton=new n.DeviceButton(this,n.Pointer.RIGHT_BUTTON),this.backButton=new n.DeviceButton(this,n.Pointer.BACK_BUTTON),this.forwardButton=new n.DeviceButton(this,n.Pointer.FORWARD_BUTTON),this.eraserButton=new n.DeviceButton(this,n.Pointer.ERASER_BUTTON),this._holdSent=!1,this._history=[],this._nextDrop=0,this._stateReset=!1,this.withinGame=!1,this.clientX=-1,this.clientY=-1,this.pageX=-1,this.pageY=-1,this.screenX=-1,this.screenY=-1,this.rawMovementX=0,this.rawMovementY=0,this.movementX=0,this.movementY=0,this.x=-1,this.y=-1,this.isMouse=0===e,this.isDown=!1,this.isUp=!0,this.timeDown=0,this.timeUp=0,this.previousTapTime=0,this.totalTouches=0,this.msSinceLastClick=Number.MAX_VALUE,this.targetObject=null,this.interactiveCandidates=[],this.active=!1,this.dirty=!1,this.position=new n.Point,this.positionDown=new n.Point,this.positionUp=new n.Point,this.circle=new n.Circle(0,0,44),this._clickTrampolines=null,this._trampolineTargetObject=null},n.Pointer.NO_BUTTON=0,n.Pointer.LEFT_BUTTON=1,n.Pointer.RIGHT_BUTTON=2,n.Pointer.MIDDLE_BUTTON=4,n.Pointer.BACK_BUTTON=8,n.Pointer.FORWARD_BUTTON=16,n.Pointer.ERASER_BUTTON=32,n.Pointer.prototype={resetButtons:function(){this.isDown=!1,this.isUp=!0,this.isMouse&&(this.leftButton.reset(),this.middleButton.reset(),this.rightButton.reset(),this.backButton.reset(),this.forwardButton.reset(),this.eraserButton.reset())},processButtonsDown:function(t,e){n.Pointer.LEFT_BUTTON&t&&this.leftButton.start(e),n.Pointer.RIGHT_BUTTON&t&&this.rightButton.start(e),n.Pointer.MIDDLE_BUTTON&t&&this.middleButton.start(e),n.Pointer.BACK_BUTTON&t&&this.backButton.start(e),n.Pointer.FORWARD_BUTTON&t&&this.forwardButton.start(e),n.Pointer.ERASER_BUTTON&t&&this.eraserButton.start(e)},processButtonsUp:function(t,e){t===n.Mouse.LEFT_BUTTON&&this.leftButton.stop(e),t===n.Mouse.RIGHT_BUTTON&&this.rightButton.stop(e),t===n.Mouse.MIDDLE_BUTTON&&this.middleButton.stop(e),t===n.Mouse.BACK_BUTTON&&this.backButton.stop(e),t===n.Mouse.FORWARD_BUTTON&&this.forwardButton.stop(e),5===t&&this.eraserButton.stop(e)},updateButtons:function(t){this.button=t.button;var e="down"===t.type.toLowerCase().substr(-4);void 0!==t.buttons?e?this.processButtonsDown(t.buttons,t):this.processButtonsUp(t.button,t):e?this.leftButton.start(t):(this.leftButton.stop(t),this.rightButton.stop(t)),1===t.buttons&&t.ctrlKey&&this.leftButton.isDown&&(this.leftButton.stop(t),this.rightButton.start(t)),this.isUp=!0,this.isDown=!1,(this.leftButton.isDown||this.rightButton.isDown||this.middleButton.isDown||this.backButton.isDown||this.forwardButton.isDown||this.eraserButton.isDown)&&(this.isUp=!1,this.isDown=!0)},start:function(t){var e=this.game.input;return t.pointerId&&(this.pointerId=t.pointerId),this.identifier=t.identifier,this.target=t.target,this.isMouse?this.updateButtons(t):(this.isDown=!0,this.isUp=!1),this.active=!0,this.withinGame=!0,this.dirty=!1,this._history=[],this._clickTrampolines=null,this._trampolineTargetObject=null,this.msSinceLastClick=this.game.time.time-this.timeDown,this.timeDown=this.game.time.time,this._holdSent=!1,this.move(t,!0),this.positionDown.setTo(this.x,this.y),(e.multiInputOverride===n.Input.MOUSE_OVERRIDES_TOUCH||e.multiInputOverride===n.Input.MOUSE_TOUCH_COMBINE||e.multiInputOverride===n.Input.TOUCH_OVERRIDES_MOUSE&&0===e.totalActivePointers)&&(e.x=this.x,e.y=this.y,e.position.setTo(this.x,this.y),e.onDown.dispatch(this,t),e.resetSpeed(this.x,this.y)),this._stateReset=!1,this.totalTouches++,null!==this.targetObject&&this.targetObject._touchedHandler(this),this},update:function(){var t=this.game.input;this.active&&(this.dirty&&(t.interactiveItems.total>0&&this.processInteractiveObjects(!1),this.dirty=!1),!1===this._holdSent&&this.duration>=t.holdRate&&((t.multiInputOverride===n.Input.MOUSE_OVERRIDES_TOUCH||t.multiInputOverride===n.Input.MOUSE_TOUCH_COMBINE||t.multiInputOverride===n.Input.TOUCH_OVERRIDES_MOUSE&&0===t.totalActivePointers)&&t.onHold.dispatch(this),this._holdSent=!0),t.recordPointerHistory&&this.game.time.time>=this._nextDrop&&(this._nextDrop=this.game.time.time+t.recordRate,this._history.push({x:this.position.x,y:this.position.y}),this._history.length>t.recordLimit&&this._history.shift()))},move:function(t,e){var i=this.game.input;if(!i.pollLocked){if(void 0===e&&(e=!1),void 0!==t.button&&(this.button=t.button),e&&this.isMouse&&this.updateButtons(t),this.clientX=t.clientX,this.clientY=t.clientY,this.pageX=t.pageX,this.pageY=t.pageY,this.screenX=t.screenX,this.screenY=t.screenY,this.isMouse&&i.mouse.locked&&!e&&(this.rawMovementX=t.movementX||t.mozMovementX||t.webkitMovementX||0,this.rawMovementY=t.movementY||t.mozMovementY||t.webkitMovementY||0,this.movementX+=this.rawMovementX,this.movementY+=this.rawMovementY),this.x=(this.pageX-this.game.scale.offset.x)*i.scale.x,this.y=(this.pageY-this.game.scale.offset.y)*i.scale.y,this.position.setTo(this.x,this.y),this.circle.x=this.x,this.circle.y=this.y,(i.multiInputOverride===n.Input.MOUSE_OVERRIDES_TOUCH||i.multiInputOverride===n.Input.MOUSE_TOUCH_COMBINE||i.multiInputOverride===n.Input.TOUCH_OVERRIDES_MOUSE&&0===i.totalActivePointers)&&(i.activePointer=this,i.x=this.x,i.y=this.y,i.position.setTo(i.x,i.y),i.circle.x=i.x,i.circle.y=i.y),this.withinGame=this.game.scale.bounds.contains(this.pageX,this.pageY),this.game.paused)return this;for(var s=i.moveCallbacks.length;s--;)i.moveCallbacks[s].callback.call(i.moveCallbacks[s].context,this,this.x,this.y,e);return null!==this.targetObject&&!0===this.targetObject.isDragged?!1===this.targetObject.update(this)&&(this.targetObject=null):i.interactiveItems.total>0&&this.processInteractiveObjects(e),this}},processInteractiveObjects:function(t){var e=0,i=-1,s=null,n=this.game.input.interactiveItems.first;for(this.interactiveCandidates=[];n;)n.checked=!1,n.validForInput(i,e,!1)&&(n.checked=!0,(t&&n.checkPointerDown(this,!0)||!t&&n.checkPointerOver(this,!0))&&(e=n.sprite.renderOrderID,i=n.priorityID,s=n,this.interactiveCandidates.push(n))),n=this.game.input.interactiveItems.next;for(n=this.game.input.interactiveItems.first;n;)!n.checked&&n.validForInput(i,e,!0)&&(t&&n.checkPointerDown(this,!1)||!t&&n.checkPointerOver(this,!1))&&(e=n.sprite.renderOrderID,i=n.priorityID,s=n,this.interactiveCandidates.push(n)),n=this.game.input.interactiveItems.next;return this.game.input.customCandidateHandler&&(s=this.game.input.customCandidateHandler.call(this.game.input.customCandidateHandlerContext,this,this.interactiveCandidates,s)),this.swapTarget(s,!1),null!==this.targetObject},swapTarget:function(t,e){void 0===e&&(e=!1),null===t?this.targetObject&&(this.targetObject._pointerOutHandler(this,e),this.targetObject=null):null===this.targetObject?(this.targetObject=t,t._pointerOverHandler(this,e)):this.targetObject===t?!1===t.update(this)&&(this.targetObject=null):(this.targetObject._pointerOutHandler(this,e),this.targetObject=t,this.targetObject._pointerOverHandler(this,e))},leave:function(t){this.withinGame=!1,this.move(t,!1)},stop:function(t){var e=this.game.input;return this._stateReset&&this.withinGame?void t.preventDefault():(this.timeUp=this.game.time.time,(e.multiInputOverride===n.Input.MOUSE_OVERRIDES_TOUCH||e.multiInputOverride===n.Input.MOUSE_TOUCH_COMBINE||e.multiInputOverride===n.Input.TOUCH_OVERRIDES_MOUSE&&0===e.totalActivePointers)&&(e.onUp.dispatch(this,t),this.duration>=0&&this.duration<=e.tapRate&&(this.timeUp-this.previousTapTime<e.doubleTapRate?e.onTap.dispatch(this,!0):e.onTap.dispatch(this,!1),this.previousTapTime=this.timeUp)),this.isMouse?this.updateButtons(t):(this.isDown=!1,this.isUp=!0),this.id>0&&(this.active=!1),this.withinGame=this.game.scale.bounds.contains(t.pageX,t.pageY),this.pointerId=null,this.identifier=null,this.positionUp.setTo(this.x,this.y),!1===this.isMouse&&e.currentPointers--,e.interactiveItems.callAll("_releasedHandler",this),this._clickTrampolines&&(this._trampolineTargetObject=this.targetObject),this.targetObject=null,this)},justPressed:function(t){return t=t||this.game.input.justPressedRate,!0===this.isDown&&this.timeDown+t>this.game.time.time},justReleased:function(t){return t=t||this.game.input.justReleasedRate,this.isUp&&this.timeUp+t>this.game.time.time},addClickTrampoline:function(t,e,i,s){if(this.isDown){for(var n=this._clickTrampolines=this._clickTrampolines||[],r=0;r<n.length;r++)if(n[r].name===t){n.splice(r,1);break}n.push({name:t,targetObject:this.targetObject,callback:e,callbackContext:i,callbackArgs:s})}},processClickTrampolines:function(){var t=this._clickTrampolines;if(t){for(var e=0;e<t.length;e++){var i=t[e];i.targetObject===this._trampolineTargetObject&&i.callback.apply(i.callbackContext,i.callbackArgs)}this._clickTrampolines=null,this._trampolineTargetObject=null}},reset:function(){!1===this.isMouse&&(this.active=!1),this.pointerId=null,this.identifier=null,this.dirty=!1,this.totalTouches=0,this._holdSent=!1,this._history.length=0,this._stateReset=!0,this.resetButtons(),this.targetObject&&this.targetObject._releasedHandler(this),this.targetObject=null},resetMovement:function(){this.movementX=0,this.movementY=0}},n.Pointer.prototype.constructor=n.Pointer,Object.defineProperty(n.Pointer.prototype,"duration",{get:function(){return this.isUp?-1:this.game.time.time-this.timeDown}}),Object.defineProperty(n.Pointer.prototype,"worldX",{get:function(){return this.game.world.camera.x+this.x}}),Object.defineProperty(n.Pointer.prototype,"worldY",{get:function(){return this.game.world.camera.y+this.y}}),n.PointerMode={CURSOR:1,CONTACT:2},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Touch=function(t){this.game=t,this.enabled=!0,this.touchLockCallbacks=[],this.callbackContext=this.game,this.touchStartCallback=null,this.touchMoveCallback=null,this.touchEndCallback=null,this.touchEnterCallback=null,this.touchLeaveCallback=null,this.touchCancelCallback=null,this.preventDefault=!0,this.event=null,this._onTouchStart=null,this._onTouchMove=null,this._onTouchEnd=null,this._onTouchEnter=null,this._onTouchLeave=null,this._onTouchCancel=null,this._onTouchMove=null},n.Touch.prototype={start:function(){if(null===this._onTouchStart){var t=this;this.game.device.touch&&(this._onTouchStart=function(e){return t.onTouchStart(e)},this._onTouchMove=function(e){return t.onTouchMove(e)},this._onTouchEnd=function(e){return t.onTouchEnd(e)},this._onTouchEnter=function(e){return t.onTouchEnter(e)},this._onTouchLeave=function(e){return t.onTouchLeave(e)},this._onTouchCancel=function(e){return t.onTouchCancel(e)},this.game.canvas.addEventListener("touchstart",this._onTouchStart,!1),this.game.canvas.addEventListener("touchmove",this._onTouchMove,!1),this.game.canvas.addEventListener("touchend",this._onTouchEnd,!1),this.game.canvas.addEventListener("touchcancel",this._onTouchCancel,!1),this.game.device.cocoonJS||(this.game.canvas.addEventListener("touchenter",this._onTouchEnter,!1),this.game.canvas.addEventListener("touchleave",this._onTouchLeave,!1)))}},consumeDocumentTouches:function(){this._documentTouchMove=function(t){t.preventDefault()},document.addEventListener("touchmove",this._documentTouchMove,!1)},addTouchLockCallback:function(t,e,i){void 0===i&&(i=!1),this.touchLockCallbacks.push({callback:t,context:e,onEnd:i})},removeTouchLockCallback:function(t,e){for(var i=this.touchLockCallbacks.length;i--;)if(this.touchLockCallbacks[i].callback===t&&this.touchLockCallbacks[i].context===e)return this.touchLockCallbacks.splice(i,1),!0;return!1},onTouchStart:function(t){for(var e=this.touchLockCallbacks.length;e--;){var i=this.touchLockCallbacks[e];!i.onEnd&&i.callback.call(i.context,this,t)&&this.touchLockCallbacks.splice(e,1)}if(this.event=t,this.game.input.enabled&&this.enabled){this.touchStartCallback&&this.touchStartCallback.call(this.callbackContext,t),this.preventDefault&&t.preventDefault();for(var e=0;e<t.changedTouches.length;e++)this.game.input.startPointer(t.changedTouches[e])}},onTouchCancel:function(t){if(this.event=t,this.touchCancelCallback&&this.touchCancelCallback.call(this.callbackContext,t),this.game.input.enabled&&this.enabled){this.preventDefault&&t.preventDefault();for(var e=0;e<t.changedTouches.length;e++)this.game.input.stopPointer(t.changedTouches[e])}},onTouchEnter:function(t){this.event=t,this.touchEnterCallback&&this.touchEnterCallback.call(this.callbackContext,t),this.game.input.enabled&&this.enabled&&this.preventDefault&&t.preventDefault()},onTouchLeave:function(t){this.event=t,this.touchLeaveCallback&&this.touchLeaveCallback.call(this.callbackContext,t),this.preventDefault&&t.preventDefault()},onTouchMove:function(t){this.event=t,this.touchMoveCallback&&this.touchMoveCallback.call(this.callbackContext,t),this.preventDefault&&t.preventDefault();for(var e=0;e<t.changedTouches.length;e++)this.game.input.updatePointer(t.changedTouches[e])},onTouchEnd:function(t){for(var e=this.touchLockCallbacks.length;e--;){var i=this.touchLockCallbacks[e];i.onEnd&&i.callback.call(i.context,this,t)&&this.touchLockCallbacks.splice(e,1)}this.event=t,this.touchEndCallback&&this.touchEndCallback.call(this.callbackContext,t),this.preventDefault&&t.preventDefault();for(var e=0;e<t.changedTouches.length;e++)this.game.input.stopPointer(t.changedTouches[e])},stop:function(){this.game.device.touch&&(this.game.canvas.removeEventListener("touchstart",this._onTouchStart),this.game.canvas.removeEventListener("touchmove",this._onTouchMove),this.game.canvas.removeEventListener("touchend",this._onTouchEnd),this.game.canvas.removeEventListener("touchenter",this._onTouchEnter),this.game.canvas.removeEventListener("touchleave",this._onTouchLeave),this.game.canvas.removeEventListener("touchcancel",this._onTouchCancel))}},n.Touch.prototype.constructor=n.Touch,/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.InputHandler=function(t){this.sprite=t,this.game=t.game,this.enabled=!1,this.checked=!1,this.priorityID=0,this.useHandCursor=!1,this._setHandCursor=!1,this.isDragged=!1,this.allowHorizontalDrag=!0,this.allowVerticalDrag=!0,this.bringToTop=!1,this.snapOffset=null,this.snapOnDrag=!1,this.snapOnRelease=!1,this.snapX=0,this.snapY=0,this.snapOffsetX=0,this.snapOffsetY=0,this.pixelPerfectOver=!1,this.pixelPerfectClick=!1,this.pixelPerfectAlpha=255,this.draggable=!1,this.boundsRect=null,this.boundsSprite=null,this.scaleLayer=!1,this.dragOffset=new n.Point,this.dragFromCenter=!1,this.dragStopBlocksInputUp=!1,this.dragStartPoint=new n.Point,this.dragDistanceThreshold=0,this.dragTimeThreshold=0,this.downPoint=new n.Point,this.snapPoint=new n.Point,this._dragPoint=new n.Point,this._dragPhase=!1,this._pendingDrag=!1,this._dragTimePass=!1,this._dragDistancePass=!1,this._wasEnabled=!1,this._tempPoint=new n.Point,this._pointerData=[],this._pointerData.push({id:0,x:0,y:0,camX:0,camY:0,isDown:!1,isUp:!1,isOver:!1,isOut:!1,timeOver:0,timeOut:0,timeDown:0,timeUp:0,downDuration:0,isDragged:!1})},n.InputHandler.prototype={start:function(t,e){if(t=t||0,void 0===e&&(e=!1),!1===this.enabled){this.game.input.interactiveItems.add(this),this.useHandCursor=e,this.priorityID=t;for(var i=0;i<10;i++)this._pointerData[i]={id:i,x:0,y:0,isDown:!1,isUp:!1,isOver:!1,isOut:!1,timeOver:0,timeOut:0,timeDown:0,timeUp:0,downDuration:0,isDragged:!1};this.snapOffset=new n.Point,this.enabled=!0,this._wasEnabled=!0}return this.sprite.events.onAddedToGroup.add(this.addedToGroup,this),this.sprite.events.onRemovedFromGroup.add(this.removedFromGroup,this),this.sprite},addedToGroup:function(){this._dragPhase||this._wasEnabled&&!this.enabled&&this.start()},removedFromGroup:function(){this._dragPhase||(this.enabled?(this._wasEnabled=!0,this.stop()):this._wasEnabled=!1)},reset:function(){this.enabled=!1;for(var t=0;t<10;t++)this._pointerData[t]={id:t,x:0,y:0,isDown:!1,isUp:!1,isOver:!1,isOut:!1,timeOver:0,timeOut:0,timeDown:0,timeUp:0,downDuration:0,isDragged:!1}},stop:function(){!1!==this.enabled&&(this.enabled=!1,this.game.input.interactiveItems.remove(this))},destroy:function(){this.sprite&&(this._setHandCursor&&(this.game.canvas.style.cursor="default",this._setHandCursor=!1),this.enabled=!1,this.game.input.interactiveItems.remove(this),this._pointerData.length=0,this.boundsRect=null,this.boundsSprite=null,this.sprite=null)},validForInput:function(t,e,i){return void 0===i&&(i=!0),!(!this.enabled||0===this.sprite.scale.x||0===this.sprite.scale.y||this.priorityID<this.game.input.minPriorityID||this.sprite.parent&&this.sprite.parent.ignoreChildInput)&&(!(!i&&(this.pixelPerfectClick||this.pixelPerfectOver))&&(this.priorityID>t||this.priorityID===t&&this.sprite.renderOrderID>e))},isPixelPerfect:function(){return this.pixelPerfectClick||this.pixelPerfectOver},pointerX:function(t){return t=t||0,this._pointerData[t].x},pointerY:function(t){return t=t||0,this._pointerData[t].y},pointerDown:function(t){return t=t||0,this._pointerData[t].isDown},pointerUp:function(t){return t=t||0,this._pointerData[t].isUp},pointerTimeDown:function(t){return t=t||0,this._pointerData[t].timeDown},pointerTimeUp:function(t){return t=t||0,this._pointerData[t].timeUp},pointerOver:function(t){if(!this.enabled)return!1;if(void 0===t){for(var e=0;e<10;e++)if(this._pointerData[e].isOver)return!0;return!1}return this._pointerData[t].isOver},pointerOut:function(t){if(!this.enabled)return!1;if(void 0!==t)return this._pointerData[t].isOut;for(var e=0;e<10;e++)if(this._pointerData[e].isOut)return!0},pointerTimeOver:function(t){return t=t||0,this._pointerData[t].timeOver},pointerTimeOut:function(t){return t=t||0,this._pointerData[t].timeOut},pointerDragged:function(t){return t=t||0,this._pointerData[t].isDragged},checkPointerDown:function(t,e){return!!(t.isDown&&this.enabled&&this.sprite&&this.sprite.parent&&this.sprite.visible&&this.sprite.parent.visible&&0!==this.sprite.worldScale.x&&0!==this.sprite.worldScale.y)&&(!!this.game.input.hitTest(this.sprite,t,this._tempPoint)&&(void 0===e&&(e=!1),!(!e&&this.pixelPerfectClick)||this.checkPixel(this._tempPoint.x,this._tempPoint.y)))},checkPointerOver:function(t,e){return!!(this.enabled&&this.sprite&&this.sprite.parent&&this.sprite.visible&&this.sprite.parent.visible&&0!==this.sprite.worldScale.x&&0!==this.sprite.worldScale.y)&&(!!this.game.input.hitTest(this.sprite,t,this._tempPoint)&&(void 0===e&&(e=!1),!(!e&&this.pixelPerfectOver)||this.checkPixel(this._tempPoint.x,this._tempPoint.y)))},checkPixel:function(t,e,i){if(this.sprite.texture.baseTexture.source){if(null===t&&null===e){this.game.input.getLocalPosition(this.sprite,i,this._tempPoint);var t=this._tempPoint.x,e=this._tempPoint.y}if(0!==this.sprite.anchor.x&&(t-=-this.sprite.texture.frame.width*this.sprite.anchor.x),0!==this.sprite.anchor.y&&(e-=-this.sprite.texture.frame.height*this.sprite.anchor.y),t+=this.sprite.texture.frame.x,e+=this.sprite.texture.frame.y,this.sprite.texture.trim&&(t-=this.sprite.texture.trim.x,e-=this.sprite.texture.trim.y,t<this.sprite.texture.crop.x||t>this.sprite.texture.crop.right||e<this.sprite.texture.crop.y||e>this.sprite.texture.crop.bottom))return this._dx=t,this._dy=e,!1;this._dx=t,this._dy=e,this.game.input.hitContext.clearRect(0,0,1,1),this.game.input.hitContext.drawImage(this.sprite.texture.baseTexture.source,t,e,1,1,0,0,1,1);if(this.game.input.hitContext.getImageData(0,0,1,1).data[3]>=this.pixelPerfectAlpha)return!0}return!1},update:function(t){if(null!==this.sprite&&void 0!==this.sprite.parent)return this.enabled&&this.sprite.visible&&this.sprite.parent.visible?this._pendingDrag?(this._dragDistancePass||(this._dragDistancePass=n.Math.distance(t.x,t.y,this.downPoint.x,this.downPoint.y)>=this.dragDistanceThreshold),this._dragDistancePass&&this._dragTimePass&&this.startDrag(t),!0):this.draggable&&this._draggedPointerID===t.id?this.updateDrag(t,!1):this._pointerData[t.id].isOver?this.checkPointerOver(t)?(this._pointerData[t.id].x=t.x-this.sprite.x,this._pointerData[t.id].y=t.y-this.sprite.y,!0):(this._pointerOutHandler(t),!1):void 0:(this._pointerOutHandler(t),!1)},_pointerOverHandler:function(t,e){if(null!==this.sprite){var i=this._pointerData[t.id];if(!1===i.isOver||t.dirty){var s=!1===i.isOver;i.isOver=!0,i.isOut=!1,i.timeOver=this.game.time.time,i.x=t.x-this.sprite.x,i.y=t.y-this.sprite.y,this.useHandCursor&&!1===i.isDragged&&(this.game.canvas.style.cursor="pointer",this._setHandCursor=!0),!e&&s&&this.sprite&&this.sprite.events&&this.sprite.events.onInputOver$dispatch(this.sprite,t),this.sprite.parent&&this.sprite.parent.type===n.GROUP&&this.sprite.parent.onChildInputOver.dispatch(this.sprite,t)}}},_pointerOutHandler:function(t,e){if(null!==this.sprite){var i=this._pointerData[t.id];i.isOver=!1,i.isOut=!0,i.timeOut=this.game.time.time,this.useHandCursor&&!1===i.isDragged&&(this.game.canvas.style.cursor="default",this._setHandCursor=!1),!e&&this.sprite&&this.sprite.events&&(this.sprite.events.onInputOut$dispatch(this.sprite,t),this.sprite&&this.sprite.parent&&this.sprite.parent.type===n.GROUP&&this.sprite.parent.onChildInputOut.dispatch(this.sprite,t))}},_touchedHandler:function(t){if(null!==this.sprite){var e=this._pointerData[t.id];if(!e.isDown&&e.isOver){if(this.pixelPerfectClick&&!this.checkPixel(null,null,t))return;if(e.isDown=!0,e.isUp=!1,e.timeDown=this.game.time.time,this.downPoint.set(t.x,t.y),t.dirty=!0,this.sprite&&this.sprite.events&&(this.sprite.events.onInputDown$dispatch(this.sprite,t),this.sprite&&this.sprite.parent&&this.sprite.parent.type===n.GROUP&&this.sprite.parent.onChildInputDown.dispatch(this.sprite,t),null===this.sprite))return;this.draggable&&!1===this.isDragged&&(0===this.dragTimeThreshold&&0===this.dragDistanceThreshold?this.startDrag(t):(this._pendingDrag=!0,this._dragDistancePass=0===this.dragDistanceThreshold,this.dragTimeThreshold>0?(this._dragTimePass=!1,this.game.time.events.add(this.dragTimeThreshold,this.dragTimeElapsed,this,t)):this._dragTimePass=!0)),this.bringToTop&&this.sprite.bringToTop()}}},dragTimeElapsed:function(t){this._dragTimePass=!0,this._pendingDrag&&this.sprite&&this._dragDistancePass&&this.startDrag(t)},_releasedHandler:function(t){if(null!==this.sprite){var e=this._pointerData[t.id];if(e.isDown&&t.isUp){e.isDown=!1,e.isUp=!0,e.timeUp=this.game.time.time,e.downDuration=e.timeUp-e.timeDown;var i=this.checkPointerOver(t);this.sprite&&this.sprite.events&&(this.dragStopBlocksInputUp&&(!this.dragStopBlocksInputUp||this.draggable&&this.isDragged&&this._draggedPointerID===t.id)||this.sprite.events.onInputUp$dispatch(this.sprite,t,i),this.sprite&&this.sprite.parent&&this.sprite.parent.type===n.GROUP&&this.sprite.parent.onChildInputUp.dispatch(this.sprite,t,i),i&&(i=this.checkPointerOver(t))),e.isOver=i,!i&&this.useHandCursor&&(this.game.canvas.style.cursor="default",this._setHandCursor=!1),t.dirty=!0,this._pendingDrag=!1,this.draggable&&this.isDragged&&this._draggedPointerID===t.id&&this.stopDrag(t)}}},updateDrag:function(t,e){if(void 0===e&&(e=!1),t.isUp)return this.stopDrag(t),!1;var i=this.globalToLocalX(t.x)+this._dragPoint.x+this.dragOffset.x,s=this.globalToLocalY(t.y)+this._dragPoint.y+this.dragOffset.y;if(this.sprite.fixedToCamera)this.allowHorizontalDrag&&(this.sprite.cameraOffset.x=i),this.allowVerticalDrag&&(this.sprite.cameraOffset.y=s),this.boundsRect&&this.checkBoundsRect(),this.boundsSprite&&this.checkBoundsSprite(),this.snapOnDrag&&(this.sprite.cameraOffset.x=Math.round((this.sprite.cameraOffset.x-this.snapOffsetX%this.snapX)/this.snapX)*this.snapX+this.snapOffsetX%this.snapX,this.sprite.cameraOffset.y=Math.round((this.sprite.cameraOffset.y-this.snapOffsetY%this.snapY)/this.snapY)*this.snapY+this.snapOffsetY%this.snapY,this.snapPoint.set(this.sprite.cameraOffset.x,this.sprite.cameraOffset.y));else{var n=this.game.camera.x-this._pointerData[t.id].camX,r=this.game.camera.y-this._pointerData[t.id].camY;this.allowHorizontalDrag&&(this.sprite.x=i+n),this.allowVerticalDrag&&(this.sprite.y=s+r),this.boundsRect&&this.checkBoundsRect(),this.boundsSprite&&this.checkBoundsSprite(),this.snapOnDrag&&(this.sprite.x=Math.round((this.sprite.x-this.snapOffsetX%this.snapX)/this.snapX)*this.snapX+this.snapOffsetX%this.snapX,this.sprite.y=Math.round((this.sprite.y-this.snapOffsetY%this.snapY)/this.snapY)*this.snapY+this.snapOffsetY%this.snapY,this.snapPoint.set(this.sprite.x,this.sprite.y))}return this.sprite.events.onDragUpdate.dispatch(this.sprite,t,i,s,this.snapPoint,e),!0},justOver:function(t,e){return t=t||0,e=e||500,this._pointerData[t].isOver&&this.overDuration(t)<e},justOut:function(t,e){return t=t||0,e=e||500,this._pointerData[t].isOut&&this.game.time.time-this._pointerData[t].timeOut<e},justPressed:function(t,e){return t=t||0,e=e||500,this._pointerData[t].isDown&&this.downDuration(t)<e},justReleased:function(t,e){return t=t||0,e=e||500,this._pointerData[t].isUp&&this.game.time.time-this._pointerData[t].timeUp<e},overDuration:function(t){return t=t||0,this._pointerData[t].isOver?this.game.time.time-this._pointerData[t].timeOver:-1},downDuration:function(t){return t=t||0,this._pointerData[t].isDown?this.game.time.time-this._pointerData[t].timeDown:-1},enableDrag:function(t,e,i,s,r,o){void 0===t&&(t=!1),void 0===e&&(e=!1),void 0===i&&(i=!1),void 0===s&&(s=255),void 0===r&&(r=null),void 0===o&&(o=null),this._dragPoint=new n.Point,this.draggable=!0,this.bringToTop=e,this.dragOffset=new n.Point,this.dragFromCenter=t,this.pixelPerfectClick=i,this.pixelPerfectAlpha=s,r&&(this.boundsRect=r),o&&(this.boundsSprite=o)},disableDrag:function(){if(this._pointerData)for(var t=0;t<10;t++)this._pointerData[t].isDragged=!1;this.draggable=!1,this.isDragged=!1,this._draggedPointerID=-1,this._pendingDrag=!1},startDrag:function(t){var e=this.sprite.x,i=this.sprite.y;if(this.isDragged=!0,this._draggedPointerID=t.id,this._pointerData[t.id].camX=this.game.camera.x,this._pointerData[t.id].camY=this.game.camera.y,this._pointerData[t.id].isDragged=!0,this.sprite.fixedToCamera){if(this.dragFromCenter){var s=this.sprite.getBounds();this.sprite.cameraOffset.x=this.globalToLocalX(t.x)+(this.sprite.cameraOffset.x-s.centerX),this.sprite.cameraOffset.y=this.globalToLocalY(t.y)+(this.sprite.cameraOffset.y-s.centerY)}this._dragPoint.setTo(this.sprite.cameraOffset.x-t.x,this.sprite.cameraOffset.y-t.y)}else{if(this.dragFromCenter){var s=this.sprite.getBounds();this.sprite.x=this.globalToLocalX(t.x)+(this.sprite.x-s.centerX),this.sprite.y=this.globalToLocalY(t.y)+(this.sprite.y-s.centerY)}this._dragPoint.setTo(this.sprite.x-this.globalToLocalX(t.x),this.sprite.y-this.globalToLocalY(t.y))}this.updateDrag(t,!0),this.bringToTop&&(this._dragPhase=!0,this.sprite.bringToTop()),this.dragStartPoint.set(e,i),this.sprite.events.onDragStart$dispatch(this.sprite,t,e,i),this._pendingDrag=!1},globalToLocalX:function(t){return this.scaleLayer&&(t-=this.game.scale.grid.boundsFluid.x,t*=this.game.scale.grid.scaleFluidInversed.x),t},globalToLocalY:function(t){return this.scaleLayer&&(t-=this.game.scale.grid.boundsFluid.y,t*=this.game.scale.grid.scaleFluidInversed.y),t},stopDrag:function(t){this.isDragged=!1,this._draggedPointerID=-1,this._pointerData[t.id].isDragged=!1,this._dragPhase=!1,this._pendingDrag=!1,this.snapOnRelease&&(this.sprite.fixedToCamera?(this.sprite.cameraOffset.x=Math.round((this.sprite.cameraOffset.x-this.snapOffsetX%this.snapX)/this.snapX)*this.snapX+this.snapOffsetX%this.snapX,this.sprite.cameraOffset.y=Math.round((this.sprite.cameraOffset.y-this.snapOffsetY%this.snapY)/this.snapY)*this.snapY+this.snapOffsetY%this.snapY):(this.sprite.x=Math.round((this.sprite.x-this.snapOffsetX%this.snapX)/this.snapX)*this.snapX+this.snapOffsetX%this.snapX,this.sprite.y=Math.round((this.sprite.y-this.snapOffsetY%this.snapY)/this.snapY)*this.snapY+this.snapOffsetY%this.snapY)),this.sprite.events.onDragStop$dispatch(this.sprite,t),!1===this.checkPointerOver(t)&&this._pointerOutHandler(t)},setDragLock:function(t,e){void 0===t&&(t=!0),void 0===e&&(e=!0),this.allowHorizontalDrag=t,this.allowVerticalDrag=e},enableSnap:function(t,e,i,s,n,r){void 0===i&&(i=!0),void 0===s&&(s=!1),void 0===n&&(n=0),void 0===r&&(r=0),this.snapX=t,this.snapY=e,this.snapOffsetX=n,this.snapOffsetY=r,this.snapOnDrag=i,this.snapOnRelease=s},disableSnap:function(){this.snapOnDrag=!1,this.snapOnRelease=!1},checkBoundsRect:function(){this.sprite.fixedToCamera?(this.sprite.cameraOffset.x<this.boundsRect.left?this.sprite.cameraOffset.x=this.boundsRect.left:this.sprite.cameraOffset.x+this.sprite.width>this.boundsRect.right&&(this.sprite.cameraOffset.x=this.boundsRect.right-this.sprite.width),this.sprite.cameraOffset.y<this.boundsRect.top?this.sprite.cameraOffset.y=this.boundsRect.top:this.sprite.cameraOffset.y+this.sprite.height>this.boundsRect.bottom&&(this.sprite.cameraOffset.y=this.boundsRect.bottom-this.sprite.height)):(this.sprite.left<this.boundsRect.left?this.sprite.x=this.boundsRect.x+this.sprite.offsetX:this.sprite.right>this.boundsRect.right&&(this.sprite.x=this.boundsRect.right-(this.sprite.width-this.sprite.offsetX)),this.sprite.top<this.boundsRect.top?this.sprite.y=this.boundsRect.top+this.sprite.offsetY:this.sprite.bottom>this.boundsRect.bottom&&(this.sprite.y=this.boundsRect.bottom-(this.sprite.height-this.sprite.offsetY)))},checkBoundsSprite:function(){this.sprite.fixedToCamera&&this.boundsSprite.fixedToCamera?(this.sprite.cameraOffset.x<this.boundsSprite.cameraOffset.x?this.sprite.cameraOffset.x=this.boundsSprite.cameraOffset.x:this.sprite.cameraOffset.x+this.sprite.width>this.boundsSprite.cameraOffset.x+this.boundsSprite.width&&(this.sprite.cameraOffset.x=this.boundsSprite.cameraOffset.x+this.boundsSprite.width-this.sprite.width),this.sprite.cameraOffset.y<this.boundsSprite.cameraOffset.y?this.sprite.cameraOffset.y=this.boundsSprite.cameraOffset.y:this.sprite.cameraOffset.y+this.sprite.height>this.boundsSprite.cameraOffset.y+this.boundsSprite.height&&(this.sprite.cameraOffset.y=this.boundsSprite.cameraOffset.y+this.boundsSprite.height-this.sprite.height)):(this.sprite.left<this.boundsSprite.left?this.sprite.x=this.boundsSprite.left+this.sprite.offsetX:this.sprite.right>this.boundsSprite.right&&(this.sprite.x=this.boundsSprite.right-(this.sprite.width-this.sprite.offsetX)),this.sprite.top<this.boundsSprite.top?this.sprite.y=this.boundsSprite.top+this.sprite.offsetY:this.sprite.bottom>this.boundsSprite.bottom&&(this.sprite.y=this.boundsSprite.bottom-(this.sprite.height-this.sprite.offsetY)))}},n.InputHandler.prototype.constructor=n.InputHandler,/**
* @author @karlmacklin <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Gamepad=function(t){this.game=t,this._gamepadIndexMap={},this._rawPads=[],this._active=!1,this.enabled=!0,this._gamepadSupportAvailable=!!navigator.webkitGetGamepads||!!navigator.webkitGamepads||-1!==navigator.userAgent.indexOf("Firefox/")||!!navigator.getGamepads,this._prevRawGamepadTypes=[],this._prevTimestamps=[],this.callbackContext=this,this.onConnectCallback=null,this.onDisconnectCallback=null,this.onDownCallback=null,this.onUpCallback=null,this.onAxisCallback=null,this.onFloatCallback=null,this._ongamepadconnected=null,this._gamepaddisconnected=null,this._gamepads=[new n.SinglePad(t,this),new n.SinglePad(t,this),new n.SinglePad(t,this),new n.SinglePad(t,this)]},n.Gamepad.prototype={addCallbacks:function(t,e){void 0!==e&&(this.onConnectCallback="function"==typeof e.onConnect?e.onConnect:this.onConnectCallback,this.onDisconnectCallback="function"==typeof e.onDisconnect?e.onDisconnect:this.onDisconnectCallback,this.onDownCallback="function"==typeof e.onDown?e.onDown:this.onDownCallback,this.onUpCallback="function"==typeof e.onUp?e.onUp:this.onUpCallback,this.onAxisCallback="function"==typeof e.onAxis?e.onAxis:this.onAxisCallback,this.onFloatCallback="function"==typeof e.onFloat?e.onFloat:this.onFloatCallback,this.callbackContext=t)},start:function(){if(!this._active){this._active=!0;var t=this;this._onGamepadConnected=function(e){return t.onGamepadConnected(e)},this._onGamepadDisconnected=function(e){return t.onGamepadDisconnected(e)},window.addEventListener("gamepadconnected",this._onGamepadConnected,!1),window.addEventListener("gamepaddisconnected",this._onGamepadDisconnected,!1)}},onGamepadConnected:function(t){var e=t.gamepad;this._rawPads.push(e),this._gamepads[e.index].connect(e)},onGamepadDisconnected:function(t){var e=t.gamepad;for(var i in this._rawPads)this._rawPads[i].index===e.index&&this._rawPads.splice(i,1);this._gamepads[e.index].disconnect()},update:function(){this._pollGamepads(),this.pad1.pollStatus(),this.pad2.pollStatus(),this.pad3.pollStatus(),this.pad4.pollStatus()},_pollGamepads:function(){if(this._active){if(navigator.getGamepads)var t=navigator.getGamepads();else if(navigator.webkitGetGamepads)var t=navigator.webkitGetGamepads();else if(navigator.webkitGamepads)var t=navigator.webkitGamepads();if(t){this._rawPads=[];for(var e=!1,i=0;i<t.length&&(typeof t[i]!==this._prevRawGamepadTypes[i]&&(e=!0,this._prevRawGamepadTypes[i]=typeof t[i]),t[i]&&this._rawPads.push(t[i]),3!==i);i++);for(var s=0;s<this._gamepads.length;s++)this._gamepads[s]._rawPad=this._rawPads[s];if(e){for(var n,r={rawIndices:{},padIndices:{}},o=0;o<this._gamepads.length;o++)if(n=this._gamepads[o],n.connected)for(var a=0;a<this._rawPads.length;a++)this._rawPads[a].index===n.index&&(r.rawIndices[n.index]=!0,r.padIndices[o]=!0);for(var h=0;h<this._gamepads.length;h++)if(n=this._gamepads[h],!r.padIndices[h]){this._rawPads.length<1&&n.disconnect();for(var l=0;l<this._rawPads.length&&!r.padIndices[h];l++){var c=this._rawPads[l];if(c){if(r.rawIndices[c.index]){n.disconnect();continue}n.connect(c),r.rawIndices[c.index]=!0,r.padIndices[h]=!0}else n.disconnect()}}}}}},setDeadZones:function(t){for(var e=0;e<this._gamepads.length;e++)this._gamepads[e].deadZone=t},stop:function(){this._active=!1,window.removeEventListener("gamepadconnected",this._onGamepadConnected),window.removeEventListener("gamepaddisconnected",this._onGamepadDisconnected)},reset:function(){this.update();for(var t=0;t<this._gamepads.length;t++)this._gamepads[t].reset()},justPressed:function(t,e){for(var i=0;i<this._gamepads.length;i++)if(!0===this._gamepads[i].justPressed(t,e))return!0;return!1},justReleased:function(t,e){for(var i=0;i<this._gamepads.length;i++)if(!0===this._gamepads[i].justReleased(t,e))return!0;return!1},isDown:function(t){for(var e=0;e<this._gamepads.length;e++)if(!0===this._gamepads[e].isDown(t))return!0;return!1},destroy:function(){this.stop();for(var t=0;t<this._gamepads.length;t++)this._gamepads[t].destroy()}},n.Gamepad.prototype.constructor=n.Gamepad,Object.defineProperty(n.Gamepad.prototype,"active",{get:function(){return this._active}}),Object.defineProperty(n.Gamepad.prototype,"supported",{get:function(){return this._gamepadSupportAvailable}}),Object.defineProperty(n.Gamepad.prototype,"padsConnected",{get:function(){return this._rawPads.length}}),Object.defineProperty(n.Gamepad.prototype,"pad1",{get:function(){return this._gamepads[0]}}),Object.defineProperty(n.Gamepad.prototype,"pad2",{get:function(){return this._gamepads[1]}}),Object.defineProperty(n.Gamepad.prototype,"pad3",{get:function(){return this._gamepads[2]}}),Object.defineProperty(n.Gamepad.prototype,"pad4",{get:function(){return this._gamepads[3]}}),n.Gamepad.BUTTON_0=0,n.Gamepad.BUTTON_1=1,n.Gamepad.BUTTON_2=2,n.Gamepad.BUTTON_3=3,n.Gamepad.BUTTON_4=4,n.Gamepad.BUTTON_5=5,n.Gamepad.BUTTON_6=6,n.Gamepad.BUTTON_7=7,n.Gamepad.BUTTON_8=8,n.Gamepad.BUTTON_9=9,n.Gamepad.BUTTON_10=10,n.Gamepad.BUTTON_11=11,n.Gamepad.BUTTON_12=12,n.Gamepad.BUTTON_13=13,n.Gamepad.BUTTON_14=14,n.Gamepad.BUTTON_15=15,n.Gamepad.AXIS_0=0,n.Gamepad.AXIS_1=1,n.Gamepad.AXIS_2=2,n.Gamepad.AXIS_3=3,n.Gamepad.AXIS_4=4,n.Gamepad.AXIS_5=5,n.Gamepad.AXIS_6=6,n.Gamepad.AXIS_7=7,n.Gamepad.AXIS_8=8,n.Gamepad.AXIS_9=9,n.Gamepad.XBOX360_A=0,n.Gamepad.XBOX360_B=1,n.Gamepad.XBOX360_X=2,n.Gamepad.XBOX360_Y=3,n.Gamepad.XBOX360_LEFT_BUMPER=4,n.Gamepad.XBOX360_RIGHT_BUMPER=5,n.Gamepad.XBOX360_LEFT_TRIGGER=6,n.Gamepad.XBOX360_RIGHT_TRIGGER=7,n.Gamepad.XBOX360_BACK=8,n.Gamepad.XBOX360_START=9,n.Gamepad.XBOX360_STICK_LEFT_BUTTON=10,n.Gamepad.XBOX360_STICK_RIGHT_BUTTON=11,n.Gamepad.XBOX360_DPAD_LEFT=14,n.Gamepad.XBOX360_DPAD_RIGHT=15,n.Gamepad.XBOX360_DPAD_UP=12,n.Gamepad.XBOX360_DPAD_DOWN=13,n.Gamepad.XBOX360_STICK_LEFT_X=0,n.Gamepad.XBOX360_STICK_LEFT_Y=1,n.Gamepad.XBOX360_STICK_RIGHT_X=2,n.Gamepad.XBOX360_STICK_RIGHT_Y=3,n.Gamepad.PS3XC_X=0,n.Gamepad.PS3XC_CIRCLE=1;n.Gamepad.PS3XC_SQUARE=2,n.Gamepad.PS3XC_TRIANGLE=3,n.Gamepad.PS3XC_L1=4,n.Gamepad.PS3XC_R1=5,n.Gamepad.PS3XC_L2=6,n.Gamepad.PS3XC_R2=7,n.Gamepad.PS3XC_SELECT=8,n.Gamepad.PS3XC_START=9,n.Gamepad.PS3XC_STICK_LEFT_BUTTON=10,n.Gamepad.PS3XC_STICK_RIGHT_BUTTON=11,n.Gamepad.PS3XC_DPAD_UP=12,n.Gamepad.PS3XC_DPAD_DOWN=13,n.Gamepad.PS3XC_DPAD_LEFT=14,n.Gamepad.PS3XC_DPAD_RIGHT=15,n.Gamepad.PS3XC_STICK_LEFT_X=0,n.Gamepad.PS3XC_STICK_LEFT_Y=1,n.Gamepad.PS3XC_STICK_RIGHT_X=2,n.Gamepad.PS3XC_STICK_RIGHT_Y=3,/**
* @author @karlmacklin <[email protected]>
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.SinglePad=function(t,e){this.game=t,this.index=null,this.connected=!1,this.callbackContext=this,this.onConnectCallback=null,this.onDisconnectCallback=null,this.onDownCallback=null,this.onUpCallback=null,this.onAxisCallback=null,this.onFloatCallback=null,this.deadZone=.26,this._padParent=e,this._rawPad=null,this._prevTimestamp=null,this._buttons=[],this._buttonsLen=0,this._axes=[],this._axesLen=0},n.SinglePad.prototype={addCallbacks:function(t,e){void 0!==e&&(this.onConnectCallback="function"==typeof e.onConnect?e.onConnect:this.onConnectCallback,this.onDisconnectCallback="function"==typeof e.onDisconnect?e.onDisconnect:this.onDisconnectCallback,this.onDownCallback="function"==typeof e.onDown?e.onDown:this.onDownCallback,this.onUpCallback="function"==typeof e.onUp?e.onUp:this.onUpCallback,this.onAxisCallback="function"==typeof e.onAxis?e.onAxis:this.onAxisCallback,this.onFloatCallback="function"==typeof e.onFloat?e.onFloat:this.onFloatCallback,this.callbackContext=t)},getButton:function(t){return this._buttons[t]?this._buttons[t]:null},pollStatus:function(){if(this.connected&&this.game.input.enabled&&this.game.input.gamepad.enabled&&(!this._rawPad.timestamp||this._rawPad.timestamp!==this._prevTimestamp)){for(var t=0;t<this._buttonsLen;t++){var e=isNaN(this._rawPad.buttons[t])?this._rawPad.buttons[t].value:this._rawPad.buttons[t];e!==this._buttons[t].value&&(1===e?this.processButtonDown(t,e):0===e?this.processButtonUp(t,e):this.processButtonFloat(t,e))}for(var i=0;i<this._axesLen;i++){var s=this._rawPad.axes[i];s>0&&s>this.deadZone||s<0&&s<-this.deadZone?this.processAxisChange(i,s):this.processAxisChange(i,0)}this._prevTimestamp=this._rawPad.timestamp}},connect:function(t){var e=!this.connected;this.connected=!0,this.index=t.index,this._rawPad=t,this._buttons=[],this._buttonsLen=t.buttons.length,this._axes=[],this._axesLen=t.axes.length;for(var i=0;i<this._axesLen;i++)this._axes[i]=t.axes[i];for(var s in t.buttons)s=parseInt(s,10),this._buttons[s]=new n.DeviceButton(this,s);e&&this._padParent.onConnectCallback&&this._padParent.onConnectCallback.call(this._padParent.callbackContext,this.index),e&&this.onConnectCallback&&this.onConnectCallback.call(this.callbackContext)},disconnect:function(){var t=this.connected,e=this.index;this.connected=!1,this.index=null,this._rawPad=void 0;for(var i=0;i<this._buttonsLen;i++)this._buttons[i].destroy();this._buttons=[],this._buttonsLen=0,this._axes=[],this._axesLen=0,t&&this._padParent.onDisconnectCallback&&this._padParent.onDisconnectCallback.call(this._padParent.callbackContext,e),t&&this.onDisconnectCallback&&this.onDisconnectCallback.call(this.callbackContext)},destroy:function(){this._rawPad=void 0;for(var t=0;t<this._buttonsLen;t++)this._buttons[t].destroy();this._buttons=[],this._buttonsLen=0,this._axes=[],this._axesLen=0,this.onConnectCallback=null,this.onDisconnectCallback=null,this.onDownCallback=null,this.onUpCallback=null,this.onAxisCallback=null,this.onFloatCallback=null},processAxisChange:function(t,e){this._axes[t]!==e&&(this._axes[t]=e,this._padParent.onAxisCallback&&this._padParent.onAxisCallback.call(this._padParent.callbackContext,this,t,e),this.onAxisCallback&&this.onAxisCallback.call(this.callbackContext,this,t,e))},processButtonDown:function(t,e){this._buttons[t]&&this._buttons[t].start(null,e),this._padParent.onDownCallback&&this._padParent.onDownCallback.call(this._padParent.callbackContext,t,e,this.index),this.onDownCallback&&this.onDownCallback.call(this.callbackContext,t,e)},processButtonUp:function(t,e){this._padParent.onUpCallback&&this._padParent.onUpCallback.call(this._padParent.callbackContext,t,e,this.index),this.onUpCallback&&this.onUpCallback.call(this.callbackContext,t,e),this._buttons[t]&&this._buttons[t].stop(null,e)},processButtonFloat:function(t,e){this._padParent.onFloatCallback&&this._padParent.onFloatCallback.call(this._padParent.callbackContext,t,e,this.index),this.onFloatCallback&&this.onFloatCallback.call(this.callbackContext,t,e),this._buttons[t]&&this._buttons[t].padFloat(e)},axis:function(t){return!!this._axes[t]&&this._axes[t]},isDown:function(t){return!!this._buttons[t]&&this._buttons[t].isDown},isUp:function(t){return!!this._buttons[t]&&this._buttons[t].isUp},justReleased:function(t,e){if(this._buttons[t])return this._buttons[t].justReleased(e)},justPressed:function(t,e){if(this._buttons[t])return this._buttons[t].justPressed(e)},buttonValue:function(t){return this._buttons[t]?this._buttons[t].value:null},reset:function(){for(var t=0;t<this._axes.length;t++)this._axes[t]=0}},n.SinglePad.prototype.constructor=n.SinglePad,/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Key=function(t,e){this.game=t,this._enabled=!0,this.event=null,this.isDown=!1,this.isUp=!0,this.altKey=!1,this.ctrlKey=!1,this.shiftKey=!1,this.timeDown=0,this.duration=0,this.timeUp=-2500,this.repeats=0,this.keyCode=e,this.onDown=new n.Signal,this.onHoldCallback=null,this.onHoldContext=null,this.onUp=new n.Signal,this._justDown=!1,this._justUp=!1},n.Key.prototype={update:function(){this._enabled&&this.isDown&&(this.duration=this.game.time.time-this.timeDown,this.repeats++,this.onHoldCallback&&this.onHoldCallback.call(this.onHoldContext,this))},processKeyDown:function(t){this._enabled&&(this.event=t,this.isDown||(this.altKey=t.altKey,this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.isDown=!0,this.isUp=!1,this.timeDown=this.game.time.time,this.duration=0,this.repeats=0,this._justDown=!0,this.onDown.dispatch(this)))},processKeyUp:function(t){this._enabled&&(this.event=t,this.isUp||(this.isDown=!1,this.isUp=!0,this.timeUp=this.game.time.time,this.duration=this.game.time.time-this.timeDown,this._justUp=!0,this.onUp.dispatch(this)))},reset:function(t){void 0===t&&(t=!0),this.isDown=!1,this.isUp=!0,this.timeUp=this.game.time.time,this.duration=0,this._enabled=!0,this._justDown=!1,this._justUp=!1,t&&(this.onDown.removeAll(),this.onUp.removeAll(),this.onHoldCallback=null,this.onHoldContext=null)},downDuration:function(t){return void 0===t&&(t=50),this.isDown&&this.duration<t},upDuration:function(t){return void 0===t&&(t=50),!this.isDown&&this.game.time.time-this.timeUp<t}},Object.defineProperty(n.Key.prototype,"justDown",{get:function(){var t=this._justDown;return this._justDown=!1,t}}),Object.defineProperty(n.Key.prototype,"justUp",{get:function(){var t=this._justUp;return this._justUp=!1,t}}),Object.defineProperty(n.Key.prototype,"enabled",{get:function(){return this._enabled},set:function(t){(t=!!t)!==this._enabled&&(t||this.reset(!1),this._enabled=t)}}),n.Key.prototype.constructor=n.Key,/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Keyboard=function(t){this.game=t,this.enabled=!0,this.event=null,this.pressEvent=null,this.callbackContext=this,this.onDownCallback=null,this.onPressCallback=null,this.onUpCallback=null,this._keys=[],this._capture=[],this._onKeyDown=null,this._onKeyPress=null,this._onKeyUp=null,this._i=0,this._k=0},n.Keyboard.prototype={addCallbacks:function(t,e,i,s){this.callbackContext=t,void 0!==e&&null!==e&&(this.onDownCallback=e),void 0!==i&&null!==i&&(this.onUpCallback=i),void 0!==s&&null!==s&&(this.onPressCallback=s)},addKey:function(t){return this._keys[t]||(this._keys[t]=new n.Key(this.game,t),this.addKeyCapture(t)),this._keys[t]},addKeys:function(t){var e={};for(var i in t)e[i]=this.addKey(t[i]);return e},removeKey:function(t){this._keys[t]&&(this._keys[t]=null,this.removeKeyCapture(t))},createCursorKeys:function(){return this.addKeys({up:n.KeyCode.UP,down:n.KeyCode.DOWN,left:n.KeyCode.LEFT,right:n.KeyCode.RIGHT})},start:function(){if(!this.game.device.cocoonJS&&null===this._onKeyDown){var t=this;this._onKeyDown=function(e){return t.processKeyDown(e)},this._onKeyUp=function(e){return t.processKeyUp(e)},this._onKeyPress=function(e){return t.processKeyPress(e)},window.addEventListener("keydown",this._onKeyDown,!1),window.addEventListener("keyup",this._onKeyUp,!1),window.addEventListener("keypress",this._onKeyPress,!1)}},stop:function(){window.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("keyup",this._onKeyUp),window.removeEventListener("keypress",this._onKeyPress),this._onKeyDown=null,this._onKeyUp=null,this._onKeyPress=null},destroy:function(){this.stop(),this.clearCaptures(),this._keys.length=0,this._i=0},addKeyCapture:function(t){if("object"==typeof t)for(var e in t)this._capture[t[e]]=!0;else this._capture[t]=!0},removeKeyCapture:function(t){delete this._capture[t]},clearCaptures:function(){this._capture={}},update:function(){for(this._i=this._keys.length;this._i--;)this._keys[this._i]&&this._keys[this._i].update()},processKeyDown:function(t){if(this.event=t,this.game.input.enabled&&this.enabled){var e=t.keyCode;this._capture[e]&&t.preventDefault(),this._keys[e]||(this._keys[e]=new n.Key(this.game,e)),this._keys[e].processKeyDown(t),this._k=e,this.onDownCallback&&this.onDownCallback.call(this.callbackContext,t)}},processKeyPress:function(t){this.pressEvent=t,this.game.input.enabled&&this.enabled&&this.onPressCallback&&this.onPressCallback.call(this.callbackContext,String.fromCharCode(t.charCode),t)},processKeyUp:function(t){if(this.event=t,this.game.input.enabled&&this.enabled){var e=t.keyCode;this._capture[e]&&t.preventDefault(),this._keys[e]||(this._keys[e]=new n.Key(this.game,e)),this._keys[e].processKeyUp(t),this.onUpCallback&&this.onUpCallback.call(this.callbackContext,t)}},reset:function(t){void 0===t&&(t=!0),this.event=null;for(var e=this._keys.length;e--;)this._keys[e]&&this._keys[e].reset(t)},downDuration:function(t,e){return this._keys[t]?this._keys[t].downDuration(e):null},upDuration:function(t,e){return this._keys[t]?this._keys[t].upDuration(e):null},isDown:function(t){return this._keys[t]?this._keys[t].isDown:null}},Object.defineProperty(n.Keyboard.prototype,"lastChar",{get:function(){return 32===this.event.charCode?"":String.fromCharCode(this.pressEvent.charCode)}}),Object.defineProperty(n.Keyboard.prototype,"lastKey",{get:function(){return this._keys[this._k]}}),n.Keyboard.prototype.constructor=n.Keyboard,n.KeyCode={A:"A".charCodeAt(0),B:"B".charCodeAt(0),C:"C".charCodeAt(0),D:"D".charCodeAt(0),E:"E".charCodeAt(0),F:"F".charCodeAt(0),G:"G".charCodeAt(0),H:"H".charCodeAt(0),I:"I".charCodeAt(0),J:"J".charCodeAt(0),K:"K".charCodeAt(0),L:"L".charCodeAt(0),M:"M".charCodeAt(0),N:"N".charCodeAt(0),O:"O".charCodeAt(0),P:"P".charCodeAt(0),Q:"Q".charCodeAt(0),R:"R".charCodeAt(0),S:"S".charCodeAt(0),T:"T".charCodeAt(0),U:"U".charCodeAt(0),V:"V".charCodeAt(0),W:"W".charCodeAt(0),X:"X".charCodeAt(0),Y:"Y".charCodeAt(0),Z:"Z".charCodeAt(0),ZERO:"0".charCodeAt(0),ONE:"1".charCodeAt(0),TWO:"2".charCodeAt(0),THREE:"3".charCodeAt(0),FOUR:"4".charCodeAt(0),FIVE:"5".charCodeAt(0),SIX:"6".charCodeAt(0),SEVEN:"7".charCodeAt(0),EIGHT:"8".charCodeAt(0),NINE:"9".charCodeAt(0),NUMPAD_0:96,NUMPAD_1:97,NUMPAD_2:98,NUMPAD_3:99,NUMPAD_4:100,NUMPAD_5:101,NUMPAD_6:102,NUMPAD_7:103,NUMPAD_8:104,NUMPAD_9:105,NUMPAD_MULTIPLY:106,NUMPAD_ADD:107,NUMPAD_ENTER:108,NUMPAD_SUBTRACT:109,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,F1:112,F2:113,F3:114,F4:115,F5:116,F6:117,F7:118,F8:119,F9:120,F10:121,F11:122,F12:123,F13:124,F14:125,F15:126,COLON:186,EQUALS:187,COMMA:188,UNDERSCORE:189,PERIOD:190,QUESTION_MARK:191,TILDE:192,OPEN_BRACKET:219,BACKWARD_SLASH:220,CLOSED_BRACKET:221,QUOTES:222,BACKSPACE:8,TAB:9,CLEAR:12,ENTER:13,SHIFT:16,CONTROL:17,ALT:18,CAPS_LOCK:20,ESC:27,SPACEBAR:32,PAGE_UP:33,PAGE_DOWN:34,END:35,HOME:36,LEFT:37,UP:38,RIGHT:39,DOWN:40,PLUS:43,MINUS:44,INSERT:45,DELETE:46,HELP:47,NUM_LOCK:144};for(var o in n.KeyCode)n.KeyCode.hasOwnProperty(o)&&!o.match(/[a-z]/)&&(n.Keyboard[o]=n.KeyCode[o]);/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component=function(){},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.Angle=function(){},n.Component.Angle.prototype={angle:{get:function(){return n.Math.wrapAngle(n.Math.radToDeg(this.rotation))},set:function(t){this.rotation=n.Math.degToRad(n.Math.wrapAngle(t))}}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.Animation=function(){},n.Component.Animation.prototype={play:function(t,e,i,s){if(this.animations)return this.animations.play(t,e,i,s)}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.AutoCull=function(){},n.Component.AutoCull.prototype={autoCull:!1,inCamera:{get:function(){return this.autoCull||this.checkWorldBounds||(this._bounds.copyFrom(this.getBounds()),this._bounds.x+=this.game.camera.view.x,this._bounds.y+=this.game.camera.view.y),this.game.world.camera.view.intersects(this._bounds)}}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.Bounds=function(){},n.Component.Bounds.prototype={offsetX:{get:function(){return this.anchor.x*this.width}},offsetY:{get:function(){return this.anchor.y*this.height}},centerX:{get:function(){return this.x-this.offsetX+.5*this.width},set:function(t){this.x=t+this.offsetX-.5*this.width}},centerY:{get:function(){return this.y-this.offsetY+.5*this.height},set:function(t){this.y=t+this.offsetY-.5*this.height}},left:{get:function(){return this.x-this.offsetX},set:function(t){this.x=t+this.offsetX}},right:{get:function(){return this.x+this.width-this.offsetX},set:function(t){this.x=t-this.width+this.offsetX}},top:{get:function(){return this.y-this.offsetY},set:function(t){this.y=t+this.offsetY}},bottom:{get:function(){return this.y+this.height-this.offsetY},set:function(t){this.y=t-this.height+this.offsetY}},alignIn:function(t,e,i,s){switch(void 0===i&&(i=0),void 0===s&&(s=0),e){default:case n.TOP_LEFT:this.left=t.left-i,this.top=t.top-s;break;case n.TOP_CENTER:this.centerX=t.centerX+i,this.top=t.top-s;break;case n.TOP_RIGHT:this.right=t.right+i,this.top=t.top-s;break;case n.LEFT_CENTER:this.left=t.left-i,this.centerY=t.centerY+s;break;case n.CENTER:this.centerX=t.centerX+i,this.centerY=t.centerY+s;break;case n.RIGHT_CENTER:this.right=t.right+i,this.centerY=t.centerY+s;break;case n.BOTTOM_LEFT:this.left=t.left-i,this.bottom=t.bottom+s;break;case n.BOTTOM_CENTER:this.centerX=t.centerX+i,this.bottom=t.bottom+s;break;case n.BOTTOM_RIGHT:this.right=t.right+i,this.bottom=t.bottom+s}return this},alignTo:function(t,e,i,s){switch(void 0===i&&(i=0),void 0===s&&(s=0),e){default:case n.TOP_LEFT:this.left=t.left-i,this.bottom=t.top-s;break;case n.TOP_CENTER:this.centerX=t.centerX+i,this.bottom=t.top-s;break;case n.TOP_RIGHT:this.right=t.right+i,this.bottom=t.top-s;break;case n.LEFT_TOP:this.right=t.left-i,this.top=t.top-s;break;case n.LEFT_CENTER:this.right=t.left-i,this.centerY=t.centerY+s;break;case n.LEFT_BOTTOM:this.right=t.left-i,this.bottom=t.bottom+s;break;case n.RIGHT_TOP:this.left=t.right+i,this.top=t.top-s;break;case n.RIGHT_CENTER:this.left=t.right+i,this.centerY=t.centerY+s;break;case n.RIGHT_BOTTOM:this.left=t.right+i,this.bottom=t.bottom+s;break;case n.BOTTOM_LEFT:this.left=t.left-i,this.top=t.bottom+s;break;case n.BOTTOM_CENTER:this.centerX=t.centerX+i,this.top=t.bottom+s;break;case n.BOTTOM_RIGHT:this.right=t.right+i,this.top=t.bottom+s}return this}},n.Group.prototype.alignIn=n.Component.Bounds.prototype.alignIn,n.Group.prototype.alignTo=n.Component.Bounds.prototype.alignTo,/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.BringToTop=function(){},n.Component.BringToTop.prototype.bringToTop=function(){return this.parent&&this.parent.bringToTop(this),this},n.Component.BringToTop.prototype.sendToBack=function(){return this.parent&&this.parent.sendToBack(this),this},n.Component.BringToTop.prototype.moveUp=function(){return this.parent&&this.parent.moveUp(this),this},n.Component.BringToTop.prototype.moveDown=function(){return this.parent&&this.parent.moveDown(this),this},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.Core=function(){},n.Component.Core.install=function(t){n.Utils.mixinPrototype(this,n.Component.Core.prototype),this.components={};for(var e=0;e<t.length;e++){var i=t[e],s=!1;"Destroy"===i&&(s=!0),n.Utils.mixinPrototype(this,n.Component[i].prototype,s),this.components[i]=!0}},n.Component.Core.init=function(t,e,i,s,r){this.game=t,this.key=s,this.data={},this.position.set(e,i),this.world=new n.Point(e,i),this.previousPosition=new n.Point(e,i),this.events=new n.Events(this),this._bounds=new n.Rectangle,this.components.PhysicsBody&&(this.body=this.body),this.components.Animation&&(this.animations=new n.AnimationManager(this)),this.components.LoadTexture&&null!==s&&this.loadTexture(s,r),this.components.FixedToCamera&&(this.cameraOffset=new n.Point(e,i))},n.Component.Core.preUpdate=function(){if(this.pendingDestroy)return void this.destroy();if(this.previousPosition.set(this.world.x,this.world.y),this.previousRotation=this.rotation,!this.exists||!this.parent.exists)return this.renderOrderID=-1,!1;this.world.setTo(this.game.camera.x+this.worldTransform.tx,this.game.camera.y+this.worldTransform.ty),this.visible&&(this.renderOrderID=this.game.stage.currentRenderOrderID++),this.animations&&this.animations.update(),this.body&&this.body.preUpdate();for(var t=0;t<this.children.length;t++)this.children[t].preUpdate();return!0},n.Component.Core.prototype={game:null,name:"",data:{},components:{},z:0,events:void 0,animations:void 0,key:"",world:null,debug:!1,previousPosition:null,previousRotation:0,renderOrderID:0,fresh:!0,pendingDestroy:!1,_bounds:null,_exists:!0,exists:{get:function(){return this._exists},set:function(t){t?(this._exists=!0,this.body&&this.body.type===n.Physics.P2JS&&this.body.addToWorld(),this.visible=!0):(this._exists=!1,this.body&&this.body.type===n.Physics.P2JS&&this.body.removeFromWorld(),this.visible=!1)}},update:function(){},postUpdate:function(){this.customRender&&this.key.render(),this.components.PhysicsBody&&n.Component.PhysicsBody.postUpdate.call(this),this.components.FixedToCamera&&n.Component.FixedToCamera.postUpdate.call(this);for(var t=0;t<this.children.length;t++)this.children[t].postUpdate()}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.Crop=function(){},n.Component.Crop.prototype={cropRect:null,_crop:null,crop:function(t,e){void 0===e&&(e=!1),t?(e&&null!==this.cropRect?this.cropRect.setTo(t.x,t.y,t.width,t.height):e&&null===this.cropRect?this.cropRect=new n.Rectangle(t.x,t.y,t.width,t.height):this.cropRect=t,this.updateCrop()):(this._crop=null,this.cropRect=null,this.resetFrame())},updateCrop:function(){if(this.cropRect){var t=this.texture.crop.x,e=this.texture.crop.y,i=this.texture.crop.width,s=this.texture.crop.height;this._crop=n.Rectangle.clone(this.cropRect,this._crop),this._crop.x+=this._frame.x,this._crop.y+=this._frame.y;var r=Math.max(this._frame.x,this._crop.x),o=Math.max(this._frame.y,this._crop.y),a=Math.min(this._frame.right,this._crop.right)-r,h=Math.min(this._frame.bottom,this._crop.bottom)-o;this.texture.crop.x=r,this.texture.crop.y=o,this.texture.crop.width=a,this.texture.crop.height=h,this.texture.frame.width=Math.min(a,this.cropRect.width),this.texture.frame.height=Math.min(h,this.cropRect.height),this.texture.width=this.texture.frame.width,this.texture.height=this.texture.frame.height,this.texture._updateUvs(),16777215===this.tint||t===r&&e===o&&i===a&&s===h||(this.texture.requiresReTint=!0)}}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.Delta=function(){},n.Component.Delta.prototype={deltaX:{get:function(){return this.world.x-this.previousPosition.x}},deltaY:{get:function(){return this.world.y-this.previousPosition.y}},deltaZ:{get:function(){return this.rotation-this.previousRotation}}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.Destroy=function(){},n.Component.Destroy.prototype={destroyPhase:!1,destroy:function(t,e){if(null!==this.game&&!this.destroyPhase){void 0===t&&(t=!0),void 0===e&&(e=!1),this.destroyPhase=!0,this.events&&this.events.onDestroy$dispatch(this),this.parent&&(this.parent instanceof n.Group?this.parent.remove(this):this.parent.removeChild(this)),this.input&&this.input.destroy(),this.animations&&this.animations.destroy(),this.body&&this.body.destroy(),this.events&&this.events.destroy(),this.game.tweens.removeFrom(this);var i=this.children.length;if(t)for(;i--;)this.children[i].destroy(t);else for(;i--;)this.removeChild(this.children[i]);this._crop&&(this._crop=null,this.cropRect=null),this._frame&&(this._frame=null),n.Video&&this.key instanceof n.Video&&this.key.onChangeSource.remove(this.resizeFrame,this),n.BitmapText&&this._glyphs&&(this._glyphs=[]),this.alive=!1,this.exists=!1,this.visible=!1,this.filters=null,this.mask=null,this.game=null,this.data={},this.renderable=!1,this.transformCallback&&(this.transformCallback=null,this.transformCallbackContext=null),this.hitArea=null,this.parent=null,this.stage=null,this.worldTransform=null,this.filterArea=null,this._bounds=null,this._currentBounds=null,this._mask=null,this._destroyCachedSprite(),e&&this.texture.destroy(!0),this.destroyPhase=!1,this.pendingDestroy=!1}}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Events=function(t){this.parent=t},n.Events.prototype={destroy:function(){this._parent=null,this._onDestroy&&this._onDestroy.dispose(),this._onAddedToGroup&&this._onAddedToGroup.dispose(),this._onRemovedFromGroup&&this._onRemovedFromGroup.dispose(),this._onRemovedFromWorld&&this._onRemovedFromWorld.dispose(),this._onKilled&&this._onKilled.dispose(),this._onRevived&&this._onRevived.dispose(),this._onEnterBounds&&this._onEnterBounds.dispose(),this._onOutOfBounds&&this._onOutOfBounds.dispose(),this._onInputOver&&this._onInputOver.dispose(),this._onInputOut&&this._onInputOut.dispose(),this._onInputDown&&this._onInputDown.dispose(),this._onInputUp&&this._onInputUp.dispose(),this._onDragStart&&this._onDragStart.dispose(),this._onDragUpdate&&this._onDragUpdate.dispose(),this._onDragStop&&this._onDragStop.dispose(),this._onAnimationStart&&this._onAnimationStart.dispose(),this._onAnimationComplete&&this._onAnimationComplete.dispose(),this._onAnimationLoop&&this._onAnimationLoop.dispose()},onAddedToGroup:null,onRemovedFromGroup:null,onRemovedFromWorld:null,onDestroy:null,onKilled:null,onRevived:null,onOutOfBounds:null,onEnterBounds:null,onInputOver:null,onInputOut:null,onInputDown:null,onInputUp:null,onDragStart:null,onDragUpdate:null,onDragStop:null,onAnimationStart:null,onAnimationComplete:null,onAnimationLoop:null},n.Events.prototype.constructor=n.Events;for(var a in n.Events.prototype)n.Events.prototype.hasOwnProperty(a)&&0===a.indexOf("on")&&null===n.Events.prototype[a]&&function(t,e){"use strict";Object.defineProperty(n.Events.prototype,t,{get:function(){return this[e]||(this[e]=new n.Signal)}}),n.Events.prototype[t+"$dispatch"]=function(){return this[e]?this[e].dispatch.apply(this[e],arguments):null}}(a,"_"+a);/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.FixedToCamera=function(){},n.Component.FixedToCamera.postUpdate=function(){this.fixedToCamera&&(this.position.x=(this.game.camera.view.x+this.cameraOffset.x)/this.game.camera.scale.x,this.position.y=(this.game.camera.view.y+this.cameraOffset.y)/this.game.camera.scale.y)},n.Component.FixedToCamera.prototype={_fixedToCamera:!1,fixedToCamera:{get:function(){return this._fixedToCamera},set:function(t){t?(this._fixedToCamera=!0,this.cameraOffset.set(this.x,this.y)):this._fixedToCamera=!1}},cameraOffset:new n.Point},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.Health=function(){},n.Component.Health.prototype={health:1,maxHealth:100,damage:function(t){return this.alive&&(this.health-=t,this.health<=0&&this.kill()),this},setHealth:function(t){return this.health=t,this.health>this.maxHealth&&(this.health=this.maxHealth),this},heal:function(t){return this.alive&&(this.health+=t,this.health>this.maxHealth&&(this.health=this.maxHealth)),this}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.InCamera=function(){},n.Component.InCamera.prototype={inCamera:{get:function(){return this.game.world.camera.view.intersects(this._bounds)}}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.InputEnabled=function(){},n.Component.InputEnabled.prototype={input:null,inputEnabled:{get:function(){return this.input&&this.input.enabled},set:function(t){t?null===this.input?(this.input=new n.InputHandler(this),this.input.start()):this.input&&!this.input.enabled&&this.input.start():this.input&&this.input.enabled&&this.input.stop()}}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.InWorld=function(){},n.Component.InWorld.preUpdate=function(){if(this.autoCull||this.checkWorldBounds){if(this._bounds.copyFrom(this.getBounds()),this._bounds.x+=this.game.camera.view.x,this._bounds.y+=this.game.camera.view.y,this.autoCull)if(this.game.world.camera.view.intersects(this._bounds))this.renderable=!0,this.game.world.camera.totalInView++;else if(this.renderable=!1,this.outOfCameraBoundsKill)return this.kill(),!1;if(this.checkWorldBounds)if(this._outOfBoundsFired&&this.game.world.bounds.intersects(this._bounds))this._outOfBoundsFired=!1,this.events.onEnterBounds$dispatch(this);else if(!this._outOfBoundsFired&&!this.game.world.bounds.intersects(this._bounds)&&(this._outOfBoundsFired=!0,this.events.onOutOfBounds$dispatch(this),this.outOfBoundsKill))return this.kill(),!1}return!0},n.Component.InWorld.prototype={checkWorldBounds:!1,outOfBoundsKill:!1,outOfCameraBoundsKill:!1,_outOfBoundsFired:!1,inWorld:{get:function(){return this.game.world.bounds.intersects(this.getBounds())}}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.LifeSpan=function(){},n.Component.LifeSpan.preUpdate=function(){return!(this.lifespan>0&&(this.lifespan-=this.game.time.physicsElapsedMS,this.lifespan<=0))||(this.kill(),!1)},n.Component.LifeSpan.prototype={alive:!0,lifespan:0,revive:function(t){return void 0===t&&(t=100),this.alive=!0,this.exists=!0,this.visible=!0,"function"==typeof this.setHealth&&this.setHealth(t),this.events&&this.events.onRevived$dispatch(this),this},kill:function(){return this.alive=!1,this.exists=!1,this.visible=!1,this.events&&this.events.onKilled$dispatch(this),this}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.LoadTexture=function(){},n.Component.LoadTexture.prototype={customRender:!1,_frame:null,loadTexture:function(t,e,i){t===n.PENDING_ATLAS?(t=e,e=0):e=e||0,(i||void 0===i)&&this.animations&&this.animations.stop(),this.key=t,this.customRender=!1;var s=this.game.cache,r=!0,o=!this.texture.baseTexture.scaleMode;if(n.RenderTexture&&t instanceof n.RenderTexture)this.key=t.key,this.setTexture(t);else if(n.BitmapData&&t instanceof n.BitmapData)this.customRender=!0,this.setTexture(t.texture),r=s.hasFrameData(t.key,n.Cache.BITMAPDATA)?!this.animations.loadFrameData(s.getFrameData(t.key,n.Cache.BITMAPDATA),e):!this.animations.loadFrameData(t.frameData,0);else if(n.Video&&t instanceof n.Video){this.customRender=!0;var a=t.texture.valid;this.setTexture(t.texture),this.setFrame(t.texture.frame.clone()),t.onChangeSource.add(this.resizeFrame,this),this.texture.valid=a}else if(n.Tilemap&&t instanceof n.TilemapLayer)this.setTexture(PIXI.Texture.fromCanvas(t.canvas));else if(t instanceof PIXI.Texture)this.setTexture(t);else{var h=s.getImage(t,!0);this.key=h.key,this.setTexture(new PIXI.Texture(h.base)),this.texture.baseTexture.skipRender="__default"===t,r=!this.animations.loadFrameData(h.frameData,e)}r&&(this._frame=n.Rectangle.clone(this.texture.frame)),o||(this.texture.baseTexture.scaleMode=1)},setFrame:function(t){this._frame=t,this.texture.frame.x=t.x,this.texture.frame.y=t.y,this.texture.frame.width=t.width,this.texture.frame.height=t.height,this.texture.crop.x=t.x,this.texture.crop.y=t.y,this.texture.crop.width=t.width,this.texture.crop.height=t.height,t.trimmed?(this.texture.trim?(this.texture.trim.x=t.spriteSourceSizeX,this.texture.trim.y=t.spriteSourceSizeY,this.texture.trim.width=t.sourceSizeW,this.texture.trim.height=t.sourceSizeH):this.texture.trim={x:t.spriteSourceSizeX,y:t.spriteSourceSizeY,width:t.sourceSizeW,height:t.sourceSizeH},this.texture.width=t.sourceSizeW,this.texture.height=t.sourceSizeH,this.texture.frame.width=t.sourceSizeW,this.texture.frame.height=t.sourceSizeH):!t.trimmed&&this.texture.trim&&(this.texture.trim=null),this.cropRect&&this.updateCrop(),this.texture.requiresReTint=!0,this.texture._updateUvs(),this.tilingTexture&&(this.refreshTexture=!0)},resizeFrame:function(t,e,i){this.texture.frame.resize(e,i),this.texture.setFrame(this.texture.frame)},resetFrame:function(){this._frame&&this.setFrame(this._frame)},frame:{get:function(){return this.animations.frame},set:function(t){this.animations.frame=t}},frameName:{get:function(){return this.animations.frameName},set:function(t){this.animations.frameName=t}}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.Overlap=function(){},n.Component.Overlap.prototype={overlap:function(t){return n.Rectangle.intersects(this.getBounds(),t.getBounds())}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.PhysicsBody=function(){},n.Component.PhysicsBody.preUpdate=function(){return this.fresh&&this.exists?(this.world.setTo(this.parent.position.x+this.position.x,this.parent.position.y+this.position.y),this.worldTransform.tx=this.world.x,this.worldTransform.ty=this.world.y,this.previousPosition.set(this.world.x,this.world.y),this.previousRotation=this.rotation,this.body&&this.body.preUpdate(),this.fresh=!1,!1):(this.previousPosition.set(this.world.x,this.world.y),this.previousRotation=this.rotation,!(!this._exists||!this.parent.exists)||(this.renderOrderID=-1,!1))},n.Component.PhysicsBody.postUpdate=function(){this.exists&&this.body&&this.body.postUpdate()},n.Component.PhysicsBody.prototype={body:null,x:{get:function(){return this.position.x},set:function(t){this.position.x=t,this.body&&!this.body.dirty&&(this.body._reset=!0)}},y:{get:function(){return this.position.y},set:function(t){this.position.y=t,this.body&&!this.body.dirty&&(this.body._reset=!0)}}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.Reset=function(){},n.Component.Reset.prototype.reset=function(t,e,i){return void 0===i&&(i=1),this.world.set(t,e),this.position.set(t,e),this.fresh=!0,this.exists=!0,this.visible=!0,this.renderable=!0,this.components.InWorld&&(this._outOfBoundsFired=!1),this.components.LifeSpan&&(this.alive=!0,this.health=i),this.components.PhysicsBody&&this.body&&this.body.reset(t,e,!1,!1),this},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.ScaleMinMax=function(){},n.Component.ScaleMinMax.prototype={transformCallback:null,transformCallbackContext:this,scaleMin:null,scaleMax:null,checkTransform:function(t){this.scaleMin&&(t.a<this.scaleMin.x&&(t.a=this.scaleMin.x),t.d<this.scaleMin.y&&(t.d=this.scaleMin.y)),this.scaleMax&&(t.a>this.scaleMax.x&&(t.a=this.scaleMax.x),t.d>this.scaleMax.y&&(t.d=this.scaleMax.y))},setScaleMinMax:function(t,e,i,s){void 0===e?e=i=s=t:void 0===i&&(i=s=e,e=t),null===t?this.scaleMin=null:this.scaleMin?this.scaleMin.set(t,e):this.scaleMin=new n.Point(t,e),null===i?this.scaleMax=null:this.scaleMax?this.scaleMax.set(i,s):this.scaleMax=new n.Point(i,s),null===this.scaleMin?this.transformCallback=null:(this.transformCallback=this.checkTransform,this.transformCallbackContext=this)}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.Smoothed=function(){},n.Component.Smoothed.prototype={smoothed:{get:function(){return!this.texture.baseTexture.scaleMode},set:function(t){t?this.texture&&(this.texture.baseTexture.scaleMode=0):this.texture&&(this.texture.baseTexture.scaleMode=1)}}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.GameObjectFactory=function(t){this.game=t,this.world=this.game.world},n.GameObjectFactory.prototype={existing:function(t){return this.world.add(t)},weapon:function(t,e,i,s){var r=this.game.plugins.add(n.Weapon);return r.createBullets(t,e,i,s),r},image:function(t,e,i,s,r){return void 0===r&&(r=this.world),r.add(new n.Image(this.game,t,e,i,s))},sprite:function(t,e,i,s,n){return void 0===n&&(n=this.world),n.create(t,e,i,s)},creature:function(t,e,i,s,r){void 0===r&&(r=this.world);var o=new n.Creature(this.game,t,e,i,s);return r.add(o),o},tween:function(t){return this.game.tweens.create(t)},group:function(t,e,i,s,r){return new n.Group(this.game,t,e,i,s,r)},physicsGroup:function(t,e,i,s){return new n.Group(this.game,e,i,s,!0,t)},spriteBatch:function(t,e,i){return void 0===t&&(t=null),void 0===e&&(e="group"),void 0===i&&(i=!1),new n.SpriteBatch(this.game,t,e,i)},audio:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},sound:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},audioSprite:function(t){return this.game.sound.addSprite(t)},tileSprite:function(t,e,i,s,r,o,a){return void 0===a&&(a=this.world),a.add(new n.TileSprite(this.game,t,e,i,s,r,o))},rope:function(t,e,i,s,r,o){return void 0===o&&(o=this.world),o.add(new n.Rope(this.game,t,e,i,s,r))},text:function(t,e,i,s,r){return void 0===r&&(r=this.world),r.add(new n.Text(this.game,t,e,i,s))},button:function(t,e,i,s,r,o,a,h,l,c){return void 0===c&&(c=this.world),c.add(new n.Button(this.game,t,e,i,s,r,o,a,h,l))},graphics:function(t,e,i){return void 0===i&&(i=this.world),i.add(new n.Graphics(this.game,t,e))},emitter:function(t,e,i){return this.game.particles.add(new n.Particles.Arcade.Emitter(this.game,t,e,i))},retroFont:function(t,e,i,s,r,o,a,h,l){return new n.RetroFont(this.game,t,e,i,s,r,o,a,h,l)},bitmapText:function(t,e,i,s,r,o){return void 0===o&&(o=this.world),o.add(new n.BitmapText(this.game,t,e,i,s,r))},tilemap:function(t,e,i,s,r){return new n.Tilemap(this.game,t,e,i,s,r)},renderTexture:function(t,e,i,s){void 0!==i&&""!==i||(i=this.game.rnd.uuid()),void 0===s&&(s=!1);var r=new n.RenderTexture(this.game,t,e,i);return s&&this.game.cache.addRenderTexture(i,r),r},video:function(t,e){return new n.Video(this.game,t,e)},bitmapData:function(t,e,i,s){void 0===s&&(s=!1),void 0!==i&&""!==i||(i=this.game.rnd.uuid());var r=new n.BitmapData(this.game,i,t,e);return s&&this.game.cache.addBitmapData(i,r),r},filter:function(t){var e=Array.prototype.slice.call(arguments,1),t=new n.Filter[t](this.game);return t.init.apply(t,e),t},plugin:function(t){return this.game.plugins.add(t)}},n.GameObjectFactory.prototype.constructor=n.GameObjectFactory,/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.GameObjectCreator=function(t){this.game=t,this.world=this.game.world},n.GameObjectCreator.prototype={image:function(t,e,i,s){return new n.Image(this.game,t,e,i,s)},sprite:function(t,e,i,s){return new n.Sprite(this.game,t,e,i,s)},tween:function(t){return new n.Tween(t,this.game,this.game.tweens)},group:function(t,e,i,s,r){return new n.Group(this.game,t,e,i,s,r)},spriteBatch:function(t,e,i){return void 0===e&&(e="group"),void 0===i&&(i=!1),new n.SpriteBatch(this.game,t,e,i)},audio:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},audioSprite:function(t){return this.game.sound.addSprite(t)},sound:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},tileSprite:function(t,e,i,s,r,o){return new n.TileSprite(this.game,t,e,i,s,r,o)},rope:function(t,e,i,s,r){return new n.Rope(this.game,t,e,i,s,r)},text:function(t,e,i,s){return new n.Text(this.game,t,e,i,s)},button:function(t,e,i,s,r,o,a,h,l){return new n.Button(this.game,t,e,i,s,r,o,a,h,l)},graphics:function(t,e){return new n.Graphics(this.game,t,e)},emitter:function(t,e,i){return new n.Particles.Arcade.Emitter(this.game,t,e,i)},retroFont:function(t,e,i,s,r,o,a,h,l){return new n.RetroFont(this.game,t,e,i,s,r,o,a,h,l)},bitmapText:function(t,e,i,s,r,o){return new n.BitmapText(this.game,t,e,i,s,r,o)},tilemap:function(t,e,i,s,r){return new n.Tilemap(this.game,t,e,i,s,r)},renderTexture:function(t,e,i,s){void 0!==i&&""!==i||(i=this.game.rnd.uuid()),void 0===s&&(s=!1);var r=new n.RenderTexture(this.game,t,e,i);return s&&this.game.cache.addRenderTexture(i,r),r},bitmapData:function(t,e,i,s){void 0===s&&(s=!1),void 0!==i&&""!==i||(i=this.game.rnd.uuid());var r=new n.BitmapData(this.game,i,t,e);return s&&this.game.cache.addBitmapData(i,r),r},filter:function(t){var e=Array.prototype.slice.call(arguments,1),t=new n.Filter[t](this.game);return t.init.apply(t,e),t}},n.GameObjectCreator.prototype.constructor=n.GameObjectCreator,/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Sprite=function(t,e,i,s,r){e=e||0,i=i||0,s=s||null,r=r||null,this.type=n.SPRITE,this.physicsType=n.SPRITE,PIXI.Sprite.call(this,n.Cache.DEFAULT),n.Component.Core.init.call(this,t,e,i,s,r)},n.Sprite.prototype=Object.create(PIXI.Sprite.prototype),n.Sprite.prototype.constructor=n.Sprite,n.Component.Core.install.call(n.Sprite.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Delta","Destroy","FixedToCamera","Health","InCamera","InputEnabled","InWorld","LifeSpan","LoadTexture","Overlap","PhysicsBody","Reset","ScaleMinMax","Smoothed"]),n.Sprite.prototype.preUpdatePhysics=n.Component.PhysicsBody.preUpdate,n.Sprite.prototype.preUpdateLifeSpan=n.Component.LifeSpan.preUpdate,n.Sprite.prototype.preUpdateInWorld=n.Component.InWorld.preUpdate,n.Sprite.prototype.preUpdateCore=n.Component.Core.preUpdate,n.Sprite.prototype.preUpdate=function(){return!!(this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld())&&this.preUpdateCore()},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Image=function(t,e,i,s,r){e=e||0,i=i||0,s=s||null,r=r||null,this.type=n.IMAGE,PIXI.Sprite.call(this,n.Cache.DEFAULT),n.Component.Core.init.call(this,t,e,i,s,r)},n.Image.prototype=Object.create(PIXI.Sprite.prototype),n.Image.prototype.constructor=n.Image,n.Component.Core.install.call(n.Image.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Destroy","FixedToCamera","InputEnabled","LifeSpan","LoadTexture","Overlap","Reset","ScaleMinMax","Smoothed"]),n.Image.prototype.preUpdateInWorld=n.Component.InWorld.preUpdate,n.Image.prototype.preUpdateCore=n.Component.Core.preUpdate,n.Image.prototype.preUpdate=function(){return!!this.preUpdateInWorld()&&this.preUpdateCore()},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Button=function(t,e,i,s,r,o,a,h,l,c){e=e||0,i=i||0,s=s||null,r=r||null,o=o||this,n.Image.call(this,t,e,i,s,h),this.type=n.BUTTON,this.physicsType=n.SPRITE,this._onOverFrame=null,this._onOutFrame=null,this._onDownFrame=null,this._onUpFrame=null,this.onOverSound=null,this.onOutSound=null,this.onDownSound=null,this.onUpSound=null,this.onOverSoundMarker="",this.onOutSoundMarker="",this.onDownSoundMarker="",this.onUpSoundMarker="",this.onInputOver=new n.Signal,this.onInputOut=new n.Signal,this.onInputDown=new n.Signal,this.onInputUp=new n.Signal,this.onOverMouseOnly=!0,this.justReleasedPreventsOver=n.PointerMode.TOUCH,this.freezeFrames=!1,this.forceOut=!1,this.inputEnabled=!0,this.input.start(0,!0),this.input.useHandCursor=!0,this.setFrames(a,h,l,c),null!==r&&this.onInputUp.add(r,o),this.events.onInputOver.add(this.onInputOverHandler,this),this.events.onInputOut.add(this.onInputOutHandler,this),this.events.onInputDown.add(this.onInputDownHandler,this),this.events.onInputUp.add(this.onInputUpHandler,this),this.events.onRemovedFromWorld.add(this.removedFromWorld,this)},n.Button.prototype=Object.create(n.Image.prototype),n.Button.prototype.constructor=n.Button;n.Button.prototype.clearFrames=function(){this.setFrames(null,null,null,null)},n.Button.prototype.removedFromWorld=function(){this.inputEnabled=!1},n.Button.prototype.setStateFrame=function(t,e,i){var s="_on"+t+"Frame";null!==e?(this[s]=e,i&&this.changeStateFrame(t)):this[s]=null},n.Button.prototype.changeStateFrame=function(t){if(this.freezeFrames)return!1;var e="_on"+t+"Frame",i=this[e];return"string"==typeof i?(this.frameName=i,!0):"number"==typeof i&&(this.frame=i,!0)},n.Button.prototype.setFrames=function(t,e,i,s){this.setStateFrame("Over",t,this.input.pointerOver()),this.setStateFrame("Out",e,!this.input.pointerOver()),this.setStateFrame("Down",i,this.input.pointerDown()),this.setStateFrame("Up",s,this.input.pointerUp())},n.Button.prototype.setStateSound=function(t,e,i){var s="on"+t+"Sound",r="on"+t+"SoundMarker";e instanceof n.Sound||e instanceof n.AudioSprite?(this[s]=e,this[r]="string"==typeof i?i:""):(this[s]=null,this[r]="")},n.Button.prototype.playStateSound=function(t){var e="on"+t+"Sound",i=this[e];if(i){var s="on"+t+"SoundMarker",n=this[s];return i.play(n),!0}return!1},n.Button.prototype.setSounds=function(t,e,i,s,n,r,o,a){this.setStateSound("Over",t,e),this.setStateSound("Out",n,r),this.setStateSound("Down",i,s),this.setStateSound("Up",o,a)},n.Button.prototype.setOverSound=function(t,e){this.setStateSound("Over",t,e)},n.Button.prototype.setOutSound=function(t,e){this.setStateSound("Out",t,e)},n.Button.prototype.setDownSound=function(t,e){this.setStateSound("Down",t,e)},n.Button.prototype.setUpSound=function(t,e){this.setStateSound("Up",t,e)},n.Button.prototype.onInputOverHandler=function(t,e){e.justReleased()&&(this.justReleasedPreventsOver&e.pointerMode)===e.pointerMode||(this.changeStateFrame("Over"),this.onOverMouseOnly&&!e.isMouse||(this.playStateSound("Over"),this.onInputOver&&this.onInputOver.dispatch(this,e)))},n.Button.prototype.onInputOutHandler=function(t,e){this.changeStateFrame("Out"),this.playStateSound("Out"),this.onInputOut&&this.onInputOut.dispatch(this,e)},n.Button.prototype.onInputDownHandler=function(t,e){this.changeStateFrame("Down"),this.playStateSound("Down"),this.onInputDown&&this.onInputDown.dispatch(this,e)},n.Button.prototype.onInputUpHandler=function(t,e,i){if(this.playStateSound("Up"),this.onInputUp&&this.onInputUp.dispatch(this,e,i),!this.freezeFrames)if(!0===this.forceOut||(this.forceOut&e.pointerMode)===e.pointerMode)this.changeStateFrame("Out");else{var s=this.changeStateFrame("Up");s||(i?this.changeStateFrame("Over"):this.changeStateFrame("Out"))}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.SpriteBatch=function(t,e,i,s){void 0!==e&&null!==e||(e=t.world),PIXI.SpriteBatch.call(this),n.Group.call(this,t,e,i,s),this.type=n.SPRITEBATCH},n.SpriteBatch.prototype=n.Utils.extend(!0,n.SpriteBatch.prototype,PIXI.SpriteBatch.prototype,n.Group.prototype),n.SpriteBatch.prototype.constructor=n.SpriteBatch,/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.BitmapData=function(t,e,i,s,r){void 0!==i&&0!==i||(i=256),void 0!==s&&0!==s||(s=256),void 0===r&&(r=!1),this.game=t,this.key=e,this.width=i,this.height=s,this.canvas=n.Canvas.create(this,i,s,null,r),this.context=this.canvas.getContext("2d",{alpha:!0}),this.ctx=this.context,this.smoothProperty=t.renderType===n.CANVAS?t.renderer.renderSession.smoothProperty:n.Canvas.getSmoothingPrefix(this.context),this.imageData=this.context.getImageData(0,0,i,s),this.data=null,this.imageData&&(this.data=this.imageData.data),this.pixels=null,this.data&&(this.imageData.data.buffer?(this.buffer=this.imageData.data.buffer,this.pixels=new Uint32Array(this.buffer)):window.ArrayBuffer?(this.buffer=new ArrayBuffer(this.imageData.data.length),this.pixels=new Uint32Array(this.buffer)):this.pixels=this.imageData.data),this.baseTexture=new PIXI.BaseTexture(this.canvas),this.texture=new PIXI.Texture(this.baseTexture),this.frameData=new n.FrameData,this.textureFrame=this.frameData.addFrame(new n.Frame(0,0,0,i,s,"bitmapData")),this.texture.frame=this.textureFrame,this.type=n.BITMAPDATA,this.disableTextureUpload=!1,this.dirty=!1,this.cls=this.clear,this._image=null,this._pos=new n.Point,this._size=new n.Point,this._scale=new n.Point,this._rotate=0,this._alpha={prev:1,current:1},this._anchor=new n.Point,this._tempR=0,this._tempG=0,this._tempB=0,this._circle=new n.Circle,this._swapCanvas=void 0},n.BitmapData.prototype={move:function(t,e,i){return 0!==t&&this.moveH(t,i),0!==e&&this.moveV(e,i),this},moveH:function(t,e){void 0===e&&(e=!0),void 0===this._swapCanvas&&(this._swapCanvas=PIXI.CanvasPool.create(this,this.width,this.height));var i=this._swapCanvas,s=i.getContext("2d"),n=this.height,r=this.canvas;if(s.clearRect(0,0,this.width,this.height),t<0){t=Math.abs(t);var o=this.width-t;e&&s.drawImage(r,0,0,t,n,o,0,t,n),s.drawImage(r,t,0,o,n,0,0,o,n)}else{var o=this.width-t;e&&s.drawImage(r,o,0,t,n,0,0,t,n),s.drawImage(r,0,0,o,n,t,0,o,n)}return this.clear(),this.copy(this._swapCanvas)},moveV:function(t,e){void 0===e&&(e=!0),void 0===this._swapCanvas&&(this._swapCanvas=PIXI.CanvasPool.create(this,this.width,this.height));var i=this._swapCanvas,s=i.getContext("2d"),n=this.width,r=this.canvas;if(s.clearRect(0,0,this.width,this.height),t<0){t=Math.abs(t);var o=this.height-t;e&&s.drawImage(r,0,0,n,t,0,o,n,t),s.drawImage(r,0,t,n,o,0,0,n,o)}else{var o=this.height-t;e&&s.drawImage(r,0,o,n,t,0,0,n,t),s.drawImage(r,0,0,n,o,0,t,n,o)}return this.clear(),this.copy(this._swapCanvas)},add:function(t){if(Array.isArray(t))for(var e=0;e<t.length;e++)t[e].loadTexture&&t[e].loadTexture(this);else t.loadTexture(this);return this},load:function(t){if("string"==typeof t&&(t=this.game.cache.getImage(t)),t)return this.resize(t.width,t.height),this.cls(),this.draw(t),this.update(),this},clear:function(t,e,i,s){return void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=this.width),void 0===s&&(s=this.height),this.context.clearRect(t,e,i,s),this.dirty=!0,this},fill:function(t,e,i,s){return void 0===s&&(s=1),this.context.fillStyle="rgba("+t+","+e+","+i+","+s+")",this.context.fillRect(0,0,this.width,this.height),this.dirty=!0,this},generateTexture:function(t){var e=new Image;e.src=this.canvas.toDataURL("image/png");var i=this.game.cache.addImage(t,"",e);return new PIXI.Texture(i.base)},resize:function(t,e){return t===this.width&&e===this.height||(this.width=t,this.height=e,this.canvas.width=t,this.canvas.height=e,void 0!==this._swapCanvas&&(this._swapCanvas.width=t,this._swapCanvas.height=e),this.baseTexture.width=t,this.baseTexture.height=e,this.textureFrame.width=t,this.textureFrame.height=e,this.texture.width=t,this.texture.height=e,this.texture.crop.width=t,this.texture.crop.height=e,this.update(),this.dirty=!0),this},update:function(t,e,i,s){return void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=Math.max(1,this.width)),void 0===s&&(s=Math.max(1,this.height)),this.imageData=this.context.getImageData(t,e,i,s),this.data=this.imageData.data,this.imageData.data.buffer?(this.buffer=this.imageData.data.buffer,this.pixels=new Uint32Array(this.buffer)):window.ArrayBuffer?(this.buffer=new ArrayBuffer(this.imageData.data.length),this.pixels=new Uint32Array(this.buffer)):this.pixels=this.imageData.data,this},processPixelRGB:function(t,e,i,s,r,o){void 0===i&&(i=0),void 0===s&&(s=0),void 0===r&&(r=this.width),void 0===o&&(o=this.height);for(var a=i+r,h=s+o,l=n.Color.createColor(),c={r:0,g:0,b:0,a:0},u=!1,d=s;d<h;d++)for(var p=i;p<a;p++)n.Color.unpackPixel(this.getPixel32(p,d),l),!1!==(c=t.call(e,l,p,d))&&null!==c&&void 0!==c&&(this.setPixel32(p,d,c.r,c.g,c.b,c.a,!1),u=!0);return u&&(this.context.putImageData(this.imageData,0,0),this.dirty=!0),this},processPixel:function(t,e,i,s,n,r){void 0===i&&(i=0),void 0===s&&(s=0),void 0===n&&(n=this.width),void 0===r&&(r=this.height);for(var o=i+n,a=s+r,h=0,l=0,c=!1,u=s;u<a;u++)for(var d=i;d<o;d++)h=this.getPixel32(d,u),(l=t.call(e,h,d,u))!==h&&(this.pixels[u*this.width+d]=l,c=!0);return c&&(this.context.putImageData(this.imageData,0,0),this.dirty=!0),this},replaceRGB:function(t,e,i,s,r,o,a,h,l){var c=0,u=0,d=this.width,p=this.height,f=n.Color.packPixel(t,e,i,s);void 0!==l&&l instanceof n.Rectangle&&(c=l.x,u=l.y,d=l.width,p=l.height);for(var g=0;g<p;g++)for(var m=0;m<d;m++)this.getPixel32(c+m,u+g)===f&&this.setPixel32(c+m,u+g,r,o,a,h,!1);return this.context.putImageData(this.imageData,0,0),this.dirty=!0,this},setHSL:function(t,e,i,s){var r=t||0===t,o=e||0===e,a=i||0===i;if(r||o||a){void 0===s&&(s=new n.Rectangle(0,0,this.width,this.height));for(var h=n.Color.createColor(),l=s.y;l<s.bottom;l++)for(var c=s.x;c<s.right;c++)n.Color.unpackPixel(this.getPixel32(c,l),h,!0),r&&(h.h=t),o&&(h.s=e),a&&(h.l=i),n.Color.HSLtoRGB(h.h,h.s,h.l,h),this.setPixel32(c,l,h.r,h.g,h.b,h.a,!1);return this.context.putImageData(this.imageData,0,0),this.dirty=!0,this}},shiftHSL:function(t,e,i,s){if(void 0!==t&&null!==t||(t=!1),void 0!==e&&null!==e||(e=!1),void 0!==i&&null!==i||(i=!1),t||e||i){void 0===s&&(s=new n.Rectangle(0,0,this.width,this.height));for(var r=n.Color.createColor(),o=s.y;o<s.bottom;o++)for(var a=s.x;a<s.right;a++)n.Color.unpackPixel(this.getPixel32(a,o),r,!0),t&&(r.h=this.game.math.wrap(r.h+t,0,1)),e&&(r.s=this.game.math.clamp(r.s+e,0,1)),i&&(r.l=this.game.math.clamp(r.l+i,0,1)),n.Color.HSLtoRGB(r.h,r.s,r.l,r),this.setPixel32(a,o,r.r,r.g,r.b,r.a,!1);return this.context.putImageData(this.imageData,0,0),this.dirty=!0,this}},setPixel32:function(t,e,i,s,r,o,a){return void 0===a&&(a=!0),t>=0&&t<=this.width&&e>=0&&e<=this.height&&(n.Device.LITTLE_ENDIAN?this.pixels[e*this.width+t]=o<<24|r<<16|s<<8|i:this.pixels[e*this.width+t]=i<<24|s<<16|r<<8|o,a&&(this.context.putImageData(this.imageData,0,0),this.dirty=!0)),this},setPixel:function(t,e,i,s,n,r){return this.setPixel32(t,e,i,s,n,255,r)},getPixel:function(t,e,i){i||(i=n.Color.createColor());var s=~~(t+e*this.width);return s*=4,i.r=this.data[s],i.g=this.data[++s],i.b=this.data[++s],i.a=this.data[++s],i},getPixel32:function(t,e){if(t>=0&&t<=this.width&&e>=0&&e<=this.height)return this.pixels[e*this.width+t]},getPixelRGB:function(t,e,i,s,r){return n.Color.unpackPixel(this.getPixel32(t,e),i,s,r)},getPixels:function(t){return this.context.getImageData(t.x,t.y,t.width,t.height)},getFirstPixel:function(t){void 0===t&&(t=0);var e=n.Color.createColor(),i=0,s=0,r=1,o=!1;1===t?(r=-1,s=this.height):3===t&&(r=-1,i=this.width);do{n.Color.unpackPixel(this.getPixel32(i,s),e),0===t||1===t?++i===this.width&&(i=0,((s+=r)>=this.height||s<=0)&&(o=!0)):2!==t&&3!==t||++s===this.height&&(s=0,((i+=r)>=this.width||i<=0)&&(o=!0))}while(0===e.a&&!o);return e.x=i,e.y=s,e},getBounds:function(t){return void 0===t&&(t=new n.Rectangle),t.x=this.getFirstPixel(2).x,t.x===this.width?t.setTo(0,0,0,0):(t.y=this.getFirstPixel(0).y,t.width=this.getFirstPixel(3).x-t.x+1,t.height=this.getFirstPixel(1).y-t.y+1,t)},addToWorld:function(t,e,i,s,n,r){n=n||1,r=r||1;var o=this.game.add.image(t,e,this);return o.anchor.set(i,s),o.scale.set(n,r),o},copy:function(t,e,i,s,r,o,a,h,l,c,u,d,p,f,g,m,y){if(void 0!==t&&null!==t||(t=this),(t instanceof n.RenderTexture||t instanceof PIXI.RenderTexture)&&(t=t.getCanvas()),this._image=t,t instanceof n.Sprite||t instanceof n.Image||t instanceof n.Text||t instanceof PIXI.Sprite)this._pos.set(t.texture.crop.x,t.texture.crop.y),this._size.set(t.texture.crop.width,t.texture.crop.height),this._scale.set(t.scale.x,t.scale.y),this._anchor.set(t.anchor.x,t.anchor.y),this._rotate=t.rotation,this._alpha.current=t.alpha,t.texture instanceof n.RenderTexture||t.texture instanceof PIXI.RenderTexture?this._image=t.texture.getCanvas():this._image=t.texture.baseTexture.source,void 0!==o&&null!==o||(o=t.x),void 0!==a&&null!==a||(a=t.y),t.texture.trim&&(o+=t.texture.trim.x-t.anchor.x*t.texture.trim.width,a+=t.texture.trim.y-t.anchor.y*t.texture.trim.height),16777215!==t.tint&&(t.cachedTint!==t.tint&&(t.cachedTint=t.tint,t.tintedTexture=PIXI.CanvasTinter.getTintedTexture(t,t.tint)),this._image=t.tintedTexture,this._pos.set(0));else{if(this._pos.set(0),this._scale.set(1),this._anchor.set(0),this._rotate=0,this._alpha.current=1,t instanceof n.BitmapData)this._image=t.canvas;else if("string"==typeof t){if(null===(t=this.game.cache.getImage(t)))return;this._image=t}this._size.set(this._image.width,this._image.height)}if(void 0!==e&&null!==e||(e=0),void 0!==i&&null!==i||(i=0),s&&(this._size.x=s),r&&(this._size.y=r),void 0!==o&&null!==o||(o=e),void 0!==a&&null!==a||(a=i),void 0!==h&&null!==h||(h=this._size.x),void 0!==l&&null!==l||(l=this._size.y),"number"==typeof c&&(this._rotate=c),"number"==typeof u&&(this._anchor.x=u),"number"==typeof d&&(this._anchor.y=d),"number"==typeof p&&(this._scale.x=p),"number"==typeof f&&(this._scale.y=f),"number"==typeof g&&(this._alpha.current=g),void 0===m&&(m=null),void 0===y&&(y=!1),!(this._alpha.current<=0||0===this._scale.x||0===this._scale.y||0===this._size.x||0===this._size.y)){var v=this.context;return this._alpha.prev=v.globalAlpha,v.save(),v.globalAlpha=this._alpha.current,m&&(this.op=m),y&&(o|=0,a|=0),v.translate(o,a),v.scale(this._scale.x,this._scale.y),v.rotate(this._rotate),v.drawImage(this._image,this._pos.x+e,this._pos.y+i,this._size.x,this._size.y,-h*this._anchor.x,-l*this._anchor.y,h,l),v.restore(),v.globalAlpha=this._alpha.prev,this.dirty=!0,this}},copyTransform:function(t,e,i){if(void 0===e&&(e=null),void 0===i&&(i=!1),!t.hasOwnProperty("worldTransform")||!t.worldVisible||0===t.worldAlpha)return this;var s=t.worldTransform;if(this._pos.set(t.texture.crop.x,t.texture.crop.y),this._size.set(t.texture.crop.width,t.texture.crop.height),0===s.a||0===s.d||0===this._size.x||0===this._size.y)return this;t.texture instanceof n.RenderTexture||t.texture instanceof PIXI.RenderTexture?this._image=t.texture.getCanvas():this._image=t.texture.baseTexture.source;var r=s.tx,o=s.ty;t.texture.trim&&(r+=t.texture.trim.x-t.anchor.x*t.texture.trim.width,o+=t.texture.trim.y-t.anchor.y*t.texture.trim.height),16777215!==t.tint&&(t.cachedTint!==t.tint&&(t.cachedTint=t.tint,t.tintedTexture=PIXI.CanvasTinter.getTintedTexture(t,t.tint)),this._image=t.tintedTexture,this._pos.set(0)),i&&(r|=0,o|=0);var a=this.context;return this._alpha.prev=a.globalAlpha,a.save(),a.globalAlpha=this._alpha.current,e&&(this.op=e),a[this.smoothProperty]=t.texture.baseTexture.scaleMode===PIXI.scaleModes.LINEAR,a.setTransform(s.a,s.b,s.c,s.d,r,o),a.drawImage(this._image,this._pos.x,this._pos.y,this._size.x,this._size.y,-this._size.x*t.anchor.x,-this._size.y*t.anchor.y,this._size.x,this._size.y),a.restore(),a.globalAlpha=this._alpha.prev,this.dirty=!0,this},copyRect:function(t,e,i,s,n,r,o){return this.copy(t,e.x,e.y,e.width,e.height,i,s,e.width,e.height,0,0,0,1,1,n,r,o)},draw:function(t,e,i,s,n,r,o){return this.copy(t,null,null,null,null,e,i,s,n,null,null,null,null,null,null,r,o)},drawGroup:function(t,e,i){return t.total>0&&t.forEachExists(this.drawGroupProxy,this,e,i),this},drawGroupProxy:function(t,e,i){if(t.hasOwnProperty("texture")&&this.copyTransform(t,e,i),t.type===n.GROUP&&t.exists)this.drawGroup(t,e,i);else if(t.hasOwnProperty("children")&&t.children.length>0)for(var s=0;s<t.children.length;s++)t.children[s].exists&&this.copyTransform(t.children[s],e,i)},drawFull:function(t,e,i){if(!1===t.worldVisible||0===t.worldAlpha||t.hasOwnProperty("exists")&&!1===t.exists)return this;if(t.type!==n.GROUP&&t.type!==n.EMITTER&&t.type!==n.BITMAPTEXT)if(t.type===n.GRAPHICS){var s=t.getBounds();this.ctx.save(),this.ctx.translate(s.x,s.y),PIXI.CanvasGraphics.renderGraphics(t,this.ctx),this.ctx.restore()}else this.copy(t,null,null,null,null,t.worldPosition.x,t.worldPosition.y,null,null,t.worldRotation,null,null,t.worldScale.x,t.worldScale.y,t.worldAlpha,e,i);if(t.children)for(var r=0;r<t.children.length;r++)this.drawFull(t.children[r],e,i);return this},shadow:function(t,e,i,s){var n=this.context;return void 0===t||null===t?n.shadowColor="rgba(0,0,0,0)":(n.shadowColor=t,n.shadowBlur=e||5,n.shadowOffsetX=i||10,n.shadowOffsetY=s||10),this},alphaMask:function(t,e,i,s){return void 0===s||null===s?this.draw(e).blendSourceAtop():this.draw(e,s.x,s.y,s.width,s.height).blendSourceAtop(),void 0===i||null===i?this.draw(t).blendReset():this.draw(t,i.x,i.y,i.width,i.height).blendReset(),this},extract:function(t,e,i,s,n,r,o,a,h){return void 0===n&&(n=255),void 0===r&&(r=!1),void 0===o&&(o=e),void 0===a&&(a=i),void 0===h&&(h=s),r&&t.resize(this.width,this.height),this.processPixelRGB(function(r,l,c){return r.r===e&&r.g===i&&r.b===s&&t.setPixel32(l,c,o,a,h,n,!1),!1},this),t.context.putImageData(t.imageData,0,0),t.dirty=!0,t},rect:function(t,e,i,s,n){return void 0!==n&&(this.context.fillStyle=n),this.context.fillRect(t,e,i,s),this},text:function(t,e,i,s,n,r){void 0===e&&(e=0),void 0===i&&(i=0),void 0===s&&(s="14px Courier"),void 0===n&&(n="rgb(255,255,255)"),void 0===r&&(r=!0);var o=this.context,a=o.font;return o.font=s,r&&(o.fillStyle="rgb(0,0,0)",o.fillText(t,e+1,i+1)),o.fillStyle=n,o.fillText(t,e,i),o.font=a,this},circle:function(t,e,i,s){var n=this.context;return void 0!==s&&(n.fillStyle=s),n.beginPath(),n.arc(t,e,i,0,2*Math.PI,!1),n.closePath(),n.fill(),this},line:function(t,e,i,s,n,r){void 0===n&&(n="#fff"),void 0===r&&(r=1);var o=this.context;return o.beginPath(),o.moveTo(t,e),o.lineTo(i,s),o.lineWidth=r,o.strokeStyle=n,o.stroke(),o.closePath(),this},textureLine:function(t,e,i){if(void 0===i&&(i="repeat-x"),"string"!=typeof e||(e=this.game.cache.getImage(e))){var s=t.length;"no-repeat"===i&&s>e.width&&(s=e.width);var r=this.context;return r.fillStyle=r.createPattern(e,i),this._circle=new n.Circle(t.start.x,t.start.y,e.height),this._circle.circumferencePoint(t.angle-1.5707963267948966,!1,this._pos),r.save(),r.translate(this._pos.x,this._pos.y),r.rotate(t.angle),r.fillRect(0,0,s,e.height),r.restore(),this.dirty=!0,this}},render:function(){return!this.disableTextureUpload&&this.dirty&&(this.baseTexture.dirty(),this.dirty=!1),this},destroy:function(){this.frameData.destroy(),this.texture.destroy(!0),PIXI.CanvasPool.remove(this)},blendReset:function(){return this.op="source-over",this},blendSourceOver:function(){return this.op="source-over",this},blendSourceIn:function(){return this.op="source-in",this},blendSourceOut:function(){return this.op="source-out",this},blendSourceAtop:function(){return this.op="source-atop",this},blendDestinationOver:function(){return this.op="destination-over",this},blendDestinationIn:function(){return this.op="destination-in",this},blendDestinationOut:function(){return this.op="destination-out",this},blendDestinationAtop:function(){return this.op="destination-atop",this},blendXor:function(){return this.op="xor",this},blendAdd:function(){return this.op="lighter",this},blendMultiply:function(){return this.op="multiply",this},blendScreen:function(){return this.op="screen",this},blendOverlay:function(){return this.op="overlay",this},blendDarken:function(){return this.op="darken",this},blendLighten:function(){return this.op="lighten",this},blendColorDodge:function(){return this.op="color-dodge",this},blendColorBurn:function(){return this.op="color-burn",this},blendHardLight:function(){return this.op="hard-light",this},blendSoftLight:function(){return this.op="soft-light",this},blendDifference:function(){return this.op="difference",this},blendExclusion:function(){return this.op="exclusion",this},blendHue:function(){return this.op="hue",this},blendSaturation:function(){return this.op="saturation",this},blendColor:function(){return this.op="color",this},blendLuminosity:function(){return this.op="luminosity",this}},Object.defineProperty(n.BitmapData.prototype,"smoothed",{get:function(){n.Canvas.getSmoothingEnabled(this.context)},set:function(t){n.Canvas.setSmoothingEnabled(this.context,t)}}),Object.defineProperty(n.BitmapData.prototype,"op",{get:function(){return this.context.globalCompositeOperation},set:function(t){this.context.globalCompositeOperation=t}}),n.BitmapData.getTransform=function(t,e,i,s,n,r){return"number"!=typeof t&&(t=0),"number"!=typeof e&&(e=0),"number"!=typeof i&&(i=1),"number"!=typeof s&&(s=1),"number"!=typeof n&&(n=0),"number"!=typeof r&&(r=0),{sx:i,sy:s,scaleX:i,scaleY:s,skewX:n,skewY:r,translateX:t,translateY:e,tx:t,ty:e}},n.BitmapData.prototype.constructor=n.BitmapData,PIXI.Graphics=function(){PIXI.DisplayObjectContainer.call(this),this.renderable=!0,this.fillAlpha=1,this.lineWidth=0,this.lineColor=0,this.graphicsData=[],this.tint=16777215,this.blendMode=PIXI.blendModes.NORMAL,this.currentPath=null,this._webGL=[],this.isMask=!1,this.boundsPadding=0,this._localBounds=new PIXI.Rectangle(0,0,1,1),this.dirty=!0,this._boundsDirty=!1,this.webGLDirty=!1,this.cachedSpriteDirty=!1},PIXI.Graphics.prototype=Object.create(PIXI.DisplayObjectContainer.prototype),PIXI.Graphics.prototype.constructor=PIXI.Graphics,PIXI.Graphics.prototype.lineStyle=function(t,e,i){return this.lineWidth=t||0,this.lineColor=e||0,this.lineAlpha=void 0===i?1:i,this.currentPath&&(this.currentPath.shape.points.length?this.drawShape(new PIXI.Polygon(this.currentPath.shape.points.slice(-2))):(this.currentPath.lineWidth=this.lineWidth,this.currentPath.lineColor=this.lineColor,this.currentPath.lineAlpha=this.lineAlpha)),this},PIXI.Graphics.prototype.moveTo=function(t,e){return this.drawShape(new PIXI.Polygon([t,e])),this},PIXI.Graphics.prototype.lineTo=function(t,e){return this.currentPath||this.moveTo(0,0),this.currentPath.shape.points.push(t,e),this.dirty=!0,this._boundsDirty=!0,this},PIXI.Graphics.prototype.quadraticCurveTo=function(t,e,i,s){this.currentPath?0===this.currentPath.shape.points.length&&(this.currentPath.shape.points=[0,0]):this.moveTo(0,0);var n,r,o=this.currentPath.shape.points;0===o.length&&this.moveTo(0,0);for(var a=o[o.length-2],h=o[o.length-1],l=0,c=1;c<=20;++c)l=c/20,n=a+(t-a)*l,r=h+(e-h)*l,o.push(n+(t+(i-t)*l-n)*l,r+(e+(s-e)*l-r)*l);return this.dirty=!0,this._boundsDirty=!0,this},PIXI.Graphics.prototype.bezierCurveTo=function(t,e,i,s,n,r){this.currentPath?0===this.currentPath.shape.points.length&&(this.currentPath.shape.points=[0,0]):this.moveTo(0,0);for(var o,a,h,l,c,u=this.currentPath.shape.points,d=u[u.length-2],p=u[u.length-1],f=0,g=1;g<=20;++g)f=g/20,o=1-f,a=o*o,h=a*o,l=f*f,c=l*f,u.push(h*d+3*a*f*t+3*o*l*i+c*n,h*p+3*a*f*e+3*o*l*s+c*r);return this.dirty=!0,this._boundsDirty=!0,this},PIXI.Graphics.prototype.arcTo=function(t,e,i,s,n){this.currentPath?0===this.currentPath.shape.points.length&&this.currentPath.shape.points.push(t,e):this.moveTo(t,e);var r=this.currentPath.shape.points,o=r[r.length-2],a=r[r.length-1],h=a-e,l=o-t,c=s-e,u=i-t,d=Math.abs(h*u-l*c);if(d<1e-8||0===n)r[r.length-2]===t&&r[r.length-1]===e||r.push(t,e);else{var p=h*h+l*l,f=c*c+u*u,g=h*c+l*u,m=n*Math.sqrt(p)/d,y=n*Math.sqrt(f)/d,v=m*g/p,b=y*g/f,x=m*u+y*l,w=m*c+y*h,_=l*(y+v),P=h*(y+v),T=u*(m+b),C=c*(m+b),S=Math.atan2(P-w,_-x),A=Math.atan2(C-w,T-x);this.arc(x+t,w+e,n,S,A,l*c>u*h)}return this.dirty=!0,this._boundsDirty=!0,this},PIXI.Graphics.prototype.arc=function(t,e,i,s,n,r,o){if(s===n)return this;void 0===r&&(r=!1),void 0===o&&(o=40),!r&&n<=s?n+=2*Math.PI:r&&s<=n&&(s+=2*Math.PI);var a=r?-1*(s-n):n-s,h=Math.ceil(Math.abs(a)/(2*Math.PI))*o;if(0===a)return this;var l=t+Math.cos(s)*i,c=e+Math.sin(s)*i;r&&this.filling?this.moveTo(t,e):this.moveTo(l,c);for(var u=this.currentPath.shape.points,d=a/(2*h),p=2*d,f=Math.cos(d),g=Math.sin(d),m=h-1,y=m%1/m,v=0;v<=m;v++){var b=v+y*v,x=d+s+p*b,w=Math.cos(x),_=-Math.sin(x);u.push((f*w+g*_)*i+t,(f*-_+g*w)*i+e)}return this.dirty=!0,this._boundsDirty=!0,this},PIXI.Graphics.prototype.beginFill=function(t,e){return this.filling=!0,this.fillColor=t||0,this.fillAlpha=void 0===e?1:e,this.currentPath&&this.currentPath.shape.points.length<=2&&(this.currentPath.fill=this.filling,this.currentPath.fillColor=this.fillColor,this.currentPath.fillAlpha=this.fillAlpha),this},PIXI.Graphics.prototype.endFill=function(){return this.filling=!1,this.fillColor=null,this.fillAlpha=1,this},PIXI.Graphics.prototype.drawRect=function(t,e,i,s){return this.drawShape(new PIXI.Rectangle(t,e,i,s)),this},PIXI.Graphics.prototype.drawRoundedRect=function(t,e,i,s,n){return this.drawShape(new PIXI.RoundedRectangle(t,e,i,s,n)),this},PIXI.Graphics.prototype.drawCircle=function(t,e,i){return this.drawShape(new PIXI.Circle(t,e,i)),this},PIXI.Graphics.prototype.drawEllipse=function(t,e,i,s){return this.drawShape(new PIXI.Ellipse(t,e,i,s)),this},PIXI.Graphics.prototype.drawPolygon=function(t){(t instanceof n.Polygon||t instanceof PIXI.Polygon)&&(t=t.points);var e=t;if(!Array.isArray(e)){e=new Array(arguments.length);for(var i=0;i<e.length;++i)e[i]=arguments[i]}return this.drawShape(new n.Polygon(e)),this},PIXI.Graphics.prototype.clear=function(){return this.lineWidth=0,this.filling=!1,this.dirty=!0,this._boundsDirty=!0,this.clearDirty=!0,this.graphicsData=[],this.updateLocalBounds(),this},PIXI.Graphics.prototype.generateTexture=function(t,e,i){void 0===t&&(t=1),void 0===e&&(e=PIXI.scaleModes.DEFAULT),void 0===i&&(i=0);var s=this.getBounds();s.width+=i,s.height+=i;var n=new PIXI.CanvasBuffer(s.width*t,s.height*t),r=PIXI.Texture.fromCanvas(n.canvas,e);return r.baseTexture.resolution=t,n.context.scale(t,t),n.context.translate(-s.x,-s.y),PIXI.CanvasGraphics.renderGraphics(this,n.context),r},PIXI.Graphics.prototype._renderWebGL=function(t){if(!1!==this.visible&&0!==this.alpha&&!0!==this.isMask){if(this._cacheAsBitmap)return(this.dirty||this.cachedSpriteDirty)&&(this._generateCachedSprite(),this.updateCachedSpriteTexture(),this.cachedSpriteDirty=!1,this.dirty=!1),this._cachedSprite.worldAlpha=this.worldAlpha,void PIXI.Sprite.prototype._renderWebGL.call(this._cachedSprite,t);if(t.spriteBatch.stop(),t.blendModeManager.setBlendMode(this.blendMode),this._mask&&t.maskManager.pushMask(this._mask,t),this._filters&&t.filterManager.pushFilter(this._filterBlock),this.blendMode!==t.spriteBatch.currentBlendMode){t.spriteBatch.currentBlendMode=this.blendMode;var e=PIXI.blendModesWebGL[t.spriteBatch.currentBlendMode];t.spriteBatch.gl.blendFunc(e[0],e[1])}if(this.webGLDirty&&(this.dirty=!0,this.webGLDirty=!1),PIXI.WebGLGraphics.renderGraphics(this,t),this.children.length){t.spriteBatch.start();for(var i=0;i<this.children.length;i++)this.children[i]._renderWebGL(t);t.spriteBatch.stop()}this._filters&&t.filterManager.popFilter(),this._mask&&t.maskManager.popMask(this.mask,t),t.drawCount++,t.spriteBatch.start()}},PIXI.Graphics.prototype._renderCanvas=function(t){if(!1!==this.visible&&0!==this.alpha&&!0!==this.isMask){if(this._prevTint!==this.tint&&(this.dirty=!0,this._prevTint=this.tint),this._cacheAsBitmap)return(this.dirty||this.cachedSpriteDirty)&&(this._generateCachedSprite(),this.updateCachedSpriteTexture(),this.cachedSpriteDirty=!1,this.dirty=!1),this._cachedSprite.alpha=this.alpha,void PIXI.Sprite.prototype._renderCanvas.call(this._cachedSprite,t);var e=t.context,i=this.worldTransform;this.blendMode!==t.currentBlendMode&&(t.currentBlendMode=this.blendMode,e.globalCompositeOperation=PIXI.blendModesCanvas[t.currentBlendMode]),this._mask&&t.maskManager.pushMask(this._mask,t);var s=t.resolution,n=i.tx*t.resolution+t.shakeX,r=i.ty*t.resolution+t.shakeY;e.setTransform(i.a*s,i.b*s,i.c*s,i.d*s,n,r),PIXI.CanvasGraphics.renderGraphics(this,e);for(var o=0;o<this.children.length;o++)this.children[o]._renderCanvas(t);this._mask&&t.maskManager.popMask(t)}},PIXI.Graphics.prototype.getBounds=function(t){if(!this._currentBounds){if(!this.renderable)return PIXI.EmptyRectangle;this.dirty&&(this.updateLocalBounds(),this.webGLDirty=!0,this.cachedSpriteDirty=!0,this.dirty=!1);var e=this._localBounds,i=e.x,s=e.width+e.x,n=e.y,r=e.height+e.y,o=t||this.worldTransform,a=o.a,h=o.b,l=o.c,c=o.d,u=o.tx,d=o.ty,p=a*s+l*r+u,f=c*r+h*s+d,g=a*i+l*r+u,m=c*r+h*i+d,y=a*i+l*n+u,v=c*n+h*i+d,b=a*s+l*n+u,x=c*n+h*s+d,w=p,_=f,P=p,T=f;P=g<P?g:P,P=y<P?y:P,P=b<P?b:P,T=m<T?m:T,T=v<T?v:T,T=x<T?x:T,w=g>w?g:w,w=y>w?y:w,w=b>w?b:w,_=m>_?m:_,_=v>_?v:_,_=x>_?x:_,this._bounds.x=P,this._bounds.width=w-P,this._bounds.y=T,this._bounds.height=_-T,this._currentBounds=this._bounds}return this._currentBounds},PIXI.Graphics.prototype.getLocalBounds=function(){var t=this.worldTransform;this.worldTransform=PIXI.identityMatrix;for(var e=0;e<this.children.length;e++)this.children[e].updateTransform();var i=this.getBounds();for(this.worldTransform=t,e=0;e<this.children.length;e++)this.children[e].updateTransform();return i},PIXI.Graphics.prototype.containsPoint=function(t){this.worldTransform.applyInverse(t,tempPoint);for(var e=this.graphicsData,i=0;i<e.length;i++){var s=e[i];if(s.fill&&(s.shape&&s.shape.contains(tempPoint.x,tempPoint.y)))return!0}return!1},PIXI.Graphics.prototype.updateLocalBounds=function(){var t=1/0,e=-1/0,i=1/0,s=-1/0;if(this.graphicsData.length)for(var r,o,a,h,l,c,u=0;u<this.graphicsData.length;u++){var d=this.graphicsData[u],p=d.type,f=d.lineWidth;if(r=d.shape,p===PIXI.Graphics.RECT||p===PIXI.Graphics.RREC)a=r.x-f/2,h=r.y-f/2,l=r.width+f,c=r.height+f,t=a<t?a:t,e=a+l>e?a+l:e,i=h<i?h:i,s=h+c>s?h+c:s;else if(p===PIXI.Graphics.CIRC)a=r.x,h=r.y,l=r.radius+f/2,c=r.radius+f/2,t=a-l<t?a-l:t,e=a+l>e?a+l:e,i=h-c<i?h-c:i,s=h+c>s?h+c:s;else if(p===PIXI.Graphics.ELIP)a=r.x,h=r.y,l=r.width+f/2,c=r.height+f/2,t=a-l<t?a-l:t,e=a+l>e?a+l:e,i=h-c<i?h-c:i,s=h+c>s?h+c:s;else{o=r.points;for(var g=0;g<o.length;g++)o[g]instanceof n.Point?(a=o[g].x,h=o[g].y):(a=o[g],h=o[g+1],g<o.length-1&&g++),t=a-f<t?a-f:t,e=a+f>e?a+f:e,i=h-f<i?h-f:i,s=h+f>s?h+f:s}}else t=0,e=0,i=0,s=0;var m=this.boundsPadding;this._localBounds.x=t-m,this._localBounds.width=e-t+2*m,this._localBounds.y=i-m,this._localBounds.height=s-i+2*m},PIXI.Graphics.prototype._generateCachedSprite=function(){var t=this.getLocalBounds();if(this._cachedSprite)this._cachedSprite.buffer.resize(t.width,t.height);else{var e=new PIXI.CanvasBuffer(t.width,t.height),i=PIXI.Texture.fromCanvas(e.canvas);this._cachedSprite=new PIXI.Sprite(i),this._cachedSprite.buffer=e,this._cachedSprite.worldTransform=this.worldTransform}this._cachedSprite.anchor.x=-t.x/t.width,this._cachedSprite.anchor.y=-t.y/t.height,this._cachedSprite.buffer.context.translate(-t.x,-t.y),this.worldAlpha=1,PIXI.CanvasGraphics.renderGraphics(this,this._cachedSprite.buffer.context),this._cachedSprite.alpha=this.alpha},PIXI.Graphics.prototype.updateCachedSpriteTexture=function(){var t=this._cachedSprite,e=t.texture,i=t.buffer.canvas;e.baseTexture.width=i.width,e.baseTexture.height=i.height,e.crop.width=e.frame.width=i.width,e.crop.height=e.frame.height=i.height,t._width=i.width,t._height=i.height,e.baseTexture.dirty()},PIXI.Graphics.prototype.destroyCachedSprite=function(){this._cachedSprite.texture.destroy(!0),this._cachedSprite=null},PIXI.Graphics.prototype.drawShape=function(t){this.currentPath&&this.currentPath.shape.points.length<=2&&this.graphicsData.pop(),this.currentPath=null,t instanceof n.Polygon&&(t=t.clone(),t.flatten());var e=new PIXI.GraphicsData(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.filling,t);return this.graphicsData.push(e),e.type===PIXI.Graphics.POLY&&(e.shape.closed=this.filling,this.currentPath=e),this.dirty=!0,this._boundsDirty=!0,e},Object.defineProperty(PIXI.Graphics.prototype,"cacheAsBitmap",{get:function(){return this._cacheAsBitmap},set:function(t){this._cacheAsBitmap=t,this._cacheAsBitmap?this._generateCachedSprite():this.destroyCachedSprite(),this.dirty=!0,this.webGLDirty=!0}}),PIXI.GraphicsData=function(t,e,i,s,n,r,o){this.lineWidth=t,this.lineColor=e,this.lineAlpha=i,this._lineTint=e,this.fillColor=s,this.fillAlpha=n,this._fillTint=s,this.fill=r,this.shape=o,this.type=o.type},PIXI.GraphicsData.prototype.constructor=PIXI.GraphicsData,PIXI.GraphicsData.prototype.clone=function(){return new GraphicsData(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.fill,this.shape)},PIXI.EarCut={},PIXI.EarCut.Triangulate=function(t,e,i){i=i||2;var s=e&&e.length,n=s?e[0]*i:t.length,r=PIXI.EarCut.linkedList(t,0,n,i,!0),o=[];if(!r)return o;var a,h,l,c,u,d,p;if(s&&(r=PIXI.EarCut.eliminateHoles(t,e,r,i)),t.length>80*i){a=l=t[0],h=c=t[1];for(var f=i;f<n;f+=i)u=t[f],d=t[f+1],u<a&&(a=u),d<h&&(h=d),u>l&&(l=u),d>c&&(c=d);p=Math.max(l-a,c-h)}return PIXI.EarCut.earcutLinked(r,o,i,a,h,p),o},PIXI.EarCut.linkedList=function(t,e,i,s,n){var r,o,a,h=0;for(r=e,o=i-s;r<i;r+=s)h+=(t[o]-t[r])*(t[r+1]+t[o+1]),o=r;if(n===h>0)for(r=e;r<i;r+=s)a=PIXI.EarCut.insertNode(r,t[r],t[r+1],a);else for(r=i-s;r>=e;r-=s)a=PIXI.EarCut.insertNode(r,t[r],t[r+1],a);return a},PIXI.EarCut.filterPoints=function(t,e){if(!t)return t;e||(e=t);var i,s=t;do{if(i=!1,s.steiner||!PIXI.EarCut.equals(s,s.next)&&0!==PIXI.EarCut.area(s.prev,s,s.next))s=s.next;else{if(PIXI.EarCut.removeNode(s),(s=e=s.prev)===s.next)return null;i=!0}}while(i||s!==e);return e},PIXI.EarCut.earcutLinked=function(t,e,i,s,n,r,o){if(t){!o&&r&&PIXI.EarCut.indexCurve(t,s,n,r);for(var a,h,l=t;t.prev!==t.next;)if(a=t.prev,h=t.next,r?PIXI.EarCut.isEarHashed(t,s,n,r):PIXI.EarCut.isEar(t))e.push(a.i/i),e.push(t.i/i),e.push(h.i/i),PIXI.EarCut.removeNode(t),t=h.next,l=h.next;else if((t=h)===l){o?1===o?(t=PIXI.EarCut.cureLocalIntersections(t,e,i),PIXI.EarCut.earcutLinked(t,e,i,s,n,r,2)):2===o&&PIXI.EarCut.splitEarcut(t,e,i,s,n,r):PIXI.EarCut.earcutLinked(PIXI.EarCut.filterPoints(t),e,i,s,n,r,1);break}}},PIXI.EarCut.isEar=function(t){var e=t.prev,i=t,s=t.next;if(PIXI.EarCut.area(e,i,s)>=0)return!1;for(var n=t.next.next;n!==t.prev;){if(PIXI.EarCut.pointInTriangle(e.x,e.y,i.x,i.y,s.x,s.y,n.x,n.y)&&PIXI.EarCut.area(n.prev,n,n.next)>=0)return!1;n=n.next}return!0},PIXI.EarCut.isEarHashed=function(t,e,i,s){var n=t.prev,r=t,o=t.next;if(PIXI.EarCut.area(n,r,o)>=0)return!1;for(var a=n.x<r.x?n.x<o.x?n.x:o.x:r.x<o.x?r.x:o.x,h=n.y<r.y?n.y<o.y?n.y:o.y:r.y<o.y?r.y:o.y,l=n.x>r.x?n.x>o.x?n.x:o.x:r.x>o.x?r.x:o.x,c=n.y>r.y?n.y>o.y?n.y:o.y:r.y>o.y?r.y:o.y,u=PIXI.EarCut.zOrder(a,h,e,i,s),d=PIXI.EarCut.zOrder(l,c,e,i,s),p=t.nextZ;p&&p.z<=d;){if(p!==t.prev&&p!==t.next&&PIXI.EarCut.pointInTriangle(n.x,n.y,r.x,r.y,o.x,o.y,p.x,p.y)&&PIXI.EarCut.area(p.prev,p,p.next)>=0)return!1;p=p.nextZ}for(p=t.prevZ;p&&p.z>=u;){if(p!==t.prev&&p!==t.next&&PIXI.EarCut.pointInTriangle(n.x,n.y,r.x,r.y,o.x,o.y,p.x,p.y)&&PIXI.EarCut.area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}return!0},PIXI.EarCut.cureLocalIntersections=function(t,e,i){var s=t;do{var n=s.prev,r=s.next.next;PIXI.EarCut.intersects(n,s,s.next,r)&&PIXI.EarCut.locallyInside(n,r)&&PIXI.EarCut.locallyInside(r,n)&&(e.push(n.i/i),e.push(s.i/i),e.push(r.i/i),PIXI.EarCut.removeNode(s),PIXI.EarCut.removeNode(s.next),s=t=r),s=s.next}while(s!==t);return s},PIXI.EarCut.splitEarcut=function(t,e,i,s,n,r){var o=t;do{for(var a=o.next.next;a!==o.prev;){if(o.i!==a.i&&PIXI.EarCut.isValidDiagonal(o,a)){var h=PIXI.EarCut.splitPolygon(o,a);return o=PIXI.EarCut.filterPoints(o,o.next),h=PIXI.EarCut.filterPoints(h,h.next),PIXI.EarCut.earcutLinked(o,e,i,s,n,r),void PIXI.EarCut.earcutLinked(h,e,i,s,n,r)}a=a.next}o=o.next}while(o!==t)},PIXI.EarCut.eliminateHoles=function(t,e,i,s){var n,r,o,a,h,l=[];for(n=0,r=e.length;n<r;n++)o=e[n]*s,a=n<r-1?e[n+1]*s:t.length,h=PIXI.EarCut.linkedList(t,o,a,s,!1),h===h.next&&(h.steiner=!0),l.push(PIXI.EarCut.getLeftmost(h));for(l.sort(compareX),n=0;n<l.length;n++)PIXI.EarCut.eliminateHole(l[n],i),i=PIXI.EarCut.filterPoints(i,i.next);return i},PIXI.EarCut.compareX=function(t,e){return t.x-e.x},PIXI.EarCut.eliminateHole=function(t,e){if(e=PIXI.EarCut.findHoleBridge(t,e)){var i=PIXI.EarCut.splitPolygon(e,t);PIXI.EarCut.filterPoints(i,i.next)}},PIXI.EarCut.findHoleBridge=function(t,e){var i,s=e,n=t.x,r=t.y,o=-1/0;do{if(r<=s.y&&r>=s.next.y){var a=s.x+(r-s.y)*(s.next.x-s.x)/(s.next.y-s.y);a<=n&&a>o&&(o=a,i=s.x<s.next.x?s:s.next)}s=s.next}while(s!==e);if(!i)return null;if(t.x===i.x)return i.prev;var h,l=i,c=1/0;for(s=i.next;s!==l;)n>=s.x&&s.x>=i.x&&PIXI.EarCut.pointInTriangle(r<i.y?n:o,r,i.x,i.y,r<i.y?o:n,r,s.x,s.y)&&((h=Math.abs(r-s.y)/(n-s.x))<c||h===c&&s.x>i.x)&&PIXI.EarCut.locallyInside(s,t)&&(i=s,c=h),s=s.next;return i},PIXI.EarCut.indexCurve=function(t,e,i,s){var n=t;do{null===n.z&&(n.z=PIXI.EarCut.zOrder(n.x,n.y,e,i,s)),n.prevZ=n.prev,n.nextZ=n.next,n=n.next}while(n!==t);n.prevZ.nextZ=null,n.prevZ=null,PIXI.EarCut.sortLinked(n)},PIXI.EarCut.sortLinked=function(t){var e,i,s,n,r,o,a,h,l=1;do{for(i=t,t=null,r=null,o=0;i;){for(o++,s=i,a=0,e=0;e<l&&(a++,s=s.nextZ);e++);for(h=l;a>0||h>0&&s;)0===a?(n=s,s=s.nextZ,h--):0!==h&&s?i.z<=s.z?(n=i,i=i.nextZ,a--):(n=s,s=s.nextZ,h--):(n=i,i=i.nextZ,a--),r?r.nextZ=n:t=n,n.prevZ=r,r=n;i=s}r.nextZ=null,l*=2}while(o>1);return t},PIXI.EarCut.zOrder=function(t,e,i,s,n){return t=32767*(t-i)/n,e=32767*(e-s)/n,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1},PIXI.EarCut.getLeftmost=function(t){var e=t,i=t;do{e.x<i.x&&(i=e),e=e.next}while(e!==t);return i},PIXI.EarCut.pointInTriangle=function(t,e,i,s,n,r,o,a){return(n-o)*(e-a)-(t-o)*(r-a)>=0&&(t-o)*(s-a)-(i-o)*(e-a)>=0&&(i-o)*(r-a)-(n-o)*(s-a)>=0},PIXI.EarCut.isValidDiagonal=function(t,e){return PIXI.EarCut.equals(t,e)||t.next.i!==e.i&&t.prev.i!==e.i&&!PIXI.EarCut.intersectsPolygon(t,e)&&PIXI.EarCut.locallyInside(t,e)&&PIXI.EarCut.locallyInside(e,t)&&PIXI.EarCut.middleInside(t,e)},PIXI.EarCut.area=function(t,e,i){return(e.y-t.y)*(i.x-e.x)-(e.x-t.x)*(i.y-e.y)},PIXI.EarCut.equals=function(t,e){return t.x===e.x&&t.y===e.y},PIXI.EarCut.intersects=function(t,e,i,s){return PIXI.EarCut.area(t,e,i)>0!=PIXI.EarCut.area(t,e,s)>0&&PIXI.EarCut.area(i,s,t)>0!=PIXI.EarCut.area(i,s,e)>0},PIXI.EarCut.intersectsPolygon=function(t,e){var i=t;do{if(i.i!==t.i&&i.next.i!==t.i&&i.i!==e.i&&i.next.i!==e.i&&PIXI.EarCut.intersects(i,i.next,t,e))return!0;i=i.next}while(i!==t);return!1},PIXI.EarCut.locallyInside=function(t,e){return PIXI.EarCut.area(t.prev,t,t.next)<0?PIXI.EarCut.area(t,e,t.next)>=0&&PIXI.EarCut.area(t,t.prev,e)>=0:PIXI.EarCut.area(t,e,t.prev)<0||PIXI.EarCut.area(t,t.next,e)<0},PIXI.EarCut.middleInside=function(t,e){var i=t,s=!1,n=(t.x+e.x)/2,r=(t.y+e.y)/2;do{i.y>r!=i.next.y>r&&n<(i.next.x-i.x)*(r-i.y)/(i.next.y-i.y)+i.x&&(s=!s),i=i.next}while(i!==t);return s},PIXI.EarCut.splitPolygon=function(t,e){var i=new PIXI.EarCut.Node(t.i,t.x,t.y),s=new PIXI.EarCut.Node(e.i,e.x,e.y),n=t.next,r=e.prev;return t.next=e,e.prev=t,i.next=n,n.prev=i,s.next=i,i.prev=s,r.next=s,s.prev=r,s},PIXI.EarCut.insertNode=function(t,e,i,s){var n=new PIXI.EarCut.Node(t,e,i);return s?(n.next=s.next,n.prev=s,s.next.prev=n,s.next=n):(n.prev=n,n.next=n),n},PIXI.EarCut.removeNode=function(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)},PIXI.EarCut.Node=function(t,e,i){this.i=t,this.x=e,this.y=i,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1},PIXI.WebGLGraphics=function(){},PIXI.WebGLGraphics.stencilBufferLimit=6,PIXI.WebGLGraphics.renderGraphics=function(t,e){var i,s=e.gl,n=e.projection,r=e.offset,o=e.shaderManager.primitiveShader;t.dirty&&PIXI.WebGLGraphics.updateGraphics(t,s);for(var a=t._webGL[s.id],h=0;h<a.data.length;h++)1===a.data[h].mode?(i=a.data[h],e.stencilManager.pushStencil(t,i,e),s.drawElements(s.TRIANGLE_FAN,4,s.UNSIGNED_SHORT,2*(i.indices.length-4)),e.stencilManager.popStencil(t,i,e)):(i=a.data[h],e.shaderManager.setShader(o),o=e.shaderManager.primitiveShader,s.uniformMatrix3fv(o.translationMatrix,!1,t.worldTransform.toArray(!0)),s.uniform1f(o.flipY,1),s.uniform2f(o.projectionVector,n.x,-n.y),s.uniform2f(o.offsetVector,-r.x,-r.y),s.uniform3fv(o.tintColor,PIXI.hex2rgb(t.tint)),s.uniform1f(o.alpha,t.worldAlpha),s.bindBuffer(s.ARRAY_BUFFER,i.buffer),s.vertexAttribPointer(o.aVertexPosition,2,s.FLOAT,!1,24,0),s.vertexAttribPointer(o.colorAttribute,4,s.FLOAT,!1,24,8),s.bindBuffer(s.ELEMENT_ARRAY_BUFFER,i.indexBuffer),s.drawElements(s.TRIANGLE_STRIP,i.indices.length,s.UNSIGNED_SHORT,0))},PIXI.WebGLGraphics.updateGraphics=function(t,e){var i=t._webGL[e.id];i||(i=t._webGL[e.id]={lastIndex:0,data:[],gl:e}),t.dirty=!1;var s;if(t.clearDirty){for(t.clearDirty=!1,s=0;s<i.data.length;s++){var n=i.data[s];n.reset(),PIXI.WebGLGraphics.graphicsDataPool.push(n)}i.data=[],i.lastIndex=0}var r;for(s=i.lastIndex;s<t.graphicsData.length;s++){var o=t.graphicsData[s];if(o.type===PIXI.Graphics.POLY){if(o.points=o.shape.points.slice(),o.shape.closed&&(o.points[0]===o.points[o.points.length-2]&&o.points[1]===o.points[o.points.length-1]||o.points.push(o.points[0],o.points[1])),o.fill&&o.points.length>=PIXI.WebGLGraphics.stencilBufferLimit)if(o.points.length<2*PIXI.WebGLGraphics.stencilBufferLimit){r=PIXI.WebGLGraphics.switchMode(i,0);var a=PIXI.WebGLGraphics.buildPoly(o,r);a||(r=PIXI.WebGLGraphics.switchMode(i,1),PIXI.WebGLGraphics.buildComplexPoly(o,r))}else r=PIXI.WebGLGraphics.switchMode(i,1),PIXI.WebGLGraphics.buildComplexPoly(o,r);o.lineWidth>0&&(r=PIXI.WebGLGraphics.switchMode(i,0),PIXI.WebGLGraphics.buildLine(o,r))}else r=PIXI.WebGLGraphics.switchMode(i,0),o.type===PIXI.Graphics.RECT?PIXI.WebGLGraphics.buildRectangle(o,r):o.type===PIXI.Graphics.CIRC||o.type===PIXI.Graphics.ELIP?PIXI.WebGLGraphics.buildCircle(o,r):o.type===PIXI.Graphics.RREC&&PIXI.WebGLGraphics.buildRoundedRectangle(o,r);i.lastIndex++}for(s=0;s<i.data.length;s++)r=i.data[s],r.dirty&&r.upload()},PIXI.WebGLGraphics.switchMode=function(t,e){var i;return t.data.length?(i=t.data[t.data.length-1],i.mode===e&&1!==e||(i=PIXI.WebGLGraphics.graphicsDataPool.pop()||new PIXI.WebGLGraphicsData(t.gl),i.mode=e,t.data.push(i))):(i=PIXI.WebGLGraphics.graphicsDataPool.pop()||new PIXI.WebGLGraphicsData(t.gl),i.mode=e,t.data.push(i)),i.dirty=!0,i},PIXI.WebGLGraphics.buildRectangle=function(t,e){var i=t.shape,s=i.x,n=i.y,r=i.width,o=i.height;if(t.fill){var a=PIXI.hex2rgb(t.fillColor),h=t.fillAlpha,l=a[0]*h,c=a[1]*h,u=a[2]*h,d=e.points,p=e.indices,f=d.length/6;d.push(s,n),d.push(l,c,u,h),d.push(s+r,n),d.push(l,c,u,h),d.push(s,n+o),d.push(l,c,u,h),d.push(s+r,n+o),d.push(l,c,u,h),p.push(f,f,f+1,f+2,f+3,f+3)}if(t.lineWidth){var g=t.points;t.points=[s,n,s+r,n,s+r,n+o,s,n+o,s,n],PIXI.WebGLGraphics.buildLine(t,e),t.points=g}},PIXI.WebGLGraphics.buildRoundedRectangle=function(t,e){var i=t.shape,s=i.x,n=i.y,r=i.width,o=i.height,a=i.radius,h=[];if(h.push(s,n+a),h=h.concat(PIXI.WebGLGraphics.quadraticBezierCurve(s,n+o-a,s,n+o,s+a,n+o)),h=h.concat(PIXI.WebGLGraphics.quadraticBezierCurve(s+r-a,n+o,s+r,n+o,s+r,n+o-a)),h=h.concat(PIXI.WebGLGraphics.quadraticBezierCurve(s+r,n+a,s+r,n,s+r-a,n)),h=h.concat(PIXI.WebGLGraphics.quadraticBezierCurve(s+a,n,s,n,s,n+a)),t.fill){var l=PIXI.hex2rgb(t.fillColor),c=t.fillAlpha,u=l[0]*c,d=l[1]*c,p=l[2]*c,f=e.points,g=e.indices,m=f.length/6,y=PIXI.EarCut.Triangulate(h,null,2),v=0;for(v=0;v<y.length;v+=3)g.push(y[v]+m),g.push(y[v]+m),g.push(y[v+1]+m),g.push(y[v+2]+m),g.push(y[v+2]+m);for(v=0;v<h.length;v++)f.push(h[v],h[++v],u,d,p,c)}if(t.lineWidth){var b=t.points;t.points=h,PIXI.WebGLGraphics.buildLine(t,e),t.points=b}},PIXI.WebGLGraphics.quadraticBezierCurve=function(t,e,i,s,n,r){function o(t,e,i){return t+(e-t)*i}for(var a,h,l,c,u,d,p=[],f=0,g=0;g<=20;g++)f=g/20,a=o(t,i,f),h=o(e,s,f),l=o(i,n,f),c=o(s,r,f),u=o(a,l,f),d=o(h,c,f),p.push(u,d);return p},PIXI.WebGLGraphics.buildCircle=function(t,e){var i,s,n=t.shape,r=n.x,o=n.y;t.type===PIXI.Graphics.CIRC?(i=n.radius,s=n.radius):(i=n.width,s=n.height);var a=2*Math.PI/40,h=0;if(t.fill){var l=PIXI.hex2rgb(t.fillColor),c=t.fillAlpha,u=l[0]*c,d=l[1]*c,p=l[2]*c,f=e.points,g=e.indices,m=f.length/6;for(g.push(m),h=0;h<41;h++)f.push(r,o,u,d,p,c),f.push(r+Math.sin(a*h)*i,o+Math.cos(a*h)*s,u,d,p,c),g.push(m++,m++);g.push(m-1)}if(t.lineWidth){var y=t.points;for(t.points=[],h=0;h<41;h++)t.points.push(r+Math.sin(a*h)*i,o+Math.cos(a*h)*s);PIXI.WebGLGraphics.buildLine(t,e),t.points=y}},PIXI.WebGLGraphics.buildLine=function(t,e){var i=0,s=t.points;if(0!==s.length){if(t.lineWidth%2)for(i=0;i<s.length;i++)s[i]+=.5;var n=new PIXI.Point(s[0],s[1]),r=new PIXI.Point(s[s.length-2],s[s.length-1]);if(n.x===r.x&&n.y===r.y){s=s.slice(),s.pop(),s.pop(),r=new PIXI.Point(s[s.length-2],s[s.length-1]);var o=r.x+.5*(n.x-r.x),a=r.y+.5*(n.y-r.y);s.unshift(o,a),s.push(o,a)}var h,l,c,u,d,p,f,g,m,y,v,b,x,w,_,P,T,C,S,A,E,I,M,R=e.points,B=e.indices,L=s.length/2,k=s.length,O=R.length/6,F=t.lineWidth/2,D=PIXI.hex2rgb(t.lineColor),U=t.lineAlpha,G=D[0]*U,N=D[1]*U,X=D[2]*U;for(c=s[0],u=s[1],d=s[2],p=s[3],m=-(u-p),y=c-d,M=Math.sqrt(m*m+y*y),m/=M,y/=M,m*=F,y*=F,R.push(c-m,u-y,G,N,X,U),R.push(c+m,u+y,G,N,X,U),i=1;i<L-1;i++)c=s[2*(i-1)],u=s[2*(i-1)+1],d=s[2*i],p=s[2*i+1],f=s[2*(i+1)],g=s[2*(i+1)+1],m=-(u-p),y=c-d,M=Math.sqrt(m*m+y*y),m/=M,y/=M,m*=F,y*=F,v=-(p-g),b=d-f,M=Math.sqrt(v*v+b*b),v/=M,b/=M,v*=F,b*=F,_=-y+u-(-y+p),P=-m+d-(-m+c),T=(-m+c)*(-y+p)-(-m+d)*(-y+u),C=-b+g-(-b+p),S=-v+d-(-v+f),A=(-v+f)*(-b+p)-(-v+d)*(-b+g),E=_*S-C*P,Math.abs(E)<.1?(E+=10.1,R.push(d-m,p-y,G,N,X,U),R.push(d+m,p+y,G,N,X,U)):(h=(P*A-S*T)/E,l=(C*T-_*A)/E,I=(h-d)*(h-d)+(l-p)+(l-p),I>19600?(x=m-v,w=y-b,M=Math.sqrt(x*x+w*w),x/=M,w/=M,x*=F,w*=F,R.push(d-x,p-w),R.push(G,N,X,U),R.push(d+x,p+w),R.push(G,N,X,U),R.push(d-x,p-w),R.push(G,N,X,U),k++):(R.push(h,l),R.push(G,N,X,U),R.push(d-(h-d),p-(l-p)),R.push(G,N,X,U)));for(c=s[2*(L-2)],u=s[2*(L-2)+1],d=s[2*(L-1)],p=s[2*(L-1)+1],m=-(u-p),y=c-d,M=Math.sqrt(m*m+y*y),m/=M,y/=M,m*=F,y*=F,R.push(d-m,p-y),R.push(G,N,X,U),R.push(d+m,p+y),R.push(G,N,X,U),B.push(O),i=0;i<k;i++)B.push(O++);B.push(O-1)}},PIXI.WebGLGraphics.buildComplexPoly=function(t,e){var i=t.points.slice();if(!(i.length<6)){var s=e.indices;e.points=i,e.alpha=t.fillAlpha,e.color=PIXI.hex2rgb(t.fillColor);for(var n,r,o=1/0,a=-1/0,h=1/0,l=-1/0,c=0;c<i.length;c+=2)n=i[c],r=i[c+1],o=n<o?n:o,a=n>a?n:a,h=r<h?r:h,l=r>l?r:l;i.push(o,h,a,h,a,l,o,l);var u=i.length/2;for(c=0;c<u;c++)s.push(c)}},PIXI.WebGLGraphics.buildPoly=function(t,e){var i=t.points;if(!(i.length<6)){var s=e.points,n=e.indices,r=i.length/2,o=PIXI.hex2rgb(t.fillColor),a=t.fillAlpha,h=o[0]*a,l=o[1]*a,c=o[2]*a,u=PIXI.EarCut.Triangulate(i,null,2);if(!u)return!1;var d=s.length/6,p=0;for(p=0;p<u.length;p+=3)n.push(u[p]+d),n.push(u[p]+d),n.push(u[p+1]+d),n.push(u[p+2]+d),n.push(u[p+2]+d);for(p=0;p<r;p++)s.push(i[2*p],i[2*p+1],h,l,c,a);return!0}},PIXI.WebGLGraphics.graphicsDataPool=[],PIXI.WebGLGraphicsData=function(t){this.gl=t,this.color=[0,0,0],this.points=[],this.indices=[],this.buffer=t.createBuffer(),this.indexBuffer=t.createBuffer(),this.mode=1,this.alpha=1,this.dirty=!0},PIXI.WebGLGraphicsData.prototype.reset=function(){this.points=[],this.indices=[]},PIXI.WebGLGraphicsData.prototype.upload=function(){var t=this.gl;this.glPoints=new PIXI.Float32Array(this.points),t.bindBuffer(t.ARRAY_BUFFER,this.buffer),t.bufferData(t.ARRAY_BUFFER,this.glPoints,t.STATIC_DRAW),this.glIndicies=new PIXI.Uint16Array(this.indices),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,this.glIndicies,t.STATIC_DRAW),this.dirty=!1},PIXI.CanvasGraphics=function(){},PIXI.CanvasGraphics.renderGraphics=function(t,e){var i=t.worldAlpha;t.dirty&&(this.updateGraphicsTint(t),t.dirty=!1);for(var s=0;s<t.graphicsData.length;s++){var n=t.graphicsData[s],r=n.shape,o=n._fillTint,a=n._lineTint;if(e.lineWidth=n.lineWidth,n.type===PIXI.Graphics.POLY){e.beginPath();var h=r.points;e.moveTo(h[0],h[1]);for(var l=1;l<h.length/2;l++)e.lineTo(h[2*l],h[2*l+1]);r.closed&&e.lineTo(h[0],h[1]),h[0]===h[h.length-2]&&h[1]===h[h.length-1]&&e.closePath(),n.fill&&(e.globalAlpha=n.fillAlpha*i,e.fillStyle="#"+("00000"+(0|o).toString(16)).substr(-6),e.fill()),n.lineWidth&&(e.globalAlpha=n.lineAlpha*i,e.strokeStyle="#"+("00000"+(0|a).toString(16)).substr(-6),e.stroke())}else if(n.type===PIXI.Graphics.RECT)(n.fillColor||0===n.fillColor)&&(e.globalAlpha=n.fillAlpha*i,e.fillStyle="#"+("00000"+(0|o).toString(16)).substr(-6),e.fillRect(r.x,r.y,r.width,r.height)),n.lineWidth&&(e.globalAlpha=n.lineAlpha*i,e.strokeStyle="#"+("00000"+(0|a).toString(16)).substr(-6),e.strokeRect(r.x,r.y,r.width,r.height));else if(n.type===PIXI.Graphics.CIRC)e.beginPath(),e.arc(r.x,r.y,r.radius,0,2*Math.PI),e.closePath(),n.fill&&(e.globalAlpha=n.fillAlpha*i,e.fillStyle="#"+("00000"+(0|o).toString(16)).substr(-6),e.fill()),n.lineWidth&&(e.globalAlpha=n.lineAlpha*i,e.strokeStyle="#"+("00000"+(0|a).toString(16)).substr(-6),e.stroke());else if(n.type===PIXI.Graphics.ELIP){var c=2*r.width,u=2*r.height,d=r.x-c/2,p=r.y-u/2;e.beginPath();var f=c/2*.5522848,g=u/2*.5522848,m=d+c,y=p+u,v=d+c/2,b=p+u/2;e.moveTo(d,b),e.bezierCurveTo(d,b-g,v-f,p,v,p),e.bezierCurveTo(v+f,p,m,b-g,m,b),e.bezierCurveTo(m,b+g,v+f,y,v,y),e.bezierCurveTo(v-f,y,d,b+g,d,b),e.closePath(),n.fill&&(e.globalAlpha=n.fillAlpha*i,e.fillStyle="#"+("00000"+(0|o).toString(16)).substr(-6),e.fill()),n.lineWidth&&(e.globalAlpha=n.lineAlpha*i,e.strokeStyle="#"+("00000"+(0|a).toString(16)).substr(-6),e.stroke())}else if(n.type===PIXI.Graphics.RREC){var x=r.x,w=r.y,_=r.width,P=r.height,T=r.radius,C=Math.min(_,P)/2|0;T=T>C?C:T,e.beginPath(),e.moveTo(x,w+T),e.lineTo(x,w+P-T),e.quadraticCurveTo(x,w+P,x+T,w+P),e.lineTo(x+_-T,w+P),e.quadraticCurveTo(x+_,w+P,x+_,w+P-T),e.lineTo(x+_,w+T),e.quadraticCurveTo(x+_,w,x+_-T,w),e.lineTo(x+T,w),e.quadraticCurveTo(x,w,x,w+T),e.closePath(),(n.fillColor||0===n.fillColor)&&(e.globalAlpha=n.fillAlpha*i,e.fillStyle="#"+("00000"+(0|o).toString(16)).substr(-6),e.fill()),n.lineWidth&&(e.globalAlpha=n.lineAlpha*i,e.strokeStyle="#"+("00000"+(0|a).toString(16)).substr(-6),e.stroke())}}},PIXI.CanvasGraphics.renderGraphicsMask=function(t,e){var i=t.graphicsData.length;if(0!==i){e.beginPath();for(var s=0;s<i;s++){var n=t.graphicsData[s],r=n.shape;if(n.type===PIXI.Graphics.POLY){var o=r.points;e.moveTo(o[0],o[1]);for(var a=1;a<o.length/2;a++)e.lineTo(o[2*a],o[2*a+1]);o[0]===o[o.length-2]&&o[1]===o[o.length-1]&&e.closePath()}else if(n.type===PIXI.Graphics.RECT)e.rect(r.x,r.y,r.width,r.height),e.closePath();else if(n.type===PIXI.Graphics.CIRC)e.arc(r.x,r.y,r.radius,0,2*Math.PI),e.closePath();else if(n.type===PIXI.Graphics.ELIP){var h=2*r.width,l=2*r.height,c=r.x-h/2,u=r.y-l/2,d=h/2*.5522848,p=l/2*.5522848,f=c+h,g=u+l,m=c+h/2,y=u+l/2;e.moveTo(c,y),e.bezierCurveTo(c,y-p,m-d,u,m,u),e.bezierCurveTo(m+d,u,f,y-p,f,y),e.bezierCurveTo(f,y+p,m+d,g,m,g),e.bezierCurveTo(m-d,g,c,y+p,c,y),e.closePath()}else if(n.type===PIXI.Graphics.RREC){var v=r.x,b=r.y,x=r.width,w=r.height,_=r.radius,P=Math.min(x,w)/2|0;_=_>P?P:_,e.moveTo(v,b+_),e.lineTo(v,b+w-_),e.quadraticCurveTo(v,b+w,v+_,b+w),e.lineTo(v+x-_,b+w),e.quadraticCurveTo(v+x,b+w,v+x,b+w-_),e.lineTo(v+x,b+_),e.quadraticCurveTo(v+x,b,v+x-_,b),e.lineTo(v+_,b),e.quadraticCurveTo(v,b,v,b+_),e.closePath()}}}},PIXI.CanvasGraphics.updateGraphicsTint=function(t){if(16777215!==t.tint)for(var e=(t.tint>>16&255)/255,i=(t.tint>>8&255)/255,s=(255&t.tint)/255,n=0;n<t.graphicsData.length;n++){var r=t.graphicsData[n],o=0|r.fillColor,a=0|r.lineColor;r._fillTint=((o>>16&255)/255*e*255<<16)+((o>>8&255)/255*i*255<<8)+(255&o)/255*s*255,r._lineTint=((a>>16&255)/255*e*255<<16)+((a>>8&255)/255*i*255<<8)+(255&a)/255*s*255}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Graphics=function(t,e,i){void 0===e&&(e=0),void 0===i&&(i=0),this.type=n.GRAPHICS,this.physicsType=n.SPRITE,this.anchor=new n.Point,PIXI.Graphics.call(this),n.Component.Core.init.call(this,t,e,i,"",null)},n.Graphics.prototype=Object.create(PIXI.Graphics.prototype),n.Graphics.prototype.constructor=n.Graphics,n.Component.Core.install.call(n.Graphics.prototype,["Angle","AutoCull","Bounds","Destroy","FixedToCamera","InputEnabled","InWorld","LifeSpan","PhysicsBody","Reset"]),n.Graphics.prototype.preUpdatePhysics=n.Component.PhysicsBody.preUpdate,n.Graphics.prototype.preUpdateLifeSpan=n.Component.LifeSpan.preUpdate,n.Graphics.prototype.preUpdateInWorld=n.Component.InWorld.preUpdate,n.Graphics.prototype.preUpdateCore=n.Component.Core.preUpdate,n.Graphics.prototype.preUpdate=function(){return!!(this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld())&&this.preUpdateCore()},n.Graphics.prototype.postUpdate=function(){n.Component.PhysicsBody.postUpdate.call(this),n.Component.FixedToCamera.postUpdate.call(this),this._boundsDirty&&(this.updateLocalBounds(),this._boundsDirty=!1);for(var t=0;t<this.children.length;t++)this.children[t].postUpdate()},n.Graphics.prototype.destroy=function(t){this.clear(),n.Component.Destroy.prototype.destroy.call(this,t)},n.Graphics.prototype.drawTriangle=function(t,e){void 0===e&&(e=!1);var i=new n.Polygon(t);if(e){var s=new n.Point(this.game.camera.x-t[0].x,this.game.camera.y-t[0].y),r=new n.Point(t[1].x-t[0].x,t[1].y-t[0].y),o=new n.Point(t[1].x-t[2].x,t[1].y-t[2].y),a=o.cross(r);s.dot(a)>0&&this.drawPolygon(i)}else this.drawPolygon(i)},n.Graphics.prototype.drawTriangles=function(t,e,i){void 0===i&&(i=!1);var s,r=new n.Point,o=new n.Point,a=new n.Point,h=[];if(e)if(t[0]instanceof n.Point)for(s=0;s<e.length/3;s++)h.push(t[e[3*s]]),h.push(t[e[3*s+1]]),h.push(t[e[3*s+2]]),3===h.length&&(this.drawTriangle(h,i),h=[]);else for(s=0;s<e.length;s++)r.x=t[2*e[s]],r.y=t[2*e[s]+1],h.push(r.copyTo({})),3===h.length&&(this.drawTriangle(h,i),h=[]);else if(t[0]instanceof n.Point)for(s=0;s<t.length/3;s++)this.drawTriangle([t[3*s],t[3*s+1],t[3*s+2]],i);else for(s=0;s<t.length/6;s++)r.x=t[6*s+0],r.y=t[6*s+1],o.x=t[6*s+2],o.y=t[6*s+3],a.x=t[6*s+4],a.y=t[6*s+5],this.drawTriangle([r,o,a],i)},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.RenderTexture=function(t,e,i,s,r,o){void 0===s&&(s=""),void 0===r&&(r=n.scaleModes.DEFAULT),void 0===o&&(o=1),this.game=t,this.key=s,this.type=n.RENDERTEXTURE,this._tempMatrix=new PIXI.Matrix,PIXI.RenderTexture.call(this,e,i,this.game.renderer,r,o),this.render=n.RenderTexture.prototype.render},n.RenderTexture.prototype=Object.create(PIXI.RenderTexture.prototype),n.RenderTexture.prototype.constructor=n.RenderTexture,n.RenderTexture.prototype.renderXY=function(t,e,i,s){t.updateTransform(),this._tempMatrix.copyFrom(t.worldTransform),this._tempMatrix.tx=e,this._tempMatrix.ty=i,this.renderer.type===PIXI.WEBGL_RENDERER?this.renderWebGL(t,this._tempMatrix,s):this.renderCanvas(t,this._tempMatrix,s)},n.RenderTexture.prototype.renderRawXY=function(t,e,i,s){this._tempMatrix.identity().translate(e,i),this.renderer.type===PIXI.WEBGL_RENDERER?this.renderWebGL(t,this._tempMatrix,s):this.renderCanvas(t,this._tempMatrix,s)},n.RenderTexture.prototype.render=function(t,e,i){void 0===e||null===e?this._tempMatrix.copyFrom(t.worldTransform):this._tempMatrix.copyFrom(e),this.renderer.type===PIXI.WEBGL_RENDERER?this.renderWebGL(t,this._tempMatrix,i):this.renderCanvas(t,this._tempMatrix,i)},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Text=function(t,e,i,s,r){e=e||0,i=i||0,s=void 0===s||null===s?"":s.toString(),r=n.Utils.extend({},r),this.type=n.TEXT,this.physicsType=n.SPRITE,this.padding=new n.Point,this.textBounds=null,this.canvas=PIXI.CanvasPool.create(this),this.context=this.canvas.getContext("2d"),this.colors=[],this.strokeColors=[],this.fontStyles=[],this.fontWeights=[],this.autoRound=!1,this.useAdvancedWrap=!1,this._res=t.renderer.resolution,this._text=s,this._fontComponents=null,this._lineSpacing=0,this._charCount=0,this._width=0,this._height=0,n.Sprite.call(this,t,e,i,PIXI.Texture.fromCanvas(this.canvas)),this.setStyle(r),""!==s&&this.updateText()},n.Text.prototype=Object.create(n.Sprite.prototype),n.Text.prototype.constructor=n.Text,n.Text.prototype.preUpdate=function(){return!!(this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld())&&this.preUpdateCore()},n.Text.prototype.update=function(){},n.Text.prototype.destroy=function(t){this.texture.destroy(!0),n.Component.Destroy.prototype.destroy.call(this,t)},n.Text.prototype.setShadow=function(t,e,i,s,n,r){return void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i="rgba(0, 0, 0, 1)"),void 0===s&&(s=0),void 0===n&&(n=!0),void 0===r&&(r=!0),this.style.shadowOffsetX=t,this.style.shadowOffsetY=e,this.style.shadowColor=i,this.style.shadowBlur=s,this.style.shadowStroke=n,this.style.shadowFill=r,this.dirty=!0,this},n.Text.prototype.setStyle=function(t,e){void 0===e&&(e=!1),t=t||{},t.font=t.font||"bold 20pt Arial",t.backgroundColor=t.backgroundColor||null,t.fill=t.fill||"black",t.align=t.align||"left",t.boundsAlignH=t.boundsAlignH||"left",t.boundsAlignV=t.boundsAlignV||"top",t.stroke=t.stroke||"black",t.strokeThickness=t.strokeThickness||0,t.wordWrap=t.wordWrap||!1,t.wordWrapWidth=t.wordWrapWidth||100,t.maxLines=t.maxLines||0,t.shadowOffsetX=t.shadowOffsetX||0,t.shadowOffsetY=t.shadowOffsetY||0,t.shadowColor=t.shadowColor||"rgba(0,0,0,0)",t.shadowBlur=t.shadowBlur||0,t.tabs=t.tabs||0;var i=this.fontToComponents(t.font);return t.fontStyle&&(i.fontStyle=t.fontStyle),t.fontVariant&&(i.fontVariant=t.fontVariant),t.fontWeight&&(i.fontWeight=t.fontWeight),t.fontSize&&("number"==typeof t.fontSize&&(t.fontSize=t.fontSize+"px"),i.fontSize=t.fontSize),this._fontComponents=i,t.font=this.componentsToFont(this._fontComponents),this.style=t,this.dirty=!0,e&&this.updateText(),this},n.Text.prototype.updateText=function(){this.texture.baseTexture.resolution=this._res,this.context.font=this.style.font;var t=this.text;this.style.wordWrap&&(t=this.runWordWrap(this.text));var e=t.split(/(?:\r\n|\r|\n)/),i=this.style.tabs,s=[],n=0,r=this.determineFontProperties(this.style.font),o=e.length;this.style.maxLines>0&&this.style.maxLines<e.length&&(o=this.style.maxLines),this._charCount=0;for(var a=0;a<o;a++){if(0===i){var h=this.style.strokeThickness+this.padding.x;this.colors.length>0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?h+=this.measureLine(e[a]):h+=this.context.measureText(e[a]).width,this.style.wordWrap&&(h-=this.context.measureText(" ").width)}else{var l=e[a].split(/(?:\t)/),h=this.padding.x+this.style.strokeThickness;if(Array.isArray(i))for(var c=0,u=0;u<l.length;u++){var d=0;d=this.colors.length>0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?this.measureLine(l[u]):Math.ceil(this.context.measureText(l[u]).width),u>0&&(c+=i[u-1]),h=c+d}else for(var u=0;u<l.length;u++){this.colors.length>0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?h+=this.measureLine(l[u]):h+=Math.ceil(this.context.measureText(l[u]).width);var p=this.game.math.snapToCeil(h,i)-h;h+=p}}s[a]=Math.ceil(h),n=Math.max(n,s[a])}this.canvas.width=n*this._res;var f=r.fontSize+this.style.strokeThickness+this.padding.y,g=f*o,m=this._lineSpacing;m<0&&Math.abs(m)>f&&(m=-f),0!==m&&(g+=m>0?m*e.length:m*(e.length-1)),this.canvas.height=g*this._res,this.context.scale(this._res,this._res),navigator.isCocoonJS&&this.context.clearRect(0,0,this.canvas.width,this.canvas.height),this.style.backgroundColor&&(this.context.fillStyle=this.style.backgroundColor,this.context.fillRect(0,0,this.canvas.width,this.canvas.height)),this.context.fillStyle=this.style.fill,this.context.font=this.style.font,this.context.strokeStyle=this.style.stroke,this.context.textBaseline="alphabetic",this.context.lineWidth=this.style.strokeThickness,this.context.lineCap="round",this.context.lineJoin="round";var y,v;for(this._charCount=0,a=0;a<o;a++)y=this.style.strokeThickness/2,v=this.style.strokeThickness/2+a*f+r.ascent,a>0&&(v+=m*a),"right"===this.style.align?y+=n-s[a]:"center"===this.style.align&&(y+=(n-s[a])/2),this.autoRound&&(y=Math.round(y),v=Math.round(v)),this.colors.length>0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?this.updateLine(e[a],y,v):(this.style.stroke&&this.style.strokeThickness&&(this.updateShadow(this.style.shadowStroke),0===i?this.context.strokeText(e[a],y,v):this.renderTabLine(e[a],y,v,!1)),this.style.fill&&(this.updateShadow(this.style.shadowFill),0===i?this.context.fillText(e[a],y,v):this.renderTabLine(e[a],y,v,!0)));this.updateTexture(),this.dirty=!1},n.Text.prototype.renderTabLine=function(t,e,i,s){var n=t.split(/(?:\t)/),r=this.style.tabs,o=0;if(Array.isArray(r))for(var a=0,h=0;h<n.length;h++)h>0&&(a+=r[h-1]),o=e+a,s?this.context.fillText(n[h],o,i):this.context.strokeText(n[h],o,i);else for(var h=0;h<n.length;h++){var l=Math.ceil(this.context.measureText(n[h]).width);o=this.game.math.snapToCeil(e,r),s?this.context.fillText(n[h],o,i):this.context.strokeText(n[h],o,i),e=o+l}},n.Text.prototype.updateShadow=function(t){t?(this.context.shadowOffsetX=this.style.shadowOffsetX,this.context.shadowOffsetY=this.style.shadowOffsetY,this.context.shadowColor=this.style.shadowColor,this.context.shadowBlur=this.style.shadowBlur):(this.context.shadowOffsetX=0,this.context.shadowOffsetY=0,this.context.shadowColor=0,this.context.shadowBlur=0)},n.Text.prototype.measureLine=function(t){for(var e=0,i=0;i<t.length;i++){var s=t[i];if(this.fontWeights.length>0||this.fontStyles.length>0){var n=this.fontToComponents(this.context.font);this.fontStyles[this._charCount]&&(n.fontStyle=this.fontStyles[this._charCount]),this.fontWeights[this._charCount]&&(n.fontWeight=this.fontWeights[this._charCount]),this.context.font=this.componentsToFont(n)}this.style.stroke&&this.style.strokeThickness&&(this.strokeColors[this._charCount]&&(this.context.strokeStyle=this.strokeColors[this._charCount]),this.updateShadow(this.style.shadowStroke)),this.style.fill&&(this.colors[this._charCount]&&(this.context.fillStyle=this.colors[this._charCount]),this.updateShadow(this.style.shadowFill)),e+=this.context.measureText(s).width,this._charCount++}return Math.ceil(e)},n.Text.prototype.updateLine=function(t,e,i){for(var s=0;s<t.length;s++){var n=t[s];if(this.fontWeights.length>0||this.fontStyles.length>0){var r=this.fontToComponents(this.context.font);this.fontStyles[this._charCount]&&(r.fontStyle=this.fontStyles[this._charCount]),this.fontWeights[this._charCount]&&(r.fontWeight=this.fontWeights[this._charCount]),this.context.font=this.componentsToFont(r)}this.style.stroke&&this.style.strokeThickness&&(this.strokeColors[this._charCount]&&(this.context.strokeStyle=this.strokeColors[this._charCount]),this.updateShadow(this.style.shadowStroke),this.context.strokeText(n,e,i)),this.style.fill&&(this.colors[this._charCount]&&(this.context.fillStyle=this.colors[this._charCount]),this.updateShadow(this.style.shadowFill),this.context.fillText(n,e,i)),e+=this.context.measureText(n).width,this._charCount++}},n.Text.prototype.clearColors=function(){return this.colors=[],this.strokeColors=[],this.dirty=!0,this},n.Text.prototype.clearFontValues=function(){return this.fontStyles=[],this.fontWeights=[],this.dirty=!0,this},n.Text.prototype.addColor=function(t,e){return this.colors[e]=t,this.dirty=!0,this},n.Text.prototype.addStrokeColor=function(t,e){return this.strokeColors[e]=t,this.dirty=!0,this},n.Text.prototype.addFontStyle=function(t,e){return this.fontStyles[e]=t,this.dirty=!0,this},n.Text.prototype.addFontWeight=function(t,e){return this.fontWeights[e]=t,this.dirty=!0,this},n.Text.prototype.precalculateWordWrap=function(t){return this.texture.baseTexture.resolution=this._res,this.context.font=this.style.font,this.runWordWrap(t).split(/(?:\r\n|\r|\n)/)},n.Text.prototype.runWordWrap=function(t){return this.useAdvancedWrap?this.advancedWordWrap(t):this.basicWordWrap(t)},n.Text.prototype.advancedWordWrap=function(t){for(var e=this.context,i=this.style.wordWrapWidth,s="",n=t.replace(/ +/gi," ").split(/\r?\n/gi),r=n.length,o=0;o<r;o++){var a=n[o],h="";a=a.replace(/^ *|\s*$/gi,"");if(e.measureText(a).width<i)s+=a+"\n";else{for(var l=i,c=a.split(" "),u=0;u<c.length;u++){var d=c[u],p=d+" ",f=e.measureText(p).width;if(f>l){if(0===u){for(var g=p;g.length&&(g=g.slice(0,-1),!((f=e.measureText(g).width)<=l)););if(!g.length)throw new Error("This text's wordWrapWidth setting is less than a single character!");var m=d.substr(g.length);c[u]=m,h+=g}var y=c[u].length?u:u+1,v=c.slice(y).join(" ").replace(/[ \n]*$/gi,"");n[o+1]=v+" "+(n[o+1]||""),r=n.length;break}h+=p,l-=f}s+=h.replace(/[ \n]*$/gi,"")+"\n"}}return s=s.replace(/[\s|\n]*$/gi,"")},n.Text.prototype.basicWordWrap=function(t){for(var e="",i=t.split("\n"),s=0;s<i.length;s++){for(var n=this.style.wordWrapWidth,r=i[s].split(" "),o=0;o<r.length;o++){var a=this.context.measureText(r[o]).width,h=a+this.context.measureText(" ").width;h>n?(o>0&&(e+="\n"),e+=r[o]+" ",n=this.style.wordWrapWidth-a):(n-=h,e+=r[o]+" ")}s<i.length-1&&(e+="\n")}return e},n.Text.prototype.updateFont=function(t){var e=this.componentsToFont(t);this.style.font!==e&&(this.style.font=e,this.dirty=!0,this.parent&&this.updateTransform())},n.Text.prototype.fontToComponents=function(t){var e=t.match(/^\s*(?:\b(normal|italic|oblique|inherit)?\b)\s*(?:\b(normal|small-caps|inherit)?\b)\s*(?:\b(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900|inherit)?\b)\s*(?:\b(xx-small|x-small|small|medium|large|x-large|xx-large|larger|smaller|0|\d*(?:[.]\d*)?(?:%|[a-z]{2,5}))?\b)\s*(.*)\s*$/);if(e){var i=e[5].trim();return/^(?:inherit|serif|sans-serif|cursive|fantasy|monospace)$/.exec(i)||/['",]/.exec(i)||(i="'"+i+"'"),{font:t,fontStyle:e[1]||"normal",fontVariant:e[2]||"normal",fontWeight:e[3]||"normal",fontSize:e[4]||"medium",fontFamily:i}}return console.warn("Phaser.Text - unparsable CSS font: "+t),{font:t}},n.Text.prototype.componentsToFont=function(t){var e,i=[];return e=t.fontStyle,e&&"normal"!==e&&i.push(e),e=t.fontVariant,e&&"normal"!==e&&i.push(e),e=t.fontWeight,e&&"normal"!==e&&i.push(e),e=t.fontSize,e&&"medium"!==e&&i.push(e),e=t.fontFamily,e&&i.push(e),i.length||i.push(t.font),i.join(" ")},n.Text.prototype.setText=function(t,e){return void 0===e&&(e=!1),this.text=t.toString()||"",e?this.updateText():this.dirty=!0,this},n.Text.prototype.parseList=function(t){if(!Array.isArray(t))return this;for(var e="",i=0;i<t.length;i++)Array.isArray(t[i])?(e+=t[i].join("\t"),i<t.length-1&&(e+="\n")):(e+=t[i],i<t.length-1&&(e+="\t"));return this.text=e,this.dirty=!0,this},n.Text.prototype.setTextBounds=function(t,e,i,s){return void 0===t?this.textBounds=null:(this.textBounds?this.textBounds.setTo(t,e,i,s):this.textBounds=new n.Rectangle(t,e,i,s),this.style.wordWrapWidth>i&&(this.style.wordWrapWidth=i)),this.updateTexture(),this},n.Text.prototype.updateTexture=function(){var t=this.texture.baseTexture,e=this.texture.crop,i=this.texture.frame,s=this.canvas.width,n=this.canvas.height;if(t.width=s,t.height=n,e.width=s,e.height=n,i.width=s,i.height=n,this.texture.width=s,this.texture.height=n,this._width=s,this._height=n,this.textBounds){var r=this.textBounds.x,o=this.textBounds.y;"right"===this.style.boundsAlignH?r+=this.textBounds.width-this.canvas.width/this.resolution:"center"===this.style.boundsAlignH&&(r+=this.textBounds.halfWidth-this.canvas.width/this.resolution/2),"bottom"===this.style.boundsAlignV?o+=this.textBounds.height-this.canvas.height/this.resolution:"middle"===this.style.boundsAlignV&&(o+=this.textBounds.halfHeight-this.canvas.height/this.resolution/2),this.pivot.x=-r,this.pivot.y=-o}this.renderable=0!==s&&0!==n,this.texture.requiresReTint=!0,this.texture.baseTexture.dirty()},n.Text.prototype._renderWebGL=function(t){this.dirty&&(this.updateText(),this.dirty=!1),PIXI.Sprite.prototype._renderWebGL.call(this,t)},n.Text.prototype._renderCanvas=function(t){this.dirty&&(this.updateText(),this.dirty=!1),PIXI.Sprite.prototype._renderCanvas.call(this,t)},n.Text.prototype.determineFontProperties=function(t){var e=n.Text.fontPropertiesCache[t];if(!e){e={};var i=n.Text.fontPropertiesCanvas,s=n.Text.fontPropertiesContext;s.font=t;var r=Math.ceil(s.measureText("|MÉq").width),o=Math.ceil(s.measureText("|MÉq").width),a=2*o;if(o=1.4*o|0,i.width=r,i.height=a,s.fillStyle="#f00",s.fillRect(0,0,r,a),s.font=t,s.textBaseline="alphabetic",s.fillStyle="#000",s.fillText("|MÉq",0,o),!s.getImageData(0,0,r,a))return e.ascent=o,e.descent=o+6,e.fontSize=e.ascent+e.descent,n.Text.fontPropertiesCache[t]=e,e;var h,l,c=s.getImageData(0,0,r,a).data,u=c.length,d=4*r,p=0,f=!1;for(h=0;h<o;h++){for(l=0;l<d;l+=4)if(255!==c[p+l]){f=!0;break}if(f)break;p+=d}for(e.ascent=o-h,p=u-d,f=!1,h=a;h>o;h--){for(l=0;l<d;l+=4)if(255!==c[p+l]){f=!0;break}if(f)break;p-=d}e.descent=h-o,e.descent+=6,e.fontSize=e.ascent+e.descent,n.Text.fontPropertiesCache[t]=e}return e},n.Text.prototype.getBounds=function(t){return this.dirty&&(this.updateText(),this.dirty=!1),PIXI.Sprite.prototype.getBounds.call(this,t)},Object.defineProperty(n.Text.prototype,"text",{get:function(){return this._text},set:function(t){t!==this._text&&(this._text=t.toString()||"",this.dirty=!0,this.parent&&this.updateTransform())}}),Object.defineProperty(n.Text.prototype,"cssFont",{get:function(){return this.componentsToFont(this._fontComponents)},set:function(t){t=t||"bold 20pt Arial",this._fontComponents=this.fontToComponents(t),this.updateFont(this._fontComponents)}}),Object.defineProperty(n.Text.prototype,"font",{get:function(){return this._fontComponents.fontFamily},set:function(t){t=t||"Arial",t=t.trim(),/^(?:inherit|serif|sans-serif|cursive|fantasy|monospace)$/.exec(t)||/['",]/.exec(t)||(t="'"+t+"'"),this._fontComponents.fontFamily=t,this.updateFont(this._fontComponents)}}),Object.defineProperty(n.Text.prototype,"fontSize",{get:function(){var t=this._fontComponents.fontSize;return t&&/(?:^0$|px$)/.exec(t)?parseInt(t,10):t},set:function(t){t=t||"0","number"==typeof t&&(t+="px"),this._fontComponents.fontSize=t,this.updateFont(this._fontComponents)}}),Object.defineProperty(n.Text.prototype,"fontWeight",{get:function(){return this._fontComponents.fontWeight||"normal"},set:function(t){t=t||"normal",this._fontComponents.fontWeight=t,this.updateFont(this._fontComponents)}}),Object.defineProperty(n.Text.prototype,"fontStyle",{get:function(){return this._fontComponents.fontStyle||"normal"},set:function(t){t=t||"normal",this._fontComponents.fontStyle=t,this.updateFont(this._fontComponents)}}),Object.defineProperty(n.Text.prototype,"fontVariant",{get:function(){return this._fontComponents.fontVariant||"normal"},set:function(t){t=t||"normal",this._fontComponents.fontVariant=t,this.updateFont(this._fontComponents)}}),Object.defineProperty(n.Text.prototype,"fill",{get:function(){return this.style.fill},set:function(t){t!==this.style.fill&&(this.style.fill=t,this.dirty=!0)}}),Object.defineProperty(n.Text.prototype,"align",{get:function(){return this.style.align},set:function(t){t!==this.style.align&&(this.style.align=t,this.dirty=!0)}}),Object.defineProperty(n.Text.prototype,"resolution",{get:function(){return this._res},set:function(t){t!==this._res&&(this._res=t,this.dirty=!0)}}),Object.defineProperty(n.Text.prototype,"tabs",{get:function(){return this.style.tabs},set:function(t){t!==this.style.tabs&&(this.style.tabs=t,this.dirty=!0)}}),Object.defineProperty(n.Text.prototype,"boundsAlignH",{get:function(){return this.style.boundsAlignH},set:function(t){t!==this.style.boundsAlignH&&(this.style.boundsAlignH=t,this.dirty=!0)}}),Object.defineProperty(n.Text.prototype,"boundsAlignV",{get:function(){return this.style.boundsAlignV},set:function(t){t!==this.style.boundsAlignV&&(this.style.boundsAlignV=t,this.dirty=!0)}}),Object.defineProperty(n.Text.prototype,"stroke",{get:function(){return this.style.stroke},set:function(t){t!==this.style.stroke&&(this.style.stroke=t,this.dirty=!0)}}),Object.defineProperty(n.Text.prototype,"strokeThickness",{get:function(){return this.style.strokeThickness},set:function(t){t!==this.style.strokeThickness&&(this.style.strokeThickness=t,this.dirty=!0)}}),Object.defineProperty(n.Text.prototype,"wordWrap",{get:function(){return this.style.wordWrap},set:function(t){t!==this.style.wordWrap&&(this.style.wordWrap=t,this.dirty=!0)}}),Object.defineProperty(n.Text.prototype,"wordWrapWidth",{get:function(){return this.style.wordWrapWidth},set:function(t){t!==this.style.wordWrapWidth&&(this.style.wordWrapWidth=t,this.dirty=!0)}}),Object.defineProperty(n.Text.prototype,"lineSpacing",{get:function(){return this._lineSpacing},set:function(t){t!==this._lineSpacing&&(this._lineSpacing=parseFloat(t),this.dirty=!0,this.parent&&this.updateTransform())}}),Object.defineProperty(n.Text.prototype,"shadowOffsetX",{get:function(){return this.style.shadowOffsetX},set:function(t){t!==this.style.shadowOffsetX&&(this.style.shadowOffsetX=t,this.dirty=!0)}}),Object.defineProperty(n.Text.prototype,"shadowOffsetY",{get:function(){return this.style.shadowOffsetY},set:function(t){t!==this.style.shadowOffsetY&&(this.style.shadowOffsetY=t,this.dirty=!0)}}),Object.defineProperty(n.Text.prototype,"shadowColor",{get:function(){return this.style.shadowColor},set:function(t){t!==this.style.shadowColor&&(this.style.shadowColor=t,this.dirty=!0)}}),Object.defineProperty(n.Text.prototype,"shadowBlur",{get:function(){return this.style.shadowBlur},set:function(t){t!==this.style.shadowBlur&&(this.style.shadowBlur=t,this.dirty=!0)}}),Object.defineProperty(n.Text.prototype,"shadowStroke",{get:function(){return this.style.shadowStroke},set:function(t){t!==this.style.shadowStroke&&(this.style.shadowStroke=t,this.dirty=!0)}}),Object.defineProperty(n.Text.prototype,"shadowFill",{get:function(){return this.style.shadowFill},set:function(t){t!==this.style.shadowFill&&(this.style.shadowFill=t,this.dirty=!0)}}),Object.defineProperty(n.Text.prototype,"width",{get:function(){return this.dirty&&(this.updateText(),this.dirty=!1),this.scale.x*this.texture.frame.width},set:function(t){this.scale.x=t/this.texture.frame.width,this._width=t}}),Object.defineProperty(n.Text.prototype,"height",{get:function(){return this.dirty&&(this.updateText(),this.dirty=!1),this.scale.y*this.texture.frame.height},set:function(t){this.scale.y=t/this.texture.frame.height,this._height=t}}),n.Text.fontPropertiesCache={},n.Text.fontPropertiesCanvas=document.createElement("canvas"),n.Text.fontPropertiesContext=n.Text.fontPropertiesCanvas.getContext("2d"),/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.BitmapText=function(t,e,i,s,r,o,a){e=e||0,i=i||0,s=s||"",r=r||"",o=o||32,a=a||"left",PIXI.DisplayObjectContainer.call(this),this.type=n.BITMAPTEXT,this.physicsType=n.SPRITE,this.textWidth=0,this.textHeight=0,this.anchor=new n.Point,this._prevAnchor=new n.Point,this._glyphs=[],this._maxWidth=0,this._text=r.toString()||"",this._data=t.cache.getBitmapFont(s),this._font=s,this._fontSize=o,this._align=a,this._tint=16777215,this.updateText(),this.dirty=!1,n.Component.Core.init.call(this,t,e,i,"",null)},n.BitmapText.prototype=Object.create(PIXI.DisplayObjectContainer.prototype),n.BitmapText.prototype.constructor=n.BitmapText,n.Component.Core.install.call(n.BitmapText.prototype,["Angle","AutoCull","Bounds","Destroy","FixedToCamera","InputEnabled","InWorld","LifeSpan","PhysicsBody","Reset"]),n.BitmapText.prototype.preUpdatePhysics=n.Component.PhysicsBody.preUpdate,n.BitmapText.prototype.preUpdateLifeSpan=n.Component.LifeSpan.preUpdate,n.BitmapText.prototype.preUpdateInWorld=n.Component.InWorld.preUpdate,n.BitmapText.prototype.preUpdateCore=n.Component.Core.preUpdate,n.BitmapText.prototype.preUpdate=function(){return!!(this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld())&&this.preUpdateCore()},n.BitmapText.prototype.postUpdate=function(){n.Component.PhysicsBody.postUpdate.call(this),n.Component.FixedToCamera.postUpdate.call(this),this.body&&this.body.type===n.Physics.ARCADE&&(this.textWidth===this.body.sourceWidth&&this.textHeight===this.body.sourceHeight||this.body.setSize(this.textWidth,this.textHeight))},n.BitmapText.prototype.setText=function(t){this.text=t};n.BitmapText.prototype.scanLine=function(t,e,i){for(var s=0,n=0,r=-1,o=0,a=null,h=this._maxWidth>0?this._maxWidth:null,l=[],c=0;c<i.length;c++){var u=c===i.length-1;if(/(?:\r\n|\r|\n)/.test(i.charAt(c)))return{width:n,text:i.substr(0,c),end:u,chars:l};var d=i.charCodeAt(c),p=t.chars[d],f=0;void 0===p&&(d=32,p=t.chars[d]);var g=a&&p.kerning[a]?p.kerning[a]:0;if(/(\s)/.test(i.charAt(c))&&(r=c,o=n),f=(g+p.texture.width+p.xOffset)*e,h&&n+f>=h&&r>-1)return{width:o||n,text:i.substr(0,c-(c-r)),end:u,chars:l};n+=(p.xAdvance+g)*e,l.push(s+(p.xOffset+g)*e),s+=(p.xAdvance+g)*e,a=d}return{width:n,text:i,end:u,chars:l}},n.BitmapText.prototype.cleanText=function(t,e){void 0===e&&(e="");var i=this._data.font;if(!i)return"";for(var s=t.replace(/\r\n|\n\r|\n|\r/g,"\n").split("\n"),n=0;n<s.length;n++){for(var r="",o=s[n],a=0;a<o.length;a++)r=i.chars[o.charCodeAt(a)]?r.concat(o[a]):r.concat(e);s[n]=r}return s.join("\n")},n.BitmapText.prototype.updateText=function(){var t=this._data.font;if(t){var e=this.text,i=this._fontSize/t.size,s=[],n=0;this.textWidth=0;do{var r=this.scanLine(t,i,e);r.y=n,s.push(r),r.width>this.textWidth&&(this.textWidth=r.width),n+=t.lineHeight*i,e=e.substr(r.text.length+1)}while(!1===r.end);this.textHeight=n;for(var o=0,a=0,h=this.textWidth*this.anchor.x,l=this.textHeight*this.anchor.y,c=0;c<s.length;c++){var r=s[c];"right"===this._align?a=this.textWidth-r.width:"center"===this._align&&(a=(this.textWidth-r.width)/2);for(var u=0;u<r.text.length;u++){var d=r.text.charCodeAt(u),p=t.chars[d];void 0===p&&(d=32,p=t.chars[d]);var f=this._glyphs[o];f?f.texture=p.texture:(f=new PIXI.Sprite(p.texture),f.name=r.text[u],this._glyphs.push(f)),f.position.x=r.chars[u]+a-h,f.position.y=r.y+p.yOffset*i-l,f.scale.set(i),f.tint=this.tint,f.texture.requiresReTint=!0,f.parent||this.addChild(f),o++}}for(c=o;c<this._glyphs.length;c++)this.removeChild(this._glyphs[c])}},n.BitmapText.prototype.purgeGlyphs=function(){for(var t=this._glyphs.length,e=[],i=0;i<this._glyphs.length;i++)this._glyphs[i].parent!==this?this._glyphs[i].destroy():e.push(this._glyphs[i]);return this._glyphs=[],this._glyphs=e,this.updateText(),t-e.length},n.BitmapText.prototype.updateTransform=function(){!this.dirty&&this.anchor.equals(this._prevAnchor)||(this.updateText(),this.dirty=!1,this._prevAnchor.copyFrom(this.anchor)),PIXI.DisplayObjectContainer.prototype.updateTransform.call(this)},Object.defineProperty(n.BitmapText.prototype,"align",{get:function(){return this._align},set:function(t){t===this._align||"left"!==t&&"center"!==t&&"right"!==t||(this._align=t,this.updateText())}}),Object.defineProperty(n.BitmapText.prototype,"tint",{get:function(){return this._tint},set:function(t){t!==this._tint&&(this._tint=t,this.updateText())}}),Object.defineProperty(n.BitmapText.prototype,"font",{get:function(){return this._font},set:function(t){t!==this._font&&(this._font=t.trim(),this._data=this.game.cache.getBitmapFont(this._font),this.updateText())}}),Object.defineProperty(n.BitmapText.prototype,"fontSize",{get:function(){return this._fontSize},set:function(t){(t=parseInt(t,10))!==this._fontSize&&t>0&&(this._fontSize=t,this.updateText())}}),Object.defineProperty(n.BitmapText.prototype,"text",{get:function(){return this._text},set:function(t){t!==this._text&&(this._text=t.toString()||"",this.updateText())}}),Object.defineProperty(n.BitmapText.prototype,"maxWidth",{get:function(){return this._maxWidth},set:function(t){t!==this._maxWidth&&(this._maxWidth=t,this.updateText())}}),Object.defineProperty(n.BitmapText.prototype,"smoothed",{get:function(){return!this._data.base.scaleMode},set:function(t){this._data.base.scaleMode=t?0:1}}),/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.RetroFont=function(t,e,i,s,r,o,a,h,l,c){if(!t.cache.checkImageKey(e))return!1;void 0!==o&&null!==o||(o=t.cache.getImage(e).width/i),this.characterWidth=i,this.characterHeight=s,this.characterSpacingX=a||0,this.characterSpacingY=h||0,this.characterPerRow=o,this.offsetX=l||0,this.offsetY=c||0,this.align="left",this.multiLine=!1,this.autoUpperCase=!0,this.customSpacingX=0,this.customSpacingY=0,this.fixedWidth=0,this.fontSet=t.cache.getImage(e),this._text="",this.grabData=[],this.frameData=new n.FrameData;for(var u=this.offsetX,d=this.offsetY,p=0,f=0;f<r.length;f++){var g=this.frameData.addFrame(new n.Frame(f,u,d,this.characterWidth,this.characterHeight));this.grabData[r.charCodeAt(f)]=g.index,p++,p===this.characterPerRow?(p=0,u=this.offsetX,d+=this.characterHeight+this.characterSpacingY):u+=this.characterWidth+this.characterSpacingX}t.cache.updateFrameData(e,this.frameData),this.stamp=new n.Image(t,0,0,e,0),n.RenderTexture.call(this,t,100,100,"",n.scaleModes.NEAREST),this.type=n.RETROFONT},n.RetroFont.prototype=Object.create(n.RenderTexture.prototype),n.RetroFont.prototype.constructor=n.RetroFont,n.RetroFont.ALIGN_LEFT="left",n.RetroFont.ALIGN_RIGHT="right",n.RetroFont.ALIGN_CENTER="center",n.RetroFont.TEXT_SET1=" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~",n.RetroFont.TEXT_SET2=" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ",n.RetroFont.TEXT_SET3="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ",n.RetroFont.TEXT_SET4="ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789",n.RetroFont.TEXT_SET5="ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789",n.RetroFont.TEXT_SET6="ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.' ",n.RetroFont.TEXT_SET7="AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-'39",n.RetroFont.TEXT_SET8="0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ",n.RetroFont.TEXT_SET9="ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'\"?!",n.RetroFont.TEXT_SET10="ABCDEFGHIJKLMNOPQRSTUVWXYZ",n.RetroFont.TEXT_SET11="ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()':;0123456789",n.RetroFont.prototype.setFixedWidth=function(t,e){void 0===e&&(e="left"),this.fixedWidth=t,this.align=e},n.RetroFont.prototype.setText=function(t,e,i,s,n,r){this.multiLine=e||!1,this.customSpacingX=i||0,this.customSpacingY=s||0,this.align=n||"left",this.autoUpperCase=!r,t.length>0&&(this.text=t)},n.RetroFont.prototype.buildRetroFontText=function(){var t=0,e=0;if(this.clear(),this.multiLine){var i=this._text.split("\n");this.fixedWidth>0?this.resize(this.fixedWidth,i.length*(this.characterHeight+this.customSpacingY)-this.customSpacingY,!0):this.resize(this.getLongestLine()*(this.characterWidth+this.customSpacingX),i.length*(this.characterHeight+this.customSpacingY)-this.customSpacingY,!0);for(var s=0;s<i.length;s++)t=0,this.align===n.RetroFont.ALIGN_RIGHT?t=this.width-i[s].length*(this.characterWidth+this.customSpacingX):this.align===n.RetroFont.ALIGN_CENTER&&(t=this.width/2-i[s].length*(this.characterWidth+this.customSpacingX)/2,t+=this.customSpacingX/2),t<0&&(t=0),this.pasteLine(i[s],t,e,this.customSpacingX),e+=this.characterHeight+this.customSpacingY}else this.fixedWidth>0?this.resize(this.fixedWidth,this.characterHeight,!0):this.resize(this._text.length*(this.characterWidth+this.customSpacingX),this.characterHeight,!0),t=0,this.align===n.RetroFont.ALIGN_RIGHT?t=this.width-this._text.length*(this.characterWidth+this.customSpacingX):this.align===n.RetroFont.ALIGN_CENTER&&(t=this.width/2-this._text.length*(this.characterWidth+this.customSpacingX)/2,t+=this.customSpacingX/2),t<0&&(t=0),this.pasteLine(this._text,t,0,this.customSpacingX);this.requiresReTint=!0},n.RetroFont.prototype.pasteLine=function(t,e,i,s){for(var n=0;n<t.length;n++)if(" "===t.charAt(n))e+=this.characterWidth+s;else if(this.grabData[t.charCodeAt(n)]>=0&&(this.stamp.frame=this.grabData[t.charCodeAt(n)],this.renderXY(this.stamp,e,i,!1),(e+=this.characterWidth+s)>this.width))break},n.RetroFont.prototype.getLongestLine=function(){var t=0;if(this._text.length>0)for(var e=this._text.split("\n"),i=0;i<e.length;i++)e[i].length>t&&(t=e[i].length);return t},n.RetroFont.prototype.removeUnsupportedCharacters=function(t){for(var e="",i=0;i<this._text.length;i++){var s=this._text[i],n=s.charCodeAt(0);(this.grabData[n]>=0||!t&&"\n"===s)&&(e=e.concat(s))}return e},n.RetroFont.prototype.updateOffset=function(t,e){if(this.offsetX!==t||this.offsetY!==e){for(var i=t-this.offsetX,s=e-this.offsetY,n=this.game.cache.getFrameData(this.stamp.key).getFrames(),r=n.length;r--;)n[r].x+=i,n[r].y+=s;this.buildRetroFontText()}},Object.defineProperty(n.RetroFont.prototype,"text",{get:function(){return this._text},set:function(t){var e;(e=this.autoUpperCase?t.toUpperCase():t)!==this._text&&(this._text=e,this.removeUnsupportedCharacters(this.multiLine),this.buildRetroFontText())}}),Object.defineProperty(n.RetroFont.prototype,"smoothed",{get:function(){return this.stamp.smoothed},set:function(t){this.stamp.smoothed=t,this.buildRetroFontText()}}),/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd, Richard Davey
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Rope=function(t,e,i,s,r,o){this.points=[],this.points=o,this._hasUpdateAnimation=!1,this._updateAnimationCallback=null,e=e||0,i=i||0,s=s||null,r=r||null,this.type=n.ROPE,PIXI.Rope.call(this,n.Cache.DEFAULT,this.points),n.Component.Core.init.call(this,t,e,i,s,r)},n.Rope.prototype=Object.create(PIXI.Rope.prototype),n.Rope.prototype.constructor=n.Rope,n.Component.Core.install.call(n.Rope.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Delta","Destroy","FixedToCamera","InWorld","LifeSpan","LoadTexture","Overlap","PhysicsBody","Reset","ScaleMinMax","Smoothed"]),n.Rope.prototype.preUpdatePhysics=n.Component.PhysicsBody.preUpdate,n.Rope.prototype.preUpdateLifeSpan=n.Component.LifeSpan.preUpdate,n.Rope.prototype.preUpdateInWorld=n.Component.InWorld.preUpdate,n.Rope.prototype.preUpdateCore=n.Component.Core.preUpdate,n.Rope.prototype.preUpdate=function(){return!!(this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld())&&this.preUpdateCore()},n.Rope.prototype.update=function(){this._hasUpdateAnimation&&this.updateAnimation.call(this)},n.Rope.prototype.reset=function(t,e){return n.Component.Reset.prototype.reset.call(this,t,e),this},Object.defineProperty(n.Rope.prototype,"updateAnimation",{get:function(){return this._updateAnimation},set:function(t){t&&"function"==typeof t?(this._hasUpdateAnimation=!0,this._updateAnimation=t):(this._hasUpdateAnimation=!1,this._updateAnimation=null)}}),Object.defineProperty(n.Rope.prototype,"segments",{get:function(){for(var t,e,i,s,r,o,a,h,l=[],c=0;c<this.points.length;c++)t=4*c,e=this.vertices[t]*this.scale.x,i=this.vertices[t+1]*this.scale.y,s=this.vertices[t+4]*this.scale.x,r=this.vertices[t+3]*this.scale.y,o=n.Math.difference(e,s),a=n.Math.difference(i,r),e+=this.world.x,i+=this.world.y,h=new n.Rectangle(e,i,o,a),l.push(h);return l}}),/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.TileSprite=function(t,e,i,s,r,o,a){e=e||0,i=i||0,s=s||256,r=r||256,o=o||null,a=a||null,this.type=n.TILESPRITE,this.physicsType=n.SPRITE,this._scroll=new n.Point;var h=t.cache.getImage("__default",!0);PIXI.TilingSprite.call(this,new PIXI.Texture(h.base),s,r),n.Component.Core.init.call(this,t,e,i,o,a)},n.TileSprite.prototype=Object.create(PIXI.TilingSprite.prototype),n.TileSprite.prototype.constructor=n.TileSprite,n.Component.Core.install.call(n.TileSprite.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Destroy","FixedToCamera","Health","InCamera","InputEnabled","InWorld","LifeSpan","LoadTexture","Overlap","PhysicsBody","Reset","Smoothed"]),n.TileSprite.prototype.preUpdatePhysics=n.Component.PhysicsBody.preUpdate,n.TileSprite.prototype.preUpdateLifeSpan=n.Component.LifeSpan.preUpdate,n.TileSprite.prototype.preUpdateInWorld=n.Component.InWorld.preUpdate,n.TileSprite.prototype.preUpdateCore=n.Component.Core.preUpdate,n.TileSprite.prototype.preUpdate=function(){return 0!==this._scroll.x&&(this.tilePosition.x+=this._scroll.x*this.game.time.physicsElapsed),0!==this._scroll.y&&(this.tilePosition.y+=this._scroll.y*this.game.time.physicsElapsed),!!(this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld())&&this.preUpdateCore()},n.TileSprite.prototype.autoScroll=function(t,e){this._scroll.set(t,e)},n.TileSprite.prototype.stopScroll=function(){this._scroll.set(0,0)},n.TileSprite.prototype.destroy=function(t){n.Component.Destroy.prototype.destroy.call(this,t),PIXI.TilingSprite.prototype.destroy.call(this)},n.TileSprite.prototype.reset=function(t,e){return n.Component.Reset.prototype.reset.call(this,t,e),this.tilePosition.x=0,this.tilePosition.y=0,this},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Device=function(){this.deviceReadyAt=0,this.initialized=!1,this.desktop=!1,this.iOS=!1,this.iOSVersion=0,this.cocoonJS=!1,this.cocoonJSApp=!1,this.cordova=!1,this.node=!1,this.nodeWebkit=!1,this.electron=!1,this.ejecta=!1,this.crosswalk=!1,this.android=!1,this.chromeOS=!1,this.linux=!1,this.macOS=!1,this.windows=!1,this.windowsPhone=!1,this.canvas=!1,this.canvasBitBltShift=null,this.webGL=!1,this.file=!1,this.fileSystem=!1,this.localStorage=!1,this.worker=!1,this.css3D=!1,this.pointerLock=!1,this.typedArray=!1,this.vibration=!1,this.getUserMedia=!0,this.quirksMode=!1,this.touch=!1,this.mspointer=!1,this.wheelEvent=null,this.arora=!1,this.chrome=!1,this.chromeVersion=0,this.epiphany=!1,this.firefox=!1,this.firefoxVersion=0,this.ie=!1,this.ieVersion=0,this.trident=!1,this.tridentVersion=0,this.edge=!1,this.mobileSafari=!1,this.midori=!1,this.opera=!1,this.safari=!1,this.safariVersion=0,this.webApp=!1,this.silk=!1,this.audioData=!1,this.webAudio=!1,this.ogg=!1,this.opus=!1,this.mp3=!1,this.wav=!1,this.m4a=!1,this.webm=!1,this.dolby=!1,this.oggVideo=!1,this.h264Video=!1,this.mp4Video=!1,this.webmVideo=!1,this.vp9Video=!1,this.hlsVideo=!1,this.iPhone=!1,this.iPhone4=!1,this.iPad=!1,this.pixelRatio=0,this.littleEndian=!1,this.LITTLE_ENDIAN=!1,this.support32bit=!1,this.fullscreen=!1,this.requestFullscreen="",this.cancelFullscreen="",this.fullscreenKeyboard=!1},n.Device=new n.Device,n.Device.onInitialized=new n.Signal,n.Device.whenReady=function(t,e,i){var s=this._readyCheck;if(this.deviceReadyAt||!s)t.call(e,this);else if(s._monitor||i)s._queue=s._queue||[],s._queue.push([t,e]);else{s._monitor=s.bind(this),s._queue=s._queue||[],s._queue.push([t,e]);var n=void 0!==window.cordova,r=navigator.isCocoonJS;"complete"===document.readyState||"interactive"===document.readyState?window.setTimeout(s._monitor,0):n&&!r?document.addEventListener("deviceready",s._monitor,!1):(document.addEventListener("DOMContentLoaded",s._monitor,!1),window.addEventListener("load",s._monitor,!1))}},n.Device._readyCheck=function(){var t=this._readyCheck;if(document.body){if(!this.deviceReadyAt){this.deviceReadyAt=Date.now(),document.removeEventListener("deviceready",t._monitor),document.removeEventListener("DOMContentLoaded",t._monitor),window.removeEventListener("load",t._monitor),this._initialize(),this.initialized=!0,this.onInitialized.dispatch(this);for(var e;e=t._queue.shift();){var i=e[0],s=e[1];i.call(s,this)}this._readyCheck=null,this._initialize=null,this.onInitialized=null}}else window.setTimeout(t._monitor,20)},n.Device._initialize=function(){function t(){var t=new ArrayBuffer(4),e=new Uint8Array(t),i=new Uint32Array(t);return e[0]=161,e[1]=178,e[2]=195,e[3]=212,3569595041===i[0]||2712847316!==i[0]&&null}function e(){if(void 0===Uint8ClampedArray)return!1;var t=PIXI.CanvasPool.create(this,1,1),e=t.getContext("2d");if(!e)return!1;var i=e.createImageData(1,1);return PIXI.CanvasPool.remove(this),i.data instanceof Uint8ClampedArray}var s=this;!function(){var t=navigator.userAgent;/Playstation Vita/.test(t)?s.vita=!0:/Kindle/.test(t)||/\bKF[A-Z][A-Z]+/.test(t)||/Silk.*Mobile Safari/.test(t)?s.kindle=!0:/Android/.test(t)?s.android=!0:/CrOS/.test(t)?s.chromeOS=!0:/iP[ao]d|iPhone/i.test(t)?(s.iOS=!0,navigator.appVersion.match(/OS (\d+)/),s.iOSVersion=parseInt(RegExp.$1,10)):/Linux/.test(t)?s.linux=!0:/Mac OS/.test(t)?s.macOS=!0:/Windows/.test(t)&&(s.windows=!0),(/Windows Phone/i.test(t)||/IEMobile/i.test(t))&&(s.android=!1,s.iOS=!1,s.macOS=!1,s.windows=!0,s.windowsPhone=!0);var e=/Silk/.test(t);(s.windows||s.macOS||s.linux&&!e||s.chromeOS)&&(s.desktop=!0),(s.windowsPhone||/Windows NT/i.test(t)&&/Touch/i.test(t))&&(s.desktop=!1)}(),function(){var t=navigator.userAgent;if(/Arora/.test(t)?s.arora=!0:/Edge\/\d+/.test(t)?s.edge=!0:/Chrome\/(\d+)/.test(t)&&!s.windowsPhone?(s.chrome=!0,s.chromeVersion=parseInt(RegExp.$1,10)):/Epiphany/.test(t)?s.epiphany=!0:/Firefox\D+(\d+)/.test(t)?(s.firefox=!0,s.firefoxVersion=parseInt(RegExp.$1,10)):/AppleWebKit/.test(t)&&s.iOS?s.mobileSafari=!0:/MSIE (\d+\.\d+);/.test(t)?(s.ie=!0,s.ieVersion=parseInt(RegExp.$1,10)):/Midori/.test(t)?s.midori=!0:/Opera/.test(t)?s.opera=!0:/Safari\/(\d+)/.test(t)&&!s.windowsPhone?(s.safari=!0,/Version\/(\d+)\./.test(t)&&(s.safariVersion=parseInt(RegExp.$1,10))):/Trident\/(\d+\.\d+)(.*)rv:(\d+\.\d+)/.test(t)&&(s.ie=!0,s.trident=!0,s.tridentVersion=parseInt(RegExp.$1,10),s.ieVersion=parseInt(RegExp.$3,10)),/Silk/.test(t)&&(s.silk=!0),navigator.standalone&&(s.webApp=!0),void 0!==window.cordova&&(s.cordova=!0),void 0!==i&&(s.node=!0),s.node&&"object"==typeof i.versions&&(s.nodeWebkit=!!i.versions["node-webkit"],s.electron=!!i.versions.electron),navigator.isCocoonJS&&(s.cocoonJS=!0),s.cocoonJS)try{s.cocoonJSApp="undefined"!=typeof CocoonJS}catch(t){s.cocoonJSApp=!1}void 0!==window.ejecta&&(s.ejecta=!0),/Crosswalk/.test(t)&&(s.crosswalk=!0)}(),function(){s.audioData=!!window.Audio,s.webAudio=!(!window.AudioContext&&!window.webkitAudioContext);var t=document.createElement("audio");try{if(t.canPlayType&&(t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(s.ogg=!0),(t.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,"")||t.canPlayType("audio/opus;").replace(/^no$/,""))&&(s.opus=!0),t.canPlayType("audio/mpeg;").replace(/^no$/,"")&&(s.mp3=!0),t.canPlayType('audio/wav; codecs="1"').replace(/^no$/,"")&&(s.wav=!0),(t.canPlayType("audio/x-m4a;")||t.canPlayType("audio/aac;").replace(/^no$/,""))&&(s.m4a=!0),t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")&&(s.webm=!0),""!==t.canPlayType('audio/mp4;codecs="ec-3"')))if(s.edge)s.dolby=!0;else if(s.safari&&s.safariVersion>=9&&/Mac OS X (\d+)_(\d+)/.test(navigator.userAgent)){var e=parseInt(RegExp.$1,10),i=parseInt(RegExp.$2,10);(10===e&&i>=11||e>10)&&(s.dolby=!0)}}catch(t){}}(),function(){var t=document.createElement("video");try{!!t.canPlayType&&(t.canPlayType('video/ogg; codecs="theora"').replace(/^no$/,"")&&(s.oggVideo=!0),t.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/,"")&&(s.h264Video=!0,s.mp4Video=!0),t.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,"")&&(s.webmVideo=!0),t.canPlayType('video/webm; codecs="vp9"').replace(/^no$/,"")&&(s.vp9Video=!0),t.canPlayType('application/x-mpegURL; codecs="avc1.42E01E"').replace(/^no$/,"")&&(s.hlsVideo=!0))}catch(t){}}(),function(){var t,e=document.createElement("p"),i={webkitTransform:"-webkit-transform",OTransform:"-o-transform",msTransform:"-ms-transform",MozTransform:"-moz-transform",transform:"transform"};document.body.insertBefore(e,null);for(var n in i)void 0!==e.style[n]&&(e.style[n]="translate3d(1px,1px,1px)",t=window.getComputedStyle(e).getPropertyValue(i[n]));document.body.removeChild(e),s.css3D=void 0!==t&&t.length>0&&"none"!==t}(),function(){s.pixelRatio=window.devicePixelRatio||1,s.iPhone=-1!==navigator.userAgent.toLowerCase().indexOf("iphone"),s.iPhone4=2===s.pixelRatio&&s.iPhone,s.iPad=-1!==navigator.userAgent.toLowerCase().indexOf("ipad"),"undefined"!=typeof Int8Array?s.typedArray=!0:s.typedArray=!1,"undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint32Array&&(s.littleEndian=t(),s.LITTLE_ENDIAN=s.littleEndian),s.support32bit="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof Int32Array&&null!==s.littleEndian&&e(),navigator.vibrate=navigator.vibrate||navigator.webkitVibrate||navigator.mozVibrate||navigator.msVibrate,navigator.vibrate&&(s.vibration=!0)}(),function(){s.canvas=!!window.CanvasRenderingContext2D||s.cocoonJS;try{s.localStorage=!!localStorage.getItem}catch(t){s.localStorage=!1}s.file=!!(window.File&&window.FileReader&&window.FileList&&window.Blob),s.fileSystem=!!window.requestFileSystem,s.webGL=function(){try{var t=document.createElement("canvas");return t.screencanvas=!1,!!window.WebGLRenderingContext&&(t.getContext("webgl")||t.getContext("experimental-webgl"))}catch(t){return!1}}(),s.webGL=!!s.webGL,s.worker=!!window.Worker,s.pointerLock="pointerLockElement"in document||"mozPointerLockElement"in document||"webkitPointerLockElement"in document,s.quirksMode="CSS1Compat"!==document.compatMode,navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia||navigator.oGetUserMedia,window.URL=window.URL||window.webkitURL||window.mozURL||window.msURL,s.getUserMedia=s.getUserMedia&&!!navigator.getUserMedia&&!!window.URL,s.firefox&&s.firefoxVersion<21&&(s.getUserMedia=!1),!s.iOS&&(s.ie||s.firefox||s.chrome)&&(s.canvasBitBltShift=!0),(s.safari||s.mobileSafari)&&(s.canvasBitBltShift=!1)}(),function(){for(var t=["requestFullscreen","requestFullScreen","webkitRequestFullscreen","webkitRequestFullScreen","msRequestFullscreen","msRequestFullScreen","mozRequestFullScreen","mozRequestFullscreen"],e=document.createElement("div"),i=0;i<t.length;i++)if(e[t[i]]){s.fullscreen=!0,s.requestFullscreen=t[i];break}var n=["cancelFullScreen","exitFullscreen","webkitCancelFullScreen","webkitExitFullscreen","msCancelFullScreen","msExitFullscreen","mozCancelFullScreen","mozExitFullscreen"];if(s.fullscreen)for(var i=0;i<n.length;i++)if(document[n[i]]){s.cancelFullscreen=n[i];break}window.Element&&Element.ALLOW_KEYBOARD_INPUT&&(s.fullscreenKeyboard=!0)}(),function(){("ontouchstart"in document.documentElement||window.navigator.maxTouchPoints&&window.navigator.maxTouchPoints>=1)&&(s.touch=!0),(window.navigator.msPointerEnabled||window.navigator.pointerEnabled)&&(s.mspointer=!0),s.cocoonJS||("onwheel"in window||s.ie&&"WheelEvent"in window?s.wheelEvent="wheel":"onmousewheel"in window?s.wheelEvent="mousewheel":s.firefox&&"MouseScrollEvent"in window&&(s.wheelEvent="DOMMouseScroll"))}()},n.Device.canPlayAudio=function(t){return!("mp3"!==t||!this.mp3)||(!("ogg"!==t||!this.ogg&&!this.opus)||(!("m4a"!==t||!this.m4a)||(!("opus"!==t||!this.opus)||(!("wav"!==t||!this.wav)||(!("webm"!==t||!this.webm)||!("mp4"!==t||!this.dolby))))))},n.Device.canPlayVideo=function(t){return!("webm"!==t||!this.webmVideo&&!this.vp9Video)||(!("mp4"!==t||!this.mp4Video&&!this.h264Video)||(!("ogg"!==t&&"ogv"!==t||!this.oggVideo)||!("mpeg"!==t||!this.hlsVideo)))},n.Device.isConsoleOpen=function(){return!(!window.console||!window.console.firebug)||!(!window.console||(console.profile(),console.profileEnd(),console.clear&&console.clear(),!console.profiles))&&console.profiles.length>0},n.Device.isAndroidStockBrowser=function(){var t=window.navigator.userAgent.match(/Android.*AppleWebKit\/([\d.]+)/);return t&&t[1]<537},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Canvas={create:function(t,e,i,s,n){e=e||256,i=i||256;var r=n?document.createElement("canvas"):PIXI.CanvasPool.create(t,e,i);return"string"==typeof s&&""!==s&&(r.id=s),r.width=e,r.height=i,r.style.display="block",r},setBackgroundColor:function(t,e){return e=e||"rgb(0,0,0)",t.style.backgroundColor=e,t},setTouchAction:function(t,e){return e=e||"none",t.style.msTouchAction=e,t.style["ms-touch-action"]=e,t.style["touch-action"]=e,t},setUserSelect:function(t,e){return e=e||"none",t.style["-webkit-touch-callout"]=e,t.style["-webkit-user-select"]=e,t.style["-khtml-user-select"]=e,t.style["-moz-user-select"]=e,t.style["-ms-user-select"]=e,t.style["user-select"]=e,t.style["-webkit-tap-highlight-color"]="rgba(0, 0, 0, 0)",t},addToDOM:function(t,e,i){var s;return void 0===i&&(i=!0),e&&("string"==typeof e?s=document.getElementById(e):"object"==typeof e&&1===e.nodeType&&(s=e)),s||(s=document.body),i&&s.style&&(s.style.overflow="hidden"),s.appendChild(t),t},removeFromDOM:function(t){t.parentNode&&t.parentNode.removeChild(t)},setTransform:function(t,e,i,s,n,r,o){return t.setTransform(s,r,o,n,e,i),t},setSmoothingEnabled:function(t,e){var i=n.Canvas.getSmoothingPrefix(t);return i&&(t[i]=e),t},getSmoothingPrefix:function(t){var e=["i","webkitI","msI","mozI","oI"];for(var i in e){var s=e[i]+"mageSmoothingEnabled";if(s in t)return s}return null},getSmoothingEnabled:function(t){var e=n.Canvas.getSmoothingPrefix(t);if(e)return t[e]},setImageRenderingCrisp:function(t){for(var e=["optimizeSpeed","crisp-edges","-moz-crisp-edges","-webkit-optimize-contrast","optimize-contrast","pixelated"],i=0;i<e.length;i++)t.style["image-rendering"]=e[i];return t.style.msInterpolationMode="nearest-neighbor",t},setImageRenderingBicubic:function(t){return t.style["image-rendering"]="auto",t.style.msInterpolationMode="bicubic",t}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.RequestAnimationFrame=function(t,e){void 0===e&&(e=!1),this.game=t,this.isRunning=!1,this.forceSetTimeOut=e;for(var i=["ms","moz","webkit","o"],s=0;s<i.length&&!window.requestAnimationFrame;s++)window.requestAnimationFrame=window[i[s]+"RequestAnimationFrame"],window.cancelAnimationFrame=window[i[s]+"CancelAnimationFrame"];this._isSetTimeOut=!1,this._onLoop=null,this._timeOutID=null},n.RequestAnimationFrame.prototype={start:function(){this.isRunning=!0;var t=this;!window.requestAnimationFrame||this.forceSetTimeOut?(this._isSetTimeOut=!0,this._onLoop=function(){return t.updateSetTimeout()},this._timeOutID=window.setTimeout(this._onLoop,0)):(this._isSetTimeOut=!1,this._onLoop=function(e){return t.updateRAF(e)},this._timeOutID=window.requestAnimationFrame(this._onLoop))},updateRAF:function(t){this.isRunning&&(this.game.update(Math.floor(t)),this._timeOutID=window.requestAnimationFrame(this._onLoop))},updateSetTimeout:function(){this.isRunning&&(this.game.update(Date.now()),this._timeOutID=window.setTimeout(this._onLoop,this.game.time.timeToCall))},stop:function(){this._isSetTimeOut?clearTimeout(this._timeOutID):window.cancelAnimationFrame(this._timeOutID),this.isRunning=!1},isSetTimeOut:function(){return this._isSetTimeOut},isRAF:function(){return!1===this._isSetTimeOut}},n.RequestAnimationFrame.prototype.constructor=n.RequestAnimationFrame,/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Math={PI2:2*Math.PI,between:function(t,e){return Math.floor(Math.random()*(e-t+1)+t)},fuzzyEqual:function(t,e,i){return void 0===i&&(i=1e-4),Math.abs(t-e)<i},fuzzyLessThan:function(t,e,i){return void 0===i&&(i=1e-4),t<e+i},fuzzyGreaterThan:function(t,e,i){return void 0===i&&(i=1e-4),t>e-i},fuzzyCeil:function(t,e){return void 0===e&&(e=1e-4),Math.ceil(t-e)},fuzzyFloor:function(t,e){return void 0===e&&(e=1e-4),Math.floor(t+e)},average:function(){for(var t=0,e=arguments.length,i=0;i<e;i++)t+=+arguments[i];return t/e},shear:function(t){return t%1},snapTo:function(t,e,i){return void 0===i&&(i=0),0===e?t:(t-=i,t=e*Math.round(t/e),i+t)},snapToFloor:function(t,e,i){return void 0===i&&(i=0),0===e?t:(t-=i,t=e*Math.floor(t/e),i+t)},snapToCeil:function(t,e,i){return void 0===i&&(i=0),0===e?t:(t-=i,t=e*Math.ceil(t/e),i+t)},roundTo:function(t,e,i){void 0===e&&(e=0),void 0===i&&(i=10);var s=Math.pow(i,-e);return Math.round(t*s)/s},floorTo:function(t,e,i){void 0===e&&(e=0),void 0===i&&(i=10);var s=Math.pow(i,-e);return Math.floor(t*s)/s},ceilTo:function(t,e,i){void 0===e&&(e=0),void 0===i&&(i=10);var s=Math.pow(i,-e);return Math.ceil(t*s)/s},rotateToAngle:function(t,e,i){return void 0===i&&(i=.05),t===e?t:(Math.abs(e-t)<=i||Math.abs(e-t)>=n.Math.PI2-i?t=e:(Math.abs(e-t)>Math.PI&&(e<t?e+=n.Math.PI2:e-=n.Math.PI2),e>t?t+=i:e<t&&(t-=i)),t)},getShortestAngle:function(t,e){var i=e-t;return 0===i?0:i-360*Math.floor((i- -180)/360)},angleBetween:function(t,e,i,s){return Math.atan2(s-e,i-t)},angleBetweenY:function(t,e,i,s){return Math.atan2(i-t,s-e)},angleBetweenPoints:function(t,e){return Math.atan2(e.y-t.y,e.x-t.x)},angleBetweenPointsY:function(t,e){return Math.atan2(e.x-t.x,e.y-t.y)},reverseAngle:function(t){return this.normalizeAngle(t+Math.PI,!0)},normalizeAngle:function(t){return t%=2*Math.PI,t>=0?t:t+2*Math.PI},maxAdd:function(t,e,i){return Math.min(t+e,i)},minSub:function(t,e,i){return Math.max(t-e,i)},wrap:function(t,e,i){var s=i-e;if(s<=0)return 0;var n=(t-e)%s;return n<0&&(n+=s),n+e},wrapValue:function(t,e,i){return t=Math.abs(t),e=Math.abs(e),i=Math.abs(i),(t+e)%i},isOdd:function(t){return!!(1&t)},isEven:function(t){return!(1&t)},min:function(){if(1===arguments.length&&"object"==typeof arguments[0])var t=arguments[0];else var t=arguments;for(var e=1,i=0,s=t.length;e<s;e++)t[e]<t[i]&&(i=e);return t[i]},max:function(){if(1===arguments.length&&"object"==typeof arguments[0])var t=arguments[0];else var t=arguments;for(var e=1,i=0,s=t.length;e<s;e++)t[e]>t[i]&&(i=e);return t[i]},minProperty:function(t){if(2===arguments.length&&"object"==typeof arguments[1])var e=arguments[1];else var e=arguments.slice(1);for(var i=1,s=0,n=e.length;i<n;i++)e[i][t]<e[s][t]&&(s=i);return e[s][t]},maxProperty:function(t){if(2===arguments.length&&"object"==typeof arguments[1])var e=arguments[1];else var e=arguments.slice(1);for(var i=1,s=0,n=e.length;i<n;i++)e[i][t]>e[s][t]&&(s=i);return e[s][t]},wrapAngle:function(t,e){return e?this.wrap(t,-Math.PI,Math.PI):this.wrap(t,-180,180)},linearInterpolation:function(t,e){var i=t.length-1,s=i*e,n=Math.floor(s);return e<0?this.linear(t[0],t[1],s):e>1?this.linear(t[i],t[i-1],i-s):this.linear(t[n],t[n+1>i?i:n+1],s-n)},bezierInterpolation:function(t,e){for(var i=0,s=t.length-1,n=0;n<=s;n++)i+=Math.pow(1-e,s-n)*Math.pow(e,n)*t[n]*this.bernstein(s,n);return i},catmullRomInterpolation:function(t,e){var i=t.length-1,s=i*e,n=Math.floor(s);return t[0]===t[i]?(e<0&&(n=Math.floor(s=i*(1+e))),this.catmullRom(t[(n-1+i)%i],t[n],t[(n+1)%i],t[(n+2)%i],s-n)):e<0?t[0]-(this.catmullRom(t[0],t[0],t[1],t[1],-s)-t[0]):e>1?t[i]-(this.catmullRom(t[i],t[i],t[i-1],t[i-1],s-i)-t[i]):this.catmullRom(t[n?n-1:0],t[n],t[i<n+1?i:n+1],t[i<n+2?i:n+2],s-n)},linear:function(t,e,i){return(e-t)*i+t},bernstein:function(t,e){return this.factorial(t)/this.factorial(e)/this.factorial(t-e)},factorial:function(t){if(0===t)return 1;for(var e=t;--t;)e*=t;return e},catmullRom:function(t,e,i,s,n){var r=.5*(i-t),o=.5*(s-e),a=n*n;return(2*e-2*i+r+o)*(n*a)+(-3*e+3*i-2*r-o)*a+r*n+e},difference:function(t,e){return Math.abs(t-e)},roundAwayFromZero:function(t){return t>0?Math.ceil(t):Math.floor(t)},sinCosGenerator:function(t,e,i,s){void 0===e&&(e=1),void 0===i&&(i=1),void 0===s&&(s=1);for(var n=e,r=i,o=s*Math.PI/t,a=[],h=[],l=0;l<t;l++)r-=n*o,n+=r*o,a[l]=r,h[l]=n;return{sin:h,cos:a,length:t}},distance:function(t,e,i,s){var n=t-i,r=e-s;return Math.sqrt(n*n+r*r)},distanceSq:function(t,e,i,s){var n=t-i,r=e-s;return n*n+r*r},distancePow:function(t,e,i,s,n){return void 0===n&&(n=2),Math.sqrt(Math.pow(i-t,n)+Math.pow(s-e,n))},clamp:function(t,e,i){return t<e?e:i<t?i:t},clampBottom:function(t,e){return t<e?e:t},within:function(t,e,i){return Math.abs(t-e)<=i},mapLinear:function(t,e,i,s,n){return s+(t-e)*(n-s)/(i-e)},smoothstep:function(t,e,i){return(t=Math.max(0,Math.min(1,(t-e)/(i-e))))*t*(3-2*t)},smootherstep:function(t,e,i){return(t=Math.max(0,Math.min(1,(t-e)/(i-e))))*t*t*(t*(6*t-15)+10)},sign:function(t){return t<0?-1:t>0?1:0},percent:function(t,e,i){return void 0===i&&(i=0),t>e||i>e?1:t<i||i>t?0:(t-i)/e}};var h=Math.PI/180,l=180/Math.PI;/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Timo Hausmann
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Jeremy Dowell <[email protected]>
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Georgios Kaleadis https://github.com/georgiee
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author George https://github.com/georgiee
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
return n.Math.degToRad=function(t){return t*h},n.Math.radToDeg=function(t){return t*l},n.RandomDataGenerator=function(t){void 0===t&&(t=[]),this.c=1,this.s0=0,this.s1=0,this.s2=0,"string"==typeof t?this.state(t):this.sow(t)},n.RandomDataGenerator.prototype={rnd:function(){var t=2091639*this.s0+2.3283064365386963e-10*this.c;return this.c=0|t,this.s0=this.s1,this.s1=this.s2,this.s2=t-this.c,this.s2},sow:function(t){if(this.s0=this.hash(" "),this.s1=this.hash(this.s0),this.s2=this.hash(this.s1),this.c=1,t)for(var e=0;e<t.length&&null!=t[e];e++){var i=t[e];this.s0-=this.hash(i),this.s0+=~~(this.s0<0),this.s1-=this.hash(i),this.s1+=~~(this.s1<0),this.s2-=this.hash(i),this.s2+=~~(this.s2<0)}},hash:function(t){var e,i,s;for(s=4022871197,t=t.toString(),i=0;i<t.length;i++)s+=t.charCodeAt(i),e=.02519603282416938*s,s=e>>>0,e-=s,e*=s,s=e>>>0,e-=s,s+=4294967296*e;return 2.3283064365386963e-10*(s>>>0)},integer:function(){return 4294967296*this.rnd.apply(this)},frac:function(){return this.rnd.apply(this)+1.1102230246251565e-16*(2097152*this.rnd.apply(this)|0)},real:function(){return this.integer()+this.frac()},integerInRange:function(t,e){return Math.floor(this.realInRange(0,e-t+1)+t)},between:function(t,e){return this.integerInRange(t,e)},realInRange:function(t,e){return this.frac()*(e-t)+t},normal:function(){return 1-2*this.frac()},uuid:function(){var t="",e="";for(e=t="";t++<36;e+=~t%5|3*t&4?(15^t?8^this.frac()*(20^t?16:4):4).toString(16):"-");return e},pick:function(t){return t[this.integerInRange(0,t.length-1)]},sign:function(){return this.pick([-1,1])},weightedPick:function(t){return t[~~(Math.pow(this.frac(),2)*(t.length-1)+.5)]},timestamp:function(t,e){return this.realInRange(t||9466848e5,e||1577862e6)},angle:function(){return this.integerInRange(-180,180)},state:function(t){return"string"==typeof t&&t.match(/^!rnd/)&&(t=t.split(","),this.c=parseFloat(t[1]),this.s0=parseFloat(t[2]),this.s1=parseFloat(t[3]),this.s2=parseFloat(t[4])),["!rnd",this.c,this.s0,this.s1,this.s2].join(",")}},n.RandomDataGenerator.prototype.constructor=n.RandomDataGenerator,n.QuadTree=function(t,e,i,s,n,r,o){this.maxObjects=10,this.maxLevels=4,this.level=0,this.bounds={},this.objects=[],this.nodes=[],this._empty=[],this.reset(t,e,i,s,n,r,o)},n.QuadTree.prototype={reset:function(t,e,i,s,n,r,o){this.maxObjects=n||10,this.maxLevels=r||4,this.level=o||0,this.bounds={x:Math.round(t),y:Math.round(e),width:i,height:s,subWidth:Math.floor(i/2),subHeight:Math.floor(s/2),right:Math.round(t)+Math.floor(i/2),bottom:Math.round(e)+Math.floor(s/2)},this.objects.length=0,this.nodes.length=0},populate:function(t){t.forEach(this.populateHandler,this,!0)},populateHandler:function(t){t.body&&t.exists&&this.insert(t.body)},split:function(){this.nodes[0]=new n.QuadTree(this.bounds.right,this.bounds.y,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[1]=new n.QuadTree(this.bounds.x,this.bounds.y,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[2]=new n.QuadTree(this.bounds.x,this.bounds.bottom,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[3]=new n.QuadTree(this.bounds.right,this.bounds.bottom,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1)},insert:function(t){var e,i=0;if(null!=this.nodes[0]&&-1!==(e=this.getIndex(t)))return void this.nodes[e].insert(t);if(this.objects.push(t),this.objects.length>this.maxObjects&&this.level<this.maxLevels)for(null==this.nodes[0]&&this.split();i<this.objects.length;)e=this.getIndex(this.objects[i]),-1!==e?this.nodes[e].insert(this.objects.splice(i,1)[0]):i++},getIndex:function(t){var e=-1;return t.x<this.bounds.right&&t.right<this.bounds.right?t.y<this.bounds.bottom&&t.bottom<this.bounds.bottom?e=1:t.y>this.bounds.bottom&&(e=2):t.x>this.bounds.right&&(t.y<this.bounds.bottom&&t.bottom<this.bounds.bottom?e=0:t.y>this.bounds.bottom&&(e=3)),e},retrieve:function(t){if(t instanceof n.Rectangle)var e=this.objects,i=this.getIndex(t);else{if(!t.body)return this._empty;var e=this.objects,i=this.getIndex(t.body)}return this.nodes[0]&&(-1!==i?e=e.concat(this.nodes[i].retrieve(t)):(e=e.concat(this.nodes[0].retrieve(t)),e=e.concat(this.nodes[1].retrieve(t)),e=e.concat(this.nodes[2].retrieve(t)),e=e.concat(this.nodes[3].retrieve(t)))),e},clear:function(){this.objects.length=0;for(var t=this.nodes.length;t--;)this.nodes[t].clear(),this.nodes.splice(t,1);this.nodes.length=0}},n.QuadTree.prototype.constructor=n.QuadTree,n.Net=function(t){this.game=t},n.Net.prototype={getHostName:function(){return window.location&&window.location.hostname?window.location.hostname:null},checkDomainName:function(t){return-1!==window.location.hostname.indexOf(t)},updateQueryString:function(t,e,i,s){void 0===i&&(i=!1),void 0!==s&&""!==s||(s=window.location.href);var n="",r=new RegExp("([?|&])"+t+"=.*?(&|#|$)(.*)","gi");if(r.test(s))n=void 0!==e&&null!==e?s.replace(r,"$1"+t+"="+e+"$2$3"):s.replace(r,"$1$3").replace(/(&|\?)$/,"");else if(void 0!==e&&null!==e){var o=-1!==s.indexOf("?")?"&":"?",a=s.split("#");s=a[0]+o+t+"="+e,a[1]&&(s+="#"+a[1]),n=s}else n=s;if(!i)return n;window.location.href=n},getQueryString:function(t){void 0===t&&(t="");var e={},i=location.search.substring(1).split("&");for(var s in i){var n=i[s].split("=");if(n.length>1){if(t&&t===this.decodeURI(n[0]))return this.decodeURI(n[1]);e[this.decodeURI(n[0])]=this.decodeURI(n[1])}}return e},decodeURI:function(t){return decodeURIComponent(t.replace(/\+/g," "))}},n.Net.prototype.constructor=n.Net,n.TweenManager=function(t){this.game=t,this.frameBased=!1,this._tweens=[],this._add=[],this.easeMap={Power0:n.Easing.Power0,Power1:n.Easing.Power1,Power2:n.Easing.Power2,Power3:n.Easing.Power3,Power4:n.Easing.Power4,Linear:n.Easing.Linear.None,Quad:n.Easing.Quadratic.Out,Cubic:n.Easing.Cubic.Out,Quart:n.Easing.Quartic.Out,Quint:n.Easing.Quintic.Out,Sine:n.Easing.Sinusoidal.Out,Expo:n.Easing.Exponential.Out,Circ:n.Easing.Circular.Out,Elastic:n.Easing.Elastic.Out,Back:n.Easing.Back.Out,Bounce:n.Easing.Bounce.Out,"Quad.easeIn":n.Easing.Quadratic.In,"Cubic.easeIn":n.Easing.Cubic.In,"Quart.easeIn":n.Easing.Quartic.In,"Quint.easeIn":n.Easing.Quintic.In,"Sine.easeIn":n.Easing.Sinusoidal.In,"Expo.easeIn":n.Easing.Exponential.In,"Circ.easeIn":n.Easing.Circular.In,"Elastic.easeIn":n.Easing.Elastic.In,"Back.easeIn":n.Easing.Back.In,"Bounce.easeIn":n.Easing.Bounce.In,"Quad.easeOut":n.Easing.Quadratic.Out,"Cubic.easeOut":n.Easing.Cubic.Out,"Quart.easeOut":n.Easing.Quartic.Out,"Quint.easeOut":n.Easing.Quintic.Out,"Sine.easeOut":n.Easing.Sinusoidal.Out,"Expo.easeOut":n.Easing.Exponential.Out,"Circ.easeOut":n.Easing.Circular.Out,"Elastic.easeOut":n.Easing.Elastic.Out,"Back.easeOut":n.Easing.Back.Out,"Bounce.easeOut":n.Easing.Bounce.Out,"Quad.easeInOut":n.Easing.Quadratic.InOut,"Cubic.easeInOut":n.Easing.Cubic.InOut,"Quart.easeInOut":n.Easing.Quartic.InOut,"Quint.easeInOut":n.Easing.Quintic.InOut,"Sine.easeInOut":n.Easing.Sinusoidal.InOut,"Expo.easeInOut":n.Easing.Exponential.InOut,"Circ.easeInOut":n.Easing.Circular.InOut,"Elastic.easeInOut":n.Easing.Elastic.InOut,"Back.easeInOut":n.Easing.Back.InOut,"Bounce.easeInOut":n.Easing.Bounce.InOut},this.game.onPause.add(this._pauseAll,this),this.game.onResume.add(this._resumeAll,this)},n.TweenManager.prototype={getAll:function(){return this._tweens},removeAll:function(){for(var t=0;t<this._tweens.length;t++)this._tweens[t].pendingDelete=!0;this._add=[]},removeFrom:function(t,e){void 0===e&&(e=!0);var i,s;if(Array.isArray(t))for(i=0,s=t.length;i<s;i++)this.removeFrom(t[i]);else if(t.type===n.GROUP&&e)for(var i=0,s=t.children.length;i<s;i++)this.removeFrom(t.children[i]);else{for(i=0,s=this._tweens.length;i<s;i++)t===this._tweens[i].target&&this.remove(this._tweens[i]);for(i=0,s=this._add.length;i<s;i++)t===this._add[i].target&&this.remove(this._add[i])}},add:function(t){t._manager=this,this._add.push(t)},create:function(t){return new n.Tween(t,this.game,this)},remove:function(t){var e=this._tweens.indexOf(t);-1!==e?this._tweens[e].pendingDelete=!0:-1!==(e=this._add.indexOf(t))&&(this._add[e].pendingDelete=!0)},update:function(){var t=this._add.length,e=this._tweens.length;if(0===e&&0===t)return!1;for(var i=0;i<e;)this._tweens[i].update(this.game.time.time)?i++:(this._tweens.splice(i,1),e--);return t>0&&(this._tweens=this._tweens.concat(this._add),this._add.length=0),!0},isTweening:function(t){return this._tweens.some(function(e){return e.target===t})},_pauseAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t]._pause()},_resumeAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t]._resume()},pauseAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t].pause()},resumeAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t].resume(!0)}},n.TweenManager.prototype.constructor=n.TweenManager,n.Tween=function(t,e,i){this.game=e,this.target=t,this.manager=i,this.timeline=[],this.reverse=!1,this.timeScale=1,this.repeatCounter=0,this.pendingDelete=!1,this.onStart=new n.Signal,this.onLoop=new n.Signal,this.onRepeat=new n.Signal,this.onChildComplete=new n.Signal,this.onComplete=new n.Signal,this.isRunning=!1,this.current=0,this.properties={},this.chainedTween=null,this.isPaused=!1,this.frameBased=i.frameBased,this._onUpdateCallback=null,this._onUpdateCallbackContext=null,this._pausedTime=0,this._codePaused=!1,this._hasStarted=!1},n.Tween.prototype={to:function(t,e,i,s,r,o,a){return(void 0===e||e<=0)&&(e=1e3),void 0!==i&&null!==i||(i=n.Easing.Default),void 0===s&&(s=!1),void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=!1),"string"==typeof i&&this.manager.easeMap[i]&&(i=this.manager.easeMap[i]),this.isRunning?(console.warn("Phaser.Tween.to cannot be called after Tween.start"),this):(this.timeline.push(new n.TweenData(this).to(t,e,i,r,o,a)),s&&this.start(),this)},from:function(t,e,i,s,r,o,a){return void 0===e&&(e=1e3),void 0!==i&&null!==i||(i=n.Easing.Default),void 0===s&&(s=!1),void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=!1),"string"==typeof i&&this.manager.easeMap[i]&&(i=this.manager.easeMap[i]),this.isRunning?(console.warn("Phaser.Tween.from cannot be called after Tween.start"),this):(this.timeline.push(new n.TweenData(this).from(t,e,i,r,o,a)),s&&this.start(),this)},start:function(t){if(void 0===t&&(t=0),null===this.game||null===this.target||0===this.timeline.length||this.isRunning)return this;for(var e=0;e<this.timeline.length;e++)for(var i in this.timeline[e].vEnd)this.properties[i]=this.target[i]||0,Array.isArray(this.properties[i])||(this.properties[i]*=1);for(var e=0;e<this.timeline.length;e++)this.timeline[e].loadValues();return this.manager.add(this),this.isRunning=!0,(t<0||t>this.timeline.length-1)&&(t=0),this.current=t,this.timeline[this.current].start(),this},stop:function(t){return void 0===t&&(t=!1),this.isRunning=!1,this._onUpdateCallback=null,this._onUpdateCallbackContext=null,t&&(this.onComplete.dispatch(this.target,this),this._hasStarted=!1,this.chainedTween&&this.chainedTween.start()),this.manager.remove(this),this},updateTweenData:function(t,e,i){if(0===this.timeline.length)return this;if(void 0===i&&(i=0),-1===i)for(var s=0;s<this.timeline.length;s++)this.timeline[s][t]=e;else this.timeline[i][t]=e;return this},delay:function(t,e){return this.updateTweenData("delay",t,e)},repeat:function(t,e,i){return void 0===e&&(e=0),this.updateTweenData("repeatCounter",t,i),this.updateTweenData("repeatDelay",e,i)},repeatDelay:function(t,e){return this.updateTweenData("repeatDelay",t,e)},yoyo:function(t,e,i){return void 0===e&&(e=0),this.updateTweenData("yoyo",t,i),this.updateTweenData("yoyoDelay",e,i)},yoyoDelay:function(t,e){return this.updateTweenData("yoyoDelay",t,e)},easing:function(t,e){return"string"==typeof t&&this.manager.easeMap[t]&&(t=this.manager.easeMap[t]),this.updateTweenData("easingFunction",t,e)},interpolation:function(t,e,i){return void 0===e&&(e=n.Math),this.updateTweenData("interpolationFunction",t,i),this.updateTweenData("interpolationContext",e,i)},repeatAll:function(t){return void 0===t&&(t=0),this.repeatCounter=t,this},chain:function(){for(var t=arguments.length;t--;)t>0?arguments[t-1].chainedTween=arguments[t]:this.chainedTween=arguments[t];return this},loop:function(t){return void 0===t&&(t=!0),this.repeatCounter=t?-1:0,this},onUpdateCallback:function(t,e){return this._onUpdateCallback=t,this._onUpdateCallbackContext=e,this},pause:function(){this.isPaused=!0,this._codePaused=!0,this._pausedTime=this.game.time.time},_pause:function(){this._codePaused||(this.isPaused=!0,this._pausedTime=this.game.time.time)},resume:function(){if(this.isPaused){this.isPaused=!1,this._codePaused=!1;for(var t=0;t<this.timeline.length;t++)this.timeline[t].isRunning||(this.timeline[t].startTime+=this.game.time.time-this._pausedTime)}},_resume:function(){this._codePaused||this.resume()},update:function(t){if(this.pendingDelete||!this.target)return!1;if(this.isPaused)return!0;var e=this.timeline[this.current].update(t);if(e===n.TweenData.PENDING)return!0;if(e===n.TweenData.RUNNING)return this._hasStarted||(this.onStart.dispatch(this.target,this),this._hasStarted=!0),null!==this._onUpdateCallback&&this._onUpdateCallback.call(this._onUpdateCallbackContext,this,this.timeline[this.current].value,this.timeline[this.current]),this.isRunning;if(e===n.TweenData.LOOPED)return-1===this.timeline[this.current].repeatCounter?this.onLoop.dispatch(this.target,this):this.onRepeat.dispatch(this.target,this),!0;if(e===n.TweenData.COMPLETE){var i=!1;return this.reverse?--this.current<0&&(this.current=this.timeline.length-1,i=!0):++this.current===this.timeline.length&&(this.current=0,i=!0),i?-1===this.repeatCounter?(this.timeline[this.current].start(),this.onLoop.dispatch(this.target,this),!0):this.repeatCounter>0?(this.repeatCounter--,this.timeline[this.current].start(),this.onRepeat.dispatch(this.target,this),!0):(this.isRunning=!1,this.onComplete.dispatch(this.target,this),this._hasStarted=!1,this.chainedTween&&this.chainedTween.start(),!1):(this.onChildComplete.dispatch(this.target,this),this.timeline[this.current].start(),!0)}},generateData:function(t,e){if(null===this.game||null===this.target)return null;void 0===t&&(t=60),void 0===e&&(e=[]);for(var i=0;i<this.timeline.length;i++)for(var s in this.timeline[i].vEnd)this.properties[s]=this.target[s]||0,Array.isArray(this.properties[s])||(this.properties[s]*=1);for(var i=0;i<this.timeline.length;i++)this.timeline[i].loadValues();for(var i=0;i<this.timeline.length;i++)e=e.concat(this.timeline[i].generateData(t));return e}},Object.defineProperty(n.Tween.prototype,"totalDuration",{get:function(){for(var t=0,e=0;e<this.timeline.length;e++)t+=this.timeline[e].duration;return t}}),n.Tween.prototype.constructor=n.Tween,n.TweenData=function(t){this.parent=t,this.game=t.game,this.vStart={},this.vStartCache={},this.vEnd={},this.vEndCache={},this.duration=1e3,this.percent=0,this.value=0,this.repeatCounter=0,this.repeatDelay=0,this.repeatTotal=0,this.interpolate=!1,this.yoyo=!1,this.yoyoDelay=0,this.inReverse=!1,this.delay=0,this.dt=0,this.startTime=null,this.easingFunction=n.Easing.Default,this.interpolationFunction=n.Math.linearInterpolation,this.interpolationContext=n.Math,this.isRunning=!1,this.isFrom=!1},n.TweenData.PENDING=0,n.TweenData.RUNNING=1,n.TweenData.LOOPED=2,n.TweenData.COMPLETE=3,n.TweenData.prototype={to:function(t,e,i,s,n,r){return this.vEnd=t,this.duration=e,this.easingFunction=i,this.delay=s,this.repeatTotal=n,this.yoyo=r,this.isFrom=!1,this},from:function(t,e,i,s,n,r){return this.vEnd=t,this.duration=e,this.easingFunction=i,this.delay=s,this.repeatTotal=n,this.yoyo=r,this.isFrom=!0,this},start:function(){if(this.startTime=this.game.time.time+this.delay,this.parent.reverse?this.dt=this.duration:this.dt=0,this.delay>0?this.isRunning=!1:this.isRunning=!0,this.isFrom)for(var t in this.vStartCache)this.vStart[t]=this.vEndCache[t],this.vEnd[t]=this.vStartCache[t],this.parent.target[t]=this.vStart[t];return this.value=0,this.yoyoCounter=0,this.repeatCounter=this.repeatTotal,this},loadValues:function(){for(var t in this.parent.properties){if(this.vStart[t]=this.parent.properties[t],Array.isArray(this.vEnd[t])){if(0===this.vEnd[t].length)continue;0===this.percent&&(this.vEnd[t]=[this.vStart[t]].concat(this.vEnd[t]))}void 0!==this.vEnd[t]?("string"==typeof this.vEnd[t]&&(this.vEnd[t]=this.vStart[t]+parseFloat(this.vEnd[t],10)),this.parent.properties[t]=this.vEnd[t]):this.vEnd[t]=this.vStart[t],this.vStartCache[t]=this.vStart[t],this.vEndCache[t]=this.vEnd[t]}return this},update:function(t){if(this.isRunning){if(t<this.startTime)return n.TweenData.RUNNING}else{if(!(t>=this.startTime))return n.TweenData.PENDING;this.isRunning=!0}var e=this.parent.frameBased?this.game.time.physicsElapsedMS:this.game.time.elapsedMS;this.parent.reverse?(this.dt-=e*this.parent.timeScale,this.dt=Math.max(this.dt,0)):(this.dt+=e*this.parent.timeScale,this.dt=Math.min(this.dt,this.duration)),this.percent=this.dt/this.duration,this.value=this.easingFunction(this.percent);for(var i in this.vEnd){var s=this.vStart[i],r=this.vEnd[i];Array.isArray(r)?this.parent.target[i]=this.interpolationFunction.call(this.interpolationContext,r,this.value):this.parent.target[i]=s+(r-s)*this.value}return!this.parent.reverse&&1===this.percent||this.parent.reverse&&0===this.percent?this.repeat():n.TweenData.RUNNING},generateData:function(t){this.parent.reverse?this.dt=this.duration:this.dt=0;var e=[],i=!1,s=1/t*1e3;do{this.parent.reverse?(this.dt-=s,this.dt=Math.max(this.dt,0)):(this.dt+=s,this.dt=Math.min(this.dt,this.duration)),this.percent=this.dt/this.duration,this.value=this.easingFunction(this.percent);var n={};for(var r in this.vEnd){var o=this.vStart[r],a=this.vEnd[r];Array.isArray(a)?n[r]=this.interpolationFunction(a,this.value):n[r]=o+(a-o)*this.value}e.push(n),(!this.parent.reverse&&1===this.percent||this.parent.reverse&&0===this.percent)&&(i=!0)}while(!i);if(this.yoyo){var h=e.slice();h.reverse(),e=e.concat(h)}return e},repeat:function(){if(this.yoyo){if(this.inReverse&&0===this.repeatCounter){for(var t in this.vStartCache)this.vStart[t]=this.vStartCache[t],this.vEnd[t]=this.vEndCache[t];return this.inReverse=!1,n.TweenData.COMPLETE}this.inReverse=!this.inReverse}else if(0===this.repeatCounter)return n.TweenData.COMPLETE;if(this.inReverse)for(var t in this.vStartCache)this.vStart[t]=this.vEndCache[t],this.vEnd[t]=this.vStartCache[t];else{for(var t in this.vStartCache)this.vStart[t]=this.vStartCache[t],this.vEnd[t]=this.vEndCache[t];this.repeatCounter>0&&this.repeatCounter--}return this.startTime=this.game.time.time,this.yoyo&&this.inReverse?this.startTime+=this.yoyoDelay:this.inReverse||(this.startTime+=this.repeatDelay),this.parent.reverse?this.dt=this.duration:this.dt=0,n.TweenData.LOOPED}},n.TweenData.prototype.constructor=n.TweenData,n.Easing={Linear:{None:function(t){return t}},Quadratic:{In:function(t){return t*t},Out:function(t){return t*(2-t)},InOut:function(t){return(t*=2)<1?.5*t*t:-.5*(--t*(t-2)-1)}},Cubic:{In:function(t){return t*t*t},Out:function(t){return--t*t*t+1},InOut:function(t){return(t*=2)<1?.5*t*t*t:.5*((t-=2)*t*t+2)}},Quartic:{In:function(t){return t*t*t*t},Out:function(t){return 1- --t*t*t*t},InOut:function(t){return(t*=2)<1?.5*t*t*t*t:-.5*((t-=2)*t*t*t-2)}},Quintic:{In:function(t){return t*t*t*t*t},Out:function(t){return--t*t*t*t*t+1},InOut:function(t){return(t*=2)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2)}},Sinusoidal:{In:function(t){return 0===t?0:1===t?1:1-Math.cos(t*Math.PI/2)},Out:function(t){return 0===t?0:1===t?1:Math.sin(t*Math.PI/2)},InOut:function(t){return 0===t?0:1===t?1:.5*(1-Math.cos(Math.PI*t))}},Exponential:{In:function(t){return 0===t?0:Math.pow(1024,t-1)},Out:function(t){return 1===t?1:1-Math.pow(2,-10*t)},InOut:function(t){return 0===t?0:1===t?1:(t*=2)<1?.5*Math.pow(1024,t-1):.5*(2-Math.pow(2,-10*(t-1)))}},Circular:{In:function(t){return 1-Math.sqrt(1-t*t)},Out:function(t){return Math.sqrt(1- --t*t)},InOut:function(t){return(t*=2)<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1)}},Elastic:{In:function(t){var e,i=.1;return 0===t?0:1===t?1:(!i||i<1?(i=1,e=.1):e=.4*Math.asin(1/i)/(2*Math.PI),-i*Math.pow(2,10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4))},Out:function(t){var e,i=.1;return 0===t?0:1===t?1:(!i||i<1?(i=1,e=.1):e=.4*Math.asin(1/i)/(2*Math.PI),i*Math.pow(2,-10*t)*Math.sin((t-e)*(2*Math.PI)/.4)+1)},InOut:function(t){var e,i=.1;return 0===t?0:1===t?1:(!i||i<1?(i=1,e=.1):e=.4*Math.asin(1/i)/(2*Math.PI),(t*=2)<1?i*Math.pow(2,10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4)*-.5:i*Math.pow(2,-10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4)*.5+1)}},Back:{In:function(t){var e=1.70158;return t*t*((e+1)*t-e)},Out:function(t){var e=1.70158;return--t*t*((e+1)*t+e)+1},InOut:function(t){var e=2.5949095;return(t*=2)<1?t*t*((e+1)*t-e)*.5:.5*((t-=2)*t*((e+1)*t+e)+2)}},Bounce:{In:function(t){return 1-n.Easing.Bounce.Out(1-t)},Out:function(t){return t<1/2.75?7.5625*t*t:t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375},InOut:function(t){return t<.5?.5*n.Easing.Bounce.In(2*t):.5*n.Easing.Bounce.Out(2*t-1)+.5}}},n.Easing.Default=n.Easing.Linear.None,n.Easing.Power0=n.Easing.Linear.None,n.Easing.Power1=n.Easing.Quadratic.Out,n.Easing.Power2=n.Easing.Cubic.Out,n.Easing.Power3=n.Easing.Quartic.Out,n.Easing.Power4=n.Easing.Quintic.Out,n.Time=function(t){this.game=t,this.time=0,this.prevTime=0,this.now=0,this.elapsed=0,this.elapsedMS=0,this.physicsElapsed=1/60,this.physicsElapsedMS=1/60*1e3,this.desiredFpsMult=1/60,this._desiredFps=60,this.suggestedFps=this.desiredFps,this.slowMotion=1,this.advancedTiming=!1,this.frames=0,this.fps=0,this.fpsMin=1e3,this.fpsMax=0,this.msMin=1e3,this.msMax=0,this.pauseDuration=0,this.timeToCall=0,this.timeExpected=0,this.events=new n.Timer(this.game,!1),this._frameCount=0,this._elapsedAccumulator=0,this._started=0,this._timeLastSecond=0,this._pauseStarted=0,this._justResumed=!1,this._timers=[]},n.Time.prototype={boot:function(){this._started=Date.now(),this.time=Date.now(),this.events.start(),this.timeExpected=this.time},add:function(t){return this._timers.push(t),t},create:function(t){void 0===t&&(t=!0);var e=new n.Timer(this.game,t);return this._timers.push(e),e},removeAll:function(){for(var t=0;t<this._timers.length;t++)this._timers[t].destroy();this._timers=[],this.events.removeAll()},refresh:function(){var t=this.time;this.time=Date.now(),this.elapsedMS=this.time-t},update:function(t){var e=this.time;this.time=Date.now(),this.elapsedMS=this.time-e,this.prevTime=this.now,this.now=t,this.elapsed=this.now-this.prevTime,this.game.raf._isSetTimeOut&&(this.timeToCall=Math.floor(Math.max(0,1e3/this._desiredFps-(this.timeExpected-t))),this.timeExpected=t+this.timeToCall),this.advancedTiming&&this.updateAdvancedTiming(),this.game.paused||(this.events.update(this.time),this._timers.length&&this.updateTimers())},updateTimers:function(){for(var t=0,e=this._timers.length;t<e;)this._timers[t].update(this.time)?t++:(this._timers.splice(t,1),e--)},updateAdvancedTiming:function(){this._frameCount++,this._elapsedAccumulator+=this.elapsed,this._frameCount>=2*this._desiredFps&&(this.suggestedFps=5*Math.floor(200/(this._elapsedAccumulator/this._frameCount)),this._frameCount=0,this._elapsedAccumulator=0),this.msMin=Math.min(this.msMin,this.elapsed),this.msMax=Math.max(this.msMax,this.elapsed),this.frames++,this.now>this._timeLastSecond+1e3&&(this.fps=Math.round(1e3*this.frames/(this.now-this._timeLastSecond)),this.fpsMin=Math.min(this.fpsMin,this.fps),this.fpsMax=Math.max(this.fpsMax,this.fps),this._timeLastSecond=this.now,this.frames=0)},gamePaused:function(){this._pauseStarted=Date.now(),this.events.pause();for(var t=this._timers.length;t--;)this._timers[t]._pause()},gameResumed:function(){this.time=Date.now(),this.pauseDuration=this.time-this._pauseStarted,this.events.resume();for(var t=this._timers.length;t--;)this._timers[t]._resume()},totalElapsedSeconds:function(){return.001*(this.time-this._started)},elapsedSince:function(t){return this.time-t},elapsedSecondsSince:function(t){return.001*(this.time-t)},reset:function(){this._started=this.time,this.removeAll()}},Object.defineProperty(n.Time.prototype,"desiredFps",{get:function(){return this._desiredFps},set:function(t){this._desiredFps=t,this.physicsElapsed=1/t,this.physicsElapsedMS=1e3*this.physicsElapsed,this.desiredFpsMult=1/t}}),n.Time.prototype.constructor=n.Time,n.Timer=function(t,e){void 0===e&&(e=!0),this.game=t,this.running=!1,this.autoDestroy=e,this.expired=!1,this.elapsed=0,this.events=[],this.onComplete=new n.Signal,this.nextTick=0,this.timeCap=1e3,this.paused=!1,this._codePaused=!1,this._started=0,this._pauseStarted=0,this._pauseTotal=0,this._now=Date.now(),this._len=0,this._marked=0,this._i=0,this._diff=0,this._newTick=0},n.Timer.MINUTE=6e4,n.Timer.SECOND=1e3,n.Timer.HALF=500,n.Timer.QUARTER=250,n.Timer.prototype={create:function(t,e,i,s,r,o){t=Math.round(t);var a=t;0===this._now?a+=this.game.time.time:a+=this._now;var h=new n.TimerEvent(this,t,a,i,e,s,r,o);return this.events.push(h),this.order(),this.expired=!1,h},add:function(t,e,i){return this.create(t,!1,0,e,i,Array.prototype.slice.call(arguments,3))},repeat:function(t,e,i,s){return this.create(t,!1,e,i,s,Array.prototype.slice.call(arguments,4))},loop:function(t,e,i){return this.create(t,!0,0,e,i,Array.prototype.slice.call(arguments,3))},start:function(t){if(!this.running){this._started=this.game.time.time+(t||0),this.running=!0;for(var e=0;e<this.events.length;e++)this.events[e].tick=this.events[e].delay+this._started}},stop:function(t){this.running=!1,void 0===t&&(t=!0),t&&(this.events.length=0)},remove:function(t){for(var e=0;e<this.events.length;e++)if(this.events[e]===t)return this.events[e].pendingDelete=!0,!0;return!1},order:function(){this.events.length>0&&(this.events.sort(this.sortHandler),this.nextTick=this.events[0].tick)},sortHandler:function(t,e){return t.tick<e.tick?-1:t.tick>e.tick?1:0},clearPendingEvents:function(){for(this._i=this.events.length;this._i--;)this.events[this._i].pendingDelete&&this.events.splice(this._i,1);this._len=this.events.length,this._i=0},update:function(t){if(this.paused)return!0;if(this.elapsed=t-this._now,this._now=t,this.elapsed>this.timeCap&&this.adjustEvents(t-this.elapsed),this._marked=0,this.clearPendingEvents(),this.running&&this._now>=this.nextTick&&this._len>0){for(;this._i<this._len&&this.running&&this._now>=this.events[this._i].tick&&!this.events[this._i].pendingDelete;)this._newTick=this._now+this.events[this._i].delay-(this._now-this.events[this._i].tick),this._newTick<0&&(this._newTick=this._now+this.events[this._i].delay),!0===this.events[this._i].loop?(this.events[this._i].tick=this._newTick,this.events[this._i].callback.apply(this.events[this._i].callbackContext,this.events[this._i].args)):this.events[this._i].repeatCount>0?(this.events[this._i].repeatCount--,this.events[this._i].tick=this._newTick,this.events[this._i].callback.apply(this.events[this._i].callbackContext,this.events[this._i].args)):(this._marked++,this.events[this._i].pendingDelete=!0,this.events[this._i].callback.apply(this.events[this._i].callbackContext,this.events[this._i].args)),this._i++;this.events.length>this._marked?this.order():(this.expired=!0,this.onComplete.dispatch(this))}return!this.expired||!this.autoDestroy},pause:function(){this.running&&(this._codePaused=!0,this.paused||(this._pauseStarted=this.game.time.time,this.paused=!0))},_pause:function(){!this.paused&&this.running&&(this._pauseStarted=this.game.time.time,this.paused=!0)},adjustEvents:function(t){for(var e=0;e<this.events.length;e++)if(!this.events[e].pendingDelete){var i=this.events[e].tick-t;i<0&&(i=0),this.events[e].tick=this._now+i}var s=this.nextTick-t;this.nextTick=s<0?this._now:this._now+s},resume:function(){if(this.paused){var t=this.game.time.time;this._pauseTotal+=t-this._now,this._now=t,this.adjustEvents(this._pauseStarted),this.paused=!1,this._codePaused=!1}},_resume:function(){this._codePaused||this.resume()},removeAll:function(){this.onComplete.removeAll(),this.events.length=0,this._len=0,this._i=0},destroy:function(){this.onComplete.removeAll(),this.running=!1,this.events=[],this._len=0,this._i=0}},Object.defineProperty(n.Timer.prototype,"next",{get:function(){return this.nextTick}}),Object.defineProperty(n.Timer.prototype,"duration",{get:function(){return this.running&&this.nextTick>this._now?this.nextTick-this._now:0}}),Object.defineProperty(n.Timer.prototype,"length",{get:function(){return this.events.length}}),Object.defineProperty(n.Timer.prototype,"ms",{get:function(){return this.running?this._now-this._started-this._pauseTotal:0}}),Object.defineProperty(n.Timer.prototype,"seconds",{get:function(){return this.running?.001*this.ms:0}}),n.Timer.prototype.constructor=n.Timer,n.TimerEvent=function(t,e,i,s,n,r,o,a){this.timer=t,this.delay=e,this.tick=i,this.repeatCount=s-1,this.loop=n,this.callback=r,this.callbackContext=o,this.args=a,this.pendingDelete=!1},n.TimerEvent.prototype.constructor=n.TimerEvent,n.AnimationManager=function(t){this.sprite=t,this.game=t.game,this.currentFrame=null,this.currentAnim=null,this.updateIfVisible=!0,this.isLoaded=!1,this._frameData=null,this._anims={},this._outputFrames=[]},n.AnimationManager.prototype={loadFrameData:function(t,e){if(void 0===t)return!1;if(this.isLoaded)for(var i in this._anims)this._anims[i].updateFrameData(t);return this._frameData=t,void 0===e||null===e?this.frame=0:"string"==typeof e?this.frameName=e:this.frame=e,this.isLoaded=!0,!0},copyFrameData:function(t,e){if(this._frameData=t.clone(),this.isLoaded)for(var i in this._anims)this._anims[i].updateFrameData(this._frameData);return void 0===e||null===e?this.frame=0:"string"==typeof e?this.frameName=e:this.frame=e,this.isLoaded=!0,!0},add:function(t,e,i,s,r){return e=e||[],i=i||60,void 0===s&&(s=!1),void 0===r&&(r=!(!e||"number"!=typeof e[0])),this._outputFrames=[],this._frameData.getFrameIndexes(e,r,this._outputFrames),this._anims[t]=new n.Animation(this.game,this.sprite,t,this._frameData,this._outputFrames,i,s),this.currentAnim=this._anims[t],this.sprite.tilingTexture&&(this.sprite.refreshTexture=!0),this._anims[t]},validateFrames:function(t,e){void 0===e&&(e=!0);for(var i=0;i<t.length;i++)if(!0===e){if(t[i]>this._frameData.total)return!1}else if(!1===this._frameData.checkFrameName(t[i]))return!1;return!0},play:function(t,e,i,s){if(this._anims[t])return this.currentAnim===this._anims[t]?!1===this.currentAnim.isPlaying?(this.currentAnim.paused=!1,this.currentAnim.play(e,i,s)):this.currentAnim:(this.currentAnim&&this.currentAnim.isPlaying&&this.currentAnim.stop(),this.currentAnim=this._anims[t],this.currentAnim.paused=!1,this.currentFrame=this.currentAnim.currentFrame,this.currentAnim.play(e,i,s))},stop:function(t,e){void 0===e&&(e=!1),!this.currentAnim||"string"==typeof t&&t!==this.currentAnim.name||this.currentAnim.stop(e)},update:function(){return!(this.updateIfVisible&&!this.sprite.visible)&&(!(!this.currentAnim||!this.currentAnim.update())&&(this.currentFrame=this.currentAnim.currentFrame,!0))},next:function(t){this.currentAnim&&(this.currentAnim.next(t),this.currentFrame=this.currentAnim.currentFrame)},previous:function(t){this.currentAnim&&(this.currentAnim.previous(t),this.currentFrame=this.currentAnim.currentFrame)},getAnimation:function(t){return"string"==typeof t&&this._anims[t]?this._anims[t]:null},refreshFrame:function(){},destroy:function(){var t=null;for(var t in this._anims)this._anims.hasOwnProperty(t)&&this._anims[t].destroy();this._anims={},this._outputFrames=[],this._frameData=null,this.currentAnim=null,this.currentFrame=null,this.sprite=null,this.game=null}},n.AnimationManager.prototype.constructor=n.AnimationManager,Object.defineProperty(n.AnimationManager.prototype,"frameData",{get:function(){return this._frameData}}),Object.defineProperty(n.AnimationManager.prototype,"frameTotal",{get:function(){return this._frameData.total}}),Object.defineProperty(n.AnimationManager.prototype,"paused",{get:function(){return this.currentAnim.isPaused},set:function(t){this.currentAnim.paused=t}}),Object.defineProperty(n.AnimationManager.prototype,"name",{get:function(){if(this.currentAnim)return this.currentAnim.name}}),Object.defineProperty(n.AnimationManager.prototype,"frame",{get:function(){if(this.currentFrame)return this.currentFrame.index},set:function(t){"number"==typeof t&&this._frameData&&null!==this._frameData.getFrame(t)&&(this.currentFrame=this._frameData.getFrame(t),this.currentFrame&&this.sprite.setFrame(this.currentFrame))}}),Object.defineProperty(n.AnimationManager.prototype,"frameName",{get:function(){if(this.currentFrame)return this.currentFrame.name},set:function(t){"string"==typeof t&&this._frameData&&null!==this._frameData.getFrameByName(t)?(this.currentFrame=this._frameData.getFrameByName(t),this.currentFrame&&(this._frameIndex=this.currentFrame.index,this.sprite.setFrame(this.currentFrame))):console.warn("Cannot set frameName: "+t)}}),n.Animation=function(t,e,i,s,r,o,a){void 0===a&&(a=!1),this.game=t,this._parent=e,this._frameData=s,this.name=i,this._frames=[],this._frames=this._frames.concat(r),this.delay=1e3/o,this.loop=a,this.loopCount=0,this.killOnComplete=!1,this.isFinished=!1,this.isPlaying=!1,this.isPaused=!1,this._pauseStartTime=0,this._frameIndex=0,this._frameDiff=0,this._frameSkip=1,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.onStart=new n.Signal,this.onUpdate=null,this.onComplete=new n.Signal,this.onLoop=new n.Signal,this.isReversed=!1,this.game.onPause.add(this.onPause,this),this.game.onResume.add(this.onResume,this)},n.Animation.prototype={play:function(t,e,i){return"number"==typeof t&&(this.delay=1e3/t),"boolean"==typeof e&&(this.loop=e),void 0!==i&&(this.killOnComplete=i),this.isPlaying=!0,this.isFinished=!1,this.paused=!1,this.loopCount=0,this._timeLastFrame=this.game.time.time,this._timeNextFrame=this.game.time.time+this.delay,this._frameIndex=this.isReversed?this._frames.length-1:0,this.updateCurrentFrame(!1,!0),this._parent.events.onAnimationStart$dispatch(this._parent,this),this.onStart.dispatch(this._parent,this),this._parent.animations.currentAnim=this,this._parent.animations.currentFrame=this.currentFrame,this},restart:function(){this.isPlaying=!0,this.isFinished=!1,this.paused=!1,this.loopCount=0,this._timeLastFrame=this.game.time.time,this._timeNextFrame=this.game.time.time+this.delay,this._frameIndex=0,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this._parent.setFrame(this.currentFrame),this._parent.animations.currentAnim=this,this._parent.animations.currentFrame=this.currentFrame,this.onStart.dispatch(this._parent,this)},reverse:function(){return this.reversed=!this.reversed,this},reverseOnce:function(){return this.onComplete.addOnce(this.reverse,this),this.reverse()},setFrame:function(t,e){var i;if(void 0===e&&(e=!1),"string"==typeof t)for(var s=0;s<this._frames.length;s++)this._frameData.getFrame(this._frames[s]).name===t&&(i=s);else if("number"==typeof t)if(e)i=t;else for(var s=0;s<this._frames.length;s++)this._frames[s]===t&&(i=s);i&&(this._frameIndex=i-1,this._timeNextFrame=this.game.time.time,this.update())},stop:function(t,e){void 0===t&&(t=!1),void 0===e&&(e=!1),this.isPlaying=!1,this.isFinished=!0,this.paused=!1,t&&(this.currentFrame=this._frameData.getFrame(this._frames[0]),this._parent.setFrame(this.currentFrame)),e&&(this._parent.events.onAnimationComplete$dispatch(this._parent,this),this.onComplete.dispatch(this._parent,this))},onPause:function(){this.isPlaying&&(this._frameDiff=this._timeNextFrame-this.game.time.time)},onResume:function(){this.isPlaying&&(this._timeNextFrame=this.game.time.time+this._frameDiff)},update:function(){return!this.isPaused&&(!!(this.isPlaying&&this.game.time.time>=this._timeNextFrame)&&(this._frameSkip=1,this._frameDiff=this.game.time.time-this._timeNextFrame,this._timeLastFrame=this.game.time.time,this._frameDiff>this.delay&&(this._frameSkip=Math.floor(this._frameDiff/this.delay),this._frameDiff-=this._frameSkip*this.delay),this._timeNextFrame=this.game.time.time+(this.delay-this._frameDiff),this.isReversed?this._frameIndex-=this._frameSkip:this._frameIndex+=this._frameSkip,!this.isReversed&&this._frameIndex>=this._frames.length||this.isReversed&&this._frameIndex<=-1?this.loop?(this._frameIndex=Math.abs(this._frameIndex)%this._frames.length,this.isReversed&&(this._frameIndex=this._frames.length-1-this._frameIndex),this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.currentFrame&&this._parent.setFrame(this.currentFrame),this.loopCount++,this._parent.events.onAnimationLoop$dispatch(this._parent,this),this.onLoop.dispatch(this._parent,this),!this.onUpdate||(this.onUpdate.dispatch(this,this.currentFrame),!!this._frameData)):(this.complete(),!1):this.updateCurrentFrame(!0)))},updateCurrentFrame:function(t,e){if(void 0===e&&(e=!1),!this._frameData)return!1;var i=this.currentFrame.index;return this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.currentFrame&&(e||!e&&i!==this.currentFrame.index)&&this._parent.setFrame(this.currentFrame),!this.onUpdate||!t||(this.onUpdate.dispatch(this,this.currentFrame),!!this._frameData)},next:function(t){void 0===t&&(t=1);var e=this._frameIndex+t;e>=this._frames.length&&(this.loop?e%=this._frames.length:e=this._frames.length-1),e!==this._frameIndex&&(this._frameIndex=e,this.updateCurrentFrame(!0))},previous:function(t){void 0===t&&(t=1);var e=this._frameIndex-t;e<0&&(this.loop?e=this._frames.length+e:e++),e!==this._frameIndex&&(this._frameIndex=e,this.updateCurrentFrame(!0))},updateFrameData:function(t){this._frameData=t,this.currentFrame=this._frameData?this._frameData.getFrame(this._frames[this._frameIndex%this._frames.length]):null},destroy:function(){this._frameData&&(this.game.onPause.remove(this.onPause,this),this.game.onResume.remove(this.onResume,this),this.game=null,this._parent=null,this._frames=null,this._frameData=null,this.currentFrame=null,this.isPlaying=!1,this.onStart.dispose(),this.onLoop.dispose(),this.onComplete.dispose(),this.onUpdate&&this.onUpdate.dispose())},complete:function(){this._frameIndex=this._frames.length-1,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.isPlaying=!1,this.isFinished=!0,this.paused=!1,this._parent.events.onAnimationComplete$dispatch(this._parent,this),this.onComplete.dispatch(this._parent,this),this.killOnComplete&&this._parent.kill()}},n.Animation.prototype.constructor=n.Animation,Object.defineProperty(n.Animation.prototype,"paused",{get:function(){return this.isPaused},set:function(t){this.isPaused=t,t?this._pauseStartTime=this.game.time.time:this.isPlaying&&(this._timeNextFrame=this.game.time.time+this.delay)}}),Object.defineProperty(n.Animation.prototype,"reversed",{get:function(){return this.isReversed},set:function(t){this.isReversed=t}}),Object.defineProperty(n.Animation.prototype,"frameTotal",{get:function(){return this._frames.length}}),Object.defineProperty(n.Animation.prototype,"frame",{get:function(){return null!==this.currentFrame?this.currentFrame.index:this._frameIndex},set:function(t){this.currentFrame=this._frameData.getFrame(this._frames[t]),null!==this.currentFrame&&(this._frameIndex=t,this._parent.setFrame(this.currentFrame),this.onUpdate&&this.onUpdate.dispatch(this,this.currentFrame))}}),Object.defineProperty(n.Animation.prototype,"speed",{get:function(){return 1e3/this.delay},set:function(t){t>0&&(this.delay=1e3/t)}}),Object.defineProperty(n.Animation.prototype,"enableUpdate",{get:function(){return null!==this.onUpdate},set:function(t){t&&null===this.onUpdate?this.onUpdate=new n.Signal:t||null===this.onUpdate||(this.onUpdate.dispose(),this.onUpdate=null)}}),n.Animation.generateFrameNames=function(t,e,i,s,r){void 0===s&&(s="");var o=[],a="";if(e<i)for(var h=e;h<=i;h++)a="number"==typeof r?n.Utils.pad(h.toString(),r,"0",1):h.toString(),a=t+a+s,o.push(a);else for(var h=e;h>=i;h--)a="number"==typeof r?n.Utils.pad(h.toString(),r,"0",1):h.toString(),a=t+a+s,o.push(a);return o},n.Frame=function(t,e,i,s,r,o){this.index=t,this.x=e,this.y=i,this.width=s,this.height=r,this.name=o,this.centerX=Math.floor(s/2),this.centerY=Math.floor(r/2),this.distance=n.Math.distance(0,0,s,r),this.rotated=!1,this.rotationDirection="cw",this.trimmed=!1,this.sourceSizeW=s,this.sourceSizeH=r,this.spriteSourceSizeX=0,this.spriteSourceSizeY=0,this.spriteSourceSizeW=0,this.spriteSourceSizeH=0,this.right=this.x+this.width,this.bottom=this.y+this.height},n.Frame.prototype={resize:function(t,e){this.width=t,this.height=e,this.centerX=Math.floor(t/2),this.centerY=Math.floor(e/2),this.distance=n.Math.distance(0,0,t,e),this.sourceSizeW=t,this.sourceSizeH=e,this.right=this.x+t,this.bottom=this.y+e},setTrim:function(t,e,i,s,n,r,o){this.trimmed=t,t&&(this.sourceSizeW=e,this.sourceSizeH=i,this.centerX=Math.floor(e/2),this.centerY=Math.floor(i/2),this.spriteSourceSizeX=s,this.spriteSourceSizeY=n,this.spriteSourceSizeW=r,this.spriteSourceSizeH=o)},clone:function(){var t=new n.Frame(this.index,this.x,this.y,this.width,this.height,this.name);for(var e in this)this.hasOwnProperty(e)&&(t[e]=this[e]);return t},getRect:function(t){return void 0===t?t=new n.Rectangle(this.x,this.y,this.width,this.height):t.setTo(this.x,this.y,this.width,this.height),t}},n.Frame.prototype.constructor=n.Frame,n.FrameData=function(){this._frames=[],this._frameNames=[]},n.FrameData.prototype={addFrame:function(t){return t.index=this._frames.length,this._frames.push(t),""!==t.name&&(this._frameNames[t.name]=t.index),t},getFrame:function(t){return t>=this._frames.length&&(t=0),this._frames[t]},getFrameByName:function(t){return"number"==typeof this._frameNames[t]?this._frames[this._frameNames[t]]:null},checkFrameName:function(t){return null!=this._frameNames[t]},clone:function(){for(var t=new n.FrameData,e=0;e<this._frames.length;e++)t._frames.push(this._frames[e].clone());for(var i in this._frameNames)this._frameNames.hasOwnProperty(i)&&t._frameNames.push(this._frameNames[i]);return t},getFrameRange:function(t,e,i){void 0===i&&(i=[]);for(var s=t;s<=e;s++)i.push(this._frames[s]);return i},getFrames:function(t,e,i){if(void 0===e&&(e=!0),void 0===i&&(i=[]),void 0===t||0===t.length)for(var s=0;s<this._frames.length;s++)i.push(this._frames[s]);else for(var s=0;s<t.length;s++)e?i.push(this.getFrame(t[s])):i.push(this.getFrameByName(t[s]));return i},getFrameIndexes:function(t,e,i){if(void 0===e&&(e=!0),void 0===i&&(i=[]),void 0===t||0===t.length)for(var s=0;s<this._frames.length;s++)i.push(this._frames[s].index);else for(var s=0;s<t.length;s++)e&&this._frames[t[s]]?i.push(this._frames[t[s]].index):this.getFrameByName(t[s])&&i.push(this.getFrameByName(t[s]).index);return i},destroy:function(){this._frames=null,this._frameNames=null}},n.FrameData.prototype.constructor=n.FrameData,Object.defineProperty(n.FrameData.prototype,"total",{get:function(){return this._frames.length}}),n.AnimationParser={spriteSheet:function(t,e,i,s,r,o,a){var h=e;if("string"==typeof e&&(h=t.cache.getImage(e)),null===h)return null;var l=h.width,c=h.height;i<=0&&(i=Math.floor(-l/Math.min(-1,i))),s<=0&&(s=Math.floor(-c/Math.min(-1,s)));var u=Math.floor((l-o)/(i+a)),d=Math.floor((c-o)/(s+a)),p=u*d;if(-1!==r&&(p=r),0===l||0===c||l<i||c<s||0===p)return console.warn("Phaser.AnimationParser.spriteSheet: '"+e+"'s width/height zero or width/height < given frameWidth/frameHeight"),null;for(var f=new n.FrameData,g=o,m=o,y=0;y<p;y++)f.addFrame(new n.Frame(y,g,m,i,s,"")),(g+=i+a)+i>l&&(g=o,m+=s+a);return f},JSONData:function(t,e){if(!e.frames)return console.warn("Phaser.AnimationParser.JSONData: Invalid Texture Atlas JSON given, missing 'frames' array"),void console.log(e);for(var i,s=new n.FrameData,r=e.frames,o=0;o<r.length;o++)i=s.addFrame(new n.Frame(o,r[o].frame.x,r[o].frame.y,r[o].frame.w,r[o].frame.h,r[o].filename)),r[o].trimmed&&i.setTrim(r[o].trimmed,r[o].sourceSize.w,r[o].sourceSize.h,r[o].spriteSourceSize.x,r[o].spriteSourceSize.y,r[o].spriteSourceSize.w,r[o].spriteSourceSize.h);return s},JSONDataPyxel:function(t,e){if(["layers","tilewidth","tileheight","tileswide","tileshigh"].forEach(function(t){if(!e[t])return console.warn('Phaser.AnimationParser.JSONDataPyxel: Invalid Pyxel Tilemap JSON given, missing "'+t+'" key.'),void console.log(e)}),1!==e.layers.length)return console.warn("Phaser.AnimationParser.JSONDataPyxel: Too many layers, this parser only supports flat Tilemaps."),void console.log(e);for(var i,s=new n.FrameData,r=e.tileheight,o=e.tilewidth,a=e.layers[0].tiles,h=0;h<a.length;h++)i=s.addFrame(new n.Frame(h,a[h].x,a[h].y,o,r,"frame_"+h)),i.setTrim(!1);return s},JSONDataHash:function(t,e){if(!e.frames)return console.warn("Phaser.AnimationParser.JSONDataHash: Invalid Texture Atlas JSON given, missing 'frames' object"),void console.log(e);var i,s=new n.FrameData,r=e.frames,o=0;for(var a in r)i=s.addFrame(new n.Frame(o,r[a].frame.x,r[a].frame.y,r[a].frame.w,r[a].frame.h,a)),r[a].trimmed&&i.setTrim(r[a].trimmed,r[a].sourceSize.w,r[a].sourceSize.h,r[a].spriteSourceSize.x,r[a].spriteSourceSize.y,r[a].spriteSourceSize.w,r[a].spriteSourceSize.h),o++;return s},XMLData:function(t,e){if(!e.getElementsByTagName("TextureAtlas"))return void console.warn("Phaser.AnimationParser.XMLData: Invalid Texture Atlas XML given, missing <TextureAtlas> tag");for(var i,s,r,o,a,h,l,c,u,d,p,f=new n.FrameData,g=e.getElementsByTagName("SubTexture"),m=0;m<g.length;m++)r=g[m].attributes,s=r.name.value,o=parseInt(r.x.value,10),a=parseInt(r.y.value,10),h=parseInt(r.width.value,10),l=parseInt(r.height.value,10),c=null,u=null,r.frameX&&(c=Math.abs(parseInt(r.frameX.value,10)),u=Math.abs(parseInt(r.frameY.value,10)),d=parseInt(r.frameWidth.value,10),p=parseInt(r.frameHeight.value,10)),i=f.addFrame(new n.Frame(m,o,a,h,l,s)),null===c&&null===u||i.setTrim(!0,h,l,c,u,d,p);return f}},n.Cache=function(t){this.game=t,this.autoResolveURL=!1,this._cache={canvas:{},image:{},texture:{},sound:{},video:{},text:{},json:{},xml:{},physics:{},tilemap:{},binary:{},bitmapData:{},bitmapFont:{},shader:{},renderTexture:{}},this._urlMap={},this._urlResolver=new Image,this._urlTemp=null,this.onSoundUnlock=new n.Signal,this._cacheMap=[],this._cacheMap[n.Cache.CANVAS]=this._cache.canvas,this._cacheMap[n.Cache.IMAGE]=this._cache.image,this._cacheMap[n.Cache.TEXTURE]=this._cache.texture,this._cacheMap[n.Cache.SOUND]=this._cache.sound,this._cacheMap[n.Cache.TEXT]=this._cache.text,this._cacheMap[n.Cache.PHYSICS]=this._cache.physics,this._cacheMap[n.Cache.TILEMAP]=this._cache.tilemap,this._cacheMap[n.Cache.BINARY]=this._cache.binary,this._cacheMap[n.Cache.BITMAPDATA]=this._cache.bitmapData,this._cacheMap[n.Cache.BITMAPFONT]=this._cache.bitmapFont,this._cacheMap[n.Cache.JSON]=this._cache.json,this._cacheMap[n.Cache.XML]=this._cache.xml,this._cacheMap[n.Cache.VIDEO]=this._cache.video,this._cacheMap[n.Cache.SHADER]=this._cache.shader,this._cacheMap[n.Cache.RENDER_TEXTURE]=this._cache.renderTexture,this.addDefaultImage(),this.addMissingImage()},n.Cache.CANVAS=1,n.Cache.IMAGE=2,n.Cache.TEXTURE=3,n.Cache.SOUND=4,n.Cache.TEXT=5,n.Cache.PHYSICS=6,n.Cache.TILEMAP=7,n.Cache.BINARY=8,n.Cache.BITMAPDATA=9,n.Cache.BITMAPFONT=10,n.Cache.JSON=11,n.Cache.XML=12,n.Cache.VIDEO=13,n.Cache.SHADER=14,n.Cache.RENDER_TEXTURE=15,n.Cache.DEFAULT=null,n.Cache.MISSING=null,n.Cache.prototype={addCanvas:function(t,e,i){void 0===i&&(i=e.getContext("2d")),this._cache.canvas[t]={canvas:e,context:i}},addImage:function(t,e,i){this.checkImageKey(t)&&this.removeImage(t);var s={key:t,url:e,data:i,base:new PIXI.BaseTexture(i),frame:new n.Frame(0,0,0,i.width,i.height,t),frameData:new n.FrameData};return s.frameData.addFrame(new n.Frame(0,0,0,i.width,i.height,e)),this._cache.image[t]=s,this._resolveURL(e,s),"__default"===t?n.Cache.DEFAULT=new PIXI.Texture(s.base):"__missing"===t&&(n.Cache.MISSING=new PIXI.Texture(s.base)),s},addDefaultImage:function(){var t=new Image;t.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgAQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg==";var e=this.addImage("__default",null,t);e.base.skipRender=!0,n.Cache.DEFAULT=new PIXI.Texture(e.base)},addMissingImage:function(){var t=new Image;t.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg==";var e=this.addImage("__missing",null,t);n.Cache.MISSING=new PIXI.Texture(e.base)},addSound:function(t,e,i,s,n){void 0===s&&(s=!0,n=!1),void 0===n&&(s=!1,n=!0);var r=!1;n&&(r=!0),this._cache.sound[t]={url:e,data:i,isDecoding:!1,decoded:r,webAudio:s,audioTag:n,locked:this.game.sound.touchLocked},this._resolveURL(e,this._cache.sound[t])},addText:function(t,e,i){this._cache.text[t]={url:e,data:i},this._resolveURL(e,this._cache.text[t])},addPhysicsData:function(t,e,i,s){this._cache.physics[t]={url:e,data:i,format:s},this._resolveURL(e,this._cache.physics[t])},addTilemap:function(t,e,i,s){this._cache.tilemap[t]={url:e,data:i,format:s},this._resolveURL(e,this._cache.tilemap[t])},addBinary:function(t,e){this._cache.binary[t]=e},addBitmapData:function(t,e,i){return e.key=t,void 0===i&&(i=new n.FrameData,i.addFrame(e.textureFrame)),this._cache.bitmapData[t]={data:e,frameData:i},e},addBitmapFont:function(t,e,i,s,r,o,a){var h={url:e,data:i,font:null,base:new PIXI.BaseTexture(i)};void 0===o&&(o=0),void 0===a&&(a=0),h.font="json"===r?n.LoaderParser.jsonBitmapFont(s,h.base,o,a):n.LoaderParser.xmlBitmapFont(s,h.base,o,a),this._cache.bitmapFont[t]=h,this._resolveURL(e,h)},addJSON:function(t,e,i){this._cache.json[t]={url:e,data:i},this._resolveURL(e,this._cache.json[t])},addXML:function(t,e,i){this._cache.xml[t]={url:e,data:i},this._resolveURL(e,this._cache.xml[t])},addVideo:function(t,e,i,s){this._cache.video[t]={url:e,data:i,isBlob:s,locked:!0},this._resolveURL(e,this._cache.video[t])},addShader:function(t,e,i){this._cache.shader[t]={url:e,data:i},this._resolveURL(e,this._cache.shader[t])},addRenderTexture:function(t,e){this._cache.renderTexture[t]={texture:e,frame:new n.Frame(0,0,0,e.width,e.height,"","")}},addSpriteSheet:function(t,e,i,s,r,o,a,h){void 0===o&&(o=-1),void 0===a&&(a=0),void 0===h&&(h=0);var l={key:t,url:e,data:i,frameWidth:s,frameHeight:r,margin:a,spacing:h,base:new PIXI.BaseTexture(i),frameData:n.AnimationParser.spriteSheet(this.game,i,s,r,o,a,h)};this._cache.image[t]=l,this._resolveURL(e,l)},addTextureAtlas:function(t,e,i,s,r){var o={key:t,url:e,data:i,base:new PIXI.BaseTexture(i)};r===n.Loader.TEXTURE_ATLAS_XML_STARLING?o.frameData=n.AnimationParser.XMLData(this.game,s,t):r===n.Loader.TEXTURE_ATLAS_JSON_PYXEL?o.frameData=n.AnimationParser.JSONDataPyxel(this.game,s,t):Array.isArray(s.frames)?o.frameData=n.AnimationParser.JSONData(this.game,s,t):o.frameData=n.AnimationParser.JSONDataHash(this.game,s,t),this._cache.image[t]=o,this._resolveURL(e,o)},reloadSound:function(t){var e=this,i=this.getSound(t);i&&(i.data.src=i.url,i.data.addEventListener("canplaythrough",function(){return e.reloadSoundComplete(t)},!1),i.data.load())},reloadSoundComplete:function(t){var e=this.getSound(t);e&&(e.locked=!1,this.onSoundUnlock.dispatch(t))},updateSound:function(t,e,i){var s=this.getSound(t);s&&(s[e]=i)},decodedSound:function(t,e){var i=this.getSound(t);i.data=e,i.decoded=!0,i.isDecoding=!1},isSoundDecoded:function(t){var e=this.getItem(t,n.Cache.SOUND,"isSoundDecoded");if(e)return e.decoded},isSoundReady:function(t){var e=this.getItem(t,n.Cache.SOUND,"isSoundDecoded");if(e)return e.decoded&&!this.game.sound.touchLocked},checkKey:function(t,e){return!!this._cacheMap[t][e]},checkURL:function(t){return!!this._urlMap[this._resolveURL(t)]},checkCanvasKey:function(t){return this.checkKey(n.Cache.CANVAS,t)},checkImageKey:function(t){return this.checkKey(n.Cache.IMAGE,t)},checkTextureKey:function(t){return this.checkKey(n.Cache.TEXTURE,t)},checkSoundKey:function(t){return this.checkKey(n.Cache.SOUND,t)},checkTextKey:function(t){return this.checkKey(n.Cache.TEXT,t)},checkPhysicsKey:function(t){return this.checkKey(n.Cache.PHYSICS,t)},checkTilemapKey:function(t){return this.checkKey(n.Cache.TILEMAP,t)},checkBinaryKey:function(t){return this.checkKey(n.Cache.BINARY,t)},checkBitmapDataKey:function(t){return this.checkKey(n.Cache.BITMAPDATA,t)},checkBitmapFontKey:function(t){return this.checkKey(n.Cache.BITMAPFONT,t)},checkJSONKey:function(t){return this.checkKey(n.Cache.JSON,t)},checkXMLKey:function(t){return this.checkKey(n.Cache.XML,t)},checkVideoKey:function(t){return this.checkKey(n.Cache.VIDEO,t)},checkShaderKey:function(t){return this.checkKey(n.Cache.SHADER,t)},checkRenderTextureKey:function(t){return this.checkKey(n.Cache.RENDER_TEXTURE,t)},getItem:function(t,e,i,s){return this.checkKey(e,t)?void 0===s?this._cacheMap[e][t]:this._cacheMap[e][t][s]:(i&&console.warn("Phaser.Cache."+i+': Key "'+t+'" not found in Cache.'),null)},getCanvas:function(t){return this.getItem(t,n.Cache.CANVAS,"getCanvas","canvas")},getImage:function(t,e){void 0!==t&&null!==t||(t="__default"),void 0===e&&(e=!1);var i=this.getItem(t,n.Cache.IMAGE,"getImage");return null===i&&(i=this.getItem("__missing",n.Cache.IMAGE,"getImage")),e?i:i.data},getTextureFrame:function(t){return this.getItem(t,n.Cache.TEXTURE,"getTextureFrame","frame")},getSound:function(t){return this.getItem(t,n.Cache.SOUND,"getSound")},getSoundData:function(t){return this.getItem(t,n.Cache.SOUND,"getSoundData","data")},getText:function(t){return this.getItem(t,n.Cache.TEXT,"getText","data")},getPhysicsData:function(t,e,i){var s=this.getItem(t,n.Cache.PHYSICS,"getPhysicsData","data");if(null===s||void 0===e||null===e)return s;if(s[e]){var r=s[e];if(!r||!i)return r;for(var o in r)if(o=r[o],o.fixtureKey===i)return o;console.warn('Phaser.Cache.getPhysicsData: Could not find given fixtureKey: "'+i+" in "+t+'"')}else console.warn('Phaser.Cache.getPhysicsData: Invalid key/object: "'+t+" / "+e+'"');return null},getTilemapData:function(t){return this.getItem(t,n.Cache.TILEMAP,"getTilemapData")},getBinary:function(t){return this.getItem(t,n.Cache.BINARY,"getBinary")},getBitmapData:function(t){return this.getItem(t,n.Cache.BITMAPDATA,"getBitmapData","data")},getBitmapFont:function(t){return this.getItem(t,n.Cache.BITMAPFONT,"getBitmapFont")},getJSON:function(t,e){var i=this.getItem(t,n.Cache.JSON,"getJSON","data");return i?e?n.Utils.extend(!0,Array.isArray(i)?[]:{},i):i:null},getXML:function(t){return this.getItem(t,n.Cache.XML,"getXML","data")},getVideo:function(t){return this.getItem(t,n.Cache.VIDEO,"getVideo")},getShader:function(t){return this.getItem(t,n.Cache.SHADER,"getShader","data")},getRenderTexture:function(t){return this.getItem(t,n.Cache.RENDER_TEXTURE,"getRenderTexture")},getBaseTexture:function(t,e){return void 0===e&&(e=n.Cache.IMAGE),this.getItem(t,e,"getBaseTexture","base")},getFrame:function(t,e){return void 0===e&&(e=n.Cache.IMAGE),this.getItem(t,e,"getFrame","frame")},getFrameCount:function(t,e){var i=this.getFrameData(t,e);return i?i.total:0},getFrameData:function(t,e){return void 0===e&&(e=n.Cache.IMAGE),this.getItem(t,e,"getFrameData","frameData")},hasFrameData:function(t,e){return void 0===e&&(e=n.Cache.IMAGE),null!==this.getItem(t,e,"","frameData")},updateFrameData:function(t,e,i){void 0===i&&(i=n.Cache.IMAGE),this._cacheMap[i][t]&&(this._cacheMap[i][t].frameData=e)},getFrameByIndex:function(t,e,i){var s=this.getFrameData(t,i);return s?s.getFrame(e):null},getFrameByName:function(t,e,i){var s=this.getFrameData(t,i);return s?s.getFrameByName(e):null},getURL:function(t){var t=this._resolveURL(t);return t?this._urlMap[t]:(console.warn('Phaser.Cache.getUrl: Invalid url: "'+t+'" or Cache.autoResolveURL was false'),null)},getKeys:function(t){void 0===t&&(t=n.Cache.IMAGE);var e=[];if(this._cacheMap[t])for(var i in this._cacheMap[t])"__default"!==i&&"__missing"!==i&&e.push(i);return e},removeCanvas:function(t){delete this._cache.canvas[t]},removeImage:function(t,e){void 0===e&&(e=!0);var i=this.getImage(t,!0);e&&i.base&&i.base.destroy(),delete this._cache.image[t]},removeSound:function(t){delete this._cache.sound[t]},removeText:function(t){delete this._cache.text[t]},removePhysics:function(t){delete this._cache.physics[t]},removeTilemap:function(t){delete this._cache.tilemap[t]},removeBinary:function(t){delete this._cache.binary[t]},removeBitmapData:function(t){delete this._cache.bitmapData[t]},removeBitmapFont:function(t){delete this._cache.bitmapFont[t]},removeJSON:function(t){delete this._cache.json[t]},removeXML:function(t){delete this._cache.xml[t]},removeVideo:function(t){delete this._cache.video[t]},removeShader:function(t){delete this._cache.shader[t]},removeRenderTexture:function(t){delete this._cache.renderTexture[t]},removeSpriteSheet:function(t){delete this._cache.spriteSheet[t]},removeTextureAtlas:function(t){delete this._cache.atlas[t]},clearGLTextures:function(){for(var t in this._cache.image)this._cache.image[t].base._glTextures=[]},_resolveURL:function(t,e){return this.autoResolveURL?(this._urlResolver.src=this.game.load.baseURL+t,this._urlTemp=this._urlResolver.src,this._urlResolver.src="",e&&(this._urlMap[this._urlTemp]=e),this._urlTemp):null},destroy:function(){for(var t=0;t<this._cacheMap.length;t++){var e=this._cacheMap[t];for(var i in e)"__default"!==i&&"__missing"!==i&&(e[i].destroy&&e[i].destroy(),delete e[i])}this._urlMap=null,this._urlResolver=null,this._urlTemp=null}},n.Cache.prototype.constructor=n.Cache,n.Loader=function(t){this.game=t,this.cache=t.cache,this.resetLocked=!1,this.isLoading=!1,this.hasLoaded=!1,this.preloadSprite=null,this.crossOrigin=!1,this.baseURL="",this.path="",this.headers={requestedWith:!1,json:"application/json",xml:"application/xml"},this.onLoadStart=new n.Signal,this.onLoadComplete=new n.Signal,this.onPackComplete=new n.Signal,this.onFileStart=new n.Signal,this.onFileComplete=new n.Signal,this.onFileError=new n.Signal,this.useXDomainRequest=!1,this._warnedAboutXDomainRequest=!1,this.enableParallel=!0,this.maxParallelDownloads=4,this._withSyncPointDepth=0,this._fileList=[],this._flightQueue=[],this._processingHead=0,this._fileLoadStarted=!1,this._totalPackCount=0,this._totalFileCount=0,this._loadedPackCount=0,this._loadedFileCount=0},n.Loader.TEXTURE_ATLAS_JSON_ARRAY=0,n.Loader.TEXTURE_ATLAS_JSON_HASH=1,n.Loader.TEXTURE_ATLAS_XML_STARLING=2,n.Loader.PHYSICS_LIME_CORONA_JSON=3,n.Loader.PHYSICS_PHASER_JSON=4,n.Loader.TEXTURE_ATLAS_JSON_PYXEL=5,n.Loader.prototype={setPreloadSprite:function(t,e){e=e||0,this.preloadSprite={sprite:t,direction:e,width:t.width,height:t.height,rect:null},this.preloadSprite.rect=0===e?new n.Rectangle(0,0,1,t.height):new n.Rectangle(0,0,t.width,1),t.crop(this.preloadSprite.rect),t.visible=!0},resize:function(){this.preloadSprite&&this.preloadSprite.height!==this.preloadSprite.sprite.height&&(this.preloadSprite.rect.height=this.preloadSprite.sprite.height)},checkKeyExists:function(t,e){return this.getAssetIndex(t,e)>-1},getAssetIndex:function(t,e){for(var i=-1,s=0;s<this._fileList.length;s++){var n=this._fileList[s];if(n.type===t&&n.key===e&&(i=s,!n.loaded&&!n.loading))break}return i},getAsset:function(t,e){var i=this.getAssetIndex(t,e);return i>-1&&{index:i,file:this._fileList[i]}},reset:function(t,e){void 0===e&&(e=!1),this.resetLocked||(t&&(this.preloadSprite=null),this.isLoading=!1,this._processingHead=0,this._fileList.length=0,this._flightQueue.length=0,this._fileLoadStarted=!1,this._totalFileCount=0,this._totalPackCount=0,this._loadedPackCount=0,this._loadedFileCount=0,e&&(this.onLoadStart.removeAll(),this.onLoadComplete.removeAll(),this.onPackComplete.removeAll(),this.onFileStart.removeAll(),this.onFileComplete.removeAll(),this.onFileError.removeAll()))},addToFileList:function(t,e,i,s,n,r){if(void 0===n&&(n=!1),void 0===e||""===e)return console.warn("Phaser.Loader: Invalid or no key given of type "+t),this;if(void 0===i||null===i){if(!r)return console.warn("Phaser.Loader: No URL given for file type: "+t+" key: "+e),this;i=e+r}var o={type:t,key:e,path:this.path,url:i,syncPoint:this._withSyncPointDepth>0,data:null,loading:!1,loaded:!1,error:!1};if(s)for(var a in s)o[a]=s[a];var h=this.getAssetIndex(t,e);if(n&&h>-1){var l=this._fileList[h];l.loading||l.loaded?(this._fileList.push(o),this._totalFileCount++):this._fileList[h]=o}else-1===h&&(this._fileList.push(o),this._totalFileCount++);return this},replaceInFileList:function(t,e,i,s){return this.addToFileList(t,e,i,s,!0)},pack:function(t,e,i,s){if(void 0===e&&(e=null),void 0===i&&(i=null),void 0===s&&(s=null),!e&&!i)return console.warn("Phaser.Loader.pack - Both url and data are null. One must be set."),this;var n={type:"packfile",key:t,url:e,path:this.path,syncPoint:!0,data:null,loading:!1,loaded:!1,error:!1,callbackContext:s};i&&("string"==typeof i&&(i=JSON.parse(i)),n.data=i||{},n.loaded=!0);for(var r=0;r<this._fileList.length+1;r++){var o=this._fileList[r];if(!o||!o.loaded&&!o.loading&&"packfile"!==o.type){this._fileList.splice(r,0,n),this._totalPackCount++;break}}return this},image:function(t,e,i){return this.addToFileList("image",t,e,void 0,i,".png")},images:function(t,e){if(Array.isArray(e))for(var i=0;i<t.length;i++)this.image(t[i],e[i]);else for(var i=0;i<t.length;i++)this.image(t[i]);return this},text:function(t,e,i){return this.addToFileList("text",t,e,void 0,i,".txt")},json:function(t,e,i){return this.addToFileList("json",t,e,void 0,i,".json")},shader:function(t,e,i){return this.addToFileList("shader",t,e,void 0,i,".frag")},xml:function(t,e,i){return this.addToFileList("xml",t,e,void 0,i,".xml")},script:function(t,e,i,s){return void 0===i&&(i=!1),!1!==i&&void 0===s&&(s=this),this.addToFileList("script",t,e,{syncPoint:!0,callback:i,callbackContext:s},!1,".js")},binary:function(t,e,i,s){return void 0===i&&(i=!1),!1!==i&&void 0===s&&(s=i),this.addToFileList("binary",t,e,{callback:i,callbackContext:s},!1,".bin")},spritesheet:function(t,e,i,s,n,r,o){return void 0===n&&(n=-1),void 0===r&&(r=0),void 0===o&&(o=0),this.addToFileList("spritesheet",t,e,{frameWidth:i,frameHeight:s,frameMax:n,margin:r,spacing:o},!1,".png")},audio:function(t,e,i){return this.game.sound.noAudio?this:(void 0===i&&(i=!0),"string"==typeof e&&(e=[e]),this.addToFileList("audio",t,e,{buffer:null,autoDecode:i}))},audioSprite:function(t,e,i,s,n){return this.game.sound.noAudio?this:(void 0===i&&(i=null),void 0===s&&(s=null),void 0===n&&(n=!0),this.audio(t,e,n),i?this.json(t+"-audioatlas",i):s?("string"==typeof s&&(s=JSON.parse(s)),this.cache.addJSON(t+"-audioatlas","",s)):console.warn("Phaser.Loader.audiosprite - You must specify either a jsonURL or provide a jsonData object"),this)},audiosprite:function(t,e,i,s,n){return this.audioSprite(t,e,i,s,n)},video:function(t,e,i,s){return void 0===i&&(i=this.game.device.firefox?"loadeddata":"canplaythrough"),void 0===s&&(s=!1),"string"==typeof e&&(e=[e]),this.addToFileList("video",t,e,{buffer:null,asBlob:s,loadEvent:i})},tilemap:function(t,e,i,s){if(void 0===e&&(e=null),void 0===i&&(i=null),void 0===s&&(s=n.Tilemap.CSV),e||i||(e=s===n.Tilemap.CSV?t+".csv":t+".json"),i){switch(s){case n.Tilemap.CSV:break;case n.Tilemap.TILED_JSON:"string"==typeof i&&(i=JSON.parse(i))}this.cache.addTilemap(t,null,i,s)}else this.addToFileList("tilemap",t,e,{format:s});return this},physics:function(t,e,i,s){return void 0===e&&(e=null),void 0===i&&(i=null),void 0===s&&(s=n.Physics.LIME_CORONA_JSON),e||i||(e=t+".json"),i?("string"==typeof i&&(i=JSON.parse(i)),this.cache.addPhysicsData(t,null,i,s)):this.addToFileList("physics",t,e,{format:s}),this},bitmapFont:function(t,e,i,s,n,r){if(void 0!==e&&null!==e||(e=t+".png"),void 0===i&&(i=null),void 0===s&&(s=null),null===i&&null===s&&(i=t+".xml"),void 0===n&&(n=0),void 0===r&&(r=0),i)this.addToFileList("bitmapfont",t,e,{atlasURL:i,xSpacing:n,ySpacing:r});else if("string"==typeof s){var o,a;try{o=JSON.parse(s)}catch(t){a=this.parseXml(s)}if(!a&&!o)throw new Error("Phaser.Loader. Invalid Bitmap Font atlas given");this.addToFileList("bitmapfont",t,e,{atlasURL:null,atlasData:o||a,atlasType:o?"json":"xml",xSpacing:n,ySpacing:r})}return this},atlasJSONArray:function(t,e,i,s){return this.atlas(t,e,i,s,n.Loader.TEXTURE_ATLAS_JSON_ARRAY)},atlasJSONHash:function(t,e,i,s){return this.atlas(t,e,i,s,n.Loader.TEXTURE_ATLAS_JSON_HASH)},atlasXML:function(t,e,i,s){return void 0===i&&(i=null),void 0===s&&(s=null),i||s||(i=t+".xml"),this.atlas(t,e,i,s,n.Loader.TEXTURE_ATLAS_XML_STARLING)},atlas:function(t,e,i,s,r){if(void 0!==e&&null!==e||(e=t+".png"),void 0===i&&(i=null),void 0===s&&(s=null),void 0===r&&(r=n.Loader.TEXTURE_ATLAS_JSON_ARRAY),i||s||(i=r===n.Loader.TEXTURE_ATLAS_XML_STARLING?t+".xml":t+".json"),i)this.addToFileList("textureatlas",t,e,{atlasURL:i,format:r});else{switch(r){case n.Loader.TEXTURE_ATLAS_JSON_ARRAY:"string"==typeof s&&(s=JSON.parse(s));break;case n.Loader.TEXTURE_ATLAS_XML_STARLING:if("string"==typeof s){var o=this.parseXml(s);if(!o)throw new Error("Phaser.Loader. Invalid Texture Atlas XML given");s=o}}this.addToFileList("textureatlas",t,e,{atlasURL:null,atlasData:s,format:r})}return this},withSyncPoint:function(t,e){this._withSyncPointDepth++;try{t.call(e||this,this)}finally{this._withSyncPointDepth--}return this},addSyncPoint:function(t,e){var i=this.getAsset(t,e);return i&&(i.file.syncPoint=!0),this},removeFile:function(t,e){var i=this.getAsset(t,e);i&&(i.loaded||i.loading||this._fileList.splice(i.index,1))},removeAll:function(){this._fileList.length=0,this._flightQueue.length=0},start:function(){this.isLoading||(this.hasLoaded=!1,this.isLoading=!0,this.updateProgress(),this.processLoadQueue())},processLoadQueue:function(){if(!this.isLoading)return console.warn("Phaser.Loader - active loading canceled / reset"),void this.finishedLoading(!0);for(var t=0;t<this._flightQueue.length;t++){var e=this._flightQueue[t];(e.loaded||e.error)&&(this._flightQueue.splice(t,1),t--,e.loading=!1,e.requestUrl=null,e.requestObject=null,e.error&&this.onFileError.dispatch(e.key,e),"packfile"!==e.type?(this._loadedFileCount++,this.onFileComplete.dispatch(this.progress,e.key,!e.error,this._loadedFileCount,this._totalFileCount)):"packfile"===e.type&&e.error&&(this._loadedPackCount++,this.onPackComplete.dispatch(e.key,!e.error,this._loadedPackCount,this._totalPackCount)))}for(var i=!1,s=this.enableParallel?n.Math.clamp(this.maxParallelDownloads,1,12):1,t=this._processingHead;t<this._fileList.length;t++){var e=this._fileList[t];if("packfile"===e.type&&!e.error&&e.loaded&&t===this._processingHead&&(this.processPack(e),this._loadedPackCount++,this.onPackComplete.dispatch(e.key,!e.error,this._loadedPackCount,this._totalPackCount)),e.loaded||e.error?t===this._processingHead&&(this._processingHead=t+1):!e.loading&&this._flightQueue.length<s&&("packfile"!==e.type||e.data?i||(this._fileLoadStarted||(this._fileLoadStarted=!0,this.onLoadStart.dispatch()),this._flightQueue.push(e),e.loading=!0,this.onFileStart.dispatch(this.progress,e.key,e.url),this.loadFile(e)):(this._flightQueue.push(e),e.loading=!0,this.loadFile(e))),!e.loaded&&e.syncPoint&&(i=!0),this._flightQueue.length>=s||i&&this._loadedPackCount===this._totalPackCount)break}if(this.updateProgress(),this._processingHead>=this._fileList.length)this.finishedLoading();else if(!this._flightQueue.length){console.warn("Phaser.Loader - aborting: processing queue empty, loading may have stalled");var r=this;setTimeout(function(){r.finishedLoading(!0)},2e3)}},finishedLoading:function(t){this.hasLoaded||(this.hasLoaded=!0,this.isLoading=!1,t||this._fileLoadStarted||(this._fileLoadStarted=!0,this.onLoadStart.dispatch()),this.onLoadComplete.dispatch(),this.game.state.loadComplete(),this.reset())},asyncComplete:function(t,e){void 0===e&&(e=""),t.loaded=!0,t.error=!!e,e&&(t.errorMessage=e,console.warn("Phaser.Loader - "+t.type+"["+t.key+"]: "+e)),this.processLoadQueue()},processPack:function(t){var e=t.data[t.key];if(!e)return void console.warn("Phaser.Loader - "+t.key+": pack has data, but not for pack key");for(var i=0;i<e.length;i++){var s=e[i];switch(s.type){case"image":this.image(s.key,s.url,s.overwrite);break;case"text":this.text(s.key,s.url,s.overwrite);break;case"json":this.json(s.key,s.url,s.overwrite);break;case"xml":this.xml(s.key,s.url,s.overwrite);break;case"script":this.script(s.key,s.url,s.callback,t.callbackContext||this);break;case"binary":this.binary(s.key,s.url,s.callback,t.callbackContext||this);break;case"spritesheet":this.spritesheet(s.key,s.url,s.frameWidth,s.frameHeight,s.frameMax,s.margin,s.spacing);break;case"video":this.video(s.key,s.urls);break;case"audio":this.audio(s.key,s.urls,s.autoDecode);break;case"audiosprite":this.audiosprite(s.key,s.urls,s.jsonURL,s.jsonData,s.autoDecode);break;case"tilemap":this.tilemap(s.key,s.url,s.data,n.Tilemap[s.format]);break;case"physics":this.physics(s.key,s.url,s.data,n.Loader[s.format]);break;case"bitmapFont":this.bitmapFont(s.key,s.textureURL,s.atlasURL,s.atlasData,s.xSpacing,s.ySpacing);break;case"atlasJSONArray":this.atlasJSONArray(s.key,s.textureURL,s.atlasURL,s.atlasData);break;case"atlasJSONHash":this.atlasJSONHash(s.key,s.textureURL,s.atlasURL,s.atlasData);break;case"atlasXML":this.atlasXML(s.key,s.textureURL,s.atlasURL,s.atlasData);break;case"atlas":this.atlas(s.key,s.textureURL,s.atlasURL,s.atlasData,n.Loader[s.format]);break;case"shader":this.shader(s.key,s.url,s.overwrite)}}},transformUrl:function(t,e){return!!t&&(t.match(/^(?:blob:|data:|http:\/\/|https:\/\/|\/\/)/)?t:this.baseURL+e.path+t)},loadFile:function(t){switch(t.type){case"packfile":this.xhrLoad(t,this.transformUrl(t.url,t),"text",this.fileComplete);break;case"image":case"spritesheet":case"textureatlas":case"bitmapfont":this.loadImageTag(t);break;case"audio":t.url=this.getAudioURL(t.url),t.url?this.game.sound.usingWebAudio?this.xhrLoad(t,this.transformUrl(t.url,t),"arraybuffer",this.fileComplete):this.game.sound.usingAudioTag&&this.loadAudioTag(t):this.fileError(t,null,"No supported audio URL specified or device does not have audio playback support");break;case"video":t.url=this.getVideoURL(t.url),t.url?t.asBlob?this.xhrLoad(t,this.transformUrl(t.url,t),"blob",this.fileComplete):this.loadVideoTag(t):this.fileError(t,null,"No supported video URL specified or device does not have video playback support");break;case"json":this.xhrLoad(t,this.transformUrl(t.url,t),"text",this.jsonLoadComplete);break;case"xml":this.xhrLoad(t,this.transformUrl(t.url,t),"text",this.xmlLoadComplete);break;case"tilemap":t.format===n.Tilemap.TILED_JSON?this.xhrLoad(t,this.transformUrl(t.url,t),"text",this.jsonLoadComplete):t.format===n.Tilemap.CSV?this.xhrLoad(t,this.transformUrl(t.url,t),"text",this.csvLoadComplete):this.asyncComplete(t,"invalid Tilemap format: "+t.format);break;case"text":case"script":case"shader":case"physics":this.xhrLoad(t,this.transformUrl(t.url,t),"text",this.fileComplete);break;case"binary":this.xhrLoad(t,this.transformUrl(t.url,t),"arraybuffer",this.fileComplete)}},loadImageTag:function(t){var e=this;t.data=new Image,t.data.name=t.key,this.crossOrigin&&(t.data.crossOrigin=this.crossOrigin),t.data.onload=function(){t.data.onload&&(t.data.onload=null,t.data.onerror=null,e.fileComplete(t))},t.data.onerror=function(){t.data.onload&&(t.data.onload=null,t.data.onerror=null,e.fileError(t))},t.data.src=this.transformUrl(t.url,t),t.data.complete&&t.data.width&&t.data.height&&(t.data.onload=null,t.data.onerror=null,this.fileComplete(t))},loadVideoTag:function(t){var e=this;t.data=document.createElement("video"),t.data.name=t.key,t.data.controls=!1,t.data.autoplay=!1;var i=function(){t.data.removeEventListener(t.loadEvent,i,!1),t.data.onerror=null,t.data.canplay=!0,n.GAMES[e.game.id].load.fileComplete(t)};t.data.onerror=function(){t.data.removeEventListener(t.loadEvent,i,!1),t.data.onerror=null,t.data.canplay=!1,e.fileError(t)},t.data.addEventListener(t.loadEvent,i,!1),t.data.src=this.transformUrl(t.url,t),t.data.load()},loadAudioTag:function(t){var e=this;if(this.game.sound.touchLocked)t.data=new Audio,t.data.name=t.key,t.data.preload="auto",t.data.src=this.transformUrl(t.url,t),this.fileComplete(t);else{t.data=new Audio,t.data.name=t.key;var i=function(){t.data.removeEventListener("canplaythrough",i,!1),t.data.onerror=null,e.fileComplete(t)};t.data.onerror=function(){t.data.removeEventListener("canplaythrough",i,!1),t.data.onerror=null,e.fileError(t)},t.data.preload="auto",t.data.src=this.transformUrl(t.url,t),t.data.addEventListener("canplaythrough",i,!1),t.data.load()}},xhrLoad:function(t,e,i,s,n){if(this.useXDomainRequest&&window.XDomainRequest)return void this.xhrLoadWithXDR(t,e,i,s,n);var r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType=i,!1!==this.headers.requestedWith&&r.setRequestHeader("X-Requested-With",this.headers.requestedWith),this.headers[t.type]&&r.setRequestHeader("Accept",this.headers[t.type]),n=n||this.fileError;var o=this;r.onload=function(){try{return 4===r.readyState&&r.status>=400&&r.status<=599?n.call(o,t,r):s.call(o,t,r)}catch(e){o.hasLoaded?window.console&&console.error(e):o.asyncComplete(t,e.message||"Exception")}},r.onerror=function(){try{return n.call(o,t,r)}catch(e){o.hasLoaded?window.console&&console.error(e):o.asyncComplete(t,e.message||"Exception")}},t.requestObject=r,t.requestUrl=e,r.send()},xhrLoadWithXDR:function(t,e,i,s,n){this._warnedAboutXDomainRequest||this.game.device.ie&&!(this.game.device.ieVersion>=10)||(this._warnedAboutXDomainRequest=!0,console.warn("Phaser.Loader - using XDomainRequest outside of IE 9"));var r=new window.XDomainRequest;r.open("GET",e,!0),r.responseType=i,r.timeout=3e3,n=n||this.fileError;var o=this;r.onerror=function(){try{return n.call(o,t,r)}catch(e){o.asyncComplete(t,e.message||"Exception")}},r.ontimeout=function(){try{return n.call(o,t,r)}catch(e){o.asyncComplete(t,e.message||"Exception")}},r.onprogress=function(){},r.onload=function(){try{return 4===r.readyState&&r.status>=400&&r.status<=599?n.call(o,t,r):s.call(o,t,r)}catch(e){o.asyncComplete(t,e.message||"Exception")}},t.requestObject=r,t.requestUrl=e,setTimeout(function(){r.send()},0)},getVideoURL:function(t){for(var e=0;e<t.length;e++){var i,s=t[e];if(s.uri){if(i=s.type,s=s.uri,this.game.device.canPlayVideo(i))return s}else{if(0===s.indexOf("blob:")||0===s.indexOf("data:"))return s;s.indexOf("?")>=0&&(s=s.substr(0,s.indexOf("?")));if(i=s.substr((Math.max(0,s.lastIndexOf("."))||1/0)+1).toLowerCase(),this.game.device.canPlayVideo(i))return t[e]}}return null},getAudioURL:function(t){if(this.game.sound.noAudio)return null;for(var e=0;e<t.length;e++){var i,s=t[e];if(s.uri){if(i=s.type,s=s.uri,this.game.device.canPlayAudio(i))return s}else{if(0===s.indexOf("blob:")||0===s.indexOf("data:"))return s;s.indexOf("?")>=0&&(s=s.substr(0,s.indexOf("?")));if(i=s.substr((Math.max(0,s.lastIndexOf("."))||1/0)+1).toLowerCase(),this.game.device.canPlayAudio(i))return t[e]}}return null},fileError:function(t,e,i){var s=t.requestUrl||this.transformUrl(t.url,t),n="error loading asset from URL "+s;!i&&e&&(i=e.status),i&&(n=n+" ("+i+")"),this.asyncComplete(t,n)},fileComplete:function(t,e){var i=!0;switch(t.type){case"packfile":var s=JSON.parse(e.responseText);t.data=s||{};break;case"image":this.cache.addImage(t.key,t.url,t.data);break;case"spritesheet":this.cache.addSpriteSheet(t.key,t.url,t.data,t.frameWidth,t.frameHeight,t.frameMax,t.margin,t.spacing);break;case"textureatlas":if(null==t.atlasURL)this.cache.addTextureAtlas(t.key,t.url,t.data,t.atlasData,t.format);else if(i=!1,t.format===n.Loader.TEXTURE_ATLAS_JSON_ARRAY||t.format===n.Loader.TEXTURE_ATLAS_JSON_HASH||t.format===n.Loader.TEXTURE_ATLAS_JSON_PYXEL)this.xhrLoad(t,this.transformUrl(t.atlasURL,t),"text",this.jsonLoadComplete);else{if(t.format!==n.Loader.TEXTURE_ATLAS_XML_STARLING)throw new Error("Phaser.Loader. Invalid Texture Atlas format: "+t.format);this.xhrLoad(t,this.transformUrl(t.atlasURL,t),"text",this.xmlLoadComplete)}break;case"bitmapfont":t.atlasURL?(i=!1,this.xhrLoad(t,this.transformUrl(t.atlasURL,t),"text",function(t,e){var i;try{i=JSON.parse(e.responseText)}catch(t){}i?(t.atlasType="json",this.jsonLoadComplete(t,e)):(t.atlasType="xml",this.xmlLoadComplete(t,e))})):this.cache.addBitmapFont(t.key,t.url,t.data,t.atlasData,t.atlasType,t.xSpacing,t.ySpacing);break;case"video":if(t.asBlob)try{t.data=e.response}catch(e){throw new Error("Phaser.Loader. Unable to parse video file as Blob: "+t.key)}this.cache.addVideo(t.key,t.url,t.data,t.asBlob);break;case"audio":this.game.sound.usingWebAudio?(t.data=e.response,this.cache.addSound(t.key,t.url,t.data,!0,!1),t.autoDecode&&this.game.sound.decode(t.key)):this.cache.addSound(t.key,t.url,t.data,!1,!0);break;case"text":t.data=e.responseText,this.cache.addText(t.key,t.url,t.data);break;case"shader":t.data=e.responseText,this.cache.addShader(t.key,t.url,t.data);break;case"physics":var s=JSON.parse(e.responseText);this.cache.addPhysicsData(t.key,t.url,s,t.format);break;case"script":t.data=document.createElement("script"),t.data.language="javascript",t.data.type="text/javascript",t.data.defer=!1,t.data.text=e.responseText,document.head.appendChild(t.data),t.callback&&(t.data=t.callback.call(t.callbackContext,t.key,e.responseText));break;case"binary":t.callback?t.data=t.callback.call(t.callbackContext,t.key,e.response):t.data=e.response,this.cache.addBinary(t.key,t.data)}i&&this.asyncComplete(t)},jsonLoadComplete:function(t,e){var i=JSON.parse(e.responseText);"tilemap"===t.type?this.cache.addTilemap(t.key,t.url,i,t.format):"bitmapfont"===t.type?this.cache.addBitmapFont(t.key,t.url,t.data,i,t.atlasType,t.xSpacing,t.ySpacing):"json"===t.type?this.cache.addJSON(t.key,t.url,i):this.cache.addTextureAtlas(t.key,t.url,t.data,i,t.format),this.asyncComplete(t)},csvLoadComplete:function(t,e){var i=e.responseText;this.cache.addTilemap(t.key,t.url,i,t.format),this.asyncComplete(t)},xmlLoadComplete:function(t,e){var i=e.responseText,s=this.parseXml(i);if(!s){var n=e.responseType||e.contentType;return console.warn("Phaser.Loader - "+t.key+": invalid XML ("+n+")"),void this.asyncComplete(t,"invalid XML")}"bitmapfont"===t.type?this.cache.addBitmapFont(t.key,t.url,t.data,s,t.atlasType,t.xSpacing,t.ySpacing):"textureatlas"===t.type?this.cache.addTextureAtlas(t.key,t.url,t.data,s,t.format):"xml"===t.type&&this.cache.addXML(t.key,t.url,s),this.asyncComplete(t)},parseXml:function(t){var e;try{if(window.DOMParser){var i=new DOMParser;e=i.parseFromString(t,"text/xml")}else e=new ActiveXObject("Microsoft.XMLDOM"),e.async="false",e.loadXML(t)}catch(t){e=null}return e&&e.documentElement&&!e.getElementsByTagName("parsererror").length?e:null},updateProgress:function(){this.preloadSprite&&(0===this.preloadSprite.direction?this.preloadSprite.rect.width=Math.floor(this.preloadSprite.width/100*this.progress):this.preloadSprite.rect.height=Math.floor(this.preloadSprite.height/100*this.progress),this.preloadSprite.sprite?this.preloadSprite.sprite.updateCrop():this.preloadSprite=null)},totalLoadedFiles:function(){return this._loadedFileCount},totalQueuedFiles:function(){return this._totalFileCount-this._loadedFileCount},totalLoadedPacks:function(){return this._totalPackCount},totalQueuedPacks:function(){return this._totalPackCount-this._loadedPackCount}},Object.defineProperty(n.Loader.prototype,"progressFloat",{get:function(){var t=this._loadedFileCount/this._totalFileCount*100;return n.Math.clamp(t||0,0,100)}}),Object.defineProperty(n.Loader.prototype,"progress",{get:function(){return Math.round(this.progressFloat)}}),n.Loader.prototype.constructor=n.Loader,n.LoaderParser={bitmapFont:function(t,e,i,s){return this.xmlBitmapFont(t,e,i,s)},xmlBitmapFont:function(t,e,i,s){var n={},r=t.getElementsByTagName("info")[0],o=t.getElementsByTagName("common")[0];n.font=r.getAttribute("face"),n.size=parseInt(r.getAttribute("size"),10),n.lineHeight=parseInt(o.getAttribute("lineHeight"),10)+s,n.chars={};for(var a=t.getElementsByTagName("char"),h=0;h<a.length;h++){var l=parseInt(a[h].getAttribute("id"),10);n.chars[l]={x:parseInt(a[h].getAttribute("x"),10),y:parseInt(a[h].getAttribute("y"),10),width:parseInt(a[h].getAttribute("width"),10),height:parseInt(a[h].getAttribute("height"),10),xOffset:parseInt(a[h].getAttribute("xoffset"),10),yOffset:parseInt(a[h].getAttribute("yoffset"),10),xAdvance:parseInt(a[h].getAttribute("xadvance"),10)+i,kerning:{}}}var c=t.getElementsByTagName("kerning");for(h=0;h<c.length;h++){var u=parseInt(c[h].getAttribute("first"),10),d=parseInt(c[h].getAttribute("second"),10),p=parseInt(c[h].getAttribute("amount"),10);n.chars[d].kerning[u]=p}return this.finalizeBitmapFont(e,n)},jsonBitmapFont:function(t,e,i,s){var n={font:t.font.info._face,size:parseInt(t.font.info._size,10),lineHeight:parseInt(t.font.common._lineHeight,10)+s,chars:{}};return t.font.chars.char.forEach(function(t){var e=parseInt(t._id,10);n.chars[e]={x:parseInt(t._x,10),y:parseInt(t._y,10),width:parseInt(t._width,10),height:parseInt(t._height,10),xOffset:parseInt(t._xoffset,10),yOffset:parseInt(t._yoffset,10),xAdvance:parseInt(t._xadvance,10)+i,kerning:{}}}),t.font.kernings&&t.font.kernings.kerning&&t.font.kernings.kerning.forEach(function(t){n.chars[t._second].kerning[t._first]=parseInt(t._amount,10)}),this.finalizeBitmapFont(e,n)},finalizeBitmapFont:function(t,e){return Object.keys(e.chars).forEach(function(i){var s=e.chars[i];s.texture=new PIXI.Texture(t,new n.Rectangle(s.x,s.y,s.width,s.height))}),e}},n.AudioSprite=function(t,e){this.game=t,this.key=e,this.config=this.game.cache.getJSON(e+"-audioatlas"),this.autoplayKey=null,this.autoplay=!1,this.sounds={};for(var i in this.config.spritemap){var s=this.config.spritemap[i],n=this.game.add.sound(this.key);n.addMarker(i,s.start,s.end-s.start,null,s.loop),this.sounds[i]=n}this.config.autoplay&&(this.autoplayKey=this.config.autoplay,this.play(this.autoplayKey),this.autoplay=this.sounds[this.autoplayKey])},n.AudioSprite.prototype={play:function(t,e){return void 0===e&&(e=1),this.sounds[t].play(t,null,e)},stop:function(t){if(t)this.sounds[t].stop();else for(var e in this.sounds)this.sounds[e].stop()},get:function(t){return this.sounds[t]}},n.AudioSprite.prototype.constructor=n.AudioSprite,n.Sound=function(t,e,i,s,r){void 0===i&&(i=1),void 0===s&&(s=!1),void 0===r&&(r=t.sound.connectToMaster),this.game=t,this.name=e,this.key=e,this.loop=s,this.markers={},this.context=null,this.autoplay=!1,this.totalDuration=0,this.startTime=0,this.currentTime=0,this.duration=0,this.durationMS=0,this.position=0,this.stopTime=0,this.paused=!1,this.pausedPosition=0,this.pausedTime=0,this.isPlaying=!1,this.currentMarker="",this.fadeTween=null,this.pendingPlayback=!1,this.override=!1,this.allowMultiple=!1,this.usingWebAudio=this.game.sound.usingWebAudio,this.usingAudioTag=this.game.sound.usingAudioTag,this.externalNode=null,this.masterGainNode=null,this.gainNode=null,this._sound=null,this.usingWebAudio?(this.context=this.game.sound.context,this.masterGainNode=this.game.sound.masterGain,void 0===this.context.createGain?this.gainNode=this.context.createGainNode():this.gainNode=this.context.createGain(),this.gainNode.gain.value=i*this.game.sound.volume,r&&this.gainNode.connect(this.masterGainNode)):this.usingAudioTag&&(this.game.cache.getSound(e)&&this.game.cache.isSoundReady(e)?(this._sound=this.game.cache.getSoundData(e),this.totalDuration=0,this._sound.duration&&(this.totalDuration=this._sound.duration)):this.game.cache.onSoundUnlock.add(this.soundHasUnlocked,this)),this.onDecoded=new n.Signal,this.onPlay=new n.Signal,this.onPause=new n.Signal,this.onResume=new n.Signal,this.onLoop=new n.Signal,this.onStop=new n.Signal,this.onMute=new n.Signal,this.onMarkerComplete=new n.Signal,this.onFadeComplete=new n.Signal,this._volume=i,this._buffer=null,this._muted=!1,this._tempMarker=0,this._tempPosition=0,this._tempVolume=0,this._tempPause=0,this._muteVolume=0,this._tempLoop=0,this._paused=!1,this._onDecodedEventDispatched=!1},n.Sound.prototype={soundHasUnlocked:function(t){t===this.key&&(this._sound=this.game.cache.getSoundData(this.key),this.totalDuration=this._sound.duration)},addMarker:function(t,e,i,s,n){void 0!==i&&null!==i||(i=1),void 0!==s&&null!==s||(s=1),void 0===n&&(n=!1),this.markers[t]={name:t,start:e,stop:e+i,volume:s,duration:i,durationMS:1e3*i,loop:n}},removeMarker:function(t){delete this.markers[t]},onEndedHandler:function(){this._sound.onended=null,this.isPlaying=!1,this.currentTime=this.durationMS,this.stop()},update:function(){if(!this.game.cache.checkSoundKey(this.key))return void this.destroy();this.isDecoded&&!this._onDecodedEventDispatched&&(this.onDecoded.dispatch(this),this._onDecodedEventDispatched=!0),this.pendingPlayback&&this.game.cache.isSoundReady(this.key)&&(this.pendingPlayback=!1,this.play(this._tempMarker,this._tempPosition,this._tempVolume,this._tempLoop)),this.isPlaying&&(this.currentTime=this.game.time.time-this.startTime,this.currentTime>=this.durationMS&&(this.usingWebAudio?this.loop?(this.onLoop.dispatch(this),this.isPlaying=!1,""===this.currentMarker?(this.currentTime=0,this.startTime=this.game.time.time,this.isPlaying=!0):(this.onMarkerComplete.dispatch(this.currentMarker,this),this.play(this.currentMarker,0,this.volume,!0,!0))):""!==this.currentMarker&&this.stop():this.loop?(this.onLoop.dispatch(this),""===this.currentMarker&&(this.currentTime=0,this.startTime=this.game.time.time),this.isPlaying=!1,this.play(this.currentMarker,0,this.volume,!0,!0)):this.stop()))},loopFull:function(t){return this.play(null,0,t,!0)},play:function(t,e,i,s,n){if(void 0!==t&&!1!==t&&null!==t||(t=""),void 0===n&&(n=!0),this.isPlaying&&!this.allowMultiple&&!n&&!this.override)return this;if(this._sound&&this.isPlaying&&!this.allowMultiple&&(this.override||n)){if(this.usingWebAudio){if(void 0===this._sound.stop)this._sound.noteOff(0);else try{this._sound.stop(0)}catch(t){}this.externalNode?this._sound.disconnect(this.externalNode):this.gainNode&&this._sound.disconnect(this.gainNode)}else this.usingAudioTag&&(this._sound.pause(),this._sound.currentTime=0);this.isPlaying=!1}if(""===t&&Object.keys(this.markers).length>0)return this;if(""!==t){if(!this.markers[t])return console.warn("Phaser.Sound.play: audio marker "+t+" doesn't exist"),this;this.currentMarker=t,this.position=this.markers[t].start,this.volume=this.markers[t].volume,this.loop=this.markers[t].loop,this.duration=this.markers[t].duration,this.durationMS=this.markers[t].durationMS,void 0!==i&&(this.volume=i),void 0!==s&&(this.loop=s),this._tempMarker=t,this._tempPosition=this.position,this._tempVolume=this.volume,this._tempLoop=this.loop}else e=e||0,void 0===i&&(i=this._volume),void 0===s&&(s=this.loop),this.position=Math.max(0,e),this.volume=i,this.loop=s,this.duration=0,this.durationMS=0,this._tempMarker=t,this._tempPosition=e,this._tempVolume=i,this._tempLoop=s;return this.usingWebAudio?this.game.cache.isSoundDecoded(this.key)?(this._sound=this.context.createBufferSource(),this.externalNode?this._sound.connect(this.externalNode):this._sound.connect(this.gainNode),this._buffer=this.game.cache.getSoundData(this.key),this._sound.buffer=this._buffer,this.loop&&""===t&&(this._sound.loop=!0),this.loop||""!==t||(this._sound.onended=this.onEndedHandler.bind(this)),this.totalDuration=this._sound.buffer.duration,0===this.duration&&(this.duration=this.totalDuration,this.durationMS=Math.ceil(1e3*this.totalDuration)),void 0===this._sound.start?this._sound.noteGrainOn(0,this.position,this.duration):this.loop&&""===t?this._sound.start(0,0):this._sound.start(0,this.position,this.duration),this.isPlaying=!0,this.startTime=this.game.time.time,this.currentTime=0,this.stopTime=this.startTime+this.durationMS,this.onPlay.dispatch(this)):(this.pendingPlayback=!0,this.game.cache.getSound(this.key)&&!1===this.game.cache.getSound(this.key).isDecoding&&this.game.sound.decode(this.key,this)):this.game.cache.getSound(this.key)&&this.game.cache.getSound(this.key).locked?(this.game.cache.reloadSound(this.key),this.pendingPlayback=!0):this._sound&&(this.game.device.cocoonJS||4===this._sound.readyState)?(this._sound.play(),this.totalDuration=this._sound.duration,0===this.duration&&(this.duration=this.totalDuration,this.durationMS=1e3*this.totalDuration),this._sound.currentTime=this.position,this._sound.muted=this._muted,this._muted||this.game.sound.mute?this._sound.volume=0:this._sound.volume=this._volume,this.isPlaying=!0,this.startTime=this.game.time.time,this.currentTime=0,this.stopTime=this.startTime+this.durationMS,this.onPlay.dispatch(this)):this.pendingPlayback=!0,this},restart:function(t,e,i,s){t=t||"",e=e||0,i=i||1,void 0===s&&(s=!1),this.play(t,e,i,s,!0)},pause:function(){this.isPlaying&&this._sound&&(this.paused=!0,this.pausedPosition=this.currentTime,this.pausedTime=this.game.time.time,this._tempPause=this._sound.currentTime,this.onPause.dispatch(this),this.stop())},resume:function(){if(this.paused&&this._sound){if(this.usingWebAudio){var t=Math.max(0,this.position+this.pausedPosition/1e3);this._sound=this.context.createBufferSource(),this._sound.buffer=this._buffer,this.externalNode?this._sound.connect(this.externalNode):this._sound.connect(this.gainNode),this.loop&&(this._sound.loop=!0),this.loop||""!==this.currentMarker||(this._sound.onended=this.onEndedHandler.bind(this));var e=this.duration-this.pausedPosition/1e3;void 0===this._sound.start?this._sound.noteGrainOn(0,t,e):this.loop&&this.game.device.chrome?42===this.game.device.chromeVersion?this._sound.start(0):this._sound.start(0,t):this._sound.start(0,t,e)}else this._sound.currentTime=this._tempPause,this._sound.play();this.isPlaying=!0,this.paused=!1,this.startTime+=this.game.time.time-this.pausedTime,this.onResume.dispatch(this)}},stop:function(){if(this.isPlaying&&this._sound)if(this.usingWebAudio){if(void 0===this._sound.stop)this._sound.noteOff(0);else try{this._sound.stop(0)}catch(t){}this.externalNode?this._sound.disconnect(this.externalNode):this.gainNode&&this._sound.disconnect(this.gainNode)}else this.usingAudioTag&&(this._sound.pause(),this._sound.currentTime=0);if(this.pendingPlayback=!1,this.isPlaying=!1,!this.paused){var t=this.currentMarker;""!==this.currentMarker&&this.onMarkerComplete.dispatch(this.currentMarker,this),this.currentMarker="",null!==this.fadeTween&&this.fadeTween.stop(),this.onStop.dispatch(this,t)}},fadeIn:function(t,e,i){void 0===e&&(e=!1),void 0===i&&(i=this.currentMarker),this.paused||(this.play(i,0,0,e),this.fadeTo(t,1))},fadeOut:function(t){this.fadeTo(t,0)},fadeTo:function(t,e){if(this.isPlaying&&!this.paused&&e!==this.volume){if(void 0===t&&(t=1e3),void 0===e)return void console.warn("Phaser.Sound.fadeTo: No Volume Specified.");this.fadeTween=this.game.add.tween(this).to({volume:e},t,n.Easing.Linear.None,!0),this.fadeTween.onComplete.add(this.fadeComplete,this)}},fadeComplete:function(){this.onFadeComplete.dispatch(this,this.volume),0===this.volume&&this.stop()},updateGlobalVolume:function(t){this.usingAudioTag&&this._sound&&(this._sound.volume=t*this._volume)},destroy:function(t){void 0===t&&(t=!0),this.stop(),t?this.game.sound.remove(this):(this.markers={},this.context=null,this._buffer=null,this.externalNode=null,this.onDecoded.dispose(),this.onPlay.dispose(),this.onPause.dispose(),this.onResume.dispose(),this.onLoop.dispose(),this.onStop.dispose(),this.onMute.dispose(),this.onMarkerComplete.dispose())}},n.Sound.prototype.constructor=n.Sound,Object.defineProperty(n.Sound.prototype,"isDecoding",{get:function(){return this.game.cache.getSound(this.key).isDecoding}}),Object.defineProperty(n.Sound.prototype,"isDecoded",{get:function(){return this.game.cache.isSoundDecoded(this.key)}}),Object.defineProperty(n.Sound.prototype,"mute",{get:function(){return this._muted||this.game.sound.mute},set:function(t){(t=t||!1)!==this._muted&&(t?(this._muted=!0,this._muteVolume=this._tempVolume,this.usingWebAudio?this.gainNode.gain.value=0:this.usingAudioTag&&this._sound&&(this._sound.volume=0)):(this._muted=!1,this.usingWebAudio?this.gainNode.gain.value=this._muteVolume:this.usingAudioTag&&this._sound&&(this._sound.volume=this._muteVolume)),this.onMute.dispatch(this))}}),Object.defineProperty(n.Sound.prototype,"volume",{get:function(){return this._volume},set:function(t){if(this.game.device.firefox&&this.usingAudioTag&&(t=this.game.math.clamp(t,0,1)),this._muted)return void(this._muteVolume=t);this._tempVolume=t,this._volume=t,this.usingWebAudio?this.gainNode.gain.value=t:this.usingAudioTag&&this._sound&&(this._sound.volume=t)}}),n.SoundManager=function(t){this.game=t,this.onSoundDecode=new n.Signal,this.onVolumeChange=new n.Signal,this.onMute=new n.Signal,this.onUnMute=new n.Signal,this.context=null,this.usingWebAudio=!1,this.usingAudioTag=!1,this.noAudio=!1,this.connectToMaster=!0,this.touchLocked=!1,this.channels=32,this.muteOnPause=!0,this._codeMuted=!1,this._muted=!1,this._unlockSource=null,this._volume=1,this._sounds=[],this._watchList=new n.ArraySet,this._watching=!1,this._watchCallback=null,this._watchContext=null},n.SoundManager.prototype={boot:function(){if(this.game.device.iOS&&!1===this.game.device.webAudio&&(this.channels=1),window.PhaserGlobal){if(!0===window.PhaserGlobal.disableAudio)return this.noAudio=!0,void(this.touchLocked=!1);if(!0===window.PhaserGlobal.disableWebAudio)return this.usingAudioTag=!0,void(this.touchLocked=!1)}if(window.PhaserGlobal&&window.PhaserGlobal.audioContext)this.context=window.PhaserGlobal.audioContext;else if(window.AudioContext)try{this.context=new window.AudioContext}catch(t){this.context=null,this.usingWebAudio=!1,this.touchLocked=!1}else if(window.webkitAudioContext)try{this.context=new window.webkitAudioContext}catch(t){this.context=null,this.usingWebAudio=!1,this.touchLocked=!1}if(null===this.context){if(void 0===window.Audio)return void(this.noAudio=!0);this.usingAudioTag=!0}else this.usingWebAudio=!0,void 0===this.context.createGain?this.masterGain=this.context.createGainNode():this.masterGain=this.context.createGain(),this.masterGain.gain.value=1,this.masterGain.connect(this.context.destination);this.noAudio||(!this.game.device.cocoonJS&&this.game.device.iOS||window.PhaserGlobal&&window.PhaserGlobal.fakeiOSTouchLock)&&this.setTouchLock()},setTouchLock:function(){this.noAudio||window.PhaserGlobal&&!0===window.PhaserGlobal.disableAudio||(this.game.device.iOSVersion>8?this.game.input.touch.addTouchLockCallback(this.unlock,this,!0):this.game.input.touch.addTouchLockCallback(this.unlock,this),this.touchLocked=!0)},unlock:function(){if(this.noAudio||!this.touchLocked||null!==this._unlockSource)return!0;if(this.usingAudioTag)this.touchLocked=!1,this._unlockSource=null;else if(this.usingWebAudio){var t=this.context.createBuffer(1,1,22050);this._unlockSource=this.context.createBufferSource(),this._unlockSource.buffer=t,this._unlockSource.connect(this.context.destination),void 0===this._unlockSource.start?this._unlockSource.noteOn(0):this._unlockSource.start(0)}return!0},stopAll:function(){if(!this.noAudio)for(var t=0;t<this._sounds.length;t++)this._sounds[t]&&this._sounds[t].stop()},pauseAll:function(){if(!this.noAudio)for(var t=0;t<this._sounds.length;t++)this._sounds[t]&&this._sounds[t].pause()},resumeAll:function(){if(!this.noAudio)for(var t=0;t<this._sounds.length;t++)this._sounds[t]&&this._sounds[t].resume()},decode:function(t,e){e=e||null;var i=this.game.cache.getSoundData(t);if(i&&!1===this.game.cache.isSoundDecoded(t)){this.game.cache.updateSound(t,"isDecoding",!0);var s=this;try{this.context.decodeAudioData(i,function(i){i&&(s.game.cache.decodedSound(t,i),s.onSoundDecode.dispatch(t,e))})}catch(t){}}},setDecodedCallback:function(t,e,i){"string"==typeof t&&(t=[t]),this._watchList.reset();for(var s=0;s<t.length;s++)t[s]instanceof n.Sound?this.game.cache.isSoundDecoded(t[s].key)||this._watchList.add(t[s].key):this.game.cache.isSoundDecoded(t[s])||this._watchList.add(t[s]);0===this._watchList.total?(this._watching=!1,e.call(i)):(this._watching=!0,this._watchCallback=e,this._watchContext=i)},update:function(){if(!this.noAudio){!this.touchLocked||null===this._unlockSource||this._unlockSource.playbackState!==this._unlockSource.PLAYING_STATE&&this._unlockSource.playbackState!==this._unlockSource.FINISHED_STATE||(this.touchLocked=!1,this._unlockSource=null);for(var t=0;t<this._sounds.length;t++)this._sounds[t].update();if(this._watching){for(var e=this._watchList.first;e;)this.game.cache.isSoundDecoded(e)&&this._watchList.remove(e),e=this._watchList.next;0===this._watchList.total&&(this._watching=!1,this._watchCallback.call(this._watchContext))}}},add:function(t,e,i,s){void 0===e&&(e=1),void 0===i&&(i=!1),void 0===s&&(s=this.connectToMaster);var r=new n.Sound(this.game,t,e,i,s);return this._sounds.push(r),r},addSprite:function(t){return new n.AudioSprite(this.game,t)},remove:function(t){for(var e=this._sounds.length;e--;)if(this._sounds[e]===t)return this._sounds[e].destroy(!1),this._sounds.splice(e,1),!0;return!1},removeByKey:function(t){for(var e=this._sounds.length,i=0;e--;)this._sounds[e].key===t&&(this._sounds[e].destroy(!1),this._sounds.splice(e,1),i++);return i},play:function(t,e,i){if(!this.noAudio){var s=this.add(t,e,i);return s.play(),s}},setMute:function(){if(!this._muted){this._muted=!0,this.usingWebAudio&&(this._muteVolume=this.masterGain.gain.value,this.masterGain.gain.value=0);for(var t=0;t<this._sounds.length;t++)this._sounds[t].usingAudioTag&&(this._sounds[t].mute=!0);this.onMute.dispatch()}},unsetMute:function(){if(this._muted&&!this._codeMuted){this._muted=!1,this.usingWebAudio&&(this.masterGain.gain.value=this._muteVolume);for(var t=0;t<this._sounds.length;t++)this._sounds[t].usingAudioTag&&(this._sounds[t].mute=!1);this.onUnMute.dispatch()}},destroy:function(){this.stopAll();for(var t=0;t<this._sounds.length;t++)this._sounds[t]&&this._sounds[t].destroy();this._sounds=[],this.onSoundDecode.dispose(),this.context&&(window.PhaserGlobal?window.PhaserGlobal.audioContext=this.context:this.context.close&&this.context.close())}},n.SoundManager.prototype.constructor=n.SoundManager,Object.defineProperty(n.SoundManager.prototype,"mute",{get:function(){return this._muted},set:function(t){if(t=t||!1){if(this._muted)return;this._codeMuted=!0,this.setMute()}else{if(!this._muted)return;this._codeMuted=!1,this.unsetMute()}}}),Object.defineProperty(n.SoundManager.prototype,"volume",{get:function(){return this._volume},set:function(t){if(t<0?t=0:t>1&&(t=1),this._volume!==t){if(this._volume=t,this.usingWebAudio)this.masterGain.gain.value=t;else for(var e=0;e<this._sounds.length;e++)this._sounds[e].usingAudioTag&&this._sounds[e].updateGlobalVolume(t);this.onVolumeChange.dispatch(t)}}}),n.ScaleManager=function(t,e,i){this.game=t,this.dom=n.DOM,this.grid=null,this.width=0,this.height=0,this.minWidth=null,this.maxWidth=null,this.minHeight=null,this.maxHeight=null,this.offset=new n.Point,this.forceLandscape=!1,this.forcePortrait=!1,this.incorrectOrientation=!1,this._pageAlignHorizontally=!1,this._pageAlignVertically=!1,this.onOrientationChange=new n.Signal,this.enterIncorrectOrientation=new n.Signal,this.leaveIncorrectOrientation=new n.Signal,this.hasPhaserSetFullScreen=!1,this.fullScreenTarget=null,this._createdFullScreenTarget=null,this.onFullScreenInit=new n.Signal,this.onFullScreenChange=new n.Signal,this.onFullScreenError=new n.Signal,this.screenOrientation=this.dom.getScreenOrientation(),this.scaleFactor=new n.Point(1,1),this.scaleFactorInversed=new n.Point(1,1),this.margin={left:0,top:0,right:0,bottom:0,x:0,y:0},this.bounds=new n.Rectangle,this.aspectRatio=0,this.sourceAspectRatio=0,this.event=null,this.windowConstraints={right:"layout",bottom:""},this.compatibility={supportsFullScreen:!1,orientationFallback:null,noMargins:!1,scrollTo:null,forceMinimumDocumentHeight:!1,canExpandParent:!0,clickTrampoline:""},this._scaleMode=n.ScaleManager.NO_SCALE,this._fullScreenScaleMode=n.ScaleManager.NO_SCALE,this.parentIsWindow=!1,this.parentNode=null,this.parentScaleFactor=new n.Point(1,1),this.trackParentInterval=2e3,this.onSizeChange=new n.Signal,this.onResize=null,this.onResizeContext=null,this._pendingScaleMode=null,this._fullScreenRestore=null,this._gameSize=new n.Rectangle,this._userScaleFactor=new n.Point(1,1),this._userScaleTrim=new n.Point(0,0),this._lastUpdate=0,this._updateThrottle=0,this._updateThrottleReset=100,this._parentBounds=new n.Rectangle,this._tempBounds=new n.Rectangle,this._lastReportedCanvasSize=new n.Rectangle,this._lastReportedGameSize=new n.Rectangle,this._booted=!1,t.config&&this.parseConfig(t.config),this.setupScale(e,i)},n.ScaleManager.EXACT_FIT=0,n.ScaleManager.NO_SCALE=1,n.ScaleManager.SHOW_ALL=2,n.ScaleManager.RESIZE=3,n.ScaleManager.USER_SCALE=4,n.ScaleManager.prototype={boot:function(){var t=this.compatibility;t.supportsFullScreen=this.game.device.fullscreen&&!this.game.device.cocoonJS,this.game.device.iPad||this.game.device.webApp||this.game.device.desktop||(this.game.device.android&&!this.game.device.chrome?t.scrollTo=new n.Point(0,1):t.scrollTo=new n.Point(0,0)),this.game.device.desktop?(t.orientationFallback="screen",t.clickTrampoline="when-not-mouse"):(t.orientationFallback="",t.clickTrampoline="");var e=this;this._orientationChange=function(t){return e.orientationChange(t)},this._windowResize=function(t){return e.windowResize(t)},window.addEventListener("orientationchange",this._orientationChange,!1),window.addEventListener("resize",this._windowResize,!1),this.compatibility.supportsFullScreen&&(this._fullScreenChange=function(t){return e.fullScreenChange(t)},this._fullScreenError=function(t){return e.fullScreenError(t)},document.addEventListener("webkitfullscreenchange",this._fullScreenChange,!1),document.addEventListener("mozfullscreenchange",this._fullScreenChange,!1),document.addEventListener("MSFullscreenChange",this._fullScreenChange,!1),document.addEventListener("fullscreenchange",this._fullScreenChange,!1),document.addEventListener("webkitfullscreenerror",this._fullScreenError,!1),document.addEventListener("mozfullscreenerror",this._fullScreenError,!1),document.addEventListener("MSFullscreenError",this._fullScreenError,!1),document.addEventListener("fullscreenerror",this._fullScreenError,!1)),this.game.onResume.add(this._gameResumed,this),this.dom.getOffset(this.game.canvas,this.offset),this.bounds.setTo(this.offset.x,this.offset.y,this.width,this.height),this.setGameSize(this.game.width,this.game.height),this.screenOrientation=this.dom.getScreenOrientation(this.compatibility.orientationFallback),n.FlexGrid&&(this.grid=new n.FlexGrid(this,this.width,this.height)),this._booted=!0,null!==this._pendingScaleMode&&(this.scaleMode=this._pendingScaleMode,this._pendingScaleMode=null)},parseConfig:function(t){void 0!==t.scaleMode&&(this._booted?this.scaleMode=t.scaleMode:this._pendingScaleMode=t.scaleMode),void 0!==t.fullScreenScaleMode&&(this.fullScreenScaleMode=t.fullScreenScaleMode),t.fullScreenTarget&&(this.fullScreenTarget=t.fullScreenTarget)},setupScale:function(t,e){var i,s=new n.Rectangle;""!==this.game.parent&&("string"==typeof this.game.parent?i=document.getElementById(this.game.parent):this.game.parent&&1===this.game.parent.nodeType&&(i=this.game.parent)),i?(this.parentNode=i,this.parentIsWindow=!1,this.getParentBounds(this._parentBounds),s.width=this._parentBounds.width,s.height=this._parentBounds.height,this.offset.set(this._parentBounds.x,this._parentBounds.y)):(this.parentNode=null,this.parentIsWindow=!0,s.width=this.dom.visualBounds.width,s.height=this.dom.visualBounds.height,this.offset.set(0,0));var r=0,o=0;"number"==typeof t?r=t:(this.parentScaleFactor.x=parseInt(t,10)/100,r=s.width*this.parentScaleFactor.x),"number"==typeof e?o=e:(this.parentScaleFactor.y=parseInt(e,10)/100,o=s.height*this.parentScaleFactor.y),r=Math.floor(r),o=Math.floor(o),this._gameSize.setTo(0,0,r,o),this.updateDimensions(r,o,!1)},_gameResumed:function(){this.queueUpdate(!0)},setGameSize:function(t,e){this._gameSize.setTo(0,0,t,e),this.currentScaleMode!==n.ScaleManager.RESIZE&&this.updateDimensions(t,e,!0),this.queueUpdate(!0)},setUserScale:function(t,e,i,s){this._userScaleFactor.setTo(t,e),this._userScaleTrim.setTo(0|i,0|s),this.queueUpdate(!0)},setResizeCallback:function(t,e){this.onResize=t,this.onResizeContext=e},signalSizeChange:function(){if(!n.Rectangle.sameDimensions(this,this._lastReportedCanvasSize)||!n.Rectangle.sameDimensions(this.game,this._lastReportedGameSize)){var t=this.width,e=this.height;this._lastReportedCanvasSize.setTo(0,0,t,e),this._lastReportedGameSize.setTo(0,0,this.game.width,this.game.height),this.grid&&this.grid.onResize(t,e),this.onSizeChange.dispatch(this,t,e),this.currentScaleMode===n.ScaleManager.RESIZE&&(this.game.state.resize(t,e),this.game.load.resize(t,e))}},setMinMax:function(t,e,i,s){this.minWidth=t,this.minHeight=e,void 0!==i&&(this.maxWidth=i),void 0!==s&&(this.maxHeight=s)},preUpdate:function(){if(!(this.game.time.time<this._lastUpdate+this._updateThrottle)){var t=this._updateThrottle;this._updateThrottleReset=t>=400?0:100,this.dom.getOffset(this.game.canvas,this.offset);var e=this._parentBounds.width,i=this._parentBounds.height,s=this.getParentBounds(this._parentBounds),r=s.width!==e||s.height!==i,o=this.updateOrientationState();(r||o)&&(this.onResize&&this.onResize.call(this.onResizeContext,this,s),this.updateLayout(),this.signalSizeChange());var a=2*this._updateThrottle;this._updateThrottle<t&&(a=Math.min(t,this._updateThrottleReset)),this._updateThrottle=n.Math.clamp(a,25,this.trackParentInterval),this._lastUpdate=this.game.time.time}},pauseUpdate:function(){this.preUpdate(),this._updateThrottle=this.trackParentInterval},updateDimensions:function(t,e,i){this.width=t*this.parentScaleFactor.x,this.height=e*this.parentScaleFactor.y,this.game.width=this.width,this.game.height=this.height,this.sourceAspectRatio=this.width/this.height,this.updateScalingAndBounds(),i&&(this.game.renderer.resize(this.width,this.height),this.game.camera.setSize(this.width,this.height),this.game.world.resize(this.width,this.height))},updateScalingAndBounds:function(){this.scaleFactor.x=this.game.width/this.width,this.scaleFactor.y=this.game.height/this.height,this.scaleFactorInversed.x=this.width/this.game.width,this.scaleFactorInversed.y=this.height/this.game.height,this.aspectRatio=this.width/this.height,this.game.canvas&&this.dom.getOffset(this.game.canvas,this.offset),this.bounds.setTo(this.offset.x,this.offset.y,this.width,this.height),this.game.input&&this.game.input.scale&&this.game.input.scale.setTo(this.scaleFactor.x,this.scaleFactor.y)},forceOrientation:function(t,e){void 0===e&&(e=!1),this.forceLandscape=t,this.forcePortrait=e,this.queueUpdate(!0)},classifyOrientation:function(t){return"portrait-primary"===t||"portrait-secondary"===t?"portrait":"landscape-primary"===t||"landscape-secondary"===t?"landscape":null},updateOrientationState:function(){var t=this.screenOrientation,e=this.incorrectOrientation;this.screenOrientation=this.dom.getScreenOrientation(this.compatibility.orientationFallback),this.incorrectOrientation=this.forceLandscape&&!this.isLandscape||this.forcePortrait&&!this.isPortrait;var i=t!==this.screenOrientation,s=e!==this.incorrectOrientation;return s&&(this.incorrectOrientation?this.enterIncorrectOrientation.dispatch():this.leaveIncorrectOrientation.dispatch()),(i||s)&&this.onOrientationChange.dispatch(this,t,e),i||s},orientationChange:function(t){this.event=t,this.queueUpdate(!0)},windowResize:function(t){this.event=t,this.queueUpdate(!0)},scrollTop:function(){var t=this.compatibility.scrollTo;t&&window.scrollTo(t.x,t.y)},refresh:function(){this.scrollTop(),this.queueUpdate(!0)},updateLayout:function(){var t=this.currentScaleMode;if(t===n.ScaleManager.RESIZE)return void this.reflowGame();if(this.scrollTop(),this.compatibility.forceMinimumDocumentHeight&&(document.documentElement.style.minHeight=window.innerHeight+"px"),this.incorrectOrientation?this.setMaximum():t===n.ScaleManager.EXACT_FIT?this.setExactFit():t===n.ScaleManager.SHOW_ALL?!this.isFullScreen&&this.boundingParent&&this.compatibility.canExpandParent?(this.setShowAll(!0),this.resetCanvas(),this.setShowAll()):this.setShowAll():t===n.ScaleManager.NO_SCALE?(this.width=this.game.width,this.height=this.game.height):t===n.ScaleManager.USER_SCALE&&(this.width=this.game.width*this._userScaleFactor.x-this._userScaleTrim.x,this.height=this.game.height*this._userScaleFactor.y-this._userScaleTrim.y),!this.compatibility.canExpandParent&&(t===n.ScaleManager.SHOW_ALL||t===n.ScaleManager.USER_SCALE)){var e=this.getParentBounds(this._tempBounds);this.width=Math.min(this.width,e.width),this.height=Math.min(this.height,e.height)}this.width=0|this.width,this.height=0|this.height,this.reflowCanvas()},getParentBounds:function(t){var e=t||new n.Rectangle,i=this.boundingParent,s=this.dom.visualBounds,r=this.dom.layoutBounds;if(i){var o=i.getBoundingClientRect(),a=i.offsetParent?i.offsetParent.getBoundingClientRect():i.getBoundingClientRect();e.setTo(o.left-a.left,o.top-a.top,o.width,o.height);var h=this.windowConstraints;if(h.right){var l="layout"===h.right?r:s;e.right=Math.min(e.right,l.width)}if(h.bottom){var l="layout"===h.bottom?r:s;e.bottom=Math.min(e.bottom,l.height)}}else e.setTo(0,0,s.width,s.height);return e.setTo(Math.round(e.x),Math.round(e.y),Math.round(e.width),Math.round(e.height)),e},alignCanvas:function(t,e){var i=this.getParentBounds(this._tempBounds),s=this.game.canvas,n=this.margin;if(t){n.left=n.right=0;var r=s.getBoundingClientRect();if(this.width<i.width&&!this.incorrectOrientation){var o=r.left-i.x,a=i.width/2-this.width/2;a=Math.max(a,0);var h=a-o;n.left=Math.round(h)}s.style.marginLeft=n.left+"px",0!==n.left&&(n.right=-(i.width-r.width-n.left),s.style.marginRight=n.right+"px")}if(e){n.top=n.bottom=0;var r=s.getBoundingClientRect();if(this.height<i.height&&!this.incorrectOrientation){var o=r.top-i.y,a=i.height/2-this.height/2;a=Math.max(a,0);var h=a-o;n.top=Math.round(h)}s.style.marginTop=n.top+"px",0!==n.top&&(n.bottom=-(i.height-r.height-n.top),s.style.marginBottom=n.bottom+"px")}n.x=n.left,n.y=n.top},reflowGame:function(){this.resetCanvas("","");var t=this.getParentBounds(this._tempBounds);this.updateDimensions(t.width,t.height,!0)},reflowCanvas:function(){this.incorrectOrientation||(this.width=n.Math.clamp(this.width,this.minWidth||0,this.maxWidth||this.width),this.height=n.Math.clamp(this.height,this.minHeight||0,this.maxHeight||this.height)),this.resetCanvas(),this.compatibility.noMargins||(this.isFullScreen&&this._createdFullScreenTarget?this.alignCanvas(!0,!0):this.alignCanvas(this.pageAlignHorizontally,this.pageAlignVertically)),this.updateScalingAndBounds()},resetCanvas:function(t,e){void 0===t&&(t=this.width+"px"),void 0===e&&(e=this.height+"px");var i=this.game.canvas;this.compatibility.noMargins||(i.style.marginLeft="",i.style.marginTop="",i.style.marginRight="",i.style.marginBottom=""),i.style.width=t,i.style.height=e},queueUpdate:function(t){t&&(this._parentBounds.width=0,this._parentBounds.height=0),this._updateThrottle=this._updateThrottleReset},reset:function(t){t&&this.grid&&this.grid.reset()},setMaximum:function(){this.width=this.dom.visualBounds.width,this.height=this.dom.visualBounds.height},setShowAll:function(t){var e,i=this.getParentBounds(this._tempBounds),s=i.width,n=i.height;e=t?Math.max(n/this.game.height,s/this.game.width):Math.min(n/this.game.height,s/this.game.width),this.width=Math.round(this.game.width*e),this.height=Math.round(this.game.height*e)},setExactFit:function(){var t=this.getParentBounds(this._tempBounds);this.width=t.width,this.height=t.height,this.isFullScreen||(this.maxWidth&&(this.width=Math.min(this.width,this.maxWidth)),this.maxHeight&&(this.height=Math.min(this.height,this.maxHeight)))},createFullScreenTarget:function(){var t=document.createElement("div");return t.style.margin="0",t.style.padding="0",t.style.background="#000",t},startFullScreen:function(t,e){if(this.isFullScreen)return!1;if(!this.compatibility.supportsFullScreen){var i=this;return void setTimeout(function(){i.fullScreenError()},10)}if("when-not-mouse"===this.compatibility.clickTrampoline){var s=this.game.input;if(s.activePointer&&s.activePointer!==s.mousePointer&&(e||!1!==e))return void s.activePointer.addClickTrampoline("startFullScreen",this.startFullScreen,this,[t,!1])}void 0!==t&&this.game.renderType===n.CANVAS&&(this.game.stage.smoothed=t);var r=this.fullScreenTarget;r||(this.cleanupCreatedTarget(),this._createdFullScreenTarget=this.createFullScreenTarget(),r=this._createdFullScreenTarget);var o={targetElement:r};if(this.hasPhaserSetFullScreen=!0,this.onFullScreenInit.dispatch(this,o),this._createdFullScreenTarget){var a=this.game.canvas;a.parentNode.insertBefore(r,a),r.appendChild(a)}return this.game.device.fullscreenKeyboard?r[this.game.device.requestFullscreen](Element.ALLOW_KEYBOARD_INPUT):r[this.game.device.requestFullscreen](),!0},stopFullScreen:function(){return!(!this.isFullScreen||!this.compatibility.supportsFullScreen)&&(this.hasPhaserSetFullScreen=!1,document[this.game.device.cancelFullscreen](),!0)},cleanupCreatedTarget:function(){var t=this._createdFullScreenTarget;if(t&&t.parentNode){var e=t.parentNode;e.insertBefore(this.game.canvas,t),e.removeChild(t)}this._createdFullScreenTarget=null},prepScreenMode:function(t){var e=!!this._createdFullScreenTarget,i=this._createdFullScreenTarget||this.fullScreenTarget;t?(e||this.fullScreenScaleMode===n.ScaleManager.EXACT_FIT)&&i!==this.game.canvas&&(this._fullScreenRestore={targetWidth:i.style.width,targetHeight:i.style.height},i.style.width="100%",i.style.height="100%"):(this._fullScreenRestore&&(i.style.width=this._fullScreenRestore.targetWidth,i.style.height=this._fullScreenRestore.targetHeight,this._fullScreenRestore=null),this.updateDimensions(this._gameSize.width,this._gameSize.height,!0),this.resetCanvas())},fullScreenChange:function(t){this.event=t,this.isFullScreen?(this.prepScreenMode(!0),this.updateLayout(),this.queueUpdate(!0)):(this.prepScreenMode(!1),this.cleanupCreatedTarget(),this.updateLayout(),this.queueUpdate(!0)),this.onFullScreenChange.dispatch(this,this.width,this.height)},fullScreenError:function(t){this.event=t,this.cleanupCreatedTarget(),console.warn("Phaser.ScaleManager: requestFullscreen failed or device does not support the Fullscreen API"),this.onFullScreenError.dispatch(this)},scaleSprite:function(t,e,i,s){if(void 0===e&&(e=this.width),void 0===i&&(i=this.height),void 0===s&&(s=!1),!t||!t.scale)return t;if(t.scale.x=1,t.scale.y=1,t.width<=0||t.height<=0||e<=0||i<=0)return t;var n=e,r=t.height*e/t.width,o=t.width*i/t.height,a=i,h=o>e;return h=h?s:!s,h?(t.width=Math.floor(n),t.height=Math.floor(r)):(t.width=Math.floor(o),t.height=Math.floor(a)),t},destroy:function(){this.game.onResume.remove(this._gameResumed,this),window.removeEventListener("orientationchange",this._orientationChange,!1),window.removeEventListener("resize",this._windowResize,!1),this.compatibility.supportsFullScreen&&(document.removeEventListener("webkitfullscreenchange",this._fullScreenChange,!1),document.removeEventListener("mozfullscreenchange",this._fullScreenChange,!1),document.removeEventListener("MSFullscreenChange",this._fullScreenChange,!1),document.removeEventListener("fullscreenchange",this._fullScreenChange,!1),document.removeEventListener("webkitfullscreenerror",this._fullScreenError,!1),document.removeEventListener("mozfullscreenerror",this._fullScreenError,!1),document.removeEventListener("MSFullscreenError",this._fullScreenError,!1),document.removeEventListener("fullscreenerror",this._fullScreenError,!1))}},n.ScaleManager.prototype.constructor=n.ScaleManager,Object.defineProperty(n.ScaleManager.prototype,"boundingParent",{get:function(){return this.parentIsWindow||this.isFullScreen&&this.hasPhaserSetFullScreen&&!this._createdFullScreenTarget?null:this.game.canvas&&this.game.canvas.parentNode||null}}),Object.defineProperty(n.ScaleManager.prototype,"scaleMode",{get:function(){return this._scaleMode},set:function(t){return t!==this._scaleMode&&(this.isFullScreen||(this.updateDimensions(this._gameSize.width,this._gameSize.height,!0),this.queueUpdate(!0)),this._scaleMode=t),this._scaleMode}}),Object.defineProperty(n.ScaleManager.prototype,"fullScreenScaleMode",{get:function(){return this._fullScreenScaleMode},set:function(t){return t!==this._fullScreenScaleMode&&(this.isFullScreen?(this.prepScreenMode(!1),this._fullScreenScaleMode=t,this.prepScreenMode(!0),this.queueUpdate(!0)):this._fullScreenScaleMode=t),this._fullScreenScaleMode}}),Object.defineProperty(n.ScaleManager.prototype,"currentScaleMode",{get:function(){return this.isFullScreen?this._fullScreenScaleMode:this._scaleMode}}),Object.defineProperty(n.ScaleManager.prototype,"pageAlignHorizontally",{get:function(){return this._pageAlignHorizontally},set:function(t){t!==this._pageAlignHorizontally&&(this._pageAlignHorizontally=t,this.queueUpdate(!0))}}),Object.defineProperty(n.ScaleManager.prototype,"pageAlignVertically",{get:function(){return this._pageAlignVertically},set:function(t){t!==this._pageAlignVertically&&(this._pageAlignVertically=t,this.queueUpdate(!0))}}),Object.defineProperty(n.ScaleManager.prototype,"isFullScreen",{get:function(){return!!(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)}}),Object.defineProperty(n.ScaleManager.prototype,"isPortrait",{get:function(){return"portrait"===this.classifyOrientation(this.screenOrientation)}}),Object.defineProperty(n.ScaleManager.prototype,"isLandscape",{get:function(){return"landscape"===this.classifyOrientation(this.screenOrientation)}}),Object.defineProperty(n.ScaleManager.prototype,"isGamePortrait",{get:function(){return this.height>this.width}}),Object.defineProperty(n.ScaleManager.prototype,"isGameLandscape",{get:function(){return this.width>this.height}}),n.Utils.Debug=function(t){this.game=t,this.sprite=null,this.bmd=null,this.canvas=null,this.context=null,this.font="14px Courier",this.columnWidth=100,this.lineHeight=16,this.renderShadow=!0,this.currentX=0,this.currentY=0,this.currentAlpha=1,this.dirty=!1},n.Utils.Debug.prototype={boot:function(){this.game.renderType===n.CANVAS?this.context=this.game.context:(this.bmd=new n.BitmapData(this.game,"__DEBUG",this.game.width,this.game.height,!0),this.sprite=this.game.make.image(0,0,this.bmd),this.game.stage.addChild(this.sprite),this.game.scale.onSizeChange.add(this.resize,this),this.canvas=PIXI.CanvasPool.create(this,this.game.width,this.game.height),this.context=this.canvas.getContext("2d"))},resize:function(t,e,i){this.bmd.resize(e,i),this.canvas.width=e,this.canvas.height=i},preUpdate:function(){this.dirty&&this.sprite&&(this.bmd.clear(),this.bmd.draw(this.canvas,0,0),this.context.clearRect(0,0,this.game.width,this.game.height),this.dirty=!1)},reset:function(){this.context&&this.context.clearRect(0,0,this.game.width,this.game.height),this.sprite&&this.bmd.clear()},start:function(t,e,i,s){"number"!=typeof t&&(t=0),"number"!=typeof e&&(e=0),i=i||"rgb(255,255,255)",void 0===s&&(s=0),this.currentX=t,this.currentY=e,this.currentColor=i,this.columnWidth=s,this.dirty=!0,this.context.save(),this.context.setTransform(1,0,0,1,0,0),this.context.strokeStyle=i,this.context.fillStyle=i,this.context.font=this.font,this.context.globalAlpha=this.currentAlpha},stop:function(){this.context.restore()},line:function(){for(var t=this.currentX,e=0;e<arguments.length;e++)this.renderShadow&&(this.context.fillStyle="rgb(0,0,0)",this.context.fillText(arguments[e],t+1,this.currentY+1),this.context.fillStyle=this.currentColor),this.context.fillText(arguments[e],t,this.currentY),t+=this.columnWidth;this.currentY+=this.lineHeight},soundInfo:function(t,e,i,s){this.start(e,i,s),this.line("Sound: "+t.key+" Locked: "+t.game.sound.touchLocked),this.line("Is Ready?: "+this.game.cache.isSoundReady(t.key)+" Pending Playback: "+t.pendingPlayback),this.line("Decoded: "+t.isDecoded+" Decoding: "+t.isDecoding),this.line("Total Duration: "+t.totalDuration+" Playing: "+t.isPlaying),this.line("Time: "+t.currentTime),this.line("Volume: "+t.volume+" Muted: "+t.mute),this.line("WebAudio: "+t.usingWebAudio+" Audio: "+t.usingAudioTag),""!==t.currentMarker&&(this.line("Marker: "+t.currentMarker+" Duration: "+t.duration+" (ms: "+t.durationMS+")"),this.line("Start: "+t.markers[t.currentMarker].start+" Stop: "+t.markers[t.currentMarker].stop),this.line("Position: "+t.position)),this.stop()},cameraInfo:function(t,e,i,s){this.start(e,i,s),this.line("Camera ("+t.width+" x "+t.height+")"),this.line("X: "+t.x+" Y: "+t.y),t.bounds&&this.line("Bounds x: "+t.bounds.x+" Y: "+t.bounds.y+" w: "+t.bounds.width+" h: "+t.bounds.height),this.line("View x: "+t.view.x+" Y: "+t.view.y+" w: "+t.view.width+" h: "+t.view.height),this.line("Total in view: "+t.totalInView),this.stop()},timer:function(t,e,i,s){this.start(e,i,s),this.line("Timer (running: "+t.running+" expired: "+t.expired+")"),this.line("Next Tick: "+t.next+" Duration: "+t.duration),this.line("Paused: "+t.paused+" Length: "+t.length),this.stop()},pointer:function(t,e,i,s,n){null!=t&&(void 0===e&&(e=!1),i=i||"rgba(0,255,0,0.5)",s=s||"rgba(255,0,0,0.5)",!0===e&&!0===t.isUp||(this.start(t.x,t.y-100,n),this.context.beginPath(),this.context.arc(t.x,t.y,t.circle.radius,0,2*Math.PI),t.active?this.context.fillStyle=i:this.context.fillStyle=s,this.context.fill(),this.context.closePath(),this.context.beginPath(),this.context.moveTo(t.positionDown.x,t.positionDown.y),this.context.lineTo(t.position.x,t.position.y),this.context.lineWidth=2,this.context.stroke(),this.context.closePath(),this.line("ID: "+t.id+" Active: "+t.active),this.line("World X: "+t.worldX+" World Y: "+t.worldY),this.line("Screen X: "+t.x+" Screen Y: "+t.y+" In: "+t.withinGame),this.line("Duration: "+t.duration+" ms"),this.line("is Down: "+t.isDown+" is Up: "+t.isUp),this.stop()))},spriteInputInfo:function(t,e,i,s){this.start(e,i,s),this.line("Sprite Input: ("+t.width+" x "+t.height+")"),this.line("x: "+t.input.pointerX().toFixed(1)+" y: "+t.input.pointerY().toFixed(1)),this.line("over: "+t.input.pointerOver()+" duration: "+t.input.overDuration().toFixed(0)),this.line("down: "+t.input.pointerDown()+" duration: "+t.input.downDuration().toFixed(0)),this.line("just over: "+t.input.justOver()+" just out: "+t.input.justOut()),this.stop()},key:function(t,e,i,s){this.start(e,i,s,150),this.line("Key:",t.keyCode,"isDown:",t.isDown),this.line("justDown:",t.justDown,"justUp:",t.justUp),this.line("Time Down:",t.timeDown.toFixed(0),"duration:",t.duration.toFixed(0)),this.stop()},inputInfo:function(t,e,i){this.start(t,e,i),this.line("Input"),this.line("X: "+this.game.input.x+" Y: "+this.game.input.y),this.line("World X: "+this.game.input.worldX+" World Y: "+this.game.input.worldY),this.line("Scale X: "+this.game.input.scale.x.toFixed(1)+" Scale Y: "+this.game.input.scale.x.toFixed(1)),this.line("Screen X: "+this.game.input.activePointer.screenX+" Screen Y: "+this.game.input.activePointer.screenY),this.stop()},spriteBounds:function(t,e,i){var s=t.getBounds();s.x+=this.game.camera.x,s.y+=this.game.camera.y,this.rectangle(s,e,i)},ropeSegments:function(t,e,i){var s=this;t.segments.forEach(function(t){s.rectangle(t,e,i)},this)},spriteInfo:function(t,e,i,s){this.start(e,i,s),this.line("Sprite: ("+t.width+" x "+t.height+") anchor: "+t.anchor.x+" x "+t.anchor.y),this.line("x: "+t.x.toFixed(1)+" y: "+t.y.toFixed(1)),this.line("angle: "+t.angle.toFixed(1)+" rotation: "+t.rotation.toFixed(1)),this.line("visible: "+t.visible+" in camera: "+t.inCamera),this.line("bounds x: "+t._bounds.x.toFixed(1)+" y: "+t._bounds.y.toFixed(1)+" w: "+t._bounds.width.toFixed(1)+" h: "+t._bounds.height.toFixed(1)),this.stop()},spriteCoords:function(t,e,i,s){this.start(e,i,s,100),t.name&&this.line(t.name),this.line("x:",t.x.toFixed(2),"y:",t.y.toFixed(2)),this.line("pos x:",t.position.x.toFixed(2),"pos y:",t.position.y.toFixed(2)),this.line("world x:",t.world.x.toFixed(2),"world y:",t.world.y.toFixed(2)),this.stop()},lineInfo:function(t,e,i,s){this.start(e,i,s,80),this.line("start.x:",t.start.x.toFixed(2),"start.y:",t.start.y.toFixed(2)),this.line("end.x:",t.end.x.toFixed(2),"end.y:",t.end.y.toFixed(2)),this.line("length:",t.length.toFixed(2),"angle:",t.angle),this.stop()},pixel:function(t,e,i,s){s=s||2,this.start(),this.context.fillStyle=i,this.context.fillRect(t,e,s,s),this.stop()},geom:function(t,e,i,s){void 0===i&&(i=!0),void 0===s&&(s=0),e=e||"rgba(0,255,0,0.4)",this.start(),this.context.fillStyle=e,this.context.strokeStyle=e,t instanceof n.Rectangle||1===s?i?this.context.fillRect(t.x-this.game.camera.x,t.y-this.game.camera.y,t.width,t.height):this.context.strokeRect(t.x-this.game.camera.x,t.y-this.game.camera.y,t.width,t.height):t instanceof n.Circle||2===s?(this.context.beginPath(),this.context.arc(t.x-this.game.camera.x,t.y-this.game.camera.y,t.radius,0,2*Math.PI,!1),this.context.closePath(),i?this.context.fill():this.context.stroke()):t instanceof n.Point||3===s?this.context.fillRect(t.x-this.game.camera.x,t.y-this.game.camera.y,4,4):(t instanceof n.Line||4===s)&&(this.context.lineWidth=1,this.context.beginPath(),this.context.moveTo(t.start.x+.5-this.game.camera.x,t.start.y+.5-this.game.camera.y),this.context.lineTo(t.end.x+.5-this.game.camera.x,t.end.y+.5-this.game.camera.y),this.context.closePath(),this.context.stroke()),this.stop()},rectangle:function(t,e,i){void 0===i&&(i=!0),e=e||"rgba(0, 255, 0, 0.4)",this.start(),i?(this.context.fillStyle=e,this.context.fillRect(t.x-this.game.camera.x,t.y-this.game.camera.y,t.width,t.height)):(this.context.strokeStyle=e,this.context.strokeRect(t.x-this.game.camera.x,t.y-this.game.camera.y,t.width,t.height)),this.stop()},text:function(t,e,i,s,n){s=s||"rgb(255,255,255)",n=n||"16px Courier",this.start(),this.context.font=n,this.renderShadow&&(this.context.fillStyle="rgb(0,0,0)",this.context.fillText(t,e+1,i+1)),this.context.fillStyle=s,this.context.fillText(t,e,i),this.stop()},quadTree:function(t,e){e=e||"rgba(255,0,0,0.3)",this.start();var i=t.bounds;if(0===t.nodes.length){this.context.strokeStyle=e,this.context.strokeRect(i.x,i.y,i.width,i.height),this.text("size: "+t.objects.length,i.x+4,i.y+16,"rgb(0,200,0)","12px Courier"),this.context.strokeStyle="rgb(0,255,0)";for(var s=0;s<t.objects.length;s++)this.context.strokeRect(t.objects[s].x,t.objects[s].y,t.objects[s].width,t.objects[s].height)}else for(var s=0;s<t.nodes.length;s++)this.quadTree(t.nodes[s]);this.stop()},body:function(t,e,i){t.body&&(this.start(),t.body.type===n.Physics.ARCADE?n.Physics.Arcade.Body.render(this.context,t.body,e,i):t.body.type===n.Physics.NINJA?n.Physics.Ninja.Body.render(this.context,t.body,e,i):t.body.type===n.Physics.BOX2D&&n.Physics.Box2D.renderBody(this.context,t.body,e),this.stop())},bodyInfo:function(t,e,i,s){t.body&&(this.start(e,i,s,210),t.body.type===n.Physics.ARCADE?n.Physics.Arcade.Body.renderBodyInfo(this,t.body):t.body.type===n.Physics.BOX2D&&this.game.physics.box2d.renderBodyInfo(this,t.body),this.stop())},box2dWorld:function(){this.start(),this.context.translate(-this.game.camera.view.x,-this.game.camera.view.y,0),this.game.physics.box2d.renderDebugDraw(this.context),this.stop()},box2dBody:function(t,e){this.start(),n.Physics.Box2D.renderBody(this.context,t,e),this.stop()},displayList:function(t){if(void 0===t&&(t=this.game.world),t.hasOwnProperty("renderOrderID")?console.log("["+t.renderOrderID+"]",t):console.log("[]",t),t.children&&t.children.length>0)for(var e=0;e<t.children.length;e++)this.game.debug.displayList(t.children[e])},destroy:function(){PIXI.CanvasPool.remove(this)}},n.Utils.Debug.prototype.constructor=n.Utils.Debug,n.DOM={getOffset:function(t,e){e=e||new n.Point;var i=t.getBoundingClientRect(),s=n.DOM.scrollY,r=n.DOM.scrollX,o=document.documentElement.clientTop,a=document.documentElement.clientLeft;return e.x=i.left+r-a,e.y=i.top+s-o,e},getBounds:function(t,e){return void 0===e&&(e=0),!(!(t=t&&!t.nodeType?t[0]:t)||1!==t.nodeType)&&this.calibrate(t.getBoundingClientRect(),e)},calibrate:function(t,e){e=+e||0;var i={width:0,height:0,left:0,right:0,top:0,bottom:0};return i.width=(i.right=t.right+e)-(i.left=t.left-e),i.height=(i.bottom=t.bottom+e)-(i.top=t.top-e),i},getAspectRatio:function(t){t=null==t?this.visualBounds:1===t.nodeType?this.getBounds(t):t;var e=t.width,i=t.height;return"function"==typeof e&&(e=e.call(t)),"function"==typeof i&&(i=i.call(t)),e/i},inLayoutViewport:function(t,e){var i=this.getBounds(t,e);return!!i&&i.bottom>=0&&i.right>=0&&i.top<=this.layoutBounds.width&&i.left<=this.layoutBounds.height},getScreenOrientation:function(t){var e=window.screen,i=e.orientation||e.mozOrientation||e.msOrientation;if(i&&"string"==typeof i.type)return i.type;if("string"==typeof i)return i;var s="portrait-primary",n="landscape-primary";if("screen"===t)return e.height>e.width?s:n;if("viewport"===t)return this.visualBounds.height>this.visualBounds.width?s:n;if("window.orientation"===t&&"number"==typeof window.orientation)return 0===window.orientation||180===window.orientation?s:n;if(window.matchMedia){if(window.matchMedia("(orientation: portrait)").matches)return s;if(window.matchMedia("(orientation: landscape)").matches)return n}return this.visualBounds.height>this.visualBounds.width?s:n},visualBounds:new n.Rectangle,layoutBounds:new n.Rectangle,documentBounds:new n.Rectangle},n.Device.whenReady(function(t){var e=window&&"pageXOffset"in window?function(){return window.pageXOffset}:function(){return document.documentElement.scrollLeft},i=window&&"pageYOffset"in window?function(){return window.pageYOffset}:function(){return document.documentElement.scrollTop};if(Object.defineProperty(n.DOM,"scrollX",{get:e}),Object.defineProperty(n.DOM,"scrollY",{get:i}),Object.defineProperty(n.DOM.visualBounds,"x",{get:e}),Object.defineProperty(n.DOM.visualBounds,"y",{get:i}),Object.defineProperty(n.DOM.layoutBounds,"x",{value:0}),Object.defineProperty(n.DOM.layoutBounds,"y",{value:0}),t.desktop&&document.documentElement.clientWidth<=window.innerWidth&&document.documentElement.clientHeight<=window.innerHeight){var s=function(){return Math.max(window.innerWidth,document.documentElement.clientWidth)},r=function(){return Math.max(window.innerHeight,document.documentElement.clientHeight)};Object.defineProperty(n.DOM.visualBounds,"width",{get:s}),Object.defineProperty(n.DOM.visualBounds,"height",{get:r}),Object.defineProperty(n.DOM.layoutBounds,"width",{get:s}),Object.defineProperty(n.DOM.layoutBounds,"height",{get:r})}else Object.defineProperty(n.DOM.visualBounds,"width",{get:function(){return window.innerWidth}}),Object.defineProperty(n.DOM.visualBounds,"height",{get:function(){return window.innerHeight}}),Object.defineProperty(n.DOM.layoutBounds,"width",{get:function(){var t=document.documentElement.clientWidth,e=window.innerWidth;return t<e?e:t}}),Object.defineProperty(n.DOM.layoutBounds,"height",{get:function(){var t=document.documentElement.clientHeight,e=window.innerHeight;return t<e?e:t}});Object.defineProperty(n.DOM.documentBounds,"x",{value:0}),Object.defineProperty(n.DOM.documentBounds,"y",{value:0}),Object.defineProperty(n.DOM.documentBounds,"width",{get:function(){var t=document.documentElement;return Math.max(t.clientWidth,t.offsetWidth,t.scrollWidth)}}),Object.defineProperty(n.DOM.documentBounds,"height",{get:function(){var t=document.documentElement;return Math.max(t.clientHeight,t.offsetHeight,t.scrollHeight)}})},null,!0),n.ArraySet=function(t){this.position=0,this.list=t||[]},n.ArraySet.prototype={add:function(t){return this.exists(t)||this.list.push(t),t},getIndex:function(t){return this.list.indexOf(t)},getByKey:function(t,e){for(var i=this.list.length;i--;)if(this.list[i][t]===e)return this.list[i];return null},exists:function(t){return this.list.indexOf(t)>-1},reset:function(){this.list.length=0},remove:function(t){var e=this.list.indexOf(t);if(e>-1)return this.list.splice(e,1),t},setAll:function(t,e){for(var i=this.list.length;i--;)this.list[i]&&(this.list[i][t]=e)},callAll:function(t){for(var e=Array.prototype.slice.call(arguments,1),i=this.list.length;i--;)this.list[i]&&this.list[i][t]&&this.list[i][t].apply(this.list[i],e)},removeAll:function(t){void 0===t&&(t=!1);for(var e=this.list.length;e--;)if(this.list[e]){var i=this.remove(this.list[e]);t&&i.destroy()}this.position=0,this.list=[]}},Object.defineProperty(n.ArraySet.prototype,"total",{get:function(){return this.list.length}}),Object.defineProperty(n.ArraySet.prototype,"first",{get:function(){return this.position=0,this.list.length>0?this.list[0]:null}}),Object.defineProperty(n.ArraySet.prototype,"next",{get:function(){return this.position<this.list.length?(this.position++,this.list[this.position]):null}}),n.ArraySet.prototype.constructor=n.ArraySet,n.ArrayUtils={getRandomItem:function(t,e,i){if(null===t)return null;void 0===e&&(e=0),void 0===i&&(i=t.length);var s=e+Math.floor(Math.random()*i);return void 0===t[s]?null:t[s]},removeRandomItem:function(t,e,i){if(null==t)return null;void 0===e&&(e=0),void 0===i&&(i=t.length);var s=e+Math.floor(Math.random()*i);if(s<t.length){var n=t.splice(s,1);return void 0===n[0]?null:n[0]}return null},shuffle:function(t){for(var e=t.length-1;e>0;e--){var i=Math.floor(Math.random()*(e+1)),s=t[e];t[e]=t[i],t[i]=s}return t},transposeMatrix:function(t){for(var e=t.length,i=t[0].length,s=new Array(i),n=0;n<i;n++){s[n]=new Array(e);for(var r=e-1;r>-1;r--)s[n][r]=t[r][n]}return s},rotateMatrix:function(t,e){if("string"!=typeof e&&(e=(e%360+360)%360),90===e||-270===e||"rotateLeft"===e)t=n.ArrayUtils.transposeMatrix(t),t=t.reverse();else if(-90===e||270===e||"rotateRight"===e)t=t.reverse(),t=n.ArrayUtils.transposeMatrix(t);else if(180===Math.abs(e)||"rotate180"===e){for(var i=0;i<t.length;i++)t[i].reverse();t=t.reverse()}return t},findClosest:function(t,e){if(!e.length)return NaN;if(1===e.length||t<e[0])return e[0];for(var i=1;e[i]<t;)i++;var s=e[i-1],n=i<e.length?e[i]:Number.POSITIVE_INFINITY;return n-t<=t-s?n:s},rotateRight:function(t){var e=t.pop();return t.unshift(e),e},rotateLeft:function(t){var e=t.shift();return t.push(e),e},rotate:function(t){var e=t.shift();return t.push(e),e},numberArray:function(t,e){for(var i=[],s=t;s<=e;s++)i.push(s);return i},numberArrayStep:function(t,e,i){void 0!==t&&null!==t||(t=0),void 0!==e&&null!==e||(e=t,t=0),void 0===i&&(i=1);for(var s=[],r=Math.max(n.Math.roundAwayFromZero((e-t)/(i||1)),0),o=0;o<r;o++)s.push(t),t+=i;return s}},n.LinkedList=function(){this.next=null,this.prev=null,this.first=null,this.last=null,this.total=0},n.LinkedList.prototype={add:function(t){return 0===this.total&&null===this.first&&null===this.last?(this.first=t,this.last=t,this.next=t,t.prev=this,this.total++,t):(this.last.next=t,t.prev=this.last,this.last=t,this.total++,t)},reset:function(){this.first=null,this.last=null,this.next=null,this.prev=null,this.total=0},remove:function(t){if(1===this.total)return this.reset(),void(t.next=t.prev=null);t===this.first?this.first=this.first.next:t===this.last&&(this.last=this.last.prev),t.prev&&(t.prev.next=t.next),t.next&&(t.next.prev=t.prev),t.next=t.prev=null,null===this.first&&(this.last=null),this.total--},callAll:function(t){if(this.first&&this.last){var e=this.first;do{e&&e[t]&&e[t].call(e),e=e.next}while(e!==this.last.next)}}},n.LinkedList.prototype.constructor=n.LinkedList,n.Create=function(t){this.game=t,this.bmd=null,this.canvas=null,this.ctx=null,this.palettes=[{0:"#000",1:"#9D9D9D",2:"#FFF",3:"#BE2633",4:"#E06F8B",5:"#493C2B",6:"#A46422",7:"#EB8931",8:"#F7E26B",9:"#2F484E",A:"#44891A",B:"#A3CE27",C:"#1B2632",D:"#005784",E:"#31A2F2",F:"#B2DCEF"},{0:"#000",1:"#191028",2:"#46af45",3:"#a1d685",4:"#453e78",5:"#7664fe",6:"#833129",7:"#9ec2e8",8:"#dc534b",9:"#e18d79",A:"#d6b97b",B:"#e9d8a1",C:"#216c4b",D:"#d365c8",E:"#afaab9",F:"#f5f4eb"},{0:"#000",1:"#2234d1",2:"#0c7e45",3:"#44aacc",4:"#8a3622",5:"#5c2e78",6:"#aa5c3d",7:"#b5b5b5",8:"#5e606e",9:"#4c81fb",A:"#6cd947",B:"#7be2f9",C:"#eb8a60",D:"#e23d69",E:"#ffd93f",F:"#fff"},{0:"#000",1:"#fff",2:"#8b4131",3:"#7bbdc5",4:"#8b41ac",5:"#6aac41",6:"#3931a4",7:"#d5de73",8:"#945a20",9:"#5a4100",A:"#bd736a",B:"#525252",C:"#838383",D:"#acee8b",E:"#7b73de",F:"#acacac"},{0:"#000",1:"#191028",2:"#46af45",3:"#a1d685",4:"#453e78",5:"#7664fe",6:"#833129",7:"#9ec2e8",8:"#dc534b",9:"#e18d79",A:"#d6b97b",B:"#e9d8a1",C:"#216c4b",D:"#d365c8",E:"#afaab9",F:"#fff"}]},n.Create.PALETTE_ARNE=0,n.Create.PALETTE_JMP=1,n.Create.PALETTE_CGA=2,n.Create.PALETTE_C64=3,n.Create.PALETTE_JAPANESE_MACHINE=4,n.Create.prototype={texture:function(t,e,i,s,n){void 0===i&&(i=8),void 0===s&&(s=i),void 0===n&&(n=0);var r=e[0].length*i,o=e.length*s;null===this.bmd&&(this.bmd=this.game.make.bitmapData(),this.canvas=this.bmd.canvas,this.ctx=this.bmd.context),this.bmd.resize(r,o),this.bmd.clear();for(var a=0;a<e.length;a++)for(var h=e[a],l=0;l<h.length;l++){var c=h[l];"."!==c&&" "!==c&&(this.ctx.fillStyle=this.palettes[n][c],this.ctx.fillRect(l*i,a*s,i,s))}return this.bmd.generateTexture(t)},grid:function(t,e,i,s,n,r){null===this.bmd&&(this.bmd=this.game.make.bitmapData(),this.canvas=this.bmd.canvas,this.ctx=this.bmd.context),this.bmd.resize(e,i),this.ctx.fillStyle=r;for(var o=0;o<i;o+=n)this.ctx.fillRect(0,o,e,1);for(var a=0;a<e;a+=s)this.ctx.fillRect(a,0,1,i);return this.bmd.generateTexture(t)}},n.Create.prototype.constructor=n.Create,n.FlexGrid=function(t,e,i){this.game=t.game,this.manager=t,this.width=e,this.height=i,this.boundsCustom=new n.Rectangle(0,0,e,i),this.boundsFluid=new n.Rectangle(0,0,e,i),this.boundsFull=new n.Rectangle(0,0,e,i),this.boundsNone=new n.Rectangle(0,0,e,i),this.positionCustom=new n.Point(0,0),this.positionFluid=new n.Point(0,0),this.positionFull=new n.Point(0,0),this.positionNone=new n.Point(0,0),this.scaleCustom=new n.Point(1,1),this.scaleFluid=new n.Point(1,1),this.scaleFluidInversed=new n.Point(1,1),this.scaleFull=new n.Point(1,1),this.scaleNone=new n.Point(1,1),this.customWidth=0,this.customHeight=0,this.customOffsetX=0,this.customOffsetY=0,this.ratioH=e/i,this.ratioV=i/e,this.multiplier=0,this.layers=[]},n.FlexGrid.prototype={setSize:function(t,e){this.width=t,this.height=e,this.ratioH=t/e,this.ratioV=e/t,this.scaleNone=new n.Point(1,1),this.boundsNone.width=this.width,this.boundsNone.height=this.height,this.refresh()},createCustomLayer:function(t,e,i,s){void 0===s&&(s=!0),this.customWidth=t,this.customHeight=e,this.boundsCustom.width=t,this.boundsCustom.height=e;var r=new n.FlexLayer(this,this.positionCustom,this.boundsCustom,this.scaleCustom);return s&&this.game.world.add(r),this.layers.push(r),void 0!==i&&null!==typeof i&&r.addMultiple(i),r},createFluidLayer:function(t,e){void 0===e&&(e=!0);var i=new n.FlexLayer(this,this.positionFluid,this.boundsFluid,this.scaleFluid);return e&&this.game.world.add(i),this.layers.push(i),void 0!==t&&null!==typeof t&&i.addMultiple(t),i},createFullLayer:function(t){var e=new n.FlexLayer(this,this.positionFull,this.boundsFull,this.scaleFluid);return this.game.world.add(e),this.layers.push(e),void 0!==t&&e.addMultiple(t),e},createFixedLayer:function(t){var e=new n.FlexLayer(this,this.positionNone,this.boundsNone,this.scaleNone);return this.game.world.add(e),this.layers.push(e),void 0!==t&&e.addMultiple(t),e},reset:function(){for(var t=this.layers.length;t--;)this.layers[t].persist||(this.layers[t].position=null,this.layers[t].scale=null,this.layers.slice(t,1))},onResize:function(t,e){this.ratioH=t/e,this.ratioV=e/t,this.refresh(t,e)},refresh:function(){this.multiplier=Math.min(this.manager.height/this.height,this.manager.width/this.width),this.boundsFluid.width=Math.round(this.width*this.multiplier),this.boundsFluid.height=Math.round(this.height*this.multiplier),this.scaleFluid.set(this.boundsFluid.width/this.width,this.boundsFluid.height/this.height),this.scaleFluidInversed.set(this.width/this.boundsFluid.width,this.height/this.boundsFluid.height),this.scaleFull.set(this.boundsFull.width/this.width,this.boundsFull.height/this.height),this.boundsFull.width=Math.round(this.manager.width*this.scaleFluidInversed.x),this.boundsFull.height=Math.round(this.manager.height*this.scaleFluidInversed.y),this.boundsFluid.centerOn(this.manager.bounds.centerX,this.manager.bounds.centerY),this.boundsNone.centerOn(this.manager.bounds.centerX,this.manager.bounds.centerY),this.positionFluid.set(this.boundsFluid.x,this.boundsFluid.y),this.positionNone.set(this.boundsNone.x,this.boundsNone.y)},fitSprite:function(t){this.manager.scaleSprite(t),t.x=this.manager.bounds.centerX,t.y=this.manager.bounds.centerY},debug:function(){this.game.debug.text(this.boundsFluid.width+" x "+this.boundsFluid.height,this.boundsFluid.x+4,this.boundsFluid.y+16),this.game.debug.geom(this.boundsFluid,"rgba(255,0,0,0.9",!1)}},n.FlexGrid.prototype.constructor=n.FlexGrid,n.FlexLayer=function(t,e,i,s){n.Group.call(this,t.game,null,"__flexLayer"+t.game.rnd.uuid(),!1),this.manager=t.manager,this.grid=t,this.persist=!1,this.position=e,this.bounds=i,this.scale=s,this.topLeft=i.topLeft,this.topMiddle=new n.Point(i.halfWidth,0),this.topRight=i.topRight,this.bottomLeft=i.bottomLeft,this.bottomMiddle=new n.Point(i.halfWidth,i.bottom),this.bottomRight=i.bottomRight},n.FlexLayer.prototype=Object.create(n.Group.prototype),n.FlexLayer.prototype.constructor=n.FlexLayer,n.FlexLayer.prototype.resize=function(){},n.FlexLayer.prototype.debug=function(){this.game.debug.text(this.bounds.width+" x "+this.bounds.height,this.bounds.x+4,this.bounds.y+16),this.game.debug.geom(this.bounds,"rgba(0,0,255,0.9",!1),this.game.debug.geom(this.topLeft,"rgba(255,255,255,0.9"),this.game.debug.geom(this.topMiddle,"rgba(255,255,255,0.9"),this.game.debug.geom(this.topRight,"rgba(255,255,255,0.9")},n.Color={packPixel:function(t,e,i,s){return n.Device.LITTLE_ENDIAN?(s<<24|i<<16|e<<8|t)>>>0:(t<<24|e<<16|i<<8|s)>>>0},unpackPixel:function(t,e,i,s){return void 0!==e&&null!==e||(e=n.Color.createColor()),void 0!==i&&null!==i||(i=!1),void 0!==s&&null!==s||(s=!1),n.Device.LITTLE_ENDIAN?(e.a=(4278190080&t)>>>24,e.b=(16711680&t)>>>16,e.g=(65280&t)>>>8,e.r=255&t):(e.r=(4278190080&t)>>>24,e.g=(16711680&t)>>>16,e.b=(65280&t)>>>8,e.a=255&t),e.color=t,e.rgba="rgba("+e.r+","+e.g+","+e.b+","+e.a/255+")",i&&n.Color.RGBtoHSL(e.r,e.g,e.b,e),s&&n.Color.RGBtoHSV(e.r,e.g,e.b,e),e},fromRGBA:function(t,e){return e||(e=n.Color.createColor()),e.r=(4278190080&t)>>>24,e.g=(16711680&t)>>>16,e.b=(65280&t)>>>8,e.a=255&t,e.rgba="rgba("+e.r+","+e.g+","+e.b+","+e.a+")",e},toRGBA:function(t,e,i,s){return t<<24|e<<16|i<<8|s},toABGR:function(t,e,i,s){return(s<<24|i<<16|e<<8|t)>>>0},RGBtoHSL:function(t,e,i,s){s||(s=n.Color.createColor(t,e,i,1)),t/=255,e/=255,i/=255;var r=Math.min(t,e,i),o=Math.max(t,e,i);if(s.h=0,s.s=0,s.l=(o+r)/2,o!==r){var a=o-r;s.s=s.l>.5?a/(2-o-r):a/(o+r),o===t?s.h=(e-i)/a+(e<i?6:0):o===e?s.h=(i-t)/a+2:o===i&&(s.h=(t-e)/a+4),s.h/=6}return s},HSLtoRGB:function(t,e,i,s){if(s?(s.r=i,s.g=i,s.b=i):s=n.Color.createColor(i,i,i),0!==e){var r=i<.5?i*(1+e):i+e-i*e,o=2*i-r;s.r=n.Color.hueToColor(o,r,t+1/3),s.g=n.Color.hueToColor(o,r,t),s.b=n.Color.hueToColor(o,r,t-1/3)}return s.r=Math.floor(255*s.r|0),s.g=Math.floor(255*s.g|0),s.b=Math.floor(255*s.b|0),n.Color.updateColor(s),s},RGBtoHSV:function(t,e,i,s){s||(s=n.Color.createColor(t,e,i,255)),t/=255,e/=255,i/=255;var r=Math.min(t,e,i),o=Math.max(t,e,i),a=o-r;return s.h=0,s.s=0===o?0:a/o,s.v=o,o!==r&&(o===t?s.h=(e-i)/a+(e<i?6:0):o===e?s.h=(i-t)/a+2:o===i&&(s.h=(t-e)/a+4),s.h/=6),s},HSVtoRGB:function(t,e,i,s){void 0===s&&(s=n.Color.createColor(0,0,0,1,t,e,0,i));var r,o,a,h=Math.floor(6*t),l=6*t-h,c=i*(1-e),u=i*(1-l*e),d=i*(1-(1-l)*e);switch(h%6){case 0:r=i,o=d,a=c;break;case 1:r=u,o=i,a=c;break;case 2:r=c,o=i,a=d;break;case 3:r=c,o=u,a=i;break;case 4:r=d,o=c,a=i;break;case 5:r=i,o=c,a=u}return s.r=Math.floor(255*r),s.g=Math.floor(255*o),s.b=Math.floor(255*a),n.Color.updateColor(s),s},hueToColor:function(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t},createColor:function(t,e,i,s,r,o,a,h){var l={r:t||0,g:e||0,b:i||0,a:s||1,h:r||0,s:o||0,l:a||0,v:h||0,color:0,color32:0,rgba:""};return n.Color.updateColor(l)},updateColor:function(t){return t.rgba="rgba("+t.r.toString()+","+t.g.toString()+","+t.b.toString()+","+t.a.toString()+")",t.color=n.Color.getColor(t.r,t.g,t.b),t.color32=n.Color.getColor32(255*t.a,t.r,t.g,t.b),t},getColor32:function(t,e,i,s){return t<<24|e<<16|i<<8|s},getColor:function(t,e,i){return t<<16|e<<8|i},RGBtoString:function(t,e,i,s,r){return void 0===s&&(s=255),void 0===r&&(r="#"),"#"===r?"#"+((1<<24)+(t<<16)+(e<<8)+i).toString(16).slice(1):"0x"+n.Color.componentToHex(s)+n.Color.componentToHex(t)+n.Color.componentToHex(e)+n.Color.componentToHex(i)},hexToRGB:function(t){var e=n.Color.hexToColor(t);if(e)return n.Color.getColor32(e.a,e.r,e.g,e.b)},hexToColor:function(t,e){t=t.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i,function(t,e,i,s){return e+e+i+i+s+s});var i=/^(?:#|0x)?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);if(i){var s=parseInt(i[1],16),r=parseInt(i[2],16),o=parseInt(i[3],16);e?(e.r=s,e.g=r,e.b=o):e=n.Color.createColor(s,r,o)}return e},webToColor:function(t,e){e||(e=n.Color.createColor());var i=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?))?\s*\)$/.exec(t);return i&&(e.r=parseInt(i[1],10),e.g=parseInt(i[2],10),e.b=parseInt(i[3],10),e.a=void 0!==i[4]?parseFloat(i[4]):1,n.Color.updateColor(e)),e},valueToColor:function(t,e){if(e||(e=n.Color.createColor()),"string"==typeof t)return 0===t.indexOf("rgb")?n.Color.webToColor(t,e):(e.a=1,n.Color.hexToColor(t,e));if("number"==typeof t){var i=n.Color.getRGB(t);return e.r=i.r,e.g=i.g,e.b=i.b,e.a=i.a/255,e}return e},componentToHex:function(t){var e=t.toString(16);return 1===e.length?"0"+e:e},HSVColorWheel:function(t,e){void 0===t&&(t=1),void 0===e&&(e=1);for(var i=[],s=0;s<=359;s++)i.push(n.Color.HSVtoRGB(s/359,t,e));return i},HSLColorWheel:function(t,e){void 0===t&&(t=.5),void 0===e&&(e=.5);for(var i=[],s=0;s<=359;s++)i.push(n.Color.HSLtoRGB(s/359,t,e));return i},interpolateColor:function(t,e,i,s,r){void 0===r&&(r=255);var o=n.Color.getRGB(t),a=n.Color.getRGB(e),h=(a.red-o.red)*s/i+o.red,l=(a.green-o.green)*s/i+o.green,c=(a.blue-o.blue)*s/i+o.blue;return n.Color.getColor32(r,h,l,c)},interpolateColorWithRGB:function(t,e,i,s,r,o){var a=n.Color.getRGB(t),h=(e-a.red)*o/r+a.red,l=(i-a.green)*o/r+a.green,c=(s-a.blue)*o/r+a.blue;return n.Color.getColor(h,l,c)},interpolateRGB:function(t,e,i,s,r,o,a,h){var l=(s-t)*h/a+t,c=(r-e)*h/a+e,u=(o-i)*h/a+i;return n.Color.getColor(l,c,u)},getRandomColor:function(t,e,i){if(void 0===t&&(t=0),void 0===e&&(e=255),void 0===i&&(i=255),e>255||t>e)return n.Color.getColor(255,255,255);var s=t+Math.round(Math.random()*(e-t)),r=t+Math.round(Math.random()*(e-t)),o=t+Math.round(Math.random()*(e-t));return n.Color.getColor32(i,s,r,o)},getRGB:function(t){return t>16777215?{alpha:t>>>24,red:t>>16&255,green:t>>8&255,blue:255&t,a:t>>>24,r:t>>16&255,g:t>>8&255,b:255&t}:{alpha:255,red:t>>16&255,green:t>>8&255,blue:255&t,a:255,r:t>>16&255,g:t>>8&255,b:255&t}},getWebRGB:function(t){if("object"==typeof t)return"rgba("+t.r.toString()+","+t.g.toString()+","+t.b.toString()+","+(t.a/255).toString()+")";var e=n.Color.getRGB(t);return"rgba("+e.r.toString()+","+e.g.toString()+","+e.b.toString()+","+(e.a/255).toString()+")"},getAlpha:function(t){return t>>>24},getAlphaFloat:function(t){return(t>>>24)/255},getRed:function(t){return t>>16&255},getGreen:function(t){return t>>8&255},getBlue:function(t){return 255&t},blendNormal:function(t){return t},blendLighten:function(t,e){return e>t?e:t},blendDarken:function(t,e){return e>t?t:e},blendMultiply:function(t,e){return t*e/255},blendAverage:function(t,e){return(t+e)/2},blendAdd:function(t,e){return Math.min(255,t+e)},blendSubtract:function(t,e){return Math.max(0,t+e-255)},blendDifference:function(t,e){return Math.abs(t-e)},blendNegation:function(t,e){return 255-Math.abs(255-t-e)},blendScreen:function(t,e){return 255-((255-t)*(255-e)>>8)},blendExclusion:function(t,e){return t+e-2*t*e/255},blendOverlay:function(t,e){return e<128?2*t*e/255:255-2*(255-t)*(255-e)/255},blendSoftLight:function(t,e){return e<128?2*(64+(t>>1))*(e/255):255-2*(255-(64+(t>>1)))*(255-e)/255},blendHardLight:function(t,e){return n.Color.blendOverlay(e,t)},blendColorDodge:function(t,e){return 255===e?e:Math.min(255,(t<<8)/(255-e))},blendColorBurn:function(t,e){return 0===e?e:Math.max(0,255-(255-t<<8)/e)},blendLinearDodge:function(t,e){return n.Color.blendAdd(t,e)},blendLinearBurn:function(t,e){return n.Color.blendSubtract(t,e)},blendLinearLight:function(t,e){return e<128?n.Color.blendLinearBurn(t,2*e):n.Color.blendLinearDodge(t,2*(e-128))},blendVividLight:function(t,e){return e<128?n.Color.blendColorBurn(t,2*e):n.Color.blendColorDodge(t,2*(e-128))},blendPinLight:function(t,e){return e<128?n.Color.blendDarken(t,2*e):n.Color.blendLighten(t,2*(e-128))},blendHardMix:function(t,e){return n.Color.blendVividLight(t,e)<128?0:255},blendReflect:function(t,e){return 255===e?e:Math.min(255,t*t/(255-e))},blendGlow:function(t,e){return n.Color.blendReflect(e,t)},blendPhoenix:function(t,e){return Math.min(t,e)-Math.max(t,e)+255}},n.Physics=function(t,e){e=e||{},this.game=t,this.config=e,this.arcade=null,this.p2=null,this.ninja=null,this.box2d=null,this.chipmunk=null,this.matter=null,this.parseConfig()},n.Physics.ARCADE=0,n.Physics.P2JS=1,n.Physics.NINJA=2,n.Physics.BOX2D=3,n.Physics.CHIPMUNK=4,n.Physics.MATTERJS=5,n.Physics.prototype={parseConfig:function(){this.config.hasOwnProperty("arcade")&&!0!==this.config.arcade||!n.Physics.hasOwnProperty("Arcade")||(this.arcade=new n.Physics.Arcade(this.game)),this.config.hasOwnProperty("ninja")&&!0===this.config.ninja&&n.Physics.hasOwnProperty("Ninja")&&(this.ninja=new n.Physics.Ninja(this.game)),this.config.hasOwnProperty("p2")&&!0===this.config.p2&&n.Physics.hasOwnProperty("P2")&&(this.p2=new n.Physics.P2(this.game,this.config)),this.config.hasOwnProperty("box2d")&&!0===this.config.box2d&&n.Physics.hasOwnProperty("BOX2D")&&(this.box2d=new n.Physics.BOX2D(this.game,this.config)),this.config.hasOwnProperty("matter")&&!0===this.config.matter&&n.Physics.hasOwnProperty("Matter")&&(this.matter=new n.Physics.Matter(this.game,this.config))},startSystem:function(t){t===n.Physics.ARCADE?this.arcade=new n.Physics.Arcade(this.game):t===n.Physics.P2JS?null===this.p2?this.p2=new n.Physics.P2(this.game,this.config):this.p2.reset():t===n.Physics.NINJA?this.ninja=new n.Physics.Ninja(this.game):t===n.Physics.BOX2D?null===this.box2d?this.box2d=new n.Physics.Box2D(this.game,this.config):this.box2d.reset():t===n.Physics.MATTERJS&&(null===this.matter?this.matter=new n.Physics.Matter(this.game,this.config):this.matter.reset())},enable:function(t,e,i){void 0===e&&(e=n.Physics.ARCADE),void 0===i&&(i=!1),e===n.Physics.ARCADE?this.arcade.enable(t):e===n.Physics.P2JS&&this.p2?this.p2.enable(t,i):e===n.Physics.NINJA&&this.ninja?this.ninja.enableAABB(t):e===n.Physics.BOX2D&&this.box2d?this.box2d.enable(t):e===n.Physics.MATTERJS&&this.matter?this.matter.enable(t):console.warn(t.key+" is attempting to enable a physics body using an unknown physics system.")},preUpdate:function(){this.p2&&this.p2.preUpdate(),this.box2d&&this.box2d.preUpdate(),this.matter&&this.matter.preUpdate()},update:function(){this.p2&&this.p2.update(),this.box2d&&this.box2d.update(),this.matter&&this.matter.update()},setBoundsToWorld:function(){this.arcade&&this.arcade.setBoundsToWorld(),this.ninja&&this.ninja.setBoundsToWorld(),this.p2&&this.p2.setBoundsToWorld(),this.box2d&&this.box2d.setBoundsToWorld(),this.matter&&this.matter.setBoundsToWorld()},clear:function(){this.p2&&this.p2.clear(),this.box2d&&this.box2d.clear(),this.matter&&this.matter.clear()},reset:function(){this.p2&&this.p2.reset(),this.box2d&&this.box2d.reset(),this.matter&&this.matter.reset()},destroy:function(){this.p2&&this.p2.destroy(),this.box2d&&this.box2d.destroy(),this.matter&&this.matter.destroy(),this.arcade=null,this.ninja=null,this.p2=null,this.box2d=null,this.matter=null}},n.Physics.prototype.constructor=n.Physics,n.Physics.Arcade=function(t){this.game=t,this.gravity=new n.Point,this.bounds=new n.Rectangle(0,0,t.world.width,t.world.height),this.checkCollision={up:!0,down:!0,left:!0,right:!0},this.maxObjects=10,this.maxLevels=4,this.OVERLAP_BIAS=4,this.forceX=!1,this.sortDirection=n.Physics.Arcade.LEFT_RIGHT,this.skipQuadTree=!0,this.isPaused=!1,this.quadTree=new n.QuadTree(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height,this.maxObjects,this.maxLevels),this._total=0,this.setBoundsToWorld()},n.Physics.Arcade.prototype.constructor=n.Physics.Arcade,n.Physics.Arcade.SORT_NONE=0,n.Physics.Arcade.LEFT_RIGHT=1,n.Physics.Arcade.RIGHT_LEFT=2,n.Physics.Arcade.TOP_BOTTOM=3,n.Physics.Arcade.BOTTOM_TOP=4,n.Physics.Arcade.prototype={setBounds:function(t,e,i,s){this.bounds.setTo(t,e,i,s)},setBoundsToWorld:function(){this.bounds.copyFrom(this.game.world.bounds)},enable:function(t,e){void 0===e&&(e=!0);var i=1;if(Array.isArray(t))for(i=t.length;i--;)t[i]instanceof n.Group?this.enable(t[i].children,e):(this.enableBody(t[i]),e&&t[i].hasOwnProperty("children")&&t[i].children.length>0&&this.enable(t[i],!0));else t instanceof n.Group?this.enable(t.children,e):(this.enableBody(t),e&&t.hasOwnProperty("children")&&t.children.length>0&&this.enable(t.children,!0))},enableBody:function(t){t.hasOwnProperty("body")&&null===t.body&&(t.body=new n.Physics.Arcade.Body(t),t.parent&&t.parent instanceof n.Group&&t.parent.addToHash(t))},updateMotion:function(t){var e=this.computeVelocity(0,t,t.angularVelocity,t.angularAcceleration,t.angularDrag,t.maxAngular)-t.angularVelocity;t.angularVelocity+=e,t.rotation+=t.angularVelocity*this.game.time.physicsElapsed,t.velocity.x=this.computeVelocity(1,t,t.velocity.x,t.acceleration.x,t.drag.x,t.maxVelocity.x),t.velocity.y=this.computeVelocity(2,t,t.velocity.y,t.acceleration.y,t.drag.y,t.maxVelocity.y)},computeVelocity:function(t,e,i,s,n,r){return void 0===r&&(r=1e4),1===t&&e.allowGravity?i+=(this.gravity.x+e.gravity.x)*this.game.time.physicsElapsed:2===t&&e.allowGravity&&(i+=(this.gravity.y+e.gravity.y)*this.game.time.physicsElapsed),s?i+=s*this.game.time.physicsElapsed:n&&(n*=this.game.time.physicsElapsed,i-n>0?i-=n:i+n<0?i+=n:i=0),i>r?i=r:i<-r&&(i=-r),i},overlap:function(t,e,i,s,n){if(i=i||null,s=s||null,n=n||i,this._total=0,!Array.isArray(t)&&Array.isArray(e))for(var r=0;r<e.length;r++)this.collideHandler(t,e[r],i,s,n,!0);else if(Array.isArray(t)&&!Array.isArray(e))for(var r=0;r<t.length;r++)this.collideHandler(t[r],e,i,s,n,!0);else if(Array.isArray(t)&&Array.isArray(e))for(var r=0;r<t.length;r++)for(var o=0;o<e.length;o++)this.collideHandler(t[r],e[o],i,s,n,!0);else this.collideHandler(t,e,i,s,n,!0);return this._total>0},collide:function(t,e,i,s,n){if(i=i||null,s=s||null,n=n||i,this._total=0,!Array.isArray(t)&&Array.isArray(e))for(var r=0;r<e.length;r++)this.collideHandler(t,e[r],i,s,n,!1);else if(Array.isArray(t)&&!Array.isArray(e))for(var r=0;r<t.length;r++)this.collideHandler(t[r],e,i,s,n,!1);else if(Array.isArray(t)&&Array.isArray(e))for(var r=0;r<t.length;r++)for(var o=0;o<e.length;o++)this.collideHandler(t[r],e[o],i,s,n,!1);else this.collideHandler(t,e,i,s,n,!1);return this._total>0},sortLeftRight:function(t,e){return t.body&&e.body?t.body.x-e.body.x:0},sortRightLeft:function(t,e){return t.body&&e.body?e.body.x-t.body.x:0},sortTopBottom:function(t,e){return t.body&&e.body?t.body.y-e.body.y:0},sortBottomTop:function(t,e){return t.body&&e.body?e.body.y-t.body.y:0},sort:function(t,e){null!==t.physicsSortDirection?e=t.physicsSortDirection:void 0===e&&(e=this.sortDirection),e===n.Physics.Arcade.LEFT_RIGHT?t.hash.sort(this.sortLeftRight):e===n.Physics.Arcade.RIGHT_LEFT?t.hash.sort(this.sortRightLeft):e===n.Physics.Arcade.TOP_BOTTOM?t.hash.sort(this.sortTopBottom):e===n.Physics.Arcade.BOTTOM_TOP&&t.hash.sort(this.sortBottomTop)},collideHandler:function(t,e,i,s,r,o){if(void 0===e&&t.physicsType===n.GROUP)return this.sort(t),void this.collideGroupVsSelf(t,i,s,r,o);t&&e&&t.exists&&e.exists&&(this.sortDirection!==n.Physics.Arcade.SORT_NONE&&(t.physicsType===n.GROUP&&this.sort(t),e.physicsType===n.GROUP&&this.sort(e)),t.physicsType===n.SPRITE?e.physicsType===n.SPRITE?this.collideSpriteVsSprite(t,e,i,s,r,o):e.physicsType===n.GROUP?this.collideSpriteVsGroup(t,e,i,s,r,o):e.physicsType===n.TILEMAPLAYER&&this.collideSpriteVsTilemapLayer(t,e,i,s,r,o):t.physicsType===n.GROUP?e.physicsType===n.SPRITE?this.collideSpriteVsGroup(e,t,i,s,r,o):e.physicsType===n.GROUP?this.collideGroupVsGroup(t,e,i,s,r,o):e.physicsType===n.TILEMAPLAYER&&this.collideGroupVsTilemapLayer(t,e,i,s,r,o):t.physicsType===n.TILEMAPLAYER&&(e.physicsType===n.SPRITE?this.collideSpriteVsTilemapLayer(e,t,i,s,r,o):e.physicsType===n.GROUP&&this.collideGroupVsTilemapLayer(e,t,i,s,r,o)))},collideSpriteVsSprite:function(t,e,i,s,n,r){return!(!t.body||!e.body)&&(this.separate(t.body,e.body,s,n,r)&&(i&&i.call(n,t,e),this._total++),!0)},collideSpriteVsGroup:function(t,e,i,s,r,o){if(0!==e.length&&t.body)if(this.skipQuadTree||t.body.skipQuadTree)for(var a={},h=0;h<e.hash.length;h++){var l=e.hash[h];if(l&&l.exists&&l.body){if(a=l.body.getBounds(a),this.sortDirection===n.Physics.Arcade.LEFT_RIGHT){if(t.body.right<a.x)break;if(a.right<t.body.x)continue}else if(this.sortDirection===n.Physics.Arcade.RIGHT_LEFT){if(t.body.x>a.right)break;if(a.x>t.body.right)continue}else if(this.sortDirection===n.Physics.Arcade.TOP_BOTTOM){if(t.body.bottom<a.y)break;if(a.bottom<t.body.y)continue}else if(this.sortDirection===n.Physics.Arcade.BOTTOM_TOP){if(t.body.y>a.bottom)break;if(a.y>t.body.bottom)continue}this.collideSpriteVsSprite(t,l,i,s,r,o)}}else{this.quadTree.clear(),this.quadTree.reset(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height,this.maxObjects,this.maxLevels),this.quadTree.populate(e);for(var c=this.quadTree.retrieve(t),h=0;h<c.length;h++)this.separate(t.body,c[h],s,r,o)&&(i&&i.call(r,t,c[h].sprite),this._total++)}},collideGroupVsSelf:function(t,e,i,s,r){if(0!==t.length)for(var o=0;o<t.hash.length;o++){var a={},h=t.hash[o];if(h&&h.exists&&h.body){a=h.body.getBounds(a);for(var l=o+1;l<t.hash.length;l++){var c={},u=t.hash[l];if(u&&u.exists&&u.body){if(c=u.body.getBounds(c),this.sortDirection===n.Physics.Arcade.LEFT_RIGHT){if(a.right<c.x)break;if(c.right<a.x)continue}else if(this.sortDirection===n.Physics.Arcade.RIGHT_LEFT){if(a.x>c.right)continue;if(c.x>a.right)break}else if(this.sortDirection===n.Physics.Arcade.TOP_BOTTOM){if(a.bottom<c.y)continue;if(c.bottom<a.y)break}else if(this.sortDirection===n.Physics.Arcade.BOTTOM_TOP){if(a.y>c.bottom)continue;if(c.y>h.body.bottom)break}this.collideSpriteVsSprite(h,u,e,i,s,r)}}}}},collideGroupVsGroup:function(t,e,i,s,r,o){if(0!==t.length&&0!==e.length)for(var a=0;a<t.children.length;a++)t.children[a].exists&&(t.children[a].physicsType===n.GROUP?this.collideGroupVsGroup(t.children[a],e,i,s,r,o):this.collideSpriteVsGroup(t.children[a],e,i,s,r,o))},separate:function(t,e,i,s,n){if(!t.enable||!e.enable||t.checkCollision.none||e.checkCollision.none||!this.intersects(t,e))return!1;if(i&&!1===i.call(s,t.sprite,e.sprite))return!1;if(t.isCircle&&e.isCircle)return this.separateCircle(t,e,n);if(t.isCircle!==e.isCircle){var r=t.isCircle?e:t,o=t.isCircle?t:e,a={x:r.x,y:r.y,right:r.right,bottom:r.bottom},h={x:o.x+o.radius,y:o.y+o.radius};if((h.y<a.y||h.y>a.bottom)&&(h.x<a.x||h.x>a.right))return this.separateCircle(t,e,n)}var l=!1,c=!1;this.forceX||Math.abs(this.gravity.y+t.gravity.y)<Math.abs(this.gravity.x+t.gravity.x)?(l=this.separateX(t,e,n),this.intersects(t,e)&&(c=this.separateY(t,e,n))):(c=this.separateY(t,e,n),this.intersects(t,e)&&(l=this.separateX(t,e,n)));var u=l||c;return u&&(n?(t.onOverlap&&t.onOverlap.dispatch(t.sprite,e.sprite),e.onOverlap&&e.onOverlap.dispatch(e.sprite,t.sprite)):(t.onCollide&&t.onCollide.dispatch(t.sprite,e.sprite),e.onCollide&&e.onCollide.dispatch(e.sprite,t.sprite))),u},intersects:function(t,e){return t!==e&&(t.isCircle?e.isCircle?n.Math.distance(t.center.x,t.center.y,e.center.x,e.center.y)<=t.radius+e.radius:this.circleBodyIntersects(t,e):e.isCircle?this.circleBodyIntersects(e,t):!(t.right<=e.position.x)&&(!(t.bottom<=e.position.y)&&(!(t.position.x>=e.right)&&!(t.position.y>=e.bottom))))},circleBodyIntersects:function(t,e){var i=n.Math.clamp(t.center.x,e.left,e.right),s=n.Math.clamp(t.center.y,e.top,e.bottom);return(t.center.x-i)*(t.center.x-i)+(t.center.y-s)*(t.center.y-s)<=t.radius*t.radius},separateCircle:function(t,e,i){this.getOverlapX(t,e),this.getOverlapY(t,e);var s=e.center.x-t.center.x,r=e.center.y-t.center.y,o=Math.atan2(r,s),a=0;if(t.isCircle!==e.isCircle){var h={x:e.isCircle?t.position.x:e.position.x,y:e.isCircle?t.position.y:e.position.y,right:e.isCircle?t.right:e.right,bottom:e.isCircle?t.bottom:e.bottom},l={x:t.isCircle?t.position.x+t.radius:e.position.x+e.radius,y:t.isCircle?t.position.y+t.radius:e.position.y+e.radius,radius:t.isCircle?t.radius:e.radius};l.y<h.y?l.x<h.x?a=n.Math.distance(l.x,l.y,h.x,h.y)-l.radius:l.x>h.right&&(a=n.Math.distance(l.x,l.y,h.right,h.y)-l.radius):l.y>h.bottom&&(l.x<h.x?a=n.Math.distance(l.x,l.y,h.x,h.bottom)-l.radius:l.x>h.right&&(a=n.Math.distance(l.x,l.y,h.right,h.bottom)-l.radius)),a*=-1}else a=t.radius+e.radius-n.Math.distance(t.center.x,t.center.y,e.center.x,e.center.y);if(i||0===a||t.immovable&&e.immovable||t.customSeparateX||e.customSeparateX)return 0!==a&&(t.onOverlap&&t.onOverlap.dispatch(t.sprite,e.sprite),e.onOverlap&&e.onOverlap.dispatch(e.sprite,t.sprite)),0!==a;var c={x:t.velocity.x*Math.cos(o)+t.velocity.y*Math.sin(o),y:t.velocity.x*Math.sin(o)-t.velocity.y*Math.cos(o)},u={x:e.velocity.x*Math.cos(o)+e.velocity.y*Math.sin(o),y:e.velocity.x*Math.sin(o)-e.velocity.y*Math.cos(o)},d=((t.mass-e.mass)*c.x+2*e.mass*u.x)/(t.mass+e.mass),p=(2*t.mass*c.x+(e.mass-t.mass)*u.x)/(t.mass+e.mass);return t.immovable||(t.velocity.x=(d*Math.cos(o)-c.y*Math.sin(o))*t.bounce.x,t.velocity.y=(c.y*Math.cos(o)+d*Math.sin(o))*t.bounce.y),e.immovable||(e.velocity.x=(p*Math.cos(o)-u.y*Math.sin(o))*e.bounce.x,e.velocity.y=(u.y*Math.cos(o)+p*Math.sin(o))*e.bounce.y),Math.abs(o)<Math.PI/2?t.velocity.x>0&&!t.immovable&&e.velocity.x>t.velocity.x?t.velocity.x*=-1:e.velocity.x<0&&!e.immovable&&t.velocity.x<e.velocity.x?e.velocity.x*=-1:t.velocity.y>0&&!t.immovable&&e.velocity.y>t.velocity.y?t.velocity.y*=-1:e.velocity.y<0&&!e.immovable&&t.velocity.y<e.velocity.y&&(e.velocity.y*=-1):Math.abs(o)>Math.PI/2&&(t.velocity.x<0&&!t.immovable&&e.velocity.x<t.velocity.x?t.velocity.x*=-1:e.velocity.x>0&&!e.immovable&&t.velocity.x>e.velocity.x?e.velocity.x*=-1:t.velocity.y<0&&!t.immovable&&e.velocity.y<t.velocity.y?t.velocity.y*=-1:e.velocity.y>0&&!e.immovable&&t.velocity.x>e.velocity.y&&(e.velocity.y*=-1)),t.immovable||(t.x+=t.velocity.x*this.game.time.physicsElapsed-a*Math.cos(o),t.y+=t.velocity.y*this.game.time.physicsElapsed-a*Math.sin(o)),e.immovable||(e.x+=e.velocity.x*this.game.time.physicsElapsed+a*Math.cos(o),e.y+=e.velocity.y*this.game.time.physicsElapsed+a*Math.sin(o)),t.onCollide&&t.onCollide.dispatch(t.sprite,e.sprite),e.onCollide&&e.onCollide.dispatch(e.sprite,t.sprite),!0},getOverlapX:function(t,e,i){var s=0,n=t.deltaAbsX()+e.deltaAbsX()+this.OVERLAP_BIAS;return 0===t.deltaX()&&0===e.deltaX()?(t.embedded=!0,e.embedded=!0):t.deltaX()>e.deltaX()?(s=t.right-e.x,s>n&&!i||!1===t.checkCollision.right||!1===e.checkCollision.left?s=0:(t.touching.none=!1,t.touching.right=!0,e.touching.none=!1,e.touching.left=!0)):t.deltaX()<e.deltaX()&&(s=t.x-e.width-e.x,-s>n&&!i||!1===t.checkCollision.left||!1===e.checkCollision.right?s=0:(t.touching.none=!1,t.touching.left=!0,e.touching.none=!1,e.touching.right=!0)),t.overlapX=s,e.overlapX=s,s},getOverlapY:function(t,e,i){var s=0,n=t.deltaAbsY()+e.deltaAbsY()+this.OVERLAP_BIAS;return 0===t.deltaY()&&0===e.deltaY()?(t.embedded=!0,e.embedded=!0):t.deltaY()>e.deltaY()?(s=t.bottom-e.y,s>n&&!i||!1===t.checkCollision.down||!1===e.checkCollision.up?s=0:(t.touching.none=!1,t.touching.down=!0,e.touching.none=!1,e.touching.up=!0)):t.deltaY()<e.deltaY()&&(s=t.y-e.bottom,-s>n&&!i||!1===t.checkCollision.up||!1===e.checkCollision.down?s=0:(t.touching.none=!1,t.touching.up=!0,e.touching.none=!1,e.touching.down=!0)),t.overlapY=s,e.overlapY=s,s},separateX:function(t,e,i){var s=this.getOverlapX(t,e,i);if(i||0===s||t.immovable&&e.immovable||t.customSeparateX||e.customSeparateX)return 0!==s||t.embedded&&e.embedded;var n=t.velocity.x,r=e.velocity.x;if(t.immovable||e.immovable)t.immovable?(e.x+=s,e.velocity.x=n-r*e.bounce.x,t.moves&&(e.y+=(t.y-t.prev.y)*t.friction.y)):(t.x-=s,t.velocity.x=r-n*t.bounce.x,e.moves&&(t.y+=(e.y-e.prev.y)*e.friction.y));else{s*=.5,t.x-=s,e.x+=s;var o=Math.sqrt(r*r*e.mass/t.mass)*(r>0?1:-1),a=Math.sqrt(n*n*t.mass/e.mass)*(n>0?1:-1),h=.5*(o+a);o-=h,a-=h,t.velocity.x=h+o*t.bounce.x,e.velocity.x=h+a*e.bounce.x}return!0},separateY:function(t,e,i){var s=this.getOverlapY(t,e,i);if(i||0===s||t.immovable&&e.immovable||t.customSeparateY||e.customSeparateY)return 0!==s||t.embedded&&e.embedded;var n=t.velocity.y,r=e.velocity.y;if(t.immovable||e.immovable)t.immovable?(e.y+=s,e.velocity.y=n-r*e.bounce.y,t.moves&&(e.x+=(t.x-t.prev.x)*t.friction.x)):(t.y-=s,t.velocity.y=r-n*t.bounce.y,e.moves&&(t.x+=(e.x-e.prev.x)*e.friction.x));else{s*=.5,t.y-=s,e.y+=s;var o=Math.sqrt(r*r*e.mass/t.mass)*(r>0?1:-1),a=Math.sqrt(n*n*t.mass/e.mass)*(n>0?1:-1),h=.5*(o+a);o-=h,a-=h,t.velocity.y=h+o*t.bounce.y,e.velocity.y=h+a*e.bounce.y}return!0},getObjectsUnderPointer:function(t,e,i,s){if(0!==e.length&&t.exists)return this.getObjectsAtLocation(t.x,t.y,e,i,s,t)},getObjectsAtLocation:function(t,e,i,s,r,o){this.quadTree.clear(),this.quadTree.reset(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height,this.maxObjects,this.maxLevels),this.quadTree.populate(i);for(var a=new n.Rectangle(t,e,1,1),h=[],l=this.quadTree.retrieve(a),c=0;c<l.length;c++)l[c].hitTest(t,e)&&(s&&s.call(r,o,l[c].sprite),h.push(l[c].sprite));return h},moveToObject:function(t,e,i,s){void 0===i&&(i=60),void 0===s&&(s=0);var n=Math.atan2(e.y-t.y,e.x-t.x);return s>0&&(i=this.distanceBetween(t,e)/(s/1e3)),t.body.velocity.x=Math.cos(n)*i,t.body.velocity.y=Math.sin(n)*i,n},moveToPointer:function(t,e,i,s){void 0===e&&(e=60),i=i||this.game.input.activePointer,void 0===s&&(s=0);var n=this.angleToPointer(t,i);return s>0&&(e=this.distanceToPointer(t,i)/(s/1e3)),t.body.velocity.x=Math.cos(n)*e,t.body.velocity.y=Math.sin(n)*e,n},moveToXY:function(t,e,i,s,n){void 0===s&&(s=60),void 0===n&&(n=0);var r=Math.atan2(i-t.y,e-t.x);return n>0&&(s=this.distanceToXY(t,e,i)/(n/1e3)),t.body.velocity.x=Math.cos(r)*s,t.body.velocity.y=Math.sin(r)*s,r},velocityFromAngle:function(t,e,i){return void 0===e&&(e=60),i=i||new n.Point,i.setTo(Math.cos(this.game.math.degToRad(t))*e,Math.sin(this.game.math.degToRad(t))*e)},velocityFromRotation:function(t,e,i){return void 0===e&&(e=60),i=i||new n.Point,i.setTo(Math.cos(t)*e,Math.sin(t)*e)},accelerationFromRotation:function(t,e,i){return void 0===e&&(e=60),i=i||new n.Point,i.setTo(Math.cos(t)*e,Math.sin(t)*e)},accelerateToObject:function(t,e,i,s,n){void 0===i&&(i=60),void 0===s&&(s=1e3),void 0===n&&(n=1e3);var r=this.angleBetween(t,e);return t.body.acceleration.setTo(Math.cos(r)*i,Math.sin(r)*i),t.body.maxVelocity.setTo(s,n),r},accelerateToPointer:function(t,e,i,s,n){void 0===i&&(i=60),void 0===e&&(e=this.game.input.activePointer),void 0===s&&(s=1e3),void 0===n&&(n=1e3);var r=this.angleToPointer(t,e);return t.body.acceleration.setTo(Math.cos(r)*i,Math.sin(r)*i),t.body.maxVelocity.setTo(s,n),r},accelerateToXY:function(t,e,i,s,n,r){void 0===s&&(s=60),void 0===n&&(n=1e3),void 0===r&&(r=1e3);var o=this.angleToXY(t,e,i);return t.body.acceleration.setTo(Math.cos(o)*s,Math.sin(o)*s),t.body.maxVelocity.setTo(n,r),o},distanceBetween:function(t,e,i){void 0===i&&(i=!1);var s=i?t.world.x-e.world.x:t.x-e.x,n=i?t.world.y-e.world.y:t.y-e.y;return Math.sqrt(s*s+n*n)},distanceToXY:function(t,e,i,s){void 0===s&&(s=!1);var n=s?t.world.x-e:t.x-e,r=s?t.world.y-i:t.y-i;return Math.sqrt(n*n+r*r)},distanceToPointer:function(t,e,i){void 0===e&&(e=this.game.input.activePointer),void 0===i&&(i=!1);var s=i?t.world.x-e.worldX:t.x-e.worldX,n=i?t.world.y-e.worldY:t.y-e.worldY;return Math.sqrt(s*s+n*n)},angleBetween:function(t,e,i){return void 0===i&&(i=!1),i?Math.atan2(e.world.y-t.world.y,e.world.x-t.world.x):Math.atan2(e.y-t.y,e.x-t.x)},angleBetweenCenters:function(t,e){var i=e.centerX-t.centerX,s=e.centerY-t.centerY;return Math.atan2(s,i)},angleToXY:function(t,e,i,s){return void 0===s&&(s=!1),s?Math.atan2(i-t.world.y,e-t.world.x):Math.atan2(i-t.y,e-t.x)},angleToPointer:function(t,e,i){return void 0===e&&(e=this.game.input.activePointer),void 0===i&&(i=!1),i?Math.atan2(e.worldY-t.world.y,e.worldX-t.world.x):Math.atan2(e.worldY-t.y,e.worldX-t.x)},worldAngleToPointer:function(t,e){return this.angleToPointer(t,e,!0)}},n.Physics.Arcade.Body=function(t){this.sprite=t,this.game=t.game,this.type=n.Physics.ARCADE,this.enable=!0,this.isCircle=!1,this.radius=0,this.offset=new n.Point,this.position=new n.Point(t.x,t.y),this.prev=new n.Point(this.position.x,this.position.y),this.allowRotation=!0,this.rotation=t.angle,this.preRotation=t.angle,this.width=t.width,this.height=t.height,this.sourceWidth=t.width,this.sourceHeight=t.height,t.texture&&(this.sourceWidth=t.texture.frame.width,this.sourceHeight=t.texture.frame.height),this.halfWidth=Math.abs(t.width/2),this.halfHeight=Math.abs(t.height/2),this.center=new n.Point(t.x+this.halfWidth,t.y+this.halfHeight),this.velocity=new n.Point,this.newVelocity=new n.Point,this.deltaMax=new n.Point,this.acceleration=new n.Point,this.drag=new n.Point,this.allowGravity=!0,this.gravity=new n.Point,this.bounce=new n.Point,this.worldBounce=null,this.onWorldBounds=null,this.onCollide=null,this.onOverlap=null,this.maxVelocity=new n.Point(1e4,1e4),this.friction=new n.Point(1,0),this.angularVelocity=0,this.angularAcceleration=0,this.angularDrag=0,this.maxAngular=1e3,this.mass=1,this.angle=0,this.speed=0,this.facing=n.NONE,this.immovable=!1,this.moves=!0,this.customSeparateX=!1,this.customSeparateY=!1,this.overlapX=0,this.overlapY=0,this.overlapR=0,this.embedded=!1,this.collideWorldBounds=!1,this.checkCollision={none:!1,any:!0,up:!0,down:!0,left:!0,right:!0},this.touching={none:!0,up:!1,down:!1,left:!1,right:!1},this.wasTouching={none:!0,up:!1,down:!1,left:!1,right:!1},this.blocked={up:!1,down:!1,left:!1,right:!1},this.tilePadding=new n.Point,this.dirty=!1,this.skipQuadTree=!1,this.syncBounds=!1,this.isMoving=!1,this.stopVelocityOnCollide=!0,this.moveTimer=0,this.moveDistance=0,this.moveDuration=0,this.moveTarget=null,this.moveEnd=null,this.onMoveComplete=new n.Signal,this.movementCallback=null,this.movementCallbackContext=null,this._reset=!0,this._sx=t.scale.x,this._sy=t.scale.y,this._dx=0,this._dy=0},n.Physics.Arcade.Body.prototype={updateBounds:function(){if(this.syncBounds){var t=this.sprite.getBounds();t.ceilAll(),t.width===this.width&&t.height===this.height||(this.width=t.width,this.height=t.height,this._reset=!0)}else{var e=Math.abs(this.sprite.scale.x),i=Math.abs(this.sprite.scale.y);e===this._sx&&i===this._sy||(this.width=this.sourceWidth*e,this.height=this.sourceHeight*i,this._sx=e,this._sy=i,this._reset=!0)}this._reset&&(this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight))},preUpdate:function(){this.enable&&!this.game.physics.arcade.isPaused&&(this.dirty=!0,this.wasTouching.none=this.touching.none,this.wasTouching.up=this.touching.up,this.wasTouching.down=this.touching.down,this.wasTouching.left=this.touching.left,this.wasTouching.right=this.touching.right,this.touching.none=!0,this.touching.up=!1,this.touching.down=!1,this.touching.left=!1,this.touching.right=!1,this.blocked.up=!1,this.blocked.down=!1,this.blocked.left=!1,this.blocked.right=!1,this.embedded=!1,this.updateBounds(),this.position.x=this.sprite.world.x-this.sprite.anchor.x*this.sprite.width+this.sprite.scale.x*this.offset.x,this.position.x-=this.sprite.scale.x<0?this.width:0,this.position.y=this.sprite.world.y-this.sprite.anchor.y*this.sprite.height+this.sprite.scale.y*this.offset.y,this.position.y-=this.sprite.scale.y<0?this.height:0,this.rotation=this.sprite.angle,this.preRotation=this.rotation,(this._reset||this.sprite.fresh)&&(this.prev.x=this.position.x,this.prev.y=this.position.y),this.moves&&(this.game.physics.arcade.updateMotion(this),this.newVelocity.set(this.velocity.x*this.game.time.physicsElapsed,this.velocity.y*this.game.time.physicsElapsed),this.position.x+=this.newVelocity.x,this.position.y+=this.newVelocity.y,this.position.x===this.prev.x&&this.position.y===this.prev.y||(this.angle=Math.atan2(this.velocity.y,this.velocity.x)),this.speed=Math.sqrt(this.velocity.x*this.velocity.x+this.velocity.y*this.velocity.y),this.collideWorldBounds&&this.checkWorldBounds()&&this.onWorldBounds&&this.onWorldBounds.dispatch(this.sprite,this.blocked.up,this.blocked.down,this.blocked.left,this.blocked.right)),this._dx=this.deltaX(),this._dy=this.deltaY(),this._reset=!1)},updateMovement:function(){var t=0,e=0!==this.overlapX||0!==this.overlapY;if(this.moveDuration>0?(this.moveTimer+=this.game.time.elapsedMS,t=this.moveTimer/this.moveDuration):(this.moveTarget.end.set(this.position.x,this.position.y),t=this.moveTarget.length/this.moveDistance),this.movementCallback)var i=this.movementCallback.call(this.movementCallbackContext,this,this.velocity,t);return!(e||t>=1||void 0!==i&&!0!==i)||(this.stopMovement(t>=1||this.stopVelocityOnCollide&&e),!1)},stopMovement:function(t){this.isMoving&&(this.isMoving=!1,t&&this.velocity.set(0),this.onMoveComplete.dispatch(this.sprite,0!==this.overlapX||0!==this.overlapY))},postUpdate:function(){this.enable&&this.dirty&&(this.isMoving&&this.updateMovement(),this.dirty=!1,this.deltaX()<0?this.facing=n.LEFT:this.deltaX()>0&&(this.facing=n.RIGHT),this.deltaY()<0?this.facing=n.UP:this.deltaY()>0&&(this.facing=n.DOWN),this.moves&&(this._dx=this.deltaX(),this._dy=this.deltaY(),0!==this.deltaMax.x&&0!==this._dx&&(this._dx<0&&this._dx<-this.deltaMax.x?this._dx=-this.deltaMax.x:this._dx>0&&this._dx>this.deltaMax.x&&(this._dx=this.deltaMax.x)),0!==this.deltaMax.y&&0!==this._dy&&(this._dy<0&&this._dy<-this.deltaMax.y?this._dy=-this.deltaMax.y:this._dy>0&&this._dy>this.deltaMax.y&&(this._dy=this.deltaMax.y)),this.sprite.position.x+=this._dx,this.sprite.position.y+=this._dy,this._reset=!0),this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight),this.allowRotation&&(this.sprite.angle+=this.deltaZ()),this.prev.x=this.position.x,this.prev.y=this.position.y)},checkWorldBounds:function(){var t=this.position,e=this.game.physics.arcade.bounds,i=this.game.physics.arcade.checkCollision,s=this.worldBounce?-this.worldBounce.x:-this.bounce.x,n=this.worldBounce?-this.worldBounce.y:-this.bounce.y;if(this.isCircle){var r={x:this.center.x-this.radius,y:this.center.y-this.radius,right:this.center.x+this.radius,bottom:this.center.y+this.radius};r.x<e.x&&i.left?(t.x=e.x-this.halfWidth+this.radius,this.velocity.x*=s,this.blocked.left=!0):r.right>e.right&&i.right&&(t.x=e.right-this.halfWidth-this.radius,this.velocity.x*=s,this.blocked.right=!0),r.y<e.y&&i.up?(t.y=e.y-this.halfHeight+this.radius,this.velocity.y*=n,this.blocked.up=!0):r.bottom>e.bottom&&i.down&&(t.y=e.bottom-this.halfHeight-this.radius,this.velocity.y*=n,this.blocked.down=!0)}else t.x<e.x&&i.left?(t.x=e.x,this.velocity.x*=s,this.blocked.left=!0):this.right>e.right&&i.right&&(t.x=e.right-this.width,this.velocity.x*=s,this.blocked.right=!0),t.y<e.y&&i.up?(t.y=e.y,this.velocity.y*=n,this.blocked.up=!0):this.bottom>e.bottom&&i.down&&(t.y=e.bottom-this.height,this.velocity.y*=n,this.blocked.down=!0);return this.blocked.up||this.blocked.down||this.blocked.left||this.blocked.right},moveFrom:function(t,e,i){if(void 0===e&&(e=this.speed),0===e)return!1;var s;return void 0===i?(s=this.angle,i=this.game.math.radToDeg(s)):s=this.game.math.degToRad(i),this.moveTimer=0,this.moveDuration=t,0===i||180===i?this.velocity.set(Math.cos(s)*e,0):90===i||270===i?this.velocity.set(0,Math.sin(s)*e):this.velocity.set(Math.cos(s)*e,Math.sin(s)*e),this.isMoving=!0,!0},moveTo:function(t,e,i){var s=e/(t/1e3);if(0===s)return!1;var r;return void 0===i?(r=this.angle,i=this.game.math.radToDeg(r)):r=this.game.math.degToRad(i),e=Math.abs(e),this.moveDuration=0,this.moveDistance=e,null===this.moveTarget&&(this.moveTarget=new n.Line,this.moveEnd=new n.Point),this.moveTarget.fromAngle(this.x,this.y,r,e),this.moveEnd.set(this.moveTarget.end.x,this.moveTarget.end.y),this.moveTarget.setTo(this.x,this.y,this.x,this.y),0===i||180===i?this.velocity.set(Math.cos(r)*s,0):90===i||270===i?this.velocity.set(0,Math.sin(r)*s):this.velocity.set(Math.cos(r)*s,Math.sin(r)*s),this.isMoving=!0,!0},setSize:function(t,e,i,s){void 0===i&&(i=this.offset.x),void 0===s&&(s=this.offset.y),this.sourceWidth=t,this.sourceHeight=e,this.width=this.sourceWidth*this._sx,this.height=this.sourceHeight*this._sy,this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.offset.setTo(i,s),this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight),this.isCircle=!1,this.radius=0},setCircle:function(t,e,i){void 0===e&&(e=this.offset.x),void 0===i&&(i=this.offset.y),t>0?(this.isCircle=!0,this.radius=t,this.sourceWidth=2*t,this.sourceHeight=2*t,this.width=this.sourceWidth*this._sx,this.height=this.sourceHeight*this._sy,this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.offset.setTo(e,i),this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight)):this.isCircle=!1},reset:function(t,e){this.velocity.set(0),this.acceleration.set(0),this.speed=0,this.angularVelocity=0,this.angularAcceleration=0,this.position.x=t-this.sprite.anchor.x*this.sprite.width+this.sprite.scale.x*this.offset.x,this.position.x-=this.sprite.scale.x<0?this.width:0,this.position.y=e-this.sprite.anchor.y*this.sprite.height+this.sprite.scale.y*this.offset.y,this.position.y-=this.sprite.scale.y<0?this.height:0,this.prev.x=this.position.x,this.prev.y=this.position.y,this.rotation=this.sprite.angle,this.preRotation=this.rotation,this._sx=this.sprite.scale.x,this._sy=this.sprite.scale.y,this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight)},getBounds:function(t){return this.isCircle?(t.x=this.center.x-this.radius,t.y=this.center.y-this.radius,t.right=this.center.x+this.radius,t.bottom=this.center.y+this.radius):(t.x=this.x,t.y=this.y,t.right=this.right,t.bottom=this.bottom),t},hitTest:function(t,e){return this.isCircle?n.Circle.contains(this,t,e):n.Rectangle.contains(this,t,e)},onFloor:function(){return this.blocked.down},onCeiling:function(){return this.blocked.up},onWall:function(){return this.blocked.left||this.blocked.right},deltaAbsX:function(){return this.deltaX()>0?this.deltaX():-this.deltaX()},deltaAbsY:function(){return this.deltaY()>0?this.deltaY():-this.deltaY()},deltaX:function(){return this.position.x-this.prev.x},deltaY:function(){return this.position.y-this.prev.y},deltaZ:function(){return this.rotation-this.preRotation},destroy:function(){this.sprite.parent&&this.sprite.parent instanceof n.Group&&this.sprite.parent.removeFromHash(this.sprite),this.sprite.body=null,this.sprite=null}},Object.defineProperty(n.Physics.Arcade.Body.prototype,"left",{get:function(){return this.position.x}}),Object.defineProperty(n.Physics.Arcade.Body.prototype,"right",{get:function(){return this.position.x+this.width}}),Object.defineProperty(n.Physics.Arcade.Body.prototype,"top",{get:function(){return this.position.y}}),Object.defineProperty(n.Physics.Arcade.Body.prototype,"bottom",{get:function(){return this.position.y+this.height}}),Object.defineProperty(n.Physics.Arcade.Body.prototype,"x",{get:function(){return this.position.x},set:function(t){this.position.x=t}}),Object.defineProperty(n.Physics.Arcade.Body.prototype,"y",{get:function(){return this.position.y},set:function(t){this.position.y=t}}),n.Physics.Arcade.Body.render=function(t,e,i,s){void 0===s&&(s=!0),i=i||"rgba(0,255,0,0.4)",t.fillStyle=i,t.strokeStyle=i,e.isCircle?(t.beginPath(),t.arc(e.center.x-e.game.camera.x,e.center.y-e.game.camera.y,e.radius,0,2*Math.PI),s?t.fill():t.stroke()):s?t.fillRect(e.position.x-e.game.camera.x,e.position.y-e.game.camera.y,e.width,e.height):t.strokeRect(e.position.x-e.game.camera.x,e.position.y-e.game.camera.y,e.width,e.height)},n.Physics.Arcade.Body.renderBodyInfo=function(t,e){t.line("x: "+e.x.toFixed(2),"y: "+e.y.toFixed(2),"width: "+e.width,"height: "+e.height),t.line("velocity x: "+e.velocity.x.toFixed(2),"y: "+e.velocity.y.toFixed(2),"deltaX: "+e._dx.toFixed(2),"deltaY: "+e._dy.toFixed(2)),t.line("acceleration x: "+e.acceleration.x.toFixed(2),"y: "+e.acceleration.y.toFixed(2),"speed: "+e.speed.toFixed(2),"angle: "+e.angle.toFixed(2)),t.line("gravity x: "+e.gravity.x,"y: "+e.gravity.y,"bounce x: "+e.bounce.x.toFixed(2),"y: "+e.bounce.y.toFixed(2)),t.line("touching left: "+e.touching.left,"right: "+e.touching.right,"up: "+e.touching.up,"down: "+e.touching.down),t.line("blocked left: "+e.blocked.left,"right: "+e.blocked.right,"up: "+e.blocked.up,"down: "+e.blocked.down)},n.Physics.Arcade.Body.prototype.constructor=n.Physics.Arcade.Body,n.Physics.Arcade.TilemapCollision=function(){},n.Physics.Arcade.TilemapCollision.prototype={TILE_BIAS:16,collideSpriteVsTilemapLayer:function(t,e,i,s,n,r){if(t.body){var o=e.getTiles(t.body.position.x-t.body.tilePadding.x,t.body.position.y-t.body.tilePadding.y,t.body.width+t.body.tilePadding.x,t.body.height+t.body.tilePadding.y,!1,!1);if(0!==o.length)for(var a=0;a<o.length;a++)s?s.call(n,t,o[a])&&this.separateTile(a,t.body,o[a],e,r)&&(this._total++,i&&i.call(n,t,o[a])):this.separateTile(a,t.body,o[a],e,r)&&(this._total++,i&&i.call(n,t,o[a]))}},collideGroupVsTilemapLayer:function(t,e,i,s,n,r){if(0!==t.length)for(var o=0;o<t.children.length;o++)t.children[o].exists&&this.collideSpriteVsTilemapLayer(t.children[o],e,i,s,n,r)},separateTile:function(t,e,i,s,n){if(!e.enable)return!1;var r=s.fixedToCamera?0:s.position.x,o=s.fixedToCamera?0:s.position.y;if(!i.intersects(e.position.x-r,e.position.y-o,e.right-r,e.bottom-o))return!1;if(n)return!0;if(i.collisionCallback&&!i.collisionCallback.call(i.collisionCallbackContext,e.sprite,i))return!1;if(void 0!==i.layer.callbacks&&i.layer.callbacks[i.index]&&!i.layer.callbacks[i.index].callback.call(i.layer.callbacks[i.index].callbackContext,e.sprite,i))return!1;if(!(i.faceLeft||i.faceRight||i.faceTop||i.faceBottom))return!1;var a=0,h=0,l=0,c=1;if(e.deltaAbsX()>e.deltaAbsY()?l=-1:e.deltaAbsX()<e.deltaAbsY()&&(c=-1),0!==e.deltaX()&&0!==e.deltaY()&&(i.faceLeft||i.faceRight)&&(i.faceTop||i.faceBottom)&&(l=Math.min(Math.abs(e.position.x-r-i.right),Math.abs(e.right-r-i.left)),c=Math.min(Math.abs(e.position.y-o-i.bottom),Math.abs(e.bottom-o-i.top))),l<c){if((i.faceLeft||i.faceRight)&&0!==(a=this.tileCheckX(e,i,s))&&!i.intersects(e.position.x-r,e.position.y-o,e.right-r,e.bottom-o))return!0;(i.faceTop||i.faceBottom)&&(h=this.tileCheckY(e,i,s))}else{if((i.faceTop||i.faceBottom)&&0!==(h=this.tileCheckY(e,i,s))&&!i.intersects(e.position.x-r,e.position.y-o,e.right-r,e.bottom-o))return!0;(i.faceLeft||i.faceRight)&&(a=this.tileCheckX(e,i,s))}return 0!==a||0!==h},tileCheckX:function(t,e,i){var s=0,n=i.fixedToCamera?0:i.position.x;return t.deltaX()<0&&!t.blocked.left&&e.collideRight&&t.checkCollision.left?e.faceRight&&t.x-n<e.right&&(s=t.x-n-e.right)<-this.TILE_BIAS&&(s=0):t.deltaX()>0&&!t.blocked.right&&e.collideLeft&&t.checkCollision.right&&e.faceLeft&&t.right-n>e.left&&(s=t.right-n-e.left)>this.TILE_BIAS&&(s=0),0!==s&&(t.customSeparateX?t.overlapX=s:this.processTileSeparationX(t,s)),s},tileCheckY:function(t,e,i){var s=0,n=i.fixedToCamera?0:i.position.y;return t.deltaY()<0&&!t.blocked.up&&e.collideDown&&t.checkCollision.up?e.faceBottom&&t.y-n<e.bottom&&(s=t.y-n-e.bottom)<-this.TILE_BIAS&&(s=0):t.deltaY()>0&&!t.blocked.down&&e.collideUp&&t.checkCollision.down&&e.faceTop&&t.bottom-n>e.top&&(s=t.bottom-n-e.top)>this.TILE_BIAS&&(s=0),0!==s&&(t.customSeparateY?t.overlapY=s:this.processTileSeparationY(t,s)),s},processTileSeparationX:function(t,e){e<0?t.blocked.left=!0:e>0&&(t.blocked.right=!0),t.position.x-=e,0===t.bounce.x?t.velocity.x=0:t.velocity.x=-t.velocity.x*t.bounce.x},processTileSeparationY:function(t,e){e<0?t.blocked.up=!0:e>0&&(t.blocked.down=!0),t.position.y-=e,0===t.bounce.y?t.velocity.y=0:t.velocity.y=-t.velocity.y*t.bounce.y}},n.Utils.mixinPrototype(n.Physics.Arcade.prototype,n.Physics.Arcade.TilemapCollision.prototype),p2.Body.prototype.parent=null,p2.Spring.prototype.parent=null,n.Physics.P2=function(t,e){this.game=t,void 0===e?e={gravity:[0,0],broadphase:new p2.SAPBroadphase}:(e.hasOwnProperty("gravity")||(e.gravity=[0,0]),e.hasOwnProperty("broadphase")||(e.broadphase=new p2.SAPBroadphase)),this.config=e,this.world=new p2.World(this.config),this.frameRate=1/60,this.useElapsedTime=!1,this.paused=!1,this.materials=[],this.gravity=new n.Physics.P2.InversePointProxy(this,this.world.gravity),this.walls={left:null,right:null,top:null,bottom:null},this.onBodyAdded=new n.Signal,this.onBodyRemoved=new n.Signal,this.onSpringAdded=new n.Signal,this.onSpringRemoved=new n.Signal,this.onConstraintAdded=new n.Signal,this.onConstraintRemoved=new n.Signal,this.onContactMaterialAdded=new n.Signal,this.onContactMaterialRemoved=new n.Signal,this.postBroadphaseCallback=null,this.callbackContext=null,this.onBeginContact=new n.Signal,this.onEndContact=new n.Signal,e.hasOwnProperty("mpx")&&e.hasOwnProperty("pxm")&&e.hasOwnProperty("mpxi")&&e.hasOwnProperty("pxmi")&&(this.mpx=e.mpx,this.mpxi=e.mpxi,this.pxm=e.pxm,this.pxmi=e.pxmi),this.world.on("beginContact",this.beginContactHandler,this),this.world.on("endContact",this.endContactHandler,this),this.collisionGroups=[],this.nothingCollisionGroup=new n.Physics.P2.CollisionGroup(1),this.boundsCollisionGroup=new n.Physics.P2.CollisionGroup(2),this.everythingCollisionGroup=new n.Physics.P2.CollisionGroup(2147483648),this.boundsCollidesWith=[],this._toRemove=[],this._collisionGroupID=2,this._boundsLeft=!0,this._boundsRight=!0,this._boundsTop=!0,this._boundsBottom=!0,this._boundsOwnGroup=!1,this.setBoundsToWorld(!0,!0,!0,!0,!1)},n.Physics.P2.prototype={removeBodyNextStep:function(t){this._toRemove.push(t)},preUpdate:function(){for(var t=this._toRemove.length;t--;)this.removeBody(this._toRemove[t]);this._toRemove.length=0},enable:function(t,e,i){void 0===e&&(e=!1),void 0===i&&(i=!0);var s=1;if(Array.isArray(t))for(s=t.length;s--;)t[s]instanceof n.Group?this.enable(t[s].children,e,i):(this.enableBody(t[s],e),i&&t[s].hasOwnProperty("children")&&t[s].children.length>0&&this.enable(t[s],e,!0));else t instanceof n.Group?this.enable(t.children,e,i):(this.enableBody(t,e),i&&t.hasOwnProperty("children")&&t.children.length>0&&this.enable(t.children,e,!0))},enableBody:function(t,e){t.hasOwnProperty("body")&&null===t.body&&(t.body=new n.Physics.P2.Body(this.game,t,t.x,t.y,1),t.body.debug=e,void 0!==t.anchor&&t.anchor.set(.5))},setImpactEvents:function(t){t?this.world.on("impact",this.impactHandler,this):this.world.off("impact",this.impactHandler,this)},setPostBroadphaseCallback:function(t,e){this.postBroadphaseCallback=t,this.callbackContext=e,null!==t?this.world.on("postBroadphase",this.postBroadphaseHandler,this):this.world.off("postBroadphase",this.postBroadphaseHandler,this)},postBroadphaseHandler:function(t){if(this.postBroadphaseCallback&&0!==t.pairs.length)for(var e=t.pairs.length-2;e>=0;e-=2)t.pairs[e].parent&&t.pairs[e+1].parent&&!this.postBroadphaseCallback.call(this.callbackContext,t.pairs[e].parent,t.pairs[e+1].parent)&&t.pairs.splice(e,2)},impactHandler:function(t){if(t.bodyA.parent&&t.bodyB.parent){var e=t.bodyA.parent,i=t.bodyB.parent;e._bodyCallbacks[t.bodyB.id]&&e._bodyCallbacks[t.bodyB.id].call(e._bodyCallbackContext[t.bodyB.id],e,i,t.shapeA,t.shapeB),i._bodyCallbacks[t.bodyA.id]&&i._bodyCallbacks[t.bodyA.id].call(i._bodyCallbackContext[t.bodyA.id],i,e,t.shapeB,t.shapeA),e._groupCallbacks[t.shapeB.collisionGroup]&&e._groupCallbacks[t.shapeB.collisionGroup].call(e._groupCallbackContext[t.shapeB.collisionGroup],e,i,t.shapeA,t.shapeB),i._groupCallbacks[t.shapeA.collisionGroup]&&i._groupCallbacks[t.shapeA.collisionGroup].call(i._groupCallbackContext[t.shapeA.collisionGroup],i,e,t.shapeB,t.shapeA)}},beginContactHandler:function(t){t.bodyA&&t.bodyB&&(this.onBeginContact.dispatch(t.bodyA,t.bodyB,t.shapeA,t.shapeB,t.contactEquations),t.bodyA.parent&&t.bodyA.parent.onBeginContact.dispatch(t.bodyB.parent,t.bodyB,t.shapeA,t.shapeB,t.contactEquations),t.bodyB.parent&&t.bodyB.parent.onBeginContact.dispatch(t.bodyA.parent,t.bodyA,t.shapeB,t.shapeA,t.contactEquations))},endContactHandler:function(t){t.bodyA&&t.bodyB&&(this.onEndContact.dispatch(t.bodyA,t.bodyB,t.shapeA,t.shapeB),t.bodyA.parent&&t.bodyA.parent.onEndContact.dispatch(t.bodyB.parent,t.bodyB,t.shapeA,t.shapeB),t.bodyB.parent&&t.bodyB.parent.onEndContact.dispatch(t.bodyA.parent,t.bodyA,t.shapeB,t.shapeA))},setBoundsToWorld:function(t,e,i,s,n){this.setBounds(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height,t,e,i,s,n)},setWorldMaterial:function(t,e,i,s,n){void 0===e&&(e=!0),void 0===i&&(i=!0),void 0===s&&(s=!0),void 0===n&&(n=!0),e&&this.walls.left&&(this.walls.left.shapes[0].material=t),i&&this.walls.right&&(this.walls.right.shapes[0].material=t),s&&this.walls.top&&(this.walls.top.shapes[0].material=t),n&&this.walls.bottom&&(this.walls.bottom.shapes[0].material=t)},updateBoundsCollisionGroup:function(t){void 0===t&&(t=!0);var e=t?this.boundsCollisionGroup.mask:this.everythingCollisionGroup.mask;this.walls.left&&(this.walls.left.shapes[0].collisionGroup=e),this.walls.right&&(this.walls.right.shapes[0].collisionGroup=e),this.walls.top&&(this.walls.top.shapes[0].collisionGroup=e),this.walls.bottom&&(this.walls.bottom.shapes[0].collisionGroup=e),this._boundsOwnGroup=t},setBounds:function(t,e,i,s,n,r,o,a,h){void 0===n&&(n=this._boundsLeft),void 0===r&&(r=this._boundsRight),void 0===o&&(o=this._boundsTop),void 0===a&&(a=this._boundsBottom),void 0===h&&(h=this._boundsOwnGroup),this.setupWall(n,"left",t,e,1.5707963267948966,h),this.setupWall(r,"right",t+i,e,-1.5707963267948966,h),this.setupWall(o,"top",t,e,-3.141592653589793,h),this.setupWall(a,"bottom",t,e+s,0,h),this._boundsLeft=n,this._boundsRight=r,this._boundsTop=o,this._boundsBottom=a,this._boundsOwnGroup=h},setupWall:function(t,e,i,s,n,r){t?(this.walls[e]?this.walls[e].position=[this.pxmi(i),this.pxmi(s)]:(this.walls[e]=new p2.Body({mass:0,position:[this.pxmi(i),this.pxmi(s)],angle:n}),this.walls[e].addShape(new p2.Plane),this.world.addBody(this.walls[e])),r&&(this.walls[e].shapes[0].collisionGroup=this.boundsCollisionGroup.mask)):this.walls[e]&&(this.world.removeBody(this.walls[e]),this.walls[e]=null)},pause:function(){this.paused=!0},resume:function(){this.paused=!1},update:function(){this.paused||(this.useElapsedTime?this.world.step(this.game.time.physicsElapsed):this.world.step(this.frameRate))},reset:function(){this.world.on("beginContact",this.beginContactHandler,this),this.world.on("endContact",this.endContactHandler,this),this.nothingCollisionGroup=new n.Physics.P2.CollisionGroup(1),this.boundsCollisionGroup=new n.Physics.P2.CollisionGroup(2),this.everythingCollisionGroup=new n.Physics.P2.CollisionGroup(2147483648),this._collisionGroupID=2,this.setBoundsToWorld(!0,!0,!0,!0,!1)},clear:function(){this.world.time=0,this.world.fixedStepTime=0,this.world.solver&&this.world.solver.equations.length&&this.world.solver.removeAllEquations();for(var t=this.world.constraints,e=t.length-1;e>=0;e--)this.world.removeConstraint(t[e]);for(var i=this.world.bodies,e=i.length-1;e>=0;e--)this.world.removeBody(i[e]);for(var s=this.world.springs,e=s.length-1;e>=0;e--)this.world.removeSpring(s[e]);for(var n=this.world.contactMaterials,e=n.length-1;e>=0;e--)this.world.removeContactMaterial(n[e]);this.world.off("beginContact",this.beginContactHandler,this),this.world.off("endContact",this.endContactHandler,this),this.postBroadphaseCallback=null,this.callbackContext=null,this.impactCallback=null,this.collisionGroups=[],this._toRemove=[],this.boundsCollidesWith=[],this.walls={left:null,right:null,top:null,bottom:null}},destroy:function(){this.clear(),this.game=null},addBody:function(t){return!t.data.world&&(this.world.addBody(t.data),this.onBodyAdded.dispatch(t),!0)},removeBody:function(t){return t.data.world===this.world&&(this.world.removeBody(t.data),this.onBodyRemoved.dispatch(t)),t},addSpring:function(t){return t instanceof n.Physics.P2.Spring||t instanceof n.Physics.P2.RotationalSpring?this.world.addSpring(t.data):this.world.addSpring(t),this.onSpringAdded.dispatch(t),t},removeSpring:function(t){return t instanceof n.Physics.P2.Spring||t instanceof n.Physics.P2.RotationalSpring?this.world.removeSpring(t.data):this.world.removeSpring(t),this.onSpringRemoved.dispatch(t),t},createDistanceConstraint:function(t,e,i,s,r,o){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new n.Physics.P2.DistanceConstraint(this,t,e,i,s,r,o));console.warn("Cannot create Constraint, invalid body objects given")},createGearConstraint:function(t,e,i,s){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new n.Physics.P2.GearConstraint(this,t,e,i,s));console.warn("Cannot create Constraint, invalid body objects given")},createRevoluteConstraint:function(t,e,i,s,r,o){if(t=this.getBody(t),i=this.getBody(i),t&&i)return this.addConstraint(new n.Physics.P2.RevoluteConstraint(this,t,e,i,s,r,o));console.warn("Cannot create Constraint, invalid body objects given")},createLockConstraint:function(t,e,i,s,r){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new n.Physics.P2.LockConstraint(this,t,e,i,s,r));console.warn("Cannot create Constraint, invalid body objects given")},createPrismaticConstraint:function(t,e,i,s,r,o,a){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new n.Physics.P2.PrismaticConstraint(this,t,e,i,s,r,o,a));console.warn("Cannot create Constraint, invalid body objects given")},addConstraint:function(t){return this.world.addConstraint(t),this.onConstraintAdded.dispatch(t),t},removeConstraint:function(t){return this.world.removeConstraint(t),this.onConstraintRemoved.dispatch(t),t},addContactMaterial:function(t){return this.world.addContactMaterial(t),this.onContactMaterialAdded.dispatch(t),t},removeContactMaterial:function(t){return this.world.removeContactMaterial(t),this.onContactMaterialRemoved.dispatch(t),t},getContactMaterial:function(t,e){return this.world.getContactMaterial(t,e)},setMaterial:function(t,e){for(var i=e.length;i--;)e[i].setMaterial(t)},createMaterial:function(t,e){t=t||"";var i=new n.Physics.P2.Material(t);return this.materials.push(i),void 0!==e&&e.setMaterial(i),i},createContactMaterial:function(t,e,i){void 0===t&&(t=this.createMaterial()),void 0===e&&(e=this.createMaterial());var s=new n.Physics.P2.ContactMaterial(t,e,i);return this.addContactMaterial(s)},getBodies:function(){for(var t=[],e=this.world.bodies.length;e--;)t.push(this.world.bodies[e].parent);return t},getBody:function(t){return t instanceof p2.Body?t:t instanceof n.Physics.P2.Body?t.data:t.body&&t.body.type===n.Physics.P2JS?t.body.data:null},getSprings:function(){for(var t=[],e=this.world.springs.length;e--;)t.push(this.world.springs[e].parent);return t},getConstraints:function(){for(var t=[],e=this.world.constraints.length;e--;)t.push(this.world.constraints[e]);return t},hitTest:function(t,e,i,s){void 0===e&&(e=this.world.bodies),void 0===i&&(i=5),void 0===s&&(s=!1);for(var r=[this.pxmi(t.x),this.pxmi(t.y)],o=[],a=e.length;a--;)e[a]instanceof n.Physics.P2.Body&&(!s||e[a].data.type!==p2.Body.STATIC)?o.push(e[a].data):e[a]instanceof p2.Body&&e[a].parent&&(!s||e[a].type!==p2.Body.STATIC)?o.push(e[a]):e[a]instanceof n.Sprite&&e[a].hasOwnProperty("body")&&(!s||e[a].body.data.type!==p2.Body.STATIC)&&o.push(e[a].body.data);return this.world.hitTest(r,o,i)},toJSON:function(){return this.world.toJSON()},createCollisionGroup:function(t){var e=Math.pow(2,this._collisionGroupID);this.walls.left&&(this.walls.left.shapes[0].collisionMask=this.walls.left.shapes[0].collisionMask|e),this.walls.right&&(this.walls.right.shapes[0].collisionMask=this.walls.right.shapes[0].collisionMask|e),this.walls.top&&(this.walls.top.shapes[0].collisionMask=this.walls.top.shapes[0].collisionMask|e),this.walls.bottom&&(this.walls.bottom.shapes[0].collisionMask=this.walls.bottom.shapes[0].collisionMask|e),this._collisionGroupID++;var i=new n.Physics.P2.CollisionGroup(e);return this.collisionGroups.push(i),t&&this.setCollisionGroup(t,i),i},setCollisionGroup:function(t,e){if(t instanceof n.Group)for(var i=0;i<t.total;i++)t.children[i].body&&t.children[i].body.type===n.Physics.P2JS&&t.children[i].body.setCollisionGroup(e);else t.body.setCollisionGroup(e)},createSpring:function(t,e,i,s,r,o,a,h,l){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addSpring(new n.Physics.P2.Spring(this,t,e,i,s,r,o,a,h,l));console.warn("Cannot create Spring, invalid body objects given")},createRotationalSpring:function(t,e,i,s,r){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addSpring(new n.Physics.P2.RotationalSpring(this,t,e,i,s,r));console.warn("Cannot create Rotational Spring, invalid body objects given")},createBody:function(t,e,i,s,r,o){void 0===s&&(s=!1);var a=new n.Physics.P2.Body(this.game,null,t,e,i);if(o){if(!a.addPolygon(r,o))return!1}return s&&this.world.addBody(a.data),a},createParticle:function(t,e,i,s,r,o){void 0===s&&(s=!1);var a=new n.Physics.P2.Body(this.game,null,t,e,i);if(o){if(!a.addPolygon(r,o))return!1}return s&&this.world.addBody(a.data),a},convertCollisionObjects:function(t,e,i){void 0===i&&(i=!0);for(var s=[],n=0,r=t.collision[e].length;n<r;n++){var o=t.collision[e][n],a=this.createBody(o.x,o.y,0,i,{},o.polyline);a&&s.push(a)}return s},clearTilemapLayerBodies:function(t,e){e=t.getLayer(e);for(var i=t.layers[e].bodies.length;i--;)t.layers[e].bodies[i].destroy();t.layers[e].bodies.length=0},convertTilemap:function(t,e,i,s){e=t.getLayer(e),void 0===i&&(i=!0),void 0===s&&(s=!0),this.clearTilemapLayerBodies(t,e);for(var n=0,r=0,o=0,a=0,h=t.layers[e].height;a<h;a++){n=0;for(var l=0,c=t.layers[e].width;l<c;l++){var u=t.layers[e].data[a][l];if(u&&u.index>-1&&u.collides)if(s){var d=t.getTileRight(e,l,a);if(0===n&&(r=u.x*u.width,o=u.y*u.height,n=u.width),d&&d.collides)n+=u.width;else{var p=this.createBody(r,o,0,!1);p.addRectangle(n,u.height,n/2,u.height/2,0),i&&this.addBody(p),t.layers[e].bodies.push(p),n=0}}else{var p=this.createBody(u.x*u.width,u.y*u.height,0,!1);p.addRectangle(u.width,u.height,u.width/2,u.height/2,0),i&&this.addBody(p),t.layers[e].bodies.push(p)}}}return t.layers[e].bodies},mpx:function(t){return t*=20},pxm:function(t){return.05*t},mpxi:function(t){return t*=-20},pxmi:function(t){return-.05*t}},Object.defineProperty(n.Physics.P2.prototype,"friction",{get:function(){return this.world.defaultContactMaterial.friction},set:function(t){this.world.defaultContactMaterial.friction=t}}),Object.defineProperty(n.Physics.P2.prototype,"restitution",{get:function(){return this.world.defaultContactMaterial.restitution},set:function(t){this.world.defaultContactMaterial.restitution=t}}),Object.defineProperty(n.Physics.P2.prototype,"contactMaterial",{get:function(){return this.world.defaultContactMaterial},set:function(t){this.world.defaultContactMaterial=t}}),Object.defineProperty(n.Physics.P2.prototype,"applySpringForces",{get:function(){return this.world.applySpringForces},set:function(t){this.world.applySpringForces=t}}),Object.defineProperty(n.Physics.P2.prototype,"applyDamping",{get:function(){return this.world.applyDamping},set:function(t){this.world.applyDamping=t}}),Object.defineProperty(n.Physics.P2.prototype,"applyGravity",{get:function(){return this.world.applyGravity},set:function(t){this.world.applyGravity=t}}),Object.defineProperty(n.Physics.P2.prototype,"solveConstraints",{get:function(){return this.world.solveConstraints},set:function(t){this.world.solveConstraints=t}}),Object.defineProperty(n.Physics.P2.prototype,"time",{get:function(){return this.world.time}}),Object.defineProperty(n.Physics.P2.prototype,"emitImpactEvent",{get:function(){return this.world.emitImpactEvent},set:function(t){this.world.emitImpactEvent=t}}),Object.defineProperty(n.Physics.P2.prototype,"sleepMode",{get:function(){return this.world.sleepMode},set:function(t){this.world.sleepMode=t}}),Object.defineProperty(n.Physics.P2.prototype,"total",{get:function(){return this.world.bodies.length}}),n.Physics.P2.FixtureList=function(t){Array.isArray(t)||(t=[t]),this.rawList=t,this.init(),this.parse(this.rawList)},n.Physics.P2.FixtureList.prototype={init:function(){this.namedFixtures={},this.groupedFixtures=[],this.allFixtures=[]},setCategory:function(t,e){var i=function(e){e.collisionGroup=t};this.getFixtures(e).forEach(i)},setMask:function(t,e){var i=function(e){e.collisionMask=t};this.getFixtures(e).forEach(i)},setSensor:function(t,e){var i=function(e){e.sensor=t};this.getFixtures(e).forEach(i)},setMaterial:function(t,e){var i=function(e){e.material=t};this.getFixtures(e).forEach(i)},getFixtures:function(t){var e=[];if(t){t instanceof Array||(t=[t]);var i=this;return t.forEach(function(t){i.namedFixtures[t]&&e.push(i.namedFixtures[t])}),this.flatten(e)}return this.allFixtures},getFixtureByKey:function(t){return this.namedFixtures[t]},getGroup:function(t){return this.groupedFixtures[t]},parse:function(){var t,e,i,s;i=this.rawList,s=[];for(t in i)e=i[t],isNaN(t-0)?this.namedFixtures[t]=this.flatten(e):(this.groupedFixtures[t]=this.groupedFixtures[t]||[],this.groupedFixtures[t]=this.groupedFixtures[t].concat(e)),s.push(this.allFixtures=this.flatten(this.groupedFixtures))},flatten:function(t){var e,i;return e=[],i=arguments.callee,t.forEach(function(t){return Array.prototype.push.apply(e,Array.isArray(t)?i(t):[t])}),e}},n.Physics.P2.PointProxy=function(t,e){this.world=t,this.destination=e},n.Physics.P2.PointProxy.prototype.constructor=n.Physics.P2.PointProxy,Object.defineProperty(n.Physics.P2.PointProxy.prototype,"x",{get:function(){return this.world.mpx(this.destination[0])},set:function(t){this.destination[0]=this.world.pxm(t)}}),Object.defineProperty(n.Physics.P2.PointProxy.prototype,"y",{get:function(){return this.world.mpx(this.destination[1])},set:function(t){this.destination[1]=this.world.pxm(t)}}),Object.defineProperty(n.Physics.P2.PointProxy.prototype,"mx",{get:function(){return this.destination[0]},set:function(t){this.destination[0]=t}}),Object.defineProperty(n.Physics.P2.PointProxy.prototype,"my",{get:function(){return this.destination[1]},set:function(t){this.destination[1]=t}}),n.Physics.P2.InversePointProxy=function(t,e){this.world=t,this.destination=e},n.Physics.P2.InversePointProxy.prototype.constructor=n.Physics.P2.InversePointProxy,Object.defineProperty(n.Physics.P2.InversePointProxy.prototype,"x",{get:function(){return this.world.mpxi(this.destination[0])},set:function(t){this.destination[0]=this.world.pxmi(t)}}),Object.defineProperty(n.Physics.P2.InversePointProxy.prototype,"y",{get:function(){return this.world.mpxi(this.destination[1])},set:function(t){this.destination[1]=this.world.pxmi(t)}}),Object.defineProperty(n.Physics.P2.InversePointProxy.prototype,"mx",{get:function(){return this.destination[0]},set:function(t){this.destination[0]=-t}}),Object.defineProperty(n.Physics.P2.InversePointProxy.prototype,"my",{get:function(){return this.destination[1]},set:function(t){this.destination[1]=-t}}),n.Physics.P2.Body=function(t,e,i,s,r){e=e||null,i=i||0,s=s||0,void 0===r&&(r=1),this.game=t,this.world=t.physics.p2,this.sprite=e,this.type=n.Physics.P2JS,this.offset=new n.Point,this.data=new p2.Body({position:[this.world.pxmi(i),this.world.pxmi(s)],mass:r}),this.data.parent=this,this.velocity=new n.Physics.P2.InversePointProxy(this.world,this.data.velocity),this.force=new n.Physics.P2.InversePointProxy(this.world,this.data.force),this.gravity=new n.Point,this.onBeginContact=new n.Signal,this.onEndContact=new n.Signal,this.collidesWith=[],this.removeNextStep=!1,this.debugBody=null,this.dirty=!1,this._collideWorldBounds=!0,this._bodyCallbacks={},this._bodyCallbackContext={},this._groupCallbacks={},this._groupCallbackContext={},this._reset=!1,e&&(this.setRectangleFromSprite(e),e.exists&&this.game.physics.p2.addBody(this))},n.Physics.P2.Body.prototype={createBodyCallback:function(t,e,i){var s=-1;t.id?s=t.id:t.body&&(s=t.body.id),s>-1&&(null===e?(delete this._bodyCallbacks[s],delete this._bodyCallbackContext[s]):(this._bodyCallbacks[s]=e,this._bodyCallbackContext[s]=i))},createGroupCallback:function(t,e,i){null===e?(delete this._groupCallbacks[t.mask],delete this._groupCallbackContext[t.mask]):(this._groupCallbacks[t.mask]=e,this._groupCallbackContext[t.mask]=i)},getCollisionMask:function(){var t=0;this._collideWorldBounds&&(t=this.game.physics.p2.boundsCollisionGroup.mask);for(var e=0;e<this.collidesWith.length;e++)t|=this.collidesWith[e].mask;return t},updateCollisionMask:function(t){var e=this.getCollisionMask();if(void 0===t)for(var i=this.data.shapes.length-1;i>=0;i--)this.data.shapes[i].collisionMask=e;else t.collisionMask=e},setCollisionGroup:function(t,e){var i=this.getCollisionMask();if(void 0===e)for(var s=this.data.shapes.length-1;s>=0;s--)this.data.shapes[s].collisionGroup=t.mask,this.data.shapes[s].collisionMask=i;else e.collisionGroup=t.mask,e.collisionMask=i},clearCollision:function(t,e,i){if(void 0===t&&(t=!0),void 0===e&&(e=!0),void 0===i)for(var s=this.data.shapes.length-1;s>=0;s--)t&&(this.data.shapes[s].collisionGroup=null),e&&(this.data.shapes[s].collisionMask=null);else t&&(i.collisionGroup=null),e&&(i.collisionMask=null);t&&(this.collidesWith.length=0)},removeCollisionGroup:function(t,e,i){void 0===e&&(e=!0);var s;if(Array.isArray(t))for(var n=0;n<t.length;n++)(s=this.collidesWith.indexOf(t[n]))>-1&&(this.collidesWith.splice(s,1),e&&(delete this._groupCallbacks[t.mask],delete this._groupCallbackContext[t.mask]));else(s=this.collidesWith.indexOf(t))>-1&&(this.collidesWith.splice(s,1),e&&(delete this._groupCallbacks[t.mask],delete this._groupCallbackContext[t.mask]));var r=this.getCollisionMask();if(void 0===i)for(var n=this.data.shapes.length-1;n>=0;n--)this.data.shapes[n].collisionMask=r;else i.collisionMask=r},collides:function(t,e,i,s){if(Array.isArray(t))for(var n=0;n<t.length;n++)-1===this.collidesWith.indexOf(t[n])&&(this.collidesWith.push(t[n]),e&&this.createGroupCallback(t[n],e,i));else-1===this.collidesWith.indexOf(t)&&(this.collidesWith.push(t),e&&this.createGroupCallback(t,e,i));var r=this.getCollisionMask();if(void 0===s)for(var n=this.data.shapes.length-1;n>=0;n--)this.data.shapes[n].collisionMask=r;else s.collisionMask=r},adjustCenterOfMass:function(){this.data.adjustCenterOfMass(),this.shapeChanged()},getVelocityAtPoint:function(t,e){return this.data.getVelocityAtPoint(t,e)},applyDamping:function(t){this.data.applyDamping(t)},applyImpulse:function(t,e,i){this.data.applyImpulse(t,[this.world.pxmi(e),this.world.pxmi(i)])},applyImpulseLocal:function(t,e,i){this.data.applyImpulseLocal(t,[this.world.pxmi(e),this.world.pxmi(i)])},applyForce:function(t,e,i){this.data.applyForce(t,[this.world.pxmi(e),this.world.pxmi(i)])},setZeroForce:function(){this.data.setZeroForce()},setZeroRotation:function(){this.data.angularVelocity=0},setZeroVelocity:function(){this.data.velocity[0]=0,this.data.velocity[1]=0},setZeroDamping:function(){this.data.damping=0,this.data.angularDamping=0},toLocalFrame:function(t,e){return this.data.toLocalFrame(t,e)},toWorldFrame:function(t,e){return this.data.toWorldFrame(t,e)},rotateLeft:function(t){this.data.angularVelocity=this.world.pxm(-t)},rotateRight:function(t){this.data.angularVelocity=this.world.pxm(t)},moveForward:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.velocity[0]=e*Math.cos(i),this.data.velocity[1]=e*Math.sin(i)},moveBackward:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.velocity[0]=-e*Math.cos(i),this.data.velocity[1]=-e*Math.sin(i)},thrust:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.force[0]+=e*Math.cos(i),this.data.force[1]+=e*Math.sin(i)},thrustLeft:function(t){var e=this.world.pxmi(-t),i=this.data.angle;this.data.force[0]+=e*Math.cos(i),this.data.force[1]+=e*Math.sin(i)},thrustRight:function(t){var e=this.world.pxmi(-t),i=this.data.angle;this.data.force[0]-=e*Math.cos(i),this.data.force[1]-=e*Math.sin(i)},reverse:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.force[0]-=e*Math.cos(i),this.data.force[1]-=e*Math.sin(i)},moveLeft:function(t){this.data.velocity[0]=this.world.pxmi(-t)},moveRight:function(t){this.data.velocity[0]=this.world.pxmi(t)},moveUp:function(t){this.data.velocity[1]=this.world.pxmi(-t)},moveDown:function(t){this.data.velocity[1]=this.world.pxmi(t)},preUpdate:function(){this.dirty=!0,this.removeNextStep&&(this.removeFromWorld(),this.removeNextStep=!1)},postUpdate:function(){this.sprite.x=this.world.mpxi(this.data.position[0])+this.offset.x,this.sprite.y=this.world.mpxi(this.data.position[1])+this.offset.y,this.fixedRotation||(this.sprite.rotation=this.data.angle),this.debugBody&&this.debugBody.updateSpriteTransform(),this.dirty=!1},reset:function(t,e,i,s){void 0===i&&(i=!1),void 0===s&&(s=!1),this.setZeroForce(),this.setZeroVelocity(),this.setZeroRotation(),i&&this.setZeroDamping(),s&&(this.mass=1),this.x=t,this.y=e},addToWorld:function(){if(this.game.physics.p2._toRemove)for(var t=0;t<this.game.physics.p2._toRemove.length;t++)this.game.physics.p2._toRemove[t]===this&&this.game.physics.p2._toRemove.splice(t,1);this.data.world!==this.game.physics.p2.world&&this.game.physics.p2.addBody(this)},removeFromWorld:function(){this.data.world===this.game.physics.p2.world&&this.game.physics.p2.removeBodyNextStep(this)},destroy:function(){this.removeFromWorld(),this.clearShapes(),this._bodyCallbacks={},this._bodyCallbackContext={},this._groupCallbacks={},this._groupCallbackContext={},this.debugBody&&this.debugBody.destroy(!0,!0),this.debugBody=null,this.sprite&&(this.sprite.body=null,this.sprite=null)},clearShapes:function(){for(var t=this.data.shapes.length;t--;)this.data.removeShape(this.data.shapes[t]);this.shapeChanged()},addShape:function(t,e,i,s){return void 0===e&&(e=0),void 0===i&&(i=0),void 0===s&&(s=0),this.data.addShape(t,[this.world.pxmi(e),this.world.pxmi(i)],s),this.shapeChanged(),t},addCircle:function(t,e,i,s){var n=new p2.Circle({radius:this.world.pxm(t)});return this.addShape(n,e,i,s)},addRectangle:function(t,e,i,s,n){var r=new p2.Box({width:this.world.pxm(t),height:this.world.pxm(e)});return this.addShape(r,i,s,n)},addPlane:function(t,e,i){var s=new p2.Plane;return this.addShape(s,t,e,i)},addParticle:function(t,e,i){var s=new p2.Particle;return this.addShape(s,t,e,i)},addLine:function(t,e,i,s){var n=new p2.Line({length:this.world.pxm(t)});return this.addShape(n,e,i,s)},addCapsule:function(t,e,i,s,n){var r=new p2.Capsule({length:this.world.pxm(t),radius:this.world.pxm(e)});return this.addShape(r,i,s,n)},addPolygon:function(t,e){t=t||{},Array.isArray(e)||(e=Array.prototype.slice.call(arguments,1));var i=[];if(1===e.length&&Array.isArray(e[0]))i=e[0].slice(0);else if(Array.isArray(e[0]))i=e.slice();else if("number"==typeof e[0])for(var s=0,n=e.length;s<n;s+=2)i.push([e[s],e[s+1]]);var r=i.length-1;i[r][0]===i[0][0]&&i[r][1]===i[0][1]&&i.pop();for(var o=0;o<i.length;o++)i[o][0]=this.world.pxmi(i[o][0]),i[o][1]=this.world.pxmi(i[o][1]);var a=this.data.fromPolygon(i,t);return this.shapeChanged(),a},removeShape:function(t){var e=this.data.removeShape(t);return this.shapeChanged(),e},setCircle:function(t,e,i,s){return this.clearShapes(),this.addCircle(t,e,i,s)},setRectangle:function(t,e,i,s,n){return void 0===t&&(t=16),void 0===e&&(e=16),this.clearShapes(),this.addRectangle(t,e,i,s,n)},setRectangleFromSprite:function(t){return void 0===t&&(t=this.sprite),this.clearShapes(),this.addRectangle(t.width,t.height,0,0,t.rotation)},setMaterial:function(t,e){if(void 0===e)for(var i=this.data.shapes.length-1;i>=0;i--)this.data.shapes[i].material=t;else e.material=t},shapeChanged:function(){this.debugBody&&this.debugBody.draw()},addPhaserPolygon:function(t,e){for(var i=this.game.cache.getPhysicsData(t,e),s=[],n=0;n<i.length;n++){var r=i[n],o=this.addFixture(r);s[r.filter.group]=s[r.filter.group]||[],s[r.filter.group]=s[r.filter.group].concat(o),r.fixtureKey&&(s[r.fixtureKey]=o)}return this.data.aabbNeedsUpdate=!0,this.shapeChanged(),s},addFixture:function(t){var e=[];if(t.circle){var i=new p2.Circle({radius:this.world.pxm(t.circle.radius)});i.collisionGroup=t.filter.categoryBits,i.collisionMask=t.filter.maskBits,i.sensor=t.isSensor;var s=p2.vec2.create();s[0]=this.world.pxmi(t.circle.position[0]-this.sprite.width/2),s[1]=this.world.pxmi(t.circle.position[1]-this.sprite.height/2),this.data.addShape(i,s),e.push(i)}else for(var n=t.polygons,r=p2.vec2.create(),o=0;o<n.length;o++){for(var a=n[o],h=[],l=0;l<a.length;l+=2)h.push([this.world.pxmi(a[l]),this.world.pxmi(a[l+1])]);for(var i=new p2.Convex({vertices:h}),c=0;c!==i.vertices.length;c++){var u=i.vertices[c];p2.vec2.sub(u,u,i.centerOfMass)}p2.vec2.scale(r,i.centerOfMass,1),r[0]-=this.world.pxmi(this.sprite.width/2),r[1]-=this.world.pxmi(this.sprite.height/2),i.updateTriangles(),i.updateCenterOfMass(),i.updateBoundingRadius(),i.collisionGroup=t.filter.categoryBits,i.collisionMask=t.filter.maskBits,i.sensor=t.isSensor,this.data.addShape(i,r),e.push(i)}return e},loadPolygon:function(t,e){if(null===t)var i=e;else var i=this.game.cache.getPhysicsData(t,e);for(var s=p2.vec2.create(),n=0;n<i.length;n++){for(var r=[],o=0;o<i[n].shape.length;o+=2)r.push([this.world.pxmi(i[n].shape[o]),this.world.pxmi(i[n].shape[o+1])]);for(var a=new p2.Convex({vertices:r}),h=0;h!==a.vertices.length;h++){var l=a.vertices[h];p2.vec2.sub(l,l,a.centerOfMass)}p2.vec2.scale(s,a.centerOfMass,1),s[0]-=this.world.pxmi(this.sprite.width/2),s[1]-=this.world.pxmi(this.sprite.height/2),a.updateTriangles(),a.updateCenterOfMass(),a.updateBoundingRadius(),this.data.addShape(a,s)}return this.data.aabbNeedsUpdate=!0,this.shapeChanged(),!0}},n.Physics.P2.Body.prototype.constructor=n.Physics.P2.Body,n.Physics.P2.Body.DYNAMIC=1,n.Physics.P2.Body.STATIC=2,n.Physics.P2.Body.KINEMATIC=4,Object.defineProperty(n.Physics.P2.Body.prototype,"static",{get:function(){return this.data.type===n.Physics.P2.Body.STATIC},set:function(t){t&&this.data.type!==n.Physics.P2.Body.STATIC?(this.data.type=n.Physics.P2.Body.STATIC,this.mass=0):t||this.data.type!==n.Physics.P2.Body.STATIC||(this.data.type=n.Physics.P2.Body.DYNAMIC,this.mass=1)}}),Object.defineProperty(n.Physics.P2.Body.prototype,"dynamic",{get:function(){return this.data.type===n.Physics.P2.Body.DYNAMIC},set:function(t){t&&this.data.type!==n.Physics.P2.Body.DYNAMIC?(this.data.type=n.Physics.P2.Body.DYNAMIC,this.mass=1):t||this.data.type!==n.Physics.P2.Body.DYNAMIC||(this.data.type=n.Physics.P2.Body.STATIC,this.mass=0)}}),Object.defineProperty(n.Physics.P2.Body.prototype,"kinematic",{get:function(){return this.data.type===n.Physics.P2.Body.KINEMATIC},set:function(t){t&&this.data.type!==n.Physics.P2.Body.KINEMATIC?(this.data.type=n.Physics.P2.Body.KINEMATIC,this.mass=4):t||this.data.type!==n.Physics.P2.Body.KINEMATIC||(this.data.type=n.Physics.P2.Body.STATIC,this.mass=0)}}),Object.defineProperty(n.Physics.P2.Body.prototype,"allowSleep",{get:function(){return this.data.allowSleep},set:function(t){t!==this.data.allowSleep&&(this.data.allowSleep=t)}}),Object.defineProperty(n.Physics.P2.Body.prototype,"angle",{get:function(){return n.Math.wrapAngle(n.Math.radToDeg(this.data.angle))},set:function(t){this.data.angle=n.Math.degToRad(n.Math.wrapAngle(t))}}),Object.defineProperty(n.Physics.P2.Body.prototype,"angularDamping",{get:function(){return this.data.angularDamping},set:function(t){this.data.angularDamping=t}}),Object.defineProperty(n.Physics.P2.Body.prototype,"angularForce",{get:function(){return this.data.angularForce},set:function(t){this.data.angularForce=t}}),Object.defineProperty(n.Physics.P2.Body.prototype,"angularVelocity",{get:function(){return this.data.angularVelocity},set:function(t){this.data.angularVelocity=t}}),Object.defineProperty(n.Physics.P2.Body.prototype,"damping",{get:function(){return this.data.damping},set:function(t){this.data.damping=t}}),Object.defineProperty(n.Physics.P2.Body.prototype,"fixedRotation",{get:function(){return this.data.fixedRotation},set:function(t){t!==this.data.fixedRotation&&(this.data.fixedRotation=t)}}),Object.defineProperty(n.Physics.P2.Body.prototype,"inertia",{get:function(){return this.data.inertia},set:function(t){this.data.inertia=t}}),Object.defineProperty(n.Physics.P2.Body.prototype,"mass",{get:function(){return this.data.mass},set:function(t){t!==this.data.mass&&(this.data.mass=t,this.data.updateMassProperties())}}),Object.defineProperty(n.Physics.P2.Body.prototype,"motionState",{get:function(){return this.data.type},set:function(t){t!==this.data.type&&(this.data.type=t)}}),Object.defineProperty(n.Physics.P2.Body.prototype,"rotation",{get:function(){return this.data.angle},set:function(t){this.data.angle=t}}),Object.defineProperty(n.Physics.P2.Body.prototype,"sleepSpeedLimit",{get:function(){return this.data.sleepSpeedLimit},set:function(t){this.data.sleepSpeedLimit=t}}),Object.defineProperty(n.Physics.P2.Body.prototype,"x",{get:function(){return this.world.mpxi(this.data.position[0])},set:function(t){this.data.position[0]=this.world.pxmi(t)}}),Object.defineProperty(n.Physics.P2.Body.prototype,"y",{get:function(){return this.world.mpxi(this.data.position[1])},set:function(t){this.data.position[1]=this.world.pxmi(t)}}),Object.defineProperty(n.Physics.P2.Body.prototype,"id",{get:function(){return this.data.id}}),Object.defineProperty(n.Physics.P2.Body.prototype,"debug",{get:function(){return null!==this.debugBody},set:function(t){t&&!this.debugBody?this.debugBody=new n.Physics.P2.BodyDebug(this.game,this.data):!t&&this.debugBody&&(this.debugBody.destroy(),this.debugBody=null)}}),Object.defineProperty(n.Physics.P2.Body.prototype,"collideWorldBounds",{get:function(){return this._collideWorldBounds},set:function(t){t&&!this._collideWorldBounds?(this._collideWorldBounds=!0,this.updateCollisionMask()):!t&&this._collideWorldBounds&&(this._collideWorldBounds=!1,this.updateCollisionMask())}}),n.Physics.P2.BodyDebug=function(t,e,i){n.Group.call(this,t);var s={pixelsPerLengthUnit:t.physics.p2.mpx(1),debugPolygons:!1,lineWidth:1,alpha:.5};this.settings=n.Utils.extend(s,i),this.ppu=this.settings.pixelsPerLengthUnit,this.ppu=-1*this.ppu,this.body=e,this.canvas=new n.Graphics(t),this.canvas.alpha=this.settings.alpha,this.add(this.canvas),this.draw(),this.updateSpriteTransform()},n.Physics.P2.BodyDebug.prototype=Object.create(n.Group.prototype),n.Physics.P2.BodyDebug.prototype.constructor=n.Physics.P2.BodyDebug,n.Utils.extend(n.Physics.P2.BodyDebug.prototype,{updateSpriteTransform:function(){this.position.x=this.body.position[0]*this.ppu,this.position.y=this.body.position[1]*this.ppu,this.rotation=this.body.angle},draw:function(){var t,e,i,s,n,r,o,a,h,l,c,u,d,p,f;if(a=this.body,l=this.canvas,l.clear(),i=parseInt(this.randomPastelHex(),16),r=16711680,o=this.lineWidth,a instanceof p2.Body&&a.shapes.length){var g=a.shapes.length;for(s=0;s!==g;){if(e=a.shapes[s],h=e.position||0,t=e.angle||0,e instanceof p2.Circle)this.drawCircle(l,h[0]*this.ppu,h[1]*this.ppu,t,e.radius*this.ppu,i,o);else if(e instanceof p2.Capsule)this.drawCapsule(l,h[0]*this.ppu,h[1]*this.ppu,t,e.length*this.ppu,e.radius*this.ppu,r,i,o);else if(e instanceof p2.Plane)this.drawPlane(l,h[0]*this.ppu,-h[1]*this.ppu,i,r,5*o,10*o,10*o,100*this.ppu,t);else if(e instanceof p2.Line)this.drawLine(l,e.length*this.ppu,r,o);else if(e instanceof p2.Box)this.drawRectangle(l,h[0]*this.ppu,h[1]*this.ppu,t,e.width*this.ppu,e.height*this.ppu,r,i,o);else if(e instanceof p2.Convex){for(u=[],d=p2.vec2.create(),n=p=0,f=e.vertices.length;0<=f?p<f:p>f;n=0<=f?++p:--p)c=e.vertices[n],p2.vec2.rotate(d,c,t),u.push([(d[0]+h[0])*this.ppu,-(d[1]+h[1])*this.ppu]);this.drawConvex(l,u,e.triangles,r,i,o,this.settings.debugPolygons,[h[0]*this.ppu,-h[1]*this.ppu])}s++}}},drawRectangle:function(t,e,i,s,n,r,o,a,h){void 0===h&&(h=1),void 0===o&&(o=0),t.lineStyle(h,o,1),t.beginFill(a),t.drawRect(e-n/2,i-r/2,n,r)},drawCircle:function(t,e,i,s,n,r,o){void 0===o&&(o=1),void 0===r&&(r=16777215),t.lineStyle(o,0,1),t.beginFill(r,1),t.drawCircle(e,i,2*-n),t.endFill(),t.moveTo(e,i),t.lineTo(e+n*Math.cos(-s),i+n*Math.sin(-s))},drawLine:function(t,e,i,s){void 0===s&&(s=1),void 0===i&&(i=0),t.lineStyle(5*s,i,1),t.moveTo(-e/2,0),t.lineTo(e/2,0)},drawConvex:function(t,e,i,s,n,r,o,a){var h,l,c,u,d,p,f,g,m,y,v;if(void 0===r&&(r=1),void 0===s&&(s=0),o){for(h=[16711680,65280,255],l=0;l!==e.length+1;)u=e[l%e.length],d=e[(l+1)%e.length],f=u[0],y=u[1],g=d[0],v=d[1],t.lineStyle(r,h[l%h.length],1),t.moveTo(f,-y),t.lineTo(g,-v),t.drawCircle(f,-y,2*r),l++;return t.lineStyle(r,0,1),t.drawCircle(a[0],a[1],2*r)}for(t.lineStyle(r,s,1),t.beginFill(n),l=0;l!==e.length;)c=e[l],p=c[0],m=c[1],0===l?t.moveTo(p,-m):t.lineTo(p,-m),l++;if(t.endFill(),e.length>2)return t.moveTo(e[e.length-1][0],-e[e.length-1][1]),t.lineTo(e[0][0],-e[0][1])},drawPath:function(t,e,i,s,n){var r,o,a,h,l,c,u,d,p,f,g,m;for(void 0===n&&(n=1),void 0===i&&(i=0),t.lineStyle(n,i,1),"number"==typeof s&&t.beginFill(s),o=null,a=null,r=0;r<e.length;)f=e[r],g=f[0],m=f[1],g===o&&m===a||(0===r?t.moveTo(g,m):(h=o,l=a,c=g,u=m,d=e[(r+1)%e.length][0],p=e[(r+1)%e.length][1],0!==(c-h)*(p-l)-(d-h)*(u-l)&&t.lineTo(g,m)),o=g,a=m),r++;"number"==typeof s&&t.endFill(),e.length>2&&"number"==typeof s&&(t.moveTo(e[e.length-1][0],e[e.length-1][1]),t.lineTo(e[0][0],e[0][1]))},drawPlane:function(t,e,i,s,n,r,o,a,h,l){var c,u;void 0===r&&(r=1),void 0===s&&(s=16777215),t.lineStyle(r,n,11),t.beginFill(s),t.moveTo(e,-i),c=e+Math.cos(l)*this.game.width,u=i+Math.sin(l)*this.game.height,t.lineTo(c,-u),t.moveTo(e,-i),c=e+Math.cos(l)*-this.game.width,u=i+Math.sin(l)*-this.game.height,t.lineTo(c,-u)},drawCapsule:function(t,e,i,s,n,r,o,a,h){void 0===h&&(h=1),void 0===o&&(o=0),t.lineStyle(h,o,1);var l=Math.cos(s),c=Math.sin(s);t.beginFill(a,1),t.drawCircle(-n/2*l+e,-n/2*c+i,2*-r),t.drawCircle(n/2*l+e,n/2*c+i,2*-r),t.endFill(),t.lineStyle(h,o,0),t.beginFill(a,1),t.moveTo(-n/2*l+r*c+e,-n/2*c+r*l+i),t.lineTo(n/2*l+r*c+e,n/2*c+r*l+i),t.lineTo(n/2*l-r*c+e,n/2*c-r*l+i),t.lineTo(-n/2*l-r*c+e,-n/2*c-r*l+i),t.endFill(),t.lineStyle(h,o,1),t.moveTo(-n/2*l+r*c+e,-n/2*c+r*l+i),t.lineTo(n/2*l+r*c+e,n/2*c+r*l+i),t.moveTo(-n/2*l-r*c+e,-n/2*c-r*l+i),t.lineTo(n/2*l-r*c+e,n/2*c-r*l+i)},randomPastelHex:function(){var t,e,i,s;return i=[255,255,255],s=Math.floor(256*Math.random()),e=Math.floor(256*Math.random()),t=Math.floor(256*Math.random()),s=Math.floor((s+3*i[0])/4),e=Math.floor((e+3*i[1])/4),t=Math.floor((t+3*i[2])/4),this.rgbToHex(s,e,t)},rgbToHex:function(t,e,i){return this.componentToHex(t)+this.componentToHex(e)+this.componentToHex(i)},componentToHex:function(t){var e;return e=t.toString(16),2===e.length?e:e+"0"}}),n.Physics.P2.Spring=function(t,e,i,s,n,r,o,a,h,l){this.game=t.game,this.world=t,void 0===s&&(s=1),void 0===n&&(n=100),void 0===r&&(r=1),s=t.pxm(s);var c={restLength:s,stiffness:n,damping:r};void 0!==o&&null!==o&&(c.worldAnchorA=[t.pxm(o[0]),t.pxm(o[1])]),void 0!==a&&null!==a&&(c.worldAnchorB=[t.pxm(a[0]),t.pxm(a[1])]),void 0!==h&&null!==h&&(c.localAnchorA=[t.pxm(h[0]),t.pxm(h[1])]),void 0!==l&&null!==l&&(c.localAnchorB=[t.pxm(l[0]),t.pxm(l[1])]),this.data=new p2.LinearSpring(e,i,c),this.data.parent=this},n.Physics.P2.Spring.prototype.constructor=n.Physics.P2.Spring,n.Physics.P2.RotationalSpring=function(t,e,i,s,n,r){this.game=t.game,this.world=t,void 0===s&&(s=null),void 0===n&&(n=100),void 0===r&&(r=1),s&&(s=t.pxm(s));var o={restAngle:s,stiffness:n,damping:r};this.data=new p2.RotationalSpring(e,i,o),this.data.parent=this},n.Physics.P2.Spring.prototype.constructor=n.Physics.P2.Spring,n.Physics.P2.Material=function(t){this.name=t,p2.Material.call(this)},n.Physics.P2.Material.prototype=Object.create(p2.Material.prototype),n.Physics.P2.Material.prototype.constructor=n.Physics.P2.Material,n.Physics.P2.ContactMaterial=function(t,e,i){p2.ContactMaterial.call(this,t,e,i)},n.Physics.P2.ContactMaterial.prototype=Object.create(p2.ContactMaterial.prototype),n.Physics.P2.ContactMaterial.prototype.constructor=n.Physics.P2.ContactMaterial,n.Physics.P2.CollisionGroup=function(t){this.mask=t},n.Physics.P2.DistanceConstraint=function(t,e,i,s,n,r,o){void 0===s&&(s=100),void 0===n&&(n=[0,0]),void 0===r&&(r=[0,0]),void 0===o&&(o=Number.MAX_VALUE),this.game=t.game,this.world=t,s=t.pxm(s),n=[t.pxmi(n[0]),t.pxmi(n[1])],r=[t.pxmi(r[0]),t.pxmi(r[1])];var a={distance:s,localAnchorA:n,localAnchorB:r,maxForce:o};p2.DistanceConstraint.call(this,e,i,a)},n.Physics.P2.DistanceConstraint.prototype=Object.create(p2.DistanceConstraint.prototype),n.Physics.P2.DistanceConstraint.prototype.constructor=n.Physics.P2.DistanceConstraint,n.Physics.P2.GearConstraint=function(t,e,i,s,n){void 0===s&&(s=0),void 0===n&&(n=1),this.game=t.game,this.world=t;var r={angle:s,ratio:n};p2.GearConstraint.call(this,e,i,r)},n.Physics.P2.GearConstraint.prototype=Object.create(p2.GearConstraint.prototype),n.Physics.P2.GearConstraint.prototype.constructor=n.Physics.P2.GearConstraint,n.Physics.P2.LockConstraint=function(t,e,i,s,n,r){void 0===s&&(s=[0,0]),void 0===n&&(n=0),void 0===r&&(r=Number.MAX_VALUE),this.game=t.game,this.world=t,s=[t.pxm(s[0]),t.pxm(s[1])];var o={localOffsetB:s,localAngleB:n,maxForce:r};p2.LockConstraint.call(this,e,i,o)},n.Physics.P2.LockConstraint.prototype=Object.create(p2.LockConstraint.prototype),n.Physics.P2.LockConstraint.prototype.constructor=n.Physics.P2.LockConstraint,n.Physics.P2.PrismaticConstraint=function(t,e,i,s,n,r,o,a){void 0===s&&(s=!0),void 0===n&&(n=[0,0]),void 0===r&&(r=[0,0]),void 0===o&&(o=[0,0]),void 0===a&&(a=Number.MAX_VALUE),this.game=t.game,this.world=t,n=[t.pxmi(n[0]),t.pxmi(n[1])],r=[t.pxmi(r[0]),t.pxmi(r[1])];var h={localAnchorA:n,localAnchorB:r,localAxisA:o,maxForce:a,disableRotationalLock:!s};p2.PrismaticConstraint.call(this,e,i,h)},n.Physics.P2.PrismaticConstraint.prototype=Object.create(p2.PrismaticConstraint.prototype),n.Physics.P2.PrismaticConstraint.prototype.constructor=n.Physics.P2.PrismaticConstraint,n.Physics.P2.RevoluteConstraint=function(t,e,i,s,n,r,o){void 0===r&&(r=Number.MAX_VALUE),void 0===o&&(o=null),this.game=t.game,this.world=t,i=[t.pxmi(i[0]),t.pxmi(i[1])],n=[t.pxmi(n[0]),t.pxmi(n[1])],o&&(o=[t.pxmi(o[0]),t.pxmi(o[1])]);var a={worldPivot:o,localPivotA:i,localPivotB:n,maxForce:r};p2.RevoluteConstraint.call(this,e,s,a)},n.Physics.P2.RevoluteConstraint.prototype=Object.create(p2.RevoluteConstraint.prototype),n.Physics.P2.RevoluteConstraint.prototype.constructor=n.Physics.P2.RevoluteConstraint,n.ImageCollection=function(t,e,i,s,n,r,o){(void 0===i||i<=0)&&(i=32),(void 0===s||s<=0)&&(s=32),void 0===n&&(n=0),void 0===r&&(r=0),this.name=t,this.firstgid=0|e,this.imageWidth=0|i,this.imageHeight=0|s,this.imageMargin=0|n,this.imageSpacing=0|r,this.properties=o||{},this.images=[],this.total=0},n.ImageCollection.prototype={containsImageIndex:function(t){return t>=this.firstgid&&t<this.firstgid+this.total},addImage:function(t,e){this.images.push({gid:t,image:e}),this.total++}},n.ImageCollection.prototype.constructor=n.ImageCollection,n.Tile=function(t,e,i,s,n,r){this.layer=t,this.index=e,this.x=i,this.y=s,this.rotation=0,this.flipped=!1,this.worldX=i*n,this.worldY=s*r,this.width=n,this.height=r,this.centerX=Math.abs(n/2),this.centerY=Math.abs(r/2),this.alpha=1,this.properties={},this.scanned=!1,this.faceTop=!1,this.faceBottom=!1,this.faceLeft=!1,this.faceRight=!1,this.collideLeft=!1,this.collideRight=!1,this.collideUp=!1,this.collideDown=!1,this.collisionCallback=null,this.collisionCallbackContext=this},n.Tile.prototype={containsPoint:function(t,e){return!(t<this.worldX||e<this.worldY||t>this.right||e>this.bottom)},intersects:function(t,e,i,s){return!(i<=this.worldX)&&(!(s<=this.worldY)&&(!(t>=this.worldX+this.width)&&!(e>=this.worldY+this.height)))},setCollisionCallback:function(t,e){this.collisionCallback=t,this.collisionCallbackContext=e},destroy:function(){this.collisionCallback=null,this.collisionCallbackContext=null,this.properties=null},setCollision:function(t,e,i,s){this.collideLeft=t,this.collideRight=e,this.collideUp=i,this.collideDown=s,this.faceLeft=t,this.faceRight=e,this.faceTop=i,this.faceBottom=s},resetCollision:function(){this.collideLeft=!1,this.collideRight=!1,this.collideUp=!1,this.collideDown=!1,this.faceTop=!1,this.faceBottom=!1,this.faceLeft=!1,this.faceRight=!1},isInteresting:function(t,e){return t&&e?this.collideLeft||this.collideRight||this.collideUp||this.collideDown||this.faceTop||this.faceBottom||this.faceLeft||this.faceRight||this.collisionCallback:t?this.collideLeft||this.collideRight||this.collideUp||this.collideDown:!!e&&(this.faceTop||this.faceBottom||this.faceLeft||this.faceRight)},copy:function(t){this.index=t.index,this.alpha=t.alpha,this.properties=t.properties,this.collideUp=t.collideUp,this.collideDown=t.collideDown,this.collideLeft=t.collideLeft,this.collideRight=t.collideRight,this.collisionCallback=t.collisionCallback,this.collisionCallbackContext=t.collisionCallbackContext}},n.Tile.prototype.constructor=n.Tile,Object.defineProperty(n.Tile.prototype,"collides",{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown}}),Object.defineProperty(n.Tile.prototype,"canCollide",{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown||this.collisionCallback}}),Object.defineProperty(n.Tile.prototype,"left",{get:function(){return this.worldX}}),Object.defineProperty(n.Tile.prototype,"right",{get:function(){return this.worldX+this.width}}),Object.defineProperty(n.Tile.prototype,"top",{get:function(){return this.worldY}}),Object.defineProperty(n.Tile.prototype,"bottom",{get:function(){return this.worldY+this.height}}),n.Tilemap=function(t,e,i,s,r,o){this.game=t,this.key=e;var a=n.TilemapParser.parse(this.game,e,i,s,r,o);null!==a&&(this.width=a.width,this.height=a.height,this.tileWidth=a.tileWidth,this.tileHeight=a.tileHeight,this.orientation=a.orientation,this.format=a.format,this.version=a.version,this.properties=a.properties,this.widthInPixels=a.widthInPixels,this.heightInPixels=a.heightInPixels,this.layers=a.layers,this.tilesets=a.tilesets,this.imagecollections=a.imagecollections,this.tiles=a.tiles,this.objects=a.objects,this.collideIndexes=[],this.collision=a.collision,this.images=a.images,this.enableDebug=!1,this.currentLayer=0,this.debugMap=[],this._results=[],this._tempA=0,this._tempB=0)},n.Tilemap.CSV=0,n.Tilemap.TILED_JSON=1,n.Tilemap.NORTH=0,n.Tilemap.EAST=1,n.Tilemap.SOUTH=2,n.Tilemap.WEST=3,n.Tilemap.prototype={create:function(t,e,i,s,n,r){return void 0===r&&(r=this.game.world),this.width=e,this.height=i,this.setTileSize(s,n),this.layers.length=0,this.createBlankLayer(t,e,i,s,n,r)},setTileSize:function(t,e){this.tileWidth=t,this.tileHeight=e,this.widthInPixels=this.width*t,this.heightInPixels=this.height*e},addTilesetImage:function(t,e,i,s,r,o,a){if(void 0===t)return null;void 0===i&&(i=this.tileWidth),void 0===s&&(s=this.tileHeight),void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=0),0===i&&(i=32),0===s&&(s=32);var h=null;if(void 0!==e&&null!==e||(e=t),e instanceof n.BitmapData)h=e.canvas;else{if(!this.game.cache.checkImageKey(e))return console.warn('Phaser.Tilemap.addTilesetImage: Invalid image key given: "'+e+'"'),null;h=this.game.cache.getImage(e)}var l=this.getTilesetIndex(t);if(null===l&&this.format===n.Tilemap.TILED_JSON)return console.warn('Phaser.Tilemap.addTilesetImage: No data found in the JSON matching the tileset name: "'+t+'"'),null;if(this.tilesets[l])return this.tilesets[l].setImage(h),this.tilesets[l];var c=new n.Tileset(t,a,i,s,r,o,{});c.setImage(h),this.tilesets.push(c);for(var u=this.tilesets.length-1,d=r,p=r,f=0,g=0,m=0,y=a;y<a+c.total&&(this.tiles[y]=[d,p,u],d+=i+o,++f!==c.total)&&(++g!==c.columns||(d=r,p+=s+o,g=0,++m!==c.rows));y++);return c},createFromObjects:function(t,e,i,s,r,o,a,h,l){if(void 0===r&&(r=!0),void 0===o&&(o=!1),void 0===a&&(a=this.game.world),void 0===h&&(h=n.Sprite),void 0===l&&(l=!0),!this.objects[t])return void console.warn("Tilemap.createFromObjects: Invalid objectgroup name given: "+t);for(var c=0;c<this.objects[t].length;c++){var u=!1,d=this.objects[t][c];if(void 0!==d.gid&&"number"==typeof e&&d.gid===e?u=!0:void 0!==d.id&&"number"==typeof e&&d.id===e?u=!0:void 0!==d.name&&"string"==typeof e&&d.name===e&&(u=!0),u){var p=new h(this.game,parseFloat(d.x,10),parseFloat(d.y,10),i,s);p.name=d.name,p.visible=d.visible,p.autoCull=o,p.exists=r,d.width&&(p.width=d.width),d.height&&(p.height=d.height),d.rotation&&(p.angle=d.rotation),l&&(p.y-=p.height),a.add(p);for(var f in d.properties)a.set(p,f,d.properties[f],!1,!1,0,!0)}}},createFromTiles:function(t,e,i,s,r,o){"number"==typeof t&&(t=[t]),void 0===e||null===e?e=[]:"number"==typeof e&&(e=[e]),s=this.getLayer(s),void 0===r&&(r=this.game.world),void 0===o&&(o={}),void 0===o.customClass&&(o.customClass=n.Sprite),void 0===o.adjustY&&(o.adjustY=!0);var a=this.layers[s].width,h=this.layers[s].height;if(this.copy(0,0,a,h,s),this._results.length<2)return 0;for(var l,c=0,u=1,d=this._results.length;u<d;u++)if(-1!==t.indexOf(this._results[u].index)){l=new o.customClass(this.game,this._results[u].worldX,this._results[u].worldY,i);for(var p in o)l[p]=o[p];r.add(l),c++}if(1===e.length)for(u=0;u<t.length;u++)this.replace(t[u],e[0],0,0,a,h,s);else if(e.length>1)for(u=0;u<t.length;u++)this.replace(t[u],e[u],0,0,a,h,s);return c},createLayer:function(t,e,i,s){void 0===e&&(e=this.game.width),void 0===i&&(i=this.game.height),void 0===s&&(s=this.game.world);var r=t;if("string"==typeof t&&(r=this.getLayerIndex(t)),null===r||r>this.layers.length)return void console.warn("Tilemap.createLayer: Invalid layer ID given: "+r);void 0===e||e<=0?e=Math.min(this.game.width,this.layers[r].widthInPixels):e>this.game.width&&(e=this.game.width),void 0===i||i<=0?i=Math.min(this.game.height,this.layers[r].heightInPixels):i>this.game.height&&(i=this.game.height),this.enableDebug&&(console.group("Tilemap.createLayer"),console.log("Name:",this.layers[r].name),console.log("Size:",e,"x",i),console.log("Tileset:",this.tilesets[0].name,"index:",r));var o=s.add(new n.TilemapLayer(this.game,this,r,e,i));return this.enableDebug&&console.groupEnd(),o},createBlankLayer:function(t,e,i,s,r,o){if(void 0===o&&(o=this.game.world),null!==this.getLayerIndex(t))return void console.warn("Tilemap.createBlankLayer: Layer with matching name already exists: "+t);for(var a,h={name:t,x:0,y:0,width:e,height:i,widthInPixels:e*s,heightInPixels:i*r,alpha:1,visible:!0,properties:{},indexes:[],callbacks:[],bodies:[],data:null},l=[],c=0;c<i;c++){a=[];for(var u=0;u<e;u++)a.push(new n.Tile(h,-1,u,c,s,r));l.push(a)}h.data=l,this.layers.push(h),this.currentLayer=this.layers.length-1;var d=h.widthInPixels,p=h.heightInPixels;d>this.game.width&&(d=this.game.width),p>this.game.height&&(p=this.game.height);var l=new n.TilemapLayer(this.game,this,this.layers.length-1,d,p);return l.name=t,o.add(l)},getIndex:function(t,e){for(var i=0;i<t.length;i++)if(t[i].name===e)return i;return null},getLayerIndex:function(t){return this.getIndex(this.layers,t)},getTilesetIndex:function(t){return this.getIndex(this.tilesets,t)},getImageIndex:function(t){return this.getIndex(this.images,t)},setTileIndexCallback:function(t,e,i,s){if(s=this.getLayer(s),"number"==typeof t)this.layers[s].callbacks[t]={callback:e,callbackContext:i};else for(var n=0,r=t.length;n<r;n++)this.layers[s].callbacks[t[n]]={callback:e,callbackContext:i}},setTileLocationCallback:function(t,e,i,s,n,r,o){if(o=this.getLayer(o),this.copy(t,e,i,s,o),!(this._results.length<2))for(var a=1;a<this._results.length;a++)this._results[a].setCollisionCallback(n,r)},setCollision:function(t,e,i,s){if(void 0===e&&(e=!0),void 0===s&&(s=!0),i=this.getLayer(i),"number"==typeof t)return this.setCollisionByIndex(t,e,i,!0);if(Array.isArray(t)){for(var n=0;n<t.length;n++)this.setCollisionByIndex(t[n],e,i,!1);s&&this.calculateFaces(i)}},setCollisionBetween:function(t,e,i,s,n){if(void 0===i&&(i=!0),void 0===n&&(n=!0),s=this.getLayer(s),!(t>e)){for(var r=t;r<=e;r++)this.setCollisionByIndex(r,i,s,!1);n&&this.calculateFaces(s)}},setCollisionByExclusion:function(t,e,i,s){void 0===e&&(e=!0),void 0===s&&(s=!0),i=this.getLayer(i);for(var n=0,r=this.tiles.length;n<r;n++)-1===t.indexOf(n)&&this.setCollisionByIndex(n,e,i,!1);s&&this.calculateFaces(i)},setCollisionByIndex:function(t,e,i,s){if(void 0===e&&(e=!0),void 0===i&&(i=this.currentLayer),void 0===s&&(s=!0),e)this.collideIndexes.push(t);else{var n=this.collideIndexes.indexOf(t);n>-1&&this.collideIndexes.splice(n,1)}for(var r=0;r<this.layers[i].height;r++)for(var o=0;o<this.layers[i].width;o++){var a=this.layers[i].data[r][o];a&&a.index===t&&(e?a.setCollision(!0,!0,!0,!0):a.resetCollision(),a.faceTop=e,a.faceBottom=e,a.faceLeft=e,a.faceRight=e)}return s&&this.calculateFaces(i),i},getLayer:function(t){return void 0===t?t=this.currentLayer:"string"==typeof t?t=this.getLayerIndex(t):t instanceof n.TilemapLayer&&(t=t.index),t},setPreventRecalculate:function(t){if(!0===t&&!0!==this.preventingRecalculate&&(this.preventingRecalculate=!0,this.needToRecalculate={}),!1===t&&!0===this.preventingRecalculate){this.preventingRecalculate=!1;for(var e in this.needToRecalculate)this.calculateFaces(e);this.needToRecalculate=!1}},calculateFaces:function(t){if(this.preventingRecalculate)return void(this.needToRecalculate[t]=!0);for(var e=null,i=null,s=null,n=null,r=0,o=this.layers[t].height;r<o;r++)for(var a=0,h=this.layers[t].width;a<h;a++){var l=this.layers[t].data[r][a];l&&(e=this.getTileAbove(t,a,r),i=this.getTileBelow(t,a,r),s=this.getTileLeft(t,a,r),n=this.getTileRight(t,a,r),l.collides&&(l.faceTop=!0,l.faceBottom=!0,l.faceLeft=!0,l.faceRight=!0),e&&e.collides&&(l.faceTop=!1),i&&i.collides&&(l.faceBottom=!1),s&&s.collides&&(l.faceLeft=!1),n&&n.collides&&(l.faceRight=!1))}},getTileAbove:function(t,e,i){return i>0?this.layers[t].data[i-1][e]:null},getTileBelow:function(t,e,i){return i<this.layers[t].height-1?this.layers[t].data[i+1][e]:null},getTileLeft:function(t,e,i){return e>0?this.layers[t].data[i][e-1]:null},getTileRight:function(t,e,i){return e<this.layers[t].width-1?this.layers[t].data[i][e+1]:null},setLayer:function(t){t=this.getLayer(t),this.layers[t]&&(this.currentLayer=t)},hasTile:function(t,e,i){return i=this.getLayer(i),void 0!==this.layers[i].data[e]&&void 0!==this.layers[i].data[e][t]&&this.layers[i].data[e][t].index>-1},removeTile:function(t,e,i){if(i=this.getLayer(i),t>=0&&t<this.layers[i].width&&e>=0&&e<this.layers[i].height&&this.hasTile(t,e,i)){var s=this.layers[i].data[e][t];return this.layers[i].data[e][t]=new n.Tile(this.layers[i],-1,t,e,this.tileWidth,this.tileHeight),this.layers[i].dirty=!0,this.calculateFaces(i),s}},removeTileWorldXY:function(t,e,i,s,n){return n=this.getLayer(n),t=this.game.math.snapToFloor(t,i)/i,e=this.game.math.snapToFloor(e,s)/s,this.removeTile(t,e,n)},putTile:function(t,e,i,s){if(null===t)return this.removeTile(e,i,s);if(s=this.getLayer(s),e>=0&&e<this.layers[s].width&&i>=0&&i<this.layers[s].height){var r;return t instanceof n.Tile?(r=t.index,this.hasTile(e,i,s)?this.layers[s].data[i][e].copy(t):this.layers[s].data[i][e]=new n.Tile(s,r,e,i,t.width,t.height)):(r=t,this.hasTile(e,i,s)?this.layers[s].data[i][e].index=r:this.layers[s].data[i][e]=new n.Tile(this.layers[s],r,e,i,this.tileWidth,this.tileHeight)),this.collideIndexes.indexOf(r)>-1?this.layers[s].data[i][e].setCollision(!0,!0,!0,!0):this.layers[s].data[i][e].resetCollision(),this.layers[s].dirty=!0,this.calculateFaces(s),this.layers[s].data[i][e]}return null},putTileWorldXY:function(t,e,i,s,n,r){return r=this.getLayer(r),e=this.game.math.snapToFloor(e,s)/s,i=this.game.math.snapToFloor(i,n)/n,this.putTile(t,e,i,r)},searchTileIndex:function(t,e,i,s){void 0===e&&(e=0),void 0===i&&(i=!1),s=this.getLayer(s);var n=0;if(i){for(var r=this.layers[s].height-1;r>=0;r--)for(var o=this.layers[s].width-1;o>=0;o--)if(this.layers[s].data[r][o].index===t){if(n===e)return this.layers[s].data[r][o];n++}}else for(var r=0;r<this.layers[s].height;r++)for(var o=0;o<this.layers[s].width;o++)if(this.layers[s].data[r][o].index===t){if(n===e)return this.layers[s].data[r][o];n++}return null},getTile:function(t,e,i,s){return void 0===s&&(s=!1),i=this.getLayer(i),t>=0&&t<this.layers[i].width&&e>=0&&e<this.layers[i].height?-1===this.layers[i].data[e][t].index?s?this.layers[i].data[e][t]:null:this.layers[i].data[e][t]:null},getTileWorldXY:function(t,e,i,s,n,r){return void 0===i&&(i=this.tileWidth),void 0===s&&(s=this.tileHeight),n=this.getLayer(n),t=this.game.math.snapToFloor(t,i)/i,e=this.game.math.snapToFloor(e,s)/s,this.getTile(t,e,n,r)},copy:function(t,e,i,s,n){if(n=this.getLayer(n),!this.layers[n])return void(this._results.length=0);void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=this.layers[n].width),void 0===s&&(s=this.layers[n].height),t<0&&(t=0),e<0&&(e=0),i>this.layers[n].width&&(i=this.layers[n].width),s>this.layers[n].height&&(s=this.layers[n].height),this._results.length=0,this._results.push({x:t,y:e,width:i,height:s,layer:n});for(var r=e;r<e+s;r++)for(var o=t;o<t+i;o++)this._results.push(this.layers[n].data[r][o]);return this._results},paste:function(t,e,i,s){if(void 0===t&&(t=0),void 0===e&&(e=0),s=this.getLayer(s),i&&!(i.length<2)){for(var n=t-i[1].x,r=e-i[1].y,o=1;o<i.length;o++)this.layers[s].data[r+i[o].y][n+i[o].x].copy(i[o]);this.layers[s].dirty=!0,this.calculateFaces(s)}},swap:function(t,e,i,s,n,r,o){o=this.getLayer(o),this.copy(i,s,n,r,o),this._results.length<2||(this._tempA=t,this._tempB=e,this._results.forEach(this.swapHandler,this),this.paste(i,s,this._results,o))},swapHandler:function(t){t.index===this._tempA?t.index=this._tempB:t.index===this._tempB&&(t.index=this._tempA)},forEach:function(t,e,i,s,n,r,o){o=this.getLayer(o),this.copy(i,s,n,r,o),this._results.length<2||(this._results.forEach(t,e),this.paste(i,s,this._results,o))},replace:function(t,e,i,s,n,r,o){if(o=this.getLayer(o),this.copy(i,s,n,r,o),!(this._results.length<2)){for(var a=1;a<this._results.length;a++)this._results[a].index===t&&(this._results[a].index=e);this.paste(i,s,this._results,o)}},random:function(t,e,i,s,n){if(n=this.getLayer(n),this.copy(t,e,i,s,n),!(this._results.length<2)){for(var r=[],o=1;o<this._results.length;o++)if(this._results[o].index){var a=this._results[o].index;-1===r.indexOf(a)&&r.push(a)}for(var h=1;h<this._results.length;h++)this._results[h].index=this.game.rnd.pick(r);this.paste(t,e,this._results,n)}},shuffle:function(t,e,i,s,r){if(r=this.getLayer(r),this.copy(t,e,i,s,r),!(this._results.length<2)){for(var o=[],a=1;a<this._results.length;a++)this._results[a].index&&o.push(this._results[a].index);n.ArrayUtils.shuffle(o);for(var h=1;h<this._results.length;h++)this._results[h].index=o[h-1];this.paste(t,e,this._results,r)}},fill:function(t,e,i,s,n,r){if(r=this.getLayer(r),this.copy(e,i,s,n,r),!(this._results.length<2)){for(var o=1;o<this._results.length;o++)this._results[o].index=t;this.paste(e,i,this._results,r)}},removeAllLayers:function(){this.layers.length=0,this.currentLayer=0},dump:function(){for(var t="",e=[""],i=0;i<this.layers[this.currentLayer].height;i++){for(var s=0;s<this.layers[this.currentLayer].width;s++)t+="%c ",this.layers[this.currentLayer].data[i][s]>1?this.debugMap[this.layers[this.currentLayer].data[i][s]]?e.push("background: "+this.debugMap[this.layers[this.currentLayer].data[i][s]]):e.push("background: #ffffff"):e.push("background: rgb(0, 0, 0)");t+="\n"}e[0]=t,console.log.apply(console,e)},destroy:function(){this.removeAllLayers(),this.data=[],this.game=null}},n.Tilemap.prototype.constructor=n.Tilemap,Object.defineProperty(n.Tilemap.prototype,"layer",{get:function(){return this.layers[this.currentLayer]},set:function(t){t!==this.currentLayer&&this.setLayer(t)}}),n.TilemapLayer=function(t,e,i,s,r){s|=0,r|=0,n.Sprite.call(this,t,0,0),this.map=e,this.index=i,this.layer=e.layers[i],this.canvas=PIXI.CanvasPool.create(this,s,r),this.context=this.canvas.getContext("2d"),this.setTexture(new PIXI.Texture(new PIXI.BaseTexture(this.canvas))),this.type=n.TILEMAPLAYER,this.physicsType=n.TILEMAPLAYER,this.renderSettings={enableScrollDelta:!1,overdrawRatio:.2,copyCanvas:null},this.debug=!1,this.exists=!0,this.debugSettings={missingImageFill:"rgb(255,255,255)",debuggedTileOverfill:"rgba(0,255,0,0.4)",forceFullRedraw:!0,debugAlpha:.5,facingEdgeStroke:"rgba(0,255,0,1)",collidingTileOverfill:"rgba(0,255,0,0.2)"},this.scrollFactorX=1,this.scrollFactorY=1,this.dirty=!0,this.rayStepRate=4,this._wrap=!1,this._mc={scrollX:0,scrollY:0,renderWidth:0,renderHeight:0,tileWidth:e.tileWidth,tileHeight:e.tileHeight,cw:e.tileWidth,ch:e.tileHeight,tilesets:[]},this._scrollX=0,this._scrollY=0,this._results=[],t.device.canvasBitBltShift||(this.renderSettings.copyCanvas=n.TilemapLayer.ensureSharedCopyCanvas()),this.fixedToCamera=!0},n.TilemapLayer.prototype=Object.create(n.Sprite.prototype),n.TilemapLayer.prototype.constructor=n.TilemapLayer,n.TilemapLayer.prototype.preUpdateCore=n.Component.Core.preUpdate,n.TilemapLayer.sharedCopyCanvas=null,n.TilemapLayer.ensureSharedCopyCanvas=function(){return this.sharedCopyCanvas||(this.sharedCopyCanvas=PIXI.CanvasPool.create(this,2,2)),this.sharedCopyCanvas},n.TilemapLayer.prototype.preUpdate=function(){return this.preUpdateCore()},n.TilemapLayer.prototype.postUpdate=function(){this.fixedToCamera&&(this.position.x=(this.game.camera.view.x+this.cameraOffset.x)/this.game.camera.scale.x,this.position.y=(this.game.camera.view.y+this.cameraOffset.y)/this.game.camera.scale.y),this._scrollX=this.game.camera.view.x*this.scrollFactorX/this.scale.x,this._scrollY=this.game.camera.view.y*this.scrollFactorY/this.scale.y},n.TilemapLayer.prototype._renderCanvas=function(t){this.fixedToCamera&&(this.position.x=(this.game.camera.view.x+this.cameraOffset.x)/this.game.camera.scale.x,this.position.y=(this.game.camera.view.y+this.cameraOffset.y)/this.game.camera.scale.y),this._scrollX=this.game.camera.view.x*this.scrollFactorX/this.scale.x,this._scrollY=this.game.camera.view.y*this.scrollFactorY/this.scale.y,this.render(),PIXI.Sprite.prototype._renderCanvas.call(this,t)},n.TilemapLayer.prototype._renderWebGL=function(t){this.fixedToCamera&&(this.position.x=(this.game.camera.view.x+this.cameraOffset.x)/this.game.camera.scale.x,this.position.y=(this.game.camera.view.y+this.cameraOffset.y)/this.game.camera.scale.y),this._scrollX=this.game.camera.view.x*this.scrollFactorX/this.scale.x,this._scrollY=this.game.camera.view.y*this.scrollFactorY/this.scale.y,this.render(),PIXI.Sprite.prototype._renderWebGL.call(this,t)},n.TilemapLayer.prototype.destroy=function(){PIXI.CanvasPool.remove(this),n.Component.Destroy.prototype.destroy.call(this)},n.TilemapLayer.prototype.resize=function(t,e){this.canvas.width=t,this.canvas.height=e,this.texture.frame.resize(t,e),this.texture.width=t,this.texture.height=e,this.texture.crop.width=t,this.texture.crop.height=e,this.texture.baseTexture.width=t,this.texture.baseTexture.height=e,this.texture.baseTexture.dirty(),this.texture.requiresUpdate=!0,this.texture._updateUvs(),this.dirty=!0},n.TilemapLayer.prototype.resizeWorld=function(){this.game.world.setBounds(0,0,this.layer.widthInPixels*this.scale.x,this.layer.heightInPixels*this.scale.y)},n.TilemapLayer.prototype._fixX=function(t){return 1===this.scrollFactorX||0===this.scrollFactorX&&0===this.position.x?t:0===this.scrollFactorX&&0!==this.position.x?t-this.position.x:this._scrollX+(t-this._scrollX/this.scrollFactorX)},n.TilemapLayer.prototype._unfixX=function(t){return 1===this.scrollFactorX?t:this._scrollX/this.scrollFactorX+(t-this._scrollX)},n.TilemapLayer.prototype._fixY=function(t){return 1===this.scrollFactorY||0===this.scrollFactorY&&0===this.position.y?t:0===this.scrollFactorY&&0!==this.position.y?t-this.position.y:this._scrollY+(t-this._scrollY/this.scrollFactorY)},n.TilemapLayer.prototype._unfixY=function(t){return 1===this.scrollFactorY?t:this._scrollY/this.scrollFactorY+(t-this._scrollY)},n.TilemapLayer.prototype.getTileX=function(t){return Math.floor(this._fixX(t)/this._mc.tileWidth)},n.TilemapLayer.prototype.getTileY=function(t){return Math.floor(this._fixY(t)/this._mc.tileHeight)},n.TilemapLayer.prototype.getTileXY=function(t,e,i){return i.x=this.getTileX(t),i.y=this.getTileY(e),i},n.TilemapLayer.prototype.getRayCastTiles=function(t,e,i,s){e||(e=this.rayStepRate),void 0===i&&(i=!1),void 0===s&&(s=!1);var n=this.getTiles(t.x,t.y,t.width,t.height,i,s);if(0===n.length)return[];for(var r=t.coordinatesOnLine(e),o=[],a=0;a<n.length;a++)for(var h=0;h<r.length;h++){var l=n[a],c=r[h];if(l.containsPoint(c[0],c[1])){o.push(l);break}}return o},n.TilemapLayer.prototype.getTiles=function(t,e,i,s,n,r){void 0===n&&(n=!1),void 0===r&&(r=!1);var o=!(n||r);t=this._fixX(t),e=this._fixY(e);for(var a=Math.floor(t/(this._mc.cw*this.scale.x)),h=Math.floor(e/(this._mc.ch*this.scale.y)),l=Math.ceil((t+i)/(this._mc.cw*this.scale.x))-a,c=Math.ceil((e+s)/(this._mc.ch*this.scale.y))-h;this._results.length;)this._results.pop();for(var u=h;u<h+c;u++)for(var d=a;d<a+l;d++){var p=this.layer.data[u];p&&p[d]&&(o||p[d].isInteresting(n,r))&&this._results.push(p[d])}return this._results.slice()},n.TilemapLayer.prototype.resolveTileset=function(t){var e=this._mc.tilesets;if(t<2e3)for(;e.length<t;)e.push(void 0);var i=this.map.tiles[t]&&this.map.tiles[t][2];if(null!==i){var s=this.map.tilesets[i];if(s&&s.containsTileIndex(t))return e[t]=s}return e[t]=null},n.TilemapLayer.prototype.resetTilesetCache=function(){for(var t=this._mc.tilesets;t.length;)t.pop()},n.TilemapLayer.prototype.setScale=function(t,e){t=t||1,e=e||t;for(var i=0;i<this.layer.data.length;i++)for(var s=this.layer.data[i],n=0;n<s.length;n++){var r=s[n];r.width=this.map.tileWidth*t,r.height=this.map.tileHeight*e,r.worldX=r.x*r.width,r.worldY=r.y*r.height}this.scale.setTo(t,e)},n.TilemapLayer.prototype.shiftCanvas=function(t,e,i){var s=t.canvas,n=s.width-Math.abs(e),r=s.height-Math.abs(i),o=0,a=0,h=e,l=i;e<0&&(o=-e,h=0),i<0&&(a=-i,l=0);var c=this.renderSettings.copyCanvas;if(c){(c.width<n||c.height<r)&&(c.width=n,c.height=r);var u=c.getContext("2d");u.clearRect(0,0,n,r),u.drawImage(s,o,a,n,r,0,0,n,r),t.clearRect(h,l,n,r),t.drawImage(c,0,0,n,r,h,l,n,r)}else t.save(),t.globalCompositeOperation="copy",t.drawImage(s,o,a,n,r,h,l,n,r),t.restore()},n.TilemapLayer.prototype.renderRegion=function(t,e,i,s,n,r){var o=this.context,a=this.layer.width,h=this.layer.height,l=this._mc.tileWidth,c=this._mc.tileHeight,u=this._mc.tilesets,d=NaN;this._wrap||(i<=n&&(i=Math.max(0,i),n=Math.min(a-1,n)),s<=r&&(s=Math.max(0,s),r=Math.min(h-1,r)));var p,f,g,m,y,v,b=i*l-t,x=s*c-e,w=(i+(1<<20)*a)%a,_=(s+(1<<20)*h)%h;for(m=_,v=r-s,f=x;v>=0;m++,v--,f+=c){m>=h&&(m-=h);var P=this.layer.data[m];for(g=w,y=n-i,p=b;y>=0;g++,y--,p+=l){g>=a&&(g-=a);var T=P[g];if(T&&!(T.index<0)){var C=T.index,S=u[C];void 0===S&&(S=this.resolveTileset(C)),T.alpha===d||this.debug||(o.globalAlpha=T.alpha,d=T.alpha),S?T.rotation||T.flipped?(o.save(),o.translate(p+T.centerX,f+T.centerY),o.rotate(T.rotation),T.flipped&&o.scale(-1,1),S.draw(o,-T.centerX,-T.centerY,C),o.restore()):S.draw(o,p,f,C):this.debugSettings.missingImageFill&&(o.fillStyle=this.debugSettings.missingImageFill,o.fillRect(p,f,l,c)),T.debug&&this.debugSettings.debuggedTileOverfill&&(o.fillStyle=this.debugSettings.debuggedTileOverfill,o.fillRect(p,f,l,c))}}}},n.TilemapLayer.prototype.renderDeltaScroll=function(t,e){var i=this._mc.scrollX,s=this._mc.scrollY,n=this.canvas.width,r=this.canvas.height,o=this._mc.tileWidth,a=this._mc.tileHeight,h=0,l=-o,c=0,u=-a;if(t<0?(h=n+t,l=n-1):t>0&&(l=t),e<0?(c=r+e,u=r-1):e>0&&(u=e),this.shiftCanvas(this.context,t,e),h=Math.floor((h+i)/o),l=Math.floor((l+i)/o),c=Math.floor((c+s)/a),u=Math.floor((u+s)/a),h<=l){this.context.clearRect(h*o-i,0,(l-h+1)*o,r);var d=Math.floor((0+s)/a),p=Math.floor((r-1+s)/a);this.renderRegion(i,s,h,d,l,p)}if(c<=u){this.context.clearRect(0,c*a-s,n,(u-c+1)*a);var f=Math.floor((0+i)/o),g=Math.floor((n-1+i)/o);this.renderRegion(i,s,f,c,g,u)}},n.TilemapLayer.prototype.renderFull=function(){var t=this._mc.scrollX,e=this._mc.scrollY,i=this.canvas.width,s=this.canvas.height,n=this._mc.tileWidth,r=this._mc.tileHeight,o=Math.floor(t/n),a=Math.floor((i-1+t)/n),h=Math.floor(e/r),l=Math.floor((s-1+e)/r);this.context.clearRect(0,0,i,s),this.renderRegion(t,e,o,h,a,l)},n.TilemapLayer.prototype.render=function(){var t=!1;if(this.visible){(this.dirty||this.layer.dirty)&&(this.layer.dirty=!1,t=!0);var e=this.canvas.width,i=this.canvas.height,s=0|this._scrollX,n=0|this._scrollY,r=this._mc,o=r.scrollX-s,a=r.scrollY-n;if(t||0!==o||0!==a||r.renderWidth!==e||r.renderHeight!==i)return this.context.save(),r.scrollX=s,r.scrollY=n,r.renderWidth===e&&r.renderHeight===i||(r.renderWidth=e,r.renderHeight=i),this.debug&&(this.context.globalAlpha=this.debugSettings.debugAlpha,this.debugSettings.forceFullRedraw&&(t=!0)),!t&&this.renderSettings.enableScrollDelta&&Math.abs(o)+Math.abs(a)<Math.min(e,i)?this.renderDeltaScroll(o,a):this.renderFull(),this.debug&&(this.context.globalAlpha=1,this.renderDebug()),this.texture.baseTexture.dirty(),this.dirty=!1,this.context.restore(),!0}},n.TilemapLayer.prototype.renderDebug=function(){var t,e,i,s,n,r,o=this._mc.scrollX,a=this._mc.scrollY,h=this.context,l=this.canvas.width,c=this.canvas.height,u=this.layer.width,d=this.layer.height,p=this._mc.tileWidth,f=this._mc.tileHeight,g=Math.floor(o/p),m=Math.floor((l-1+o)/p),y=Math.floor(a/f),v=Math.floor((c-1+a)/f),b=g*p-o,x=y*f-a,w=(g+(1<<20)*u)%u,_=(y+(1<<20)*d)%d;for(h.strokeStyle=this.debugSettings.facingEdgeStroke,s=_,r=v-y,e=x;r>=0;s++,r--,e+=f){s>=d&&(s-=d);var P=this.layer.data[s];for(i=w,n=m-g,t=b;n>=0;i++,n--,t+=p){i>=u&&(i-=u);var T=P[i];!T||T.index<0||!T.collides||(this.debugSettings.collidingTileOverfill&&(h.fillStyle=this.debugSettings.collidingTileOverfill,h.fillRect(t,e,this._mc.cw,this._mc.ch)),this.debugSettings.facingEdgeStroke&&(h.beginPath(),T.faceTop&&(h.moveTo(t,e),h.lineTo(t+this._mc.cw,e)),T.faceBottom&&(h.moveTo(t,e+this._mc.ch),h.lineTo(t+this._mc.cw,e+this._mc.ch)),T.faceLeft&&(h.moveTo(t,e),h.lineTo(t,e+this._mc.ch)),T.faceRight&&(h.moveTo(t+this._mc.cw,e),h.lineTo(t+this._mc.cw,e+this._mc.ch)),h.closePath(),h.stroke()))}}},Object.defineProperty(n.TilemapLayer.prototype,"wrap",{get:function(){return this._wrap},set:function(t){this._wrap=t,this.dirty=!0}}),Object.defineProperty(n.TilemapLayer.prototype,"scrollX",{get:function(){return this._scrollX},set:function(t){this._scrollX=t}}),Object.defineProperty(n.TilemapLayer.prototype,"scrollY",{get:function(){return this._scrollY},set:function(t){this._scrollY=t}}),Object.defineProperty(n.TilemapLayer.prototype,"collisionWidth",{get:function(){return this._mc.cw},set:function(t){this._mc.cw=0|t,this.dirty=!0}}),Object.defineProperty(n.TilemapLayer.prototype,"collisionHeight",{get:function(){return this._mc.ch},set:function(t){this._mc.ch=0|t,this.dirty=!0}}),n.TilemapParser={INSERT_NULL:!1,parse:function(t,e,i,s,r,o){if(void 0===i&&(i=32),void 0===s&&(s=32),void 0===r&&(r=10),void 0===o&&(o=10),void 0===e)return this.getEmptyData();if(null===e)return this.getEmptyData(i,s,r,o);var a=t.cache.getTilemapData(e);if(a){if(a.format===n.Tilemap.CSV)return this.parseCSV(e,a.data,i,s);if(!a.format||a.format===n.Tilemap.TILED_JSON)return this.parseTiledJSON(a.data)}else console.warn("Phaser.TilemapParser.parse - No map data found for key "+e)},parseCSV:function(t,e,i,s){var r=this.getEmptyData();e=e.trim();for(var o=[],a=e.split("\n"),h=a.length,l=0,c=0;c<a.length;c++){o[c]=[];for(var u=a[c].split(","),d=0;d<u.length;d++)o[c][d]=new n.Tile(r.layers[0],parseInt(u[d],10),d,c,i,s);0===l&&(l=u.length)}return r.format=n.Tilemap.CSV,r.name=t,r.width=l,r.height=h,r.tileWidth=i,r.tileHeight=s,r.widthInPixels=l*i,r.heightInPixels=h*s,r.layers[0].width=l,r.layers[0].height=h,r.layers[0].widthInPixels=r.widthInPixels,r.layers[0].heightInPixels=r.heightInPixels,r.layers[0].data=o,r},getEmptyData:function(t,e,i,s){return{width:void 0!==i&&null!==i?i:0,height:void 0!==s&&null!==s?s:0,tileWidth:void 0!==t&&null!==t?t:0,tileHeight:void 0!==e&&null!==e?e:0,orientation:"orthogonal",version:"1",properties:{},widthInPixels:0,heightInPixels:0,layers:[{name:"layer",x:0,y:0,width:0,height:0,widthInPixels:0,heightInPixels:0,alpha:1,visible:!0,properties:{},indexes:[],callbacks:[],bodies:[],data:[]}],images:[],objects:{},collision:{},tilesets:[],tiles:[]}},parseTiledJSON:function(t){function e(t,e){var i={};for(var s in e){var n=e[s];void 0!==t[n]&&(i[n]=t[n])}return i}if("orthogonal"!==t.orientation)return console.warn("TilemapParser.parseTiledJSON - Only orthogonal map types are supported in this version of Phaser"),null;for(var i={width:t.width,height:t.height,tileWidth:t.tilewidth,tileHeight:t.tileheight,orientation:t.orientation,format:n.Tilemap.TILED_JSON,version:t.version,properties:t.properties,widthInPixels:t.width*t.tilewidth,heightInPixels:t.height*t.tileheight},s=[],r=0;r<t.layers.length;r++)if("tilelayer"===t.layers[r].type){var o=t.layers[r];if(!o.compression&&o.encoding&&"base64"===o.encoding){for(var a=window.atob(o.data),h=a.length,l=new Array(h),c=0;c<h;c+=4)l[c/4]=(a.charCodeAt(c)|a.charCodeAt(c+1)<<8|a.charCodeAt(c+2)<<16|a.charCodeAt(c+3)<<24)>>>0;o.data=l,delete o.encoding}else if(o.compression){console.warn("TilemapParser.parseTiledJSON - Layer compression is unsupported, skipping layer '"+o.name+"'");continue}var u={name:o.name,x:o.x,y:o.y,width:o.width,height:o.height,widthInPixels:o.width*t.tilewidth,heightInPixels:o.height*t.tileheight,alpha:o.opacity,visible:o.visible,properties:{},indexes:[],callbacks:[],bodies:[]};o.properties&&(u.properties=o.properties);for(var d,p,f,g,m=0,y=[],v=[],b=0,h=o.data.length;b<h;b++){if(d=0,p=!1,g=o.data[b],f=0,g>536870912)switch(g>2147483648&&(g-=2147483648,f+=4),g>1073741824&&(g-=1073741824,f+=2),g>536870912&&(g-=536870912,f+=1),f){case 5:d=Math.PI/2;break;case 6:d=Math.PI;break;case 3:d=3*Math.PI/2;break;case 4:d=0,p=!0;break;case 7:d=Math.PI/2,p=!0;break;case 2:d=Math.PI,p=!0;break;case 1:d=3*Math.PI/2,p=!0}if(g>0){var x=new n.Tile(u,g,m,v.length,t.tilewidth,t.tileheight);x.rotation=d,x.flipped=p,0!==f&&(x.flippedVal=f),y.push(x)}else n.TilemapParser.INSERT_NULL?y.push(null):y.push(new n.Tile(u,-1,m,v.length,t.tilewidth,t.tileheight));m++,m===o.width&&(v.push(y),m=0,y=[])}u.data=v,s.push(u)}i.layers=s;for(var w=[],r=0;r<t.layers.length;r++)if("imagelayer"===t.layers[r].type){var _=t.layers[r],P={name:_.name,image:_.image,x:_.x,y:_.y,alpha:_.opacity,visible:_.visible,properties:{}};_.properties&&(P.properties=_.properties),w.push(P)}i.images=w;for(var T=[],C=[],S=null,r=0;r<t.tilesets.length;r++){var A=t.tilesets[r];if(A.image){var E=new n.Tileset(A.name,A.firstgid,A.tilewidth,A.tileheight,A.margin,A.spacing,A.properties);A.tileproperties&&(E.tileProperties=A.tileproperties),E.updateTileData(A.imagewidth,A.imageheight),T.push(E)}else{var I=new n.ImageCollection(A.name,A.firstgid,A.tilewidth,A.tileheight,A.margin,A.spacing,A.properties);for(var M in A.tiles){var P=A.tiles[M].image,g=A.firstgid+parseInt(M,10);I.addImage(g,P)}C.push(I)}S&&(S.lastgid=A.firstgid-1),S=A}i.tilesets=T,i.imagecollections=C;for(var R={},B={},r=0;r<t.layers.length;r++)if("objectgroup"===t.layers[r].type){var L=t.layers[r];R[L.name]=[],B[L.name]=[];for(var k=0,h=L.objects.length;k<h;k++)if(L.objects[k].gid){var O={gid:L.objects[k].gid,name:L.objects[k].name,type:L.objects[k].hasOwnProperty("type")?L.objects[k].type:"",x:L.objects[k].x,y:L.objects[k].y,visible:L.objects[k].visible,properties:L.objects[k].properties};L.objects[k].rotation&&(O.rotation=L.objects[k].rotation),R[L.name].push(O)}else if(L.objects[k].polyline){var O={name:L.objects[k].name,type:L.objects[k].type,x:L.objects[k].x,y:L.objects[k].y,width:L.objects[k].width,height:L.objects[k].height,visible:L.objects[k].visible,properties:L.objects[k].properties};L.objects[k].rotation&&(O.rotation=L.objects[k].rotation),O.polyline=[];for(var F=0;F<L.objects[k].polyline.length;F++)O.polyline.push([L.objects[k].polyline[F].x,L.objects[k].polyline[F].y]);B[L.name].push(O),R[L.name].push(O)}else if(L.objects[k].polygon){var O=e(L.objects[k],["name","type","x","y","visible","rotation","properties"]);O.polygon=[];for(var F=0;F<L.objects[k].polygon.length;F++)O.polygon.push([L.objects[k].polygon[F].x,L.objects[k].polygon[F].y]);R[L.name].push(O)}else if(L.objects[k].ellipse){var O=e(L.objects[k],["name","type","ellipse","x","y","width","height","visible","rotation","properties"]);R[L.name].push(O)}else{var O=e(L.objects[k],["name","type","x","y","width","height","visible","rotation","properties"]);O.rectangle=!0,R[L.name].push(O)}}i.objects=R,i.collision=B,i.tiles=[];for(var r=0;r<i.tilesets.length;r++)for(var A=i.tilesets[r],m=A.tileMargin,D=A.tileMargin,U=0,G=0,N=0,b=A.firstgid;b<A.firstgid+A.total&&(i.tiles[b]=[m,D,r],m+=A.tileWidth+A.tileSpacing,++U!==A.total)&&(++G!==A.columns||(m=A.tileMargin,D+=A.tileHeight+A.tileSpacing,G=0,++N!==A.rows));b++);for(var u,x,X,A,r=0;r<i.layers.length;r++){u=i.layers[r],A=null;for(var c=0;c<u.data.length;c++){y=u.data[c];for(var W=0;W<y.length;W++)null===(x=y[W])||x.index<0||(X=i.tiles[x.index][2],A=i.tilesets[X],A.tileProperties&&A.tileProperties[x.index-A.firstgid]&&(x.properties=n.Utils.mixin(A.tileProperties[x.index-A.firstgid],x.properties)))}}return i}},n.Tileset=function(t,e,i,s,n,r,o){(void 0===i||i<=0)&&(i=32),(void 0===s||s<=0)&&(s=32),void 0===n&&(n=0),void 0===r&&(r=0),this.name=t,this.firstgid=0|e,this.tileWidth=0|i,this.tileHeight=0|s,this.tileMargin=0|n,this.tileSpacing=0|r,this.properties=o||{},this.image=null,this.rows=0,this.columns=0,this.total=0,this.drawCoords=[]},n.Tileset.prototype={draw:function(t,e,i,s){var n=s-this.firstgid<<1;n>=0&&n+1<this.drawCoords.length&&t.drawImage(this.image,this.drawCoords[n],this.drawCoords[n+1],this.tileWidth,this.tileHeight,e,i,this.tileWidth,this.tileHeight)},containsTileIndex:function(t){return t>=this.firstgid&&t<this.firstgid+this.total},setImage:function(t){this.image=t,this.updateTileData(t.width,t.height)},setSpacing:function(t,e){this.tileMargin=0|t,this.tileSpacing=0|e,this.image&&this.updateTileData(this.image.width,this.image.height)},updateTileData:function(t,e){var i=(e-2*this.tileMargin+this.tileSpacing)/(this.tileHeight+this.tileSpacing),s=(t-2*this.tileMargin+this.tileSpacing)/(this.tileWidth+this.tileSpacing);i%1==0&&s%1==0||console.warn("Phaser.Tileset - "+this.name+" image tile area is not an even multiple of tile size"),i=Math.floor(i),s=Math.floor(s),(this.rows&&this.rows!==i||this.columns&&this.columns!==s)&&console.warn("Phaser.Tileset - actual and expected number of tile rows and columns differ"),this.rows=i,this.columns=s,this.total=i*s,this.drawCoords.length=0;for(var n=this.tileMargin,r=this.tileMargin,o=0;o<this.rows;o++){for(var a=0;a<this.columns;a++)this.drawCoords.push(n),this.drawCoords.push(r),n+=this.tileWidth+this.tileSpacing;n=this.tileMargin,r+=this.tileHeight+this.tileSpacing}}},n.Tileset.prototype.constructor=n.Tileset,n.Particle=function(t,e,i,s,r){n.Sprite.call(this,t,e,i,s,r),this.autoScale=!1,this.scaleData=null,this._s=0,this.autoAlpha=!1,this.alphaData=null,this._a=0},n.Particle.prototype=Object.create(n.Sprite.prototype),n.Particle.prototype.constructor=n.Particle,n.Particle.prototype.update=function(){this.autoScale&&(this._s--,this._s?this.scale.set(this.scaleData[this._s].x,this.scaleData[this._s].y):this.autoScale=!1),this.autoAlpha&&(this._a--,this._a?this.alpha=this.alphaData[this._a].v:this.autoAlpha=!1)},n.Particle.prototype.onEmit=function(){},n.Particle.prototype.setAlphaData=function(t){this.alphaData=t,this._a=t.length-1,this.alpha=this.alphaData[this._a].v,this.autoAlpha=!0},n.Particle.prototype.setScaleData=function(t){this.scaleData=t,this._s=t.length-1,this.scale.set(this.scaleData[this._s].x,this.scaleData[this._s].y),this.autoScale=!0},n.Particle.prototype.reset=function(t,e,i){return n.Component.Reset.prototype.reset.call(this,t,e,i),this.alpha=1,this.scale.set(1),this.autoScale=!1,this.autoAlpha=!1,this},n.Particles=function(t){this.game=t,this.emitters={},this.ID=0},n.Particles.prototype={add:function(t){return this.emitters[t.name]=t,t},remove:function(t){delete this.emitters[t.name]},update:function(){for(var t in this.emitters)this.emitters[t].exists&&this.emitters[t].update()}},n.Particles.prototype.constructor=n.Particles,n.Particles.Arcade={},n.Particles.Arcade.Emitter=function(t,e,i,s){this.maxParticles=s||50,n.Group.call(this,t),this.name="emitter"+this.game.particles.ID++,this.type=n.EMITTER,this.physicsType=n.GROUP,this.area=new n.Rectangle(e,i,1,1),this.minParticleSpeed=new n.Point(-100,-100),this.maxParticleSpeed=new n.Point(100,100),this.minParticleScale=1,this.maxParticleScale=1,this.scaleData=null,this.minRotation=-360,this.maxRotation=360,this.minParticleAlpha=1,this.maxParticleAlpha=1,this.alphaData=null,this.gravity=100,this.particleClass=n.Particle,this.particleDrag=new n.Point,this.angularDrag=0,this.frequency=100,this.lifespan=2e3,this.bounce=new n.Point,this.on=!1,this.particleAnchor=new n.Point(.5,.5),this.blendMode=n.blendModes.NORMAL,this.emitX=e,this.emitY=i,this.autoScale=!1,this.autoAlpha=!1,this.particleBringToTop=!1,this.particleSendToBack=!1,this._minParticleScale=new n.Point(1,1),this._maxParticleScale=new n.Point(1,1),this._quantity=0,this._timer=0,this._counter=0,this._flowQuantity=0,this._flowTotal=0,this._explode=!0,this._frames=null},n.Particles.Arcade.Emitter.prototype=Object.create(n.Group.prototype),n.Particles.Arcade.Emitter.prototype.constructor=n.Particles.Arcade.Emitter,n.Particles.Arcade.Emitter.prototype.update=function(){if(this.on&&this.game.time.time>=this._timer)if(this._timer=this.game.time.time+this.frequency*this.game.time.slowMotion,0!==this._flowTotal)if(this._flowQuantity>0){for(var t=0;t<this._flowQuantity;t++)if(this.emitParticle()&&(this._counter++,-1!==this._flowTotal&&this._counter>=this._flowTotal)){this.on=!1;break}}else this.emitParticle()&&(this._counter++,-1!==this._flowTotal&&this._counter>=this._flowTotal&&(this.on=!1));else this.emitParticle()&&(this._counter++,this._quantity>0&&this._counter>=this._quantity&&(this.on=!1));for(var t=this.children.length;t--;)this.children[t].exists&&this.children[t].update()},n.Particles.Arcade.Emitter.prototype.makeParticles=function(t,e,i,s,n){void 0===e&&(e=0),void 0===i&&(i=this.maxParticles),void 0===s&&(s=!1),void 0===n&&(n=!1);var r,o=0,a=t,h=e;for(this._frames=e,i>this.maxParticles&&(this.maxParticles=i);o<i;)Array.isArray(t)&&(a=this.game.rnd.pick(t)),Array.isArray(e)&&(h=this.game.rnd.pick(e)),r=new this.particleClass(this.game,0,0,a,h),this.game.physics.arcade.enable(r,!1),s?(r.body.checkCollision.any=!0,r.body.checkCollision.none=!1):r.body.checkCollision.none=!0,r.body.collideWorldBounds=n,r.body.skipQuadTree=!0,r.exists=!1,r.visible=!1,r.anchor.copyFrom(this.particleAnchor),this.add(r),o++;return this},n.Particles.Arcade.Emitter.prototype.kill=function(){return this.on=!1,this.alive=!1,this.exists=!1,this},n.Particles.Arcade.Emitter.prototype.revive=function(){return this.alive=!0,this.exists=!0,this},n.Particles.Arcade.Emitter.prototype.explode=function(t,e){return this._flowTotal=0,this.start(!0,t,0,e,!1),this},n.Particles.Arcade.Emitter.prototype.flow=function(t,e,i,s,n){return void 0!==i&&0!==i||(i=1),void 0===s&&(s=-1),void 0===n&&(n=!0),i>this.maxParticles&&(i=this.maxParticles),this._counter=0,this._flowQuantity=i,this._flowTotal=s,n?(this.start(!0,t,e,i),this._counter+=i,this.on=!0,this._timer=this.game.time.time+e*this.game.time.slowMotion):this.start(!1,t,e,i),this},n.Particles.Arcade.Emitter.prototype.start=function(t,e,i,s,n){if(void 0===t&&(t=!0),void 0===e&&(e=0),void 0!==i&&null!==i||(i=250),void 0===s&&(s=0),void 0===n&&(n=!1),s>this.maxParticles&&(s=this.maxParticles),this.revive(),this.visible=!0,this.lifespan=e,this.frequency=i,t||n)for(var r=0;r<s;r++)this.emitParticle();else this.on=!0,this._quantity=s,this._counter=0,this._timer=this.game.time.time+i*this.game.time.slowMotion;return this},n.Particles.Arcade.Emitter.prototype.emitParticle=function(t,e,i,s){void 0===t&&(t=null),void 0===e&&(e=null);var n=this.getFirstExists(!1);if(null===n)return!1;var r=this.game.rnd;void 0!==i&&void 0!==s?n.loadTexture(i,s):void 0!==i&&n.loadTexture(i);var o=this.emitX,a=this.emitY;null!==t?o=t:this.width>1&&(o=r.between(this.left,this.right)),null!==e?a=e:this.height>1&&(a=r.between(this.top,this.bottom)),n.reset(o,a),n.angle=0,n.lifespan=this.lifespan,this.particleBringToTop?this.bringToTop(n):this.particleSendToBack&&this.sendToBack(n),this.autoScale?n.setScaleData(this.scaleData):1!==this.minParticleScale||1!==this.maxParticleScale?n.scale.set(r.realInRange(this.minParticleScale,this.maxParticleScale)):this._minParticleScale.x===this._maxParticleScale.x&&this._minParticleScale.y===this._maxParticleScale.y||n.scale.set(r.realInRange(this._minParticleScale.x,this._maxParticleScale.x),r.realInRange(this._minParticleScale.y,this._maxParticleScale.y)),void 0===s&&(Array.isArray(this._frames)?n.frame=this.game.rnd.pick(this._frames):n.frame=this._frames),this.autoAlpha?n.setAlphaData(this.alphaData):n.alpha=r.realInRange(this.minParticleAlpha,this.maxParticleAlpha),n.blendMode=this.blendMode;var h=n.body;return h.updateBounds(),h.bounce.copyFrom(this.bounce),h.drag.copyFrom(this.particleDrag),h.velocity.x=r.between(this.minParticleSpeed.x,this.maxParticleSpeed.x),h.velocity.y=r.between(this.minParticleSpeed.y,this.maxParticleSpeed.y),h.angularVelocity=r.between(this.minRotation,this.maxRotation),h.gravity.y=this.gravity,h.angularDrag=this.angularDrag,n.onEmit(),!0},n.Particles.Arcade.Emitter.prototype.destroy=function(){this.game.particles.remove(this),n.Group.prototype.destroy.call(this,!0,!1)},n.Particles.Arcade.Emitter.prototype.setSize=function(t,e){return this.area.width=t,this.area.height=e,this},n.Particles.Arcade.Emitter.prototype.setXSpeed=function(t,e){return t=t||0,e=e||0,this.minParticleSpeed.x=t,this.maxParticleSpeed.x=e,this},n.Particles.Arcade.Emitter.prototype.setYSpeed=function(t,e){return t=t||0,e=e||0,this.minParticleSpeed.y=t,this.maxParticleSpeed.y=e,this},n.Particles.Arcade.Emitter.prototype.setRotation=function(t,e){return t=t||0,e=e||0,this.minRotation=t,this.maxRotation=e,this},n.Particles.Arcade.Emitter.prototype.setAlpha=function(t,e,i,s,r){if(void 0===t&&(t=1),void 0===e&&(e=1),void 0===i&&(i=0),void 0===s&&(s=n.Easing.Linear.None),void 0===r&&(r=!1),this.minParticleAlpha=t,this.maxParticleAlpha=e,this.autoAlpha=!1,i>0&&t!==e){var o={v:t},a=this.game.make.tween(o).to({v:e},i,s);a.yoyo(r),this.alphaData=a.generateData(60),this.alphaData.reverse(),this.autoAlpha=!0}return this},n.Particles.Arcade.Emitter.prototype.setScale=function(t,e,i,s,r,o,a){if(void 0===t&&(t=1),void 0===e&&(e=1),void 0===i&&(i=1),void 0===s&&(s=1),void 0===r&&(r=0),void 0===o&&(o=n.Easing.Linear.None),void 0===a&&(a=!1),this.minParticleScale=1,this.maxParticleScale=1,this._minParticleScale.set(t,i),this._maxParticleScale.set(e,s),this.autoScale=!1,r>0&&(t!==e||i!==s)){var h={x:t,y:i},l=this.game.make.tween(h).to({x:e,y:s},r,o);l.yoyo(a),this.scaleData=l.generateData(60),this.scaleData.reverse(),this.autoScale=!0}return this},n.Particles.Arcade.Emitter.prototype.at=function(t){return t.center?(this.emitX=t.center.x,this.emitY=t.center.y):(this.emitX=t.world.x+t.anchor.x*t.width,this.emitY=t.world.y+t.anchor.y*t.height),this},Object.defineProperty(n.Particles.Arcade.Emitter.prototype,"width",{get:function(){return this.area.width},set:function(t){this.area.width=t}}),Object.defineProperty(n.Particles.Arcade.Emitter.prototype,"height",{get:function(){return this.area.height},set:function(t){this.area.height=t}}),Object.defineProperty(n.Particles.Arcade.Emitter.prototype,"x",{get:function(){return this.emitX},set:function(t){this.emitX=t}}),Object.defineProperty(n.Particles.Arcade.Emitter.prototype,"y",{get:function(){return this.emitY},set:function(t){this.emitY=t}}),Object.defineProperty(n.Particles.Arcade.Emitter.prototype,"left",{get:function(){return Math.floor(this.x-this.area.width/2)}}),Object.defineProperty(n.Particles.Arcade.Emitter.prototype,"right",{get:function(){return Math.floor(this.x+this.area.width/2)}}),Object.defineProperty(n.Particles.Arcade.Emitter.prototype,"top",{get:function(){return Math.floor(this.y-this.area.height/2)}}),Object.defineProperty(n.Particles.Arcade.Emitter.prototype,"bottom",{get:function(){return Math.floor(this.y+this.area.height/2)}}),n.Weapon=function(t,e){n.Plugin.call(this,t,e),this.bullets=null,this.autoExpandBulletsGroup=!1,this.autofire=!1,this.shots=0,this.fireLimit=0,this.fireRate=100,this.fireRateVariance=0,this.fireFrom=new n.Rectangle(0,0,1,1),this.fireAngle=n.ANGLE_UP,this.bulletInheritSpriteSpeed=!1,this.bulletAnimation="",this.bulletFrameRandom=!1,this.bulletFrameCycle=!1,this.bulletWorldWrap=!1,this.bulletWorldWrapPadding=0,this.bulletAngleOffset=0,this.bulletAngleVariance=0,this.bulletSpeed=200,this.bulletSpeedVariance=0,this.bulletLifespan=0,this.bulletKillDistance=0,this.bulletGravity=new n.Point(0,0),this.bulletRotateToVelocity=!1,this.bulletKey="",this.bulletFrame="",this._bulletClass=n.Bullet,this._bulletCollideWorldBounds=!1,this._bulletKillType=n.Weapon.KILL_WORLD_BOUNDS,this._data={customBody:!1,width:0,height:0,offsetX:0,offsetY:0},this.bounds=new n.Rectangle,this.bulletBounds=t.world.bounds,this.bulletFrames=[],this.bulletFrameIndex=0,this.anims={},this.onFire=new n.Signal,this.onKill=new n.Signal,this.onFireLimit=new n.Signal,this.trackedSprite=null,this.trackedPointer=null,this.trackRotation=!1,this.trackOffset=new n.Point,this._nextFire=0,this._rotatedPoint=new n.Point},n.Weapon.prototype=Object.create(n.Plugin.prototype),n.Weapon.prototype.constructor=n.Weapon,n.Weapon.KILL_NEVER=0,n.Weapon.KILL_LIFESPAN=1,n.Weapon.KILL_DISTANCE=2,n.Weapon.KILL_WEAPON_BOUNDS=3,n.Weapon.KILL_CAMERA_BOUNDS=4,n.Weapon.KILL_WORLD_BOUNDS=5,n.Weapon.KILL_STATIC_BOUNDS=6,n.Weapon.prototype.createBullets=function(t,e,i,s){return void 0===t&&(t=1),void 0===s&&(s=this.game.world),this.bullets||(this.bullets=this.game.add.physicsGroup(n.Physics.ARCADE,s),this.bullets.classType=this._bulletClass),0!==t&&(-1===t&&(this.autoExpandBulletsGroup=!0,t=1),this.bullets.createMultiple(t,e,i),this.bullets.setAll("data.bulletManager",this),this.bulletKey=e,this.bulletFrame=i),this},n.Weapon.prototype.forEach=function(t,e){return this.bullets.forEachExists(t,e,arguments),this},n.Weapon.prototype.pauseAll=function(){return this.bullets.setAll("body.enable",!1),this},n.Weapon.prototype.resumeAll=function(){return this.bullets.setAll("body.enable",!0),this},n.Weapon.prototype.killAll=function(){return this.bullets.callAllExists("kill",!0),this.bullets.setAll("body.enable",!0),this},n.Weapon.prototype.resetShots=function(t){return this.shots=0,void 0!==t&&(this.fireLimit=t),this},n.Weapon.prototype.destroy=function(){this.parent.remove(this,!1),this.bullets.destroy(),this.game=null,this.parent=null,this.active=!1,this.visible=!1},n.Weapon.prototype.update=function(){this._bulletKillType===n.Weapon.KILL_WEAPON_BOUNDS&&(this.trackedSprite?(this.trackedSprite.updateTransform(),this.bounds.centerOn(this.trackedSprite.worldPosition.x,this.trackedSprite.worldPosition.y)):this.trackedPointer&&this.bounds.centerOn(this.trackedPointer.worldX,this.trackedPointer.worldY)),this.autofire&&this.fire()},n.Weapon.prototype.trackSprite=function(t,e,i,s){return void 0===e&&(e=0),void 0===i&&(i=0),void 0===s&&(s=!1),this.trackedPointer=null,this.trackedSprite=t,this.trackRotation=s,this.trackOffset.set(e,i),this},n.Weapon.prototype.trackPointer=function(t,e,i){return void 0===t&&(t=this.game.input.activePointer),void 0===e&&(e=0),void 0===i&&(i=0),this.trackedPointer=t,this.trackedSprite=null,this.trackRotation=!1,this.trackOffset.set(e,i),this},n.Weapon.prototype.fire=function(t,e,i){if(this.game.time.now<this._nextFire||this.fireLimit>0&&this.shots===this.fireLimit)return!1;var s=this.bulletSpeed;0!==this.bulletSpeedVariance&&(s+=n.Math.between(-this.bulletSpeedVariance,this.bulletSpeedVariance)),t?this.fireFrom.width>1?this.fireFrom.centerOn(t.x,t.y):(this.fireFrom.x=t.x,this.fireFrom.y=t.y):this.trackedSprite?(this.trackRotation?(this._rotatedPoint.set(this.trackedSprite.world.x+this.trackOffset.x,this.trackedSprite.world.y+this.trackOffset.y),this._rotatedPoint.rotate(this.trackedSprite.world.x,this.trackedSprite.world.y,this.trackedSprite.rotation),this.fireFrom.width>1?this.fireFrom.centerOn(this._rotatedPoint.x,this._rotatedPoint.y):(this.fireFrom.x=this._rotatedPoint.x,this.fireFrom.y=this._rotatedPoint.y)):this.fireFrom.width>1?this.fireFrom.centerOn(this.trackedSprite.world.x+this.trackOffset.x,this.trackedSprite.world.y+this.trackOffset.y):(this.fireFrom.x=this.trackedSprite.world.x+this.trackOffset.x,this.fireFrom.y=this.trackedSprite.world.y+this.trackOffset.y),this.bulletInheritSpriteSpeed&&(s+=this.trackedSprite.body.speed)):this.trackedPointer&&(this.fireFrom.width>1?this.fireFrom.centerOn(this.trackedPointer.world.x+this.trackOffset.x,this.trackedPointer.world.y+this.trackOffset.y):(this.fireFrom.x=this.trackedPointer.world.x+this.trackOffset.x,this.fireFrom.y=this.trackedPointer.world.y+this.trackOffset.y));var r=this.fireFrom.width>1?this.fireFrom.randomX:this.fireFrom.x,o=this.fireFrom.height>1?this.fireFrom.randomY:this.fireFrom.y,a=this.trackRotation?this.trackedSprite.angle:this.fireAngle;void 0!==e&&void 0!==i&&(a=this.game.math.radToDeg(Math.atan2(i-o,e-r))),0!==this.bulletAngleVariance&&(a+=n.Math.between(-this.bulletAngleVariance,this.bulletAngleVariance));var h=0,l=0;0===a||180===a?h=Math.cos(this.game.math.degToRad(a))*s:90===a||270===a?l=Math.sin(this.game.math.degToRad(a))*s:(h=Math.cos(this.game.math.degToRad(a))*s,l=Math.sin(this.game.math.degToRad(a))*s);var c=null;if(this.autoExpandBulletsGroup?(c=this.bullets.getFirstExists(!1,!0,r,o,this.bulletKey,this.bulletFrame),c.data.bulletManager=this):c=this.bullets.getFirstExists(!1),c){if(c.reset(r,o),c.data.fromX=r,c.data.fromY=o,c.data.killType=this.bulletKillType,c.data.killDistance=this.bulletKillDistance,c.data.rotateToVelocity=this.bulletRotateToVelocity,this.bulletKillType===n.Weapon.KILL_LIFESPAN&&(c.lifespan=this.bulletLifespan),c.angle=a+this.bulletAngleOffset,""!==this.bulletAnimation){if(null===c.animations.getAnimation(this.bulletAnimation)){var u=this.anims[this.bulletAnimation];c.animations.add(u.name,u.frames,u.frameRate,u.loop,u.useNumericIndex)}c.animations.play(this.bulletAnimation)}else this.bulletFrameCycle?(c.frame=this.bulletFrames[this.bulletFrameIndex],++this.bulletFrameIndex>=this.bulletFrames.length&&(this.bulletFrameIndex=0)):this.bulletFrameRandom&&(c.frame=this.bulletFrames[Math.floor(Math.random()*this.bulletFrames.length)]);if(c.data.bodyDirty&&(this._data.customBody&&c.body.setSize(this._data.width,this._data.height,this._data.offsetX,this._data.offsetY),c.body.collideWorldBounds=this.bulletCollideWorldBounds,c.data.bodyDirty=!1),c.body.velocity.set(h,l),c.body.gravity.set(this.bulletGravity.x,this.bulletGravity.y),0!==this.bulletSpeedVariance){var d=this.fireRate;d+=n.Math.between(-this.fireRateVariance,this.fireRateVariance),d<0&&(d=0),this._nextFire=this.game.time.now+d}else this._nextFire=this.game.time.now+this.fireRate;this.shots++,this.onFire.dispatch(c,this,s),this.fireLimit>0&&this.shots===this.fireLimit&&this.onFireLimit.dispatch(this,this.fireLimit)}return c},n.Weapon.prototype.fireAtPointer=function(t){return void 0===t&&(t=this.game.input.activePointer),this.fire(null,t.worldX,t.worldY)},n.Weapon.prototype.fireAtSprite=function(t){return this.fire(null,t.world.x,t.world.y)},n.Weapon.prototype.fireAtXY=function(t,e){return this.fire(null,t,e)},n.Weapon.prototype.setBulletBodyOffset=function(t,e,i,s){return void 0===i&&(i=0),void 0===s&&(s=0),this._data.customBody=!0,this._data.width=t,this._data.height=e,this._data.offsetX=i,this._data.offsetY=s,this.bullets.callAll("body.setSize","body",t,e,i,s),this.bullets.setAll("data.bodyDirty",!1),this},n.Weapon.prototype.setBulletFrames=function(t,e,i,s){return void 0===i&&(i=!0),void 0===s&&(s=!1),this.bulletFrames=n.ArrayUtils.numberArray(t,e),this.bulletFrameIndex=0,this.bulletFrameCycle=i,this.bulletFrameRandom=s,this},n.Weapon.prototype.addBulletAnimation=function(t,e,i,s,n){return this.anims[t]={name:t,frames:e,frameRate:i,loop:s,useNumericIndex:n},this.bullets.callAll("animations.add","animations",t,e,i,s,n),this.bulletAnimation=t,this},n.Weapon.prototype.debug=function(t,e,i){void 0===t&&(t=16),void 0===e&&(e=32),void 0===i&&(i=!1),this.game.debug.text("Weapon Plugin",t,e),this.game.debug.text("Bullets Alive: "+this.bullets.total+" - Total: "+this.bullets.length,t,e+24),i&&this.bullets.forEachExists(this.game.debug.body,this.game.debug,"rgba(255, 0, 255, 0.8)")},Object.defineProperty(n.Weapon.prototype,"bulletClass",{get:function(){return this._bulletClass},set:function(t){this._bulletClass=t,this.bullets.classType=this._bulletClass}}),Object.defineProperty(n.Weapon.prototype,"bulletKillType",{get:function(){return this._bulletKillType},set:function(t){switch(t){case n.Weapon.KILL_STATIC_BOUNDS:case n.Weapon.KILL_WEAPON_BOUNDS:this.bulletBounds=this.bounds;break;case n.Weapon.KILL_CAMERA_BOUNDS:this.bulletBounds=this.game.camera.view;break;case n.Weapon.KILL_WORLD_BOUNDS:this.bulletBounds=this.game.world.bounds}this._bulletKillType=t}}),Object.defineProperty(n.Weapon.prototype,"bulletCollideWorldBounds",{get:function(){return this._bulletCollideWorldBounds},set:function(t){this._bulletCollideWorldBounds=t,this.bullets.setAll("body.collideWorldBounds",t),this.bullets.setAll("data.bodyDirty",!1)}}),Object.defineProperty(n.Weapon.prototype,"x",{get:function(){return this.fireFrom.x},set:function(t){this.fireFrom.x=t}}),Object.defineProperty(n.Weapon.prototype,"y",{get:function(){return this.fireFrom.y},set:function(t){this.fireFrom.y=t}}),n.Bullet=function(t,e,i,s,r){n.Sprite.call(this,t,e,i,s,r),this.anchor.set(.5),this.data={bulletManager:null,fromX:0,fromY:0,bodyDirty:!0,rotateToVelocity:!1,killType:0,killDistance:0}},n.Bullet.prototype=Object.create(n.Sprite.prototype),n.Bullet.prototype.constructor=n.Bullet,n.Bullet.prototype.kill=function(){return this.alive=!1,this.exists=!1,this.visible=!1,this.data.bulletManager.onKill.dispatch(this),this},n.Bullet.prototype.update=function(){this.exists&&(this.data.killType>n.Weapon.KILL_LIFESPAN&&(this.data.killType===n.Weapon.KILL_DISTANCE?this.game.physics.arcade.distanceToXY(this,this.data.fromX,this.data.fromY,!0)>this.data.killDistance&&this.kill():this.data.bulletManager.bulletBounds.intersects(this)||this.kill()),this.data.rotateToVelocity&&(this.rotation=Math.atan2(this.body.velocity.y,this.body.velocity.x)),this.data.bulletManager.bulletWorldWrap&&this.game.world.wrap(this,this.data.bulletManager.bulletWorldWrapPadding))},n.Video=function(t,e,i){if(void 0===e&&(e=null),void 0===i&&(i=null),this.game=t,this.key=e,this.width=0,this.height=0,this.type=n.VIDEO,this.disableTextureUpload=!1,this.touchLocked=!1,this.onPlay=new n.Signal,this.onChangeSource=new n.Signal,this.onComplete=new n.Signal,this.onAccess=new n.Signal,this.onError=new n.Signal,this.onTimeout=new n.Signal,this.timeout=15e3,this._timeOutID=null,this.video=null,this.videoStream=null,this.isStreaming=!1,this.retryLimit=20,this.retry=0,this.retryInterval=500,this._retryID=null,this._codeMuted=!1,this._muted=!1,this._codePaused=!1,this._paused=!1,this._pending=!1,this._autoplay=!1,this._endCallback=null,this._playCallback=null,e&&this.game.cache.checkVideoKey(e)){var s=this.game.cache.getVideo(e);s.isBlob?this.createVideoFromBlob(s.data):this.video=s.data,this.width=this.video.videoWidth,this.height=this.video.videoHeight}else i&&this.createVideoFromURL(i,!1);this.video&&!i?(this.baseTexture=new PIXI.BaseTexture(this.video),this.baseTexture.forceLoaded(this.width,this.height)):(this.baseTexture=new PIXI.BaseTexture(n.Cache.DEFAULT.baseTexture.source),this.baseTexture.forceLoaded(this.width,this.height)),this.texture=new PIXI.Texture(this.baseTexture),this.textureFrame=new n.Frame(0,0,0,this.width,this.height,"video"),this.texture.setFrame(this.textureFrame),this.texture.valid=!1,null!==e&&this.video&&(this.texture.valid=this.video.canplay),this.snapshot=null,n.BitmapData&&(this.snapshot=new n.BitmapData(this.game,"",this.width,this.height)),!this.game.device.cocoonJS&&(this.game.device.iOS||this.game.device.android)||window.PhaserGlobal&&window.PhaserGlobal.fakeiOSTouchLock?this.setTouchLock():s&&(s.locked=!1)},n.Video.prototype={connectToMediaStream:function(t,e){return t&&e&&(this.video=t,this.videoStream=e,this.isStreaming=!0,this.baseTexture.source=this.video,this.updateTexture(null,this.video.videoWidth,this.video.videoHeight),this.onAccess.dispatch(this)),this},startMediaStream:function(t,e,i){if(void 0===t&&(t=!1),void 0===e&&(e=null),void 0===i&&(i=null),!this.game.device.getUserMedia)return this.onError.dispatch(this,"No getUserMedia"),!1;null!==this.videoStream&&(this.videoStream.active?this.videoStream.active=!1:this.videoStream.stop()),this.removeVideoElement(),this.video=document.createElement("video"),this.video.setAttribute("autoplay","autoplay"),null!==e&&(this.video.width=e),null!==i&&(this.video.height=i),this._timeOutID=window.setTimeout(this.getUserMediaTimeout.bind(this),this.timeout);try{navigator.getUserMedia({audio:t,video:!0},this.getUserMediaSuccess.bind(this),this.getUserMediaError.bind(this))}catch(t){this.getUserMediaError(t)}return this},getUserMediaTimeout:function(){clearTimeout(this._timeOutID),this.onTimeout.dispatch(this)},getUserMediaError:function(t){clearTimeout(this._timeOutID),this.onError.dispatch(this,t)},getUserMediaSuccess:function(t){clearTimeout(this._timeOutID),this.videoStream=t,void 0!==this.video.mozSrcObject?this.video.mozSrcObject=t:this.video.src=window.URL&&window.URL.createObjectURL(t)||t;var e=this;this.video.onloadeddata=function(){function t(){if(i>0)if(e.video.videoWidth>0){var s=e.video.videoWidth,n=e.video.videoHeight;isNaN(e.video.videoHeight)&&(n=s/(4/3)),e.video.play(),e.isStreaming=!0,e.baseTexture.source=e.video,e.updateTexture(null,s,n),e.onAccess.dispatch(e)}else window.setTimeout(t,500);else console.warn("Unable to connect to video stream. Webcam error?");i--}var i=10;t()}},createVideoFromBlob:function(t){var e=this;return this.video=document.createElement("video"),this.video.controls=!1,this.video.setAttribute("autoplay","autoplay"),this.video.addEventListener("loadeddata",function(t){e.updateTexture(t)},!0),this.video.src=window.URL.createObjectURL(t),this.video.canplay=!0,this},createVideoFromURL:function(t,e){return void 0===e&&(e=!1),this.texture&&(this.texture.valid=!1),this.video=document.createElement("video"),this.video.controls=!1,e&&this.video.setAttribute("autoplay","autoplay"),this.video.src=t,this.video.canplay=!0,this.video.load(),this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval),this.key=t,this},updateTexture:function(t,e,i){var s=!1;void 0!==e&&null!==e||(e=this.video.videoWidth,s=!0),void 0!==i&&null!==i||(i=this.video.videoHeight),this.width=e,this.height=i,this.baseTexture.source!==this.video&&(this.baseTexture.source=this.video),this.baseTexture.forceLoaded(e,i),this.texture.frame.resize(e,i),this.texture.width=e,this.texture.height=i,this.texture.valid=!0,this.snapshot&&this.snapshot.resize(e,i),s&&null!==this.key&&(this.onChangeSource.dispatch(this,e,i),this._autoplay&&(this.video.play(),this.onPlay.dispatch(this,this.loop,this.playbackRate)))},complete:function(){this.onComplete.dispatch(this)},play:function(t,e){return void 0===t&&(t=!1),void 0===e&&(e=1),this.game.sound.onMute&&(this.game.sound.onMute.add(this.setMute,this),this.game.sound.onUnMute.add(this.unsetMute,this),this.game.sound.mute&&this.setMute()),this.game.onPause.add(this.setPause,this),this.game.onResume.add(this.setResume,this),this._endCallback=this.complete.bind(this),this.video.addEventListener("ended",this._endCallback,!0),this.video.addEventListener("webkitendfullscreen",this._endCallback,!0),this.video.loop=t?"loop":"",this.video.playbackRate=e,this.touchLocked?this._pending=!0:(this._pending=!1,null!==this.key&&(4!==this.video.readyState?(this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval)):(this._playCallback=this.playHandler.bind(this),this.video.addEventListener("playing",this._playCallback,!0))),this.video.play(),this.onPlay.dispatch(this,t,e)),this},playHandler:function(){this.video.removeEventListener("playing",this._playCallback,!0),this.updateTexture()},stop:function(){return this.game.sound.onMute&&(this.game.sound.onMute.remove(this.setMute,this),this.game.sound.onUnMute.remove(this.unsetMute,this)),this.game.onPause.remove(this.setPause,this),this.game.onResume.remove(this.setResume,this),this.isStreaming?(this.video.mozSrcObject?(this.video.mozSrcObject.stop(),this.video.src=null):(this.video.src="",this.videoStream.active?this.videoStream.active=!1:this.videoStream.getTracks?this.videoStream.getTracks().forEach(function(t){t.stop()}):this.videoStream.stop()),this.videoStream=null,this.isStreaming=!1):(this.video.removeEventListener("ended",this._endCallback,!0),this.video.removeEventListener("webkitendfullscreen",this._endCallback,!0),this.video.removeEventListener("playing",this._playCallback,!0),this.touchLocked?this._pending=!1:this.video.pause()),this},add:function(t){if(Array.isArray(t))for(var e=0;e<t.length;e++)t[e].loadTexture&&t[e].loadTexture(this);else t.loadTexture(this);return this},addToWorld:function(t,e,i,s,n,r){n=n||1,r=r||1;var o=this.game.add.image(t,e,this);return o.anchor.set(i,s),o.scale.set(n,r),o},render:function(){!this.disableTextureUpload&&this.playing&&this.baseTexture.dirty()},setMute:function(){this._muted||(this._muted=!0,this.video.muted=!0)},unsetMute:function(){this._muted&&!this._codeMuted&&(this._muted=!1,this.video.muted=!1)},setPause:function(){this._paused||this.touchLocked||(this._paused=!0,this.video.pause())},setResume:function(){!this._paused||this._codePaused||this.touchLocked||(this._paused=!1,this.video.ended||this.video.play())},changeSource:function(t,e){return void 0===e&&(e=!0),this.texture.valid=!1,this.video.pause(),this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval),this.video.src=t,this.video.load(),this._autoplay=e,e||(this.paused=!0),this},checkVideoProgress:function(){4===this.video.readyState?this.updateTexture():(this.retry--,this.retry>0?this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval):console.warn("Phaser.Video: Unable to start downloading video in time",this.isStreaming))},setTouchLock:function(){this.game.input.touch.addTouchLockCallback(this.unlock,this),this.touchLocked=!0},unlock:function(){if(this.touchLocked=!1,this.video.play(),this.onPlay.dispatch(this,this.loop,this.playbackRate),this.key){var t=this.game.cache.getVideo(this.key);t&&!t.isBlob&&(t.locked=!1)}return!0},grab:function(t,e,i){return void 0===t&&(t=!1),void 0===e&&(e=1),void 0===i&&(i=null),null===this.snapshot?void console.warn("Video.grab cannot run because Phaser.BitmapData is unavailable"):(t&&this.snapshot.cls(),this.snapshot.copy(this.video,0,0,this.width,this.height,0,0,this.width,this.height,0,0,0,1,1,e,i),this.snapshot)},removeVideoElement:function(){if(this.video){for(this.video.parentNode&&this.video.parentNode.removeChild(this.video);this.video.hasChildNodes();)this.video.removeChild(this.video.firstChild);this.video.removeAttribute("autoplay"),this.video.removeAttribute("src"),this.video=null}},destroy:function(){this.stop(),this.removeVideoElement(),this.touchLocked&&this.game.input.touch.removeTouchLockCallback(this.unlock,this),this._retryID&&window.clearTimeout(this._retryID)}},Object.defineProperty(n.Video.prototype,"currentTime",{get:function(){return this.video?this.video.currentTime:0},set:function(t){this.video.currentTime=t}}),Object.defineProperty(n.Video.prototype,"duration",{get:function(){return this.video?this.video.duration:0}}),Object.defineProperty(n.Video.prototype,"progress",{get:function(){return this.video?this.video.currentTime/this.video.duration:0}}),Object.defineProperty(n.Video.prototype,"mute",{get:function(){return this._muted},set:function(t){if(t=t||null){if(this._muted)return;this._codeMuted=!0,this.setMute()}else{if(!this._muted)return;this._codeMuted=!1,this.unsetMute()}}}),Object.defineProperty(n.Video.prototype,"paused",{get:function(){return this._paused},set:function(t){if(t=t||null,!this.touchLocked)if(t){if(this._paused)return;this._codePaused=!0,this.setPause()}else{if(!this._paused)return;this._codePaused=!1,this.setResume()}}}),Object.defineProperty(n.Video.prototype,"volume",{get:function(){return this.video?this.video.volume:1},set:function(t){t<0?t=0:t>1&&(t=1),this.video&&(this.video.volume=t)}}),Object.defineProperty(n.Video.prototype,"playbackRate",{get:function(){return this.video?this.video.playbackRate:1},set:function(t){this.video&&(this.video.playbackRate=t)}}),Object.defineProperty(n.Video.prototype,"loop",{get:function(){return!!this.video&&this.video.loop},set:function(t){t&&this.video?this.video.loop="loop":this.video&&(this.video.loop="")}}),Object.defineProperty(n.Video.prototype,"playing",{get:function(){return!(this.video.paused&&this.video.ended)}}),n.Video.prototype.constructor=n.Video,void 0===PIXI.blendModes&&(PIXI.blendModes=n.blendModes),void 0===PIXI.scaleModes&&(PIXI.scaleModes=n.scaleModes),void 0===PIXI.Texture.emptyTexture&&(PIXI.Texture.emptyTexture=new PIXI.Texture(new PIXI.BaseTexture)),void 0===PIXI.DisplayObject._tempMatrix&&(PIXI.DisplayObject._tempMatrix=new PIXI.Matrix),void 0===PIXI.RenderTexture.tempMatrix&&(PIXI.RenderTexture.tempMatrix=new PIXI.Matrix),PIXI.Graphics&&void 0===PIXI.Graphics.POLY&&(PIXI.Graphics.POLY=n.POLYGON,PIXI.Graphics.RECT=n.RECTANGLE,PIXI.Graphics.CIRC=n.CIRCLE,PIXI.Graphics.ELIP=n.ELLIPSE,PIXI.Graphics.RREC=n.ROUNDEDRECTANGLE),PIXI.TextureSilentFail=!0,void 0!==t&&t.exports&&(e=t.exports=n),e.Phaser=n,n}).call(this)}).call(e,i(4))},function(t,e,i){/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*
* @overview
*
* Phaser - http://phaser.io
*
* v2.6.2 "Kore Springs" - Built: Fri Aug 26 2016 01:03:18
*
* By Richard Davey http://www.photonstorm.com @photonstorm
*
* Phaser is a fun, free and fast 2D game framework for making HTML5 games
* for desktop and mobile web browsers, supporting Canvas and WebGL rendering.
*
* Phaser uses Pixi.js for rendering, created by Mat Groves http://matgroves.com @Doormat23
* Phaser uses p2.js for full-body physics, created by Stefan Hedman https://github.com/schteppe/p2.js @schteppe
* Phaser contains a port of N+ Physics, converted by Richard Davey, original by http://www.metanetsoftware.com
*
* Many thanks to Adam Saltsman (@ADAMATOMIC) for releasing Flixel, from which both Phaser and my love of framework development originate.
*
* Follow development at http://phaser.io and on our forum
*
* "If you want your children to be intelligent, read them fairy tales."
* "If you want them to be more intelligent, read them more fairy tales."
* -- Albert Einstein
*/
(function(){var i=i||{};/**
* @author Mat Groves http://matgroves.com @Doormat23
* @author Richard Davey <[email protected]>
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
return i.game=null,i.WEBGL_RENDERER=0,i.CANVAS_RENDERER=1,i.VERSION="v2.2.9",i._UID=0,"undefined"!=typeof Float32Array?(i.Float32Array=Float32Array,i.Uint16Array=Uint16Array,i.Uint32Array=Uint32Array,i.ArrayBuffer=ArrayBuffer):(i.Float32Array=Array,i.Uint16Array=Array),i.PI_2=2*Math.PI,i.RAD_TO_DEG=180/Math.PI,i.DEG_TO_RAD=Math.PI/180,i.RETINA_PREFIX="@2x",i.DisplayObject=function(){this.position=new i.Point(0,0),this.scale=new i.Point(1,1),this.pivot=new i.Point(0,0),this.rotation=0,this.alpha=1,this.visible=!0,this.hitArea=null,this.renderable=!1,this.parent=null,this.worldAlpha=1,this.worldTransform=new i.Matrix,this.worldPosition=new i.Point(0,0),this.worldScale=new i.Point(1,1),this.worldRotation=0,this.filterArea=null,this._sr=0,this._cr=1,this._bounds=new i.Rectangle(0,0,0,0),this._currentBounds=null,this._mask=null,this._cacheAsBitmap=!1,this._cacheIsDirty=!1},i.DisplayObject.prototype.constructor=i.DisplayObject,i.DisplayObject.prototype={destroy:function(){if(this.children){for(var t=this.children.length;t--;)this.children[t].destroy();this.children=[]}this.hitArea=null,this.parent=null,this.worldTransform=null,this.filterArea=null,this.renderable=!1,this._bounds=null,this._currentBounds=null,this._mask=null,this._destroyCachedSprite()},updateTransform:function(t){if(!t&&!this.parent&&!this.game)return this;var e=this.parent;t?e=t:this.parent||(e=this.game.world);var s,n,r,o,a,h,l=e.worldTransform,c=this.worldTransform;return this.rotation%i.PI_2?(this.rotation!==this.rotationCache&&(this.rotationCache=this.rotation,this._sr=Math.sin(this.rotation),this._cr=Math.cos(this.rotation)),s=this._cr*this.scale.x,n=this._sr*this.scale.x,r=-this._sr*this.scale.y,o=this._cr*this.scale.y,a=this.position.x,h=this.position.y,(this.pivot.x||this.pivot.y)&&(a-=this.pivot.x*s+this.pivot.y*r,h-=this.pivot.x*n+this.pivot.y*o),c.a=s*l.a+n*l.c,c.b=s*l.b+n*l.d,c.c=r*l.a+o*l.c,c.d=r*l.b+o*l.d,c.tx=a*l.a+h*l.c+l.tx,c.ty=a*l.b+h*l.d+l.ty):(s=this.scale.x,o=this.scale.y,a=this.position.x-this.pivot.x*s,h=this.position.y-this.pivot.y*o,c.a=s*l.a,c.b=s*l.b,c.c=o*l.c,c.d=o*l.d,c.tx=a*l.a+h*l.c+l.tx,c.ty=a*l.b+h*l.d+l.ty),this.worldAlpha=this.alpha*e.worldAlpha,this.worldPosition.set(c.tx,c.ty),this.worldScale.set(this.scale.x*Math.sqrt(c.a*c.a+c.c*c.c),this.scale.y*Math.sqrt(c.b*c.b+c.d*c.d)),this.worldRotation=Math.atan2(-c.c,c.d),this._currentBounds=null,this.transformCallback&&this.transformCallback.call(this.transformCallbackContext,c,l),this},preUpdate:function(){},generateTexture:function(t,e,s){var n=this.getLocalBounds(),r=new i.RenderTexture(0|n.width,0|n.height,s,e,t);return i.DisplayObject._tempMatrix.tx=-n.x,i.DisplayObject._tempMatrix.ty=-n.y,r.render(this,i.DisplayObject._tempMatrix),r},updateCache:function(){return this._generateCachedSprite(),this},toGlobal:function(t){return this.updateTransform(),this.worldTransform.apply(t)},toLocal:function(t,e){return e&&(t=e.toGlobal(t)),this.updateTransform(),this.worldTransform.applyInverse(t)},_renderCachedSprite:function(t){this._cachedSprite.worldAlpha=this.worldAlpha,t.gl?i.Sprite.prototype._renderWebGL.call(this._cachedSprite,t):i.Sprite.prototype._renderCanvas.call(this._cachedSprite,t)},_generateCachedSprite:function(){this._cacheAsBitmap=!1;var t=this.getLocalBounds();if(t.width=Math.max(1,Math.ceil(t.width)),t.height=Math.max(1,Math.ceil(t.height)),this.updateTransform(),this._cachedSprite)this._cachedSprite.texture.resize(t.width,t.height);else{var e=new i.RenderTexture(t.width,t.height);this._cachedSprite=new i.Sprite(e),this._cachedSprite.worldTransform=this.worldTransform}var s=this._filters;this._filters=null,this._cachedSprite.filters=s,i.DisplayObject._tempMatrix.tx=-t.x,i.DisplayObject._tempMatrix.ty=-t.y,this._cachedSprite.texture.render(this,i.DisplayObject._tempMatrix,!0),this._cachedSprite.anchor.x=-t.x/t.width,this._cachedSprite.anchor.y=-t.y/t.height,this._filters=s,this._cacheAsBitmap=!0},_destroyCachedSprite:function(){this._cachedSprite&&(this._cachedSprite.texture.destroy(!0),this._cachedSprite=null)}},i.DisplayObject.prototype.displayObjectUpdateTransform=i.DisplayObject.prototype.updateTransform,Object.defineProperties(i.DisplayObject.prototype,{x:{get:function(){return this.position.x},set:function(t){this.position.x=t}},y:{get:function(){return this.position.y},set:function(t){this.position.y=t}},worldVisible:{get:function(){if(this.visible){var t=this.parent;if(!t)return this.visible;do{if(!t.visible)return!1;t=t.parent}while(t);return!0}return!1}},mask:{get:function(){return this._mask},set:function(t){this._mask&&(this._mask.isMask=!1),this._mask=t,t&&(this._mask.isMask=!0)}},filters:{get:function(){return this._filters},set:function(t){if(Array.isArray(t)){for(var e=[],s=0;s<t.length;s++)for(var n=t[s].passes,r=0;r<n.length;r++)e.push(n[r]);this._filterBlock={target:this,filterPasses:e}}this._filters=t,this.blendMode&&this.blendMode===i.blendModes.MULTIPLY&&(this.blendMode=i.blendModes.NORMAL)}},cacheAsBitmap:{get:function(){return this._cacheAsBitmap},set:function(t){this._cacheAsBitmap!==t&&(t?this._generateCachedSprite():this._destroyCachedSprite(),this._cacheAsBitmap=t)}}}),i.DisplayObjectContainer=function(){i.DisplayObject.call(this),this.children=[],this.ignoreChildInput=!1},i.DisplayObjectContainer.prototype=Object.create(i.DisplayObject.prototype),i.DisplayObjectContainer.prototype.constructor=i.DisplayObjectContainer,i.DisplayObjectContainer.prototype.addChild=function(t){return this.addChildAt(t,this.children.length)},i.DisplayObjectContainer.prototype.addChildAt=function(t,e){if(e>=0&&e<=this.children.length)return t.parent&&t.parent.removeChild(t),t.parent=this,this.children.splice(e,0,t),t;throw new Error(t+"addChildAt: The index "+e+" supplied is out of bounds "+this.children.length)},i.DisplayObjectContainer.prototype.swapChildren=function(t,e){if(t!==e){var i=this.getChildIndex(t),s=this.getChildIndex(e);if(i<0||s<0)throw new Error("swapChildren: Both the supplied DisplayObjects must be a child of the caller.");this.children[i]=e,this.children[s]=t}},i.DisplayObjectContainer.prototype.getChildIndex=function(t){var e=this.children.indexOf(t);if(-1===e)throw new Error("The supplied DisplayObject must be a child of the caller");return e},i.DisplayObjectContainer.prototype.setChildIndex=function(t,e){if(e<0||e>=this.children.length)throw new Error("The supplied index is out of bounds");var i=this.getChildIndex(t);this.children.splice(i,1),this.children.splice(e,0,t)},i.DisplayObjectContainer.prototype.getChildAt=function(t){if(t<0||t>=this.children.length)throw new Error("getChildAt: Supplied index "+t+" does not exist in the child list, or the supplied DisplayObject must be a child of the caller");return this.children[t]},i.DisplayObjectContainer.prototype.removeChild=function(t){var e=this.children.indexOf(t);if(-1!==e)return this.removeChildAt(e)},i.DisplayObjectContainer.prototype.removeChildAt=function(t){var e=this.getChildAt(t);return e&&(e.parent=void 0,this.children.splice(t,1)),e},i.DisplayObjectContainer.prototype.removeChildren=function(t,e){void 0===t&&(t=0),void 0===e&&(e=this.children.length);var i=e-t;if(i>0&&i<=e){for(var s=this.children.splice(begin,i),n=0;n<s.length;n++){s[n].parent=void 0}return s}if(0===i&&0===this.children.length)return[];throw new Error("removeChildren: Range Error, numeric values are outside the acceptable range")},i.DisplayObjectContainer.prototype.updateTransform=function(){if(this.visible&&(this.displayObjectUpdateTransform(),!this._cacheAsBitmap))for(var t=0;t<this.children.length;t++)this.children[t].updateTransform()},i.DisplayObjectContainer.prototype.displayObjectContainerUpdateTransform=i.DisplayObjectContainer.prototype.updateTransform,i.DisplayObjectContainer.prototype.getBounds=function(t){var e=t&&t instanceof i.DisplayObject,s=!0;e?s=t instanceof i.DisplayObjectContainer&&t.contains(this):t=this;var n;if(e){var r=t.worldTransform;for(t.worldTransform=i.identityMatrix,n=0;n<t.children.length;n++)t.children[n].updateTransform()}var o,a,h,l=1/0,c=1/0,u=-1/0,d=-1/0,p=!1;for(n=0;n<this.children.length;n++){this.children[n].visible&&(p=!0,o=this.children[n].getBounds(),l=l<o.x?l:o.x,c=c<o.y?c:o.y,a=o.width+o.x,h=o.height+o.y,u=u>a?u:a,d=d>h?d:h)}var f=this._bounds;if(!p){f=new i.Rectangle;var g=f.x,m=f.width+f.x,y=f.y,v=f.height+f.y,b=this.worldTransform,x=b.a,w=b.b,_=b.c,P=b.d,T=b.tx,C=b.ty,S=x*m+_*v+T,A=P*v+w*m+C,E=x*g+_*v+T,I=P*v+w*g+C,M=x*g+_*y+T,R=P*y+w*g+C,B=x*m+_*y+T,L=P*y+w*m+C;u=S,d=A,l=S,c=A,l=E<l?E:l,l=M<l?M:l,l=B<l?B:l,c=I<c?I:c,c=R<c?R:c,c=L<c?L:c,u=E>u?E:u,u=M>u?M:u,u=B>u?B:u,d=I>d?I:d,d=R>d?R:d,d=L>d?L:d}if(f.x=l,f.y=c,f.width=u-l,f.height=d-c,e)for(t.worldTransform=r,n=0;n<t.children.length;n++)t.children[n].updateTransform();if(!s){var k=t.getBounds();f.x-=k.x,f.y-=k.y}return f},i.DisplayObjectContainer.prototype.getLocalBounds=function(){return this.getBounds(this)},i.DisplayObjectContainer.prototype.contains=function(t){return!!t&&(t===this||this.contains(t.parent))},i.DisplayObjectContainer.prototype._renderWebGL=function(t){if(this.visible&&!(this.alpha<=0)){if(this._cacheAsBitmap)return void this._renderCachedSprite(t);var e;if(this._mask||this._filters){for(this._filters&&(t.spriteBatch.flush(),t.filterManager.pushFilter(this._filterBlock)),this._mask&&(t.spriteBatch.stop(),t.maskManager.pushMask(this.mask,t),t.spriteBatch.start()),e=0;e<this.children.length;e++)this.children[e]._renderWebGL(t);t.spriteBatch.stop(),this._mask&&t.maskManager.popMask(this._mask,t),this._filters&&t.filterManager.popFilter(),t.spriteBatch.start()}else for(e=0;e<this.children.length;e++)this.children[e]._renderWebGL(t)}},i.DisplayObjectContainer.prototype._renderCanvas=function(t){if(!1!==this.visible&&0!==this.alpha){if(this._cacheAsBitmap)return void this._renderCachedSprite(t);this._mask&&t.maskManager.pushMask(this._mask,t);for(var e=0;e<this.children.length;e++)this.children[e]._renderCanvas(t);this._mask&&t.maskManager.popMask(t)}},Object.defineProperty(i.DisplayObjectContainer.prototype,"width",{get:function(){return this.getLocalBounds().width*this.scale.x},set:function(t){var e=this.getLocalBounds().width;this.scale.x=0!==e?t/e:1,this._width=t}}),Object.defineProperty(i.DisplayObjectContainer.prototype,"height",{get:function(){return this.getLocalBounds().height*this.scale.y},set:function(t){var e=this.getLocalBounds().height;this.scale.y=0!==e?t/e:1,this._height=t}}),i.Sprite=function(t){i.DisplayObjectContainer.call(this),this.anchor=new i.Point,this.texture=t||i.Texture.emptyTexture,this._width=0,this._height=0,this.tint=16777215,this.cachedTint=-1,this.tintedTexture=null,this.blendMode=i.blendModes.NORMAL,this.shader=null,this.exists=!0,this.texture.baseTexture.hasLoaded&&this.onTextureUpdate(),this.renderable=!0},i.Sprite.prototype=Object.create(i.DisplayObjectContainer.prototype),i.Sprite.prototype.constructor=i.Sprite,Object.defineProperty(i.Sprite.prototype,"width",{get:function(){return this.scale.x*this.texture.frame.width},set:function(t){this.scale.x=t/this.texture.frame.width,this._width=t}}),Object.defineProperty(i.Sprite.prototype,"height",{get:function(){return this.scale.y*this.texture.frame.height},set:function(t){this.scale.y=t/this.texture.frame.height,this._height=t}}),i.Sprite.prototype.setTexture=function(t,e){void 0!==e&&this.texture.baseTexture.destroy(),this.texture.baseTexture.skipRender=!1,this.texture=t,this.texture.valid=!0,this.cachedTint=-1},i.Sprite.prototype.onTextureUpdate=function(){this._width&&(this.scale.x=this._width/this.texture.frame.width),this._height&&(this.scale.y=this._height/this.texture.frame.height)},i.Sprite.prototype.getBounds=function(t){var e=this.texture.frame.width,i=this.texture.frame.height,s=e*(1-this.anchor.x),n=e*-this.anchor.x,r=i*(1-this.anchor.y),o=i*-this.anchor.y,a=t||this.worldTransform,h=a.a,l=a.b,c=a.c,u=a.d,d=a.tx,p=a.ty,f=-1/0,g=-1/0,m=1/0,y=1/0;if(0===l&&0===c){if(h<0){h*=-1;var v=s;s=-n,n=-v}if(u<0){u*=-1;var v=r;r=-o,o=-v}m=h*n+d,f=h*s+d,y=u*o+p,g=u*r+p}else{var b=h*n+c*o+d,x=u*o+l*n+p,w=h*s+c*o+d,_=u*o+l*s+p,P=h*s+c*r+d,T=u*r+l*s+p,C=h*n+c*r+d,S=u*r+l*n+p;m=b<m?b:m,m=w<m?w:m,m=P<m?P:m,m=C<m?C:m,y=x<y?x:y,y=_<y?_:y,y=T<y?T:y,y=S<y?S:y,f=b>f?b:f,f=w>f?w:f,f=P>f?P:f,f=C>f?C:f,g=x>g?x:g,g=_>g?_:g,g=T>g?T:g,g=S>g?S:g}var A=this._bounds;return A.x=m,A.width=f-m,A.y=y,A.height=g-y,this._currentBounds=A,A},i.Sprite.prototype.getLocalBounds=function(){var t=this.worldTransform;this.worldTransform=i.identityMatrix;for(var e=0;e<this.children.length;e++)this.children[e].updateTransform();var s=this.getBounds();for(this.worldTransform=t,e=0;e<this.children.length;e++)this.children[e].updateTransform();return s},i.Sprite.prototype._renderWebGL=function(t,e){if(this.visible&&!(this.alpha<=0)&&this.renderable){var i=this.worldTransform;if(e&&(i=e),this._mask||this._filters){var s=t.spriteBatch;this._filters&&(s.flush(),t.filterManager.pushFilter(this._filterBlock)),this._mask&&(s.stop(),t.maskManager.pushMask(this.mask,t),s.start()),s.render(this);for(var n=0;n<this.children.length;n++)this.children[n]._renderWebGL(t);s.stop(),this._mask&&t.maskManager.popMask(this._mask,t),this._filters&&t.filterManager.popFilter(),s.start()}else{t.spriteBatch.render(this);for(var n=0;n<this.children.length;n++)this.children[n]._renderWebGL(t,i)}}},i.Sprite.prototype._renderCanvas=function(t,e){if(!(!this.visible||0===this.alpha||!this.renderable||this.texture.crop.width<=0||this.texture.crop.height<=0)){var s=this.worldTransform;if(e&&(s=e),this.blendMode!==t.currentBlendMode&&(t.currentBlendMode=this.blendMode,t.context.globalCompositeOperation=i.blendModesCanvas[t.currentBlendMode]),this._mask&&t.maskManager.pushMask(this._mask,t),this.texture.valid){var n=this.texture.baseTexture.resolution/t.resolution;t.context.globalAlpha=this.worldAlpha,t.smoothProperty&&t.scaleMode!==this.texture.baseTexture.scaleMode&&(t.scaleMode=this.texture.baseTexture.scaleMode,t.context[t.smoothProperty]=t.scaleMode===i.scaleModes.LINEAR);var r=this.texture.trim?this.texture.trim.x-this.anchor.x*this.texture.trim.width:this.anchor.x*-this.texture.frame.width,o=this.texture.trim?this.texture.trim.y-this.anchor.y*this.texture.trim.height:this.anchor.y*-this.texture.frame.height,a=s.tx*t.resolution+t.shakeX,h=s.ty*t.resolution+t.shakeY;t.roundPixels?(t.context.setTransform(s.a,s.b,s.c,s.d,0|a,0|h),r|=0,o|=0):t.context.setTransform(s.a,s.b,s.c,s.d,a,h);var l=this.texture.crop.width,c=this.texture.crop.height;if(r/=n,o/=n,16777215!==this.tint)(this.texture.requiresReTint||this.cachedTint!==this.tint)&&(this.tintedTexture=i.CanvasTinter.getTintedTexture(this,this.tint),this.cachedTint=this.tint,this.texture.requiresReTint=!1),t.context.drawImage(this.tintedTexture,0,0,l,c,r,o,l/n,c/n);else{var u=this.texture.crop.x,d=this.texture.crop.y;t.context.drawImage(this.texture.baseTexture.source,u,d,l,c,r,o,l/n,c/n)}}for(var p=0;p<this.children.length;p++)this.children[p]._renderCanvas(t);this._mask&&t.maskManager.popMask(t)}},i.SpriteBatch=function(t){i.DisplayObjectContainer.call(this),this.textureThing=t,this.ready=!1},i.SpriteBatch.prototype=Object.create(i.DisplayObjectContainer.prototype),i.SpriteBatch.prototype.constructor=i.SpriteBatch,i.SpriteBatch.prototype.initWebGL=function(t){this.fastSpriteBatch=new i.WebGLFastSpriteBatch(t),this.ready=!0},i.SpriteBatch.prototype.updateTransform=function(){this.displayObjectUpdateTransform()},i.SpriteBatch.prototype._renderWebGL=function(t){!this.visible||this.alpha<=0||!this.children.length||(this.ready||this.initWebGL(t.gl),this.fastSpriteBatch.gl!==t.gl&&this.fastSpriteBatch.setContext(t.gl),t.spriteBatch.stop(),t.shaderManager.setShader(t.shaderManager.fastShader),this.fastSpriteBatch.begin(this,t),this.fastSpriteBatch.render(this),t.spriteBatch.start())},i.SpriteBatch.prototype._renderCanvas=function(t){if(this.visible&&!(this.alpha<=0)&&this.children.length){var e=t.context;e.globalAlpha=this.worldAlpha,this.displayObjectUpdateTransform();for(var i=this.worldTransform,s=!0,n=0;n<this.children.length;n++){var r=this.children[n];if(r.visible){var o=r.texture,a=o.frame;if(e.globalAlpha=this.worldAlpha*r.alpha,r.rotation%(2*Math.PI)==0)s&&(e.setTransform(i.a,i.b,i.c,i.d,i.tx,i.ty),s=!1),e.drawImage(o.baseTexture.source,a.x,a.y,a.width,a.height,r.anchor.x*(-a.width*r.scale.x)+r.position.x+.5+t.shakeX|0,r.anchor.y*(-a.height*r.scale.y)+r.position.y+.5+t.shakeY|0,a.width*r.scale.x,a.height*r.scale.y);else{s||(s=!0),r.displayObjectUpdateTransform();var h=r.worldTransform,l=h.tx*t.resolution+t.shakeX,c=h.ty*t.resolution+t.shakeY;t.roundPixels?e.setTransform(h.a,h.b,h.c,h.d,0|l,0|c):e.setTransform(h.a,h.b,h.c,h.d,l,c),e.drawImage(o.baseTexture.source,a.x,a.y,a.width,a.height,r.anchor.x*-a.width+.5|0,r.anchor.y*-a.height+.5|0,a.width,a.height)}}}}},i.hex2rgb=function(t){return[(t>>16&255)/255,(t>>8&255)/255,(255&t)/255]},i.rgb2hex=function(t){return(255*t[0]<<16)+(255*t[1]<<8)+255*t[2]},i.canUseNewCanvasBlendModes=function(){if(void 0===document)return!1;var t="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAABAQMAAADD8p2OAAAAA1BMVEX/",e="AAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJggg==",s=new Image;s.src=t+"AP804Oa6"+e;var n=new Image;n.src=t+"/wCKxvRF"+e;var r=i.CanvasPool.create(this,6,1),o=r.getContext("2d");if(o.globalCompositeOperation="multiply",o.drawImage(s,0,0),o.drawImage(n,2,0),!o.getImageData(2,0,1,1))return!1;var a=o.getImageData(2,0,1,1).data;return i.CanvasPool.remove(this),255===a[0]&&0===a[1]&&0===a[2]},i.getNextPowerOfTwo=function(t){if(t>0&&0==(t&t-1))return t;for(var e=1;e<t;)e<<=1;return e},i.isPowerOfTwo=function(t,e){return t>0&&0==(t&t-1)&&e>0&&0==(e&e-1)},i.CanvasPool={create:function(t,e,s){var n,r=i.CanvasPool.getFirst();if(-1===r){var o={parent:t,canvas:document.createElement("canvas")};i.CanvasPool.pool.push(o),n=o.canvas}else i.CanvasPool.pool[r].parent=t,n=i.CanvasPool.pool[r].canvas;return void 0!==e&&(n.width=e,n.height=s),n},getFirst:function(){for(var t=i.CanvasPool.pool,e=0;e<t.length;e++)if(!t[e].parent)return e;return-1},remove:function(t){for(var e=i.CanvasPool.pool,s=0;s<e.length;s++)e[s].parent===t&&(e[s].parent=null,e[s].canvas.width=1,e[s].canvas.height=1)},removeByCanvas:function(t){for(var e=i.CanvasPool.pool,s=0;s<e.length;s++)e[s].canvas===t&&(e[s].parent=null,e[s].canvas.width=1,e[s].canvas.height=1)},getTotal:function(){for(var t=i.CanvasPool.pool,e=0,s=0;s<t.length;s++)t[s].parent&&e++;return e},getFree:function(){for(var t=i.CanvasPool.pool,e=0,s=0;s<t.length;s++)t[s].parent||e++;return e}},i.CanvasPool.pool=[],i.initDefaultShaders=function(){},i.CompileVertexShader=function(t,e){return i._CompileShader(t,e,t.VERTEX_SHADER)},i.CompileFragmentShader=function(t,e){return i._CompileShader(t,e,t.FRAGMENT_SHADER)},i._CompileShader=function(t,e,i){var s=e;Array.isArray(e)&&(s=e.join("\n"));var n=t.createShader(i);return t.shaderSource(n,s),t.compileShader(n),t.getShaderParameter(n,t.COMPILE_STATUS)?n:(window.console.log(t.getShaderInfoLog(n)),null)},i.compileProgram=function(t,e,s){var n=i.CompileFragmentShader(t,s),r=i.CompileVertexShader(t,e),o=t.createProgram();return t.attachShader(o,r),t.attachShader(o,n),t.linkProgram(o),t.getProgramParameter(o,t.LINK_STATUS)||(window.console.log(t.getProgramInfoLog(o)),window.console.log("Could not initialise shaders")),o},i.PixiShader=function(t){this._UID=i._UID++,this.gl=t,this.program=null,this.fragmentSrc=["precision lowp float;","varying vec2 vTextureCoord;","varying vec4 vColor;","uniform sampler2D uSampler;","void main(void) {"," gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;","}"],this.textureCount=0,this.firstRun=!0,this.dirty=!0,this.attributes=[],this.init()},i.PixiShader.prototype.constructor=i.PixiShader,i.PixiShader.prototype.init=function(){var t=this.gl,e=i.compileProgram(t,this.vertexSrc||i.PixiShader.defaultVertexSrc,this.fragmentSrc);t.useProgram(e),this.uSampler=t.getUniformLocation(e,"uSampler"),this.projectionVector=t.getUniformLocation(e,"projectionVector"),this.offsetVector=t.getUniformLocation(e,"offsetVector"),this.dimensions=t.getUniformLocation(e,"dimensions"),this.aVertexPosition=t.getAttribLocation(e,"aVertexPosition"),this.aTextureCoord=t.getAttribLocation(e,"aTextureCoord"),this.colorAttribute=t.getAttribLocation(e,"aColor"),-1===this.colorAttribute&&(this.colorAttribute=2),this.attributes=[this.aVertexPosition,this.aTextureCoord,this.colorAttribute];for(var s in this.uniforms)this.uniforms[s].uniformLocation=t.getUniformLocation(e,s);this.initUniforms(),this.program=e},i.PixiShader.prototype.initUniforms=function(){this.textureCount=1;var t,e=this.gl;for(var i in this.uniforms){t=this.uniforms[i];var s=t.type;"sampler2D"===s?(t._init=!1,null!==t.value&&this.initSampler2D(t)):"mat2"===s||"mat3"===s||"mat4"===s?(t.glMatrix=!0,t.glValueLength=1,"mat2"===s?t.glFunc=e.uniformMatrix2fv:"mat3"===s?t.glFunc=e.uniformMatrix3fv:"mat4"===s&&(t.glFunc=e.uniformMatrix4fv)):(t.glFunc=e["uniform"+s],t.glValueLength="2f"===s||"2i"===s?2:"3f"===s||"3i"===s?3:"4f"===s||"4i"===s?4:1)}},i.PixiShader.prototype.initSampler2D=function(t){if(t.value&&t.value.baseTexture&&t.value.baseTexture.hasLoaded){var e=this.gl;if(e.activeTexture(e["TEXTURE"+this.textureCount]),e.bindTexture(e.TEXTURE_2D,t.value.baseTexture._glTextures[e.id]),t.textureData){var i=t.textureData,s=i.magFilter?i.magFilter:e.LINEAR,n=i.minFilter?i.minFilter:e.LINEAR,r=i.wrapS?i.wrapS:e.CLAMP_TO_EDGE,o=i.wrapT?i.wrapT:e.CLAMP_TO_EDGE,a=i.luminance?e.LUMINANCE:e.RGBA;if(i.repeat&&(r=e.REPEAT,o=e.REPEAT),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!!i.flipY),i.width){var h=i.width?i.width:512,l=i.height?i.height:2,c=i.border?i.border:0;e.texImage2D(e.TEXTURE_2D,0,a,h,l,c,a,e.UNSIGNED_BYTE,null)}else e.texImage2D(e.TEXTURE_2D,0,a,e.RGBA,e.UNSIGNED_BYTE,t.value.baseTexture.source);e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,s),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,n),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,r),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,o)}e.uniform1i(t.uniformLocation,this.textureCount),t._init=!0,this.textureCount++}},i.PixiShader.prototype.syncUniforms=function(){this.textureCount=1;var t,e=this.gl;for(var s in this.uniforms)t=this.uniforms[s],1===t.glValueLength?!0===t.glMatrix?t.glFunc.call(e,t.uniformLocation,t.transpose,t.value):t.glFunc.call(e,t.uniformLocation,t.value):2===t.glValueLength?t.glFunc.call(e,t.uniformLocation,t.value.x,t.value.y):3===t.glValueLength?t.glFunc.call(e,t.uniformLocation,t.value.x,t.value.y,t.value.z):4===t.glValueLength?t.glFunc.call(e,t.uniformLocation,t.value.x,t.value.y,t.value.z,t.value.w):"sampler2D"===t.type&&(t._init?(e.activeTexture(e["TEXTURE"+this.textureCount]),t.value.baseTexture._dirty[e.id]?i.instances[e.id].updateTexture(t.value.baseTexture):e.bindTexture(e.TEXTURE_2D,t.value.baseTexture._glTextures[e.id]),e.uniform1i(t.uniformLocation,this.textureCount),this.textureCount++):this.initSampler2D(t))},i.PixiShader.prototype.destroy=function(){this.gl.deleteProgram(this.program),this.uniforms=null,this.gl=null,this.attributes=null},i.PixiShader.defaultVertexSrc=["attribute vec2 aVertexPosition;","attribute vec2 aTextureCoord;","attribute vec4 aColor;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","varying vec2 vTextureCoord;","varying vec4 vColor;","const vec2 center = vec2(-1.0, 1.0);","void main(void) {"," gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);"," vTextureCoord = aTextureCoord;"," vColor = vec4(aColor.rgb * aColor.a, aColor.a);","}"],i.PixiFastShader=function(t){this._UID=i._UID++,this.gl=t,this.program=null,this.fragmentSrc=["precision lowp float;","varying vec2 vTextureCoord;","varying float vColor;","uniform sampler2D uSampler;","void main(void) {"," gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;","}"],this.vertexSrc=["attribute vec2 aVertexPosition;","attribute vec2 aPositionCoord;","attribute vec2 aScale;","attribute float aRotation;","attribute vec2 aTextureCoord;","attribute float aColor;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","uniform mat3 uMatrix;","varying vec2 vTextureCoord;","varying float vColor;","const vec2 center = vec2(-1.0, 1.0);","void main(void) {"," vec2 v;"," vec2 sv = aVertexPosition * aScale;"," v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);"," v.y = (sv.x) * sin(aRotation) + (sv.y) * cos(aRotation);"," v = ( uMatrix * vec3(v + aPositionCoord , 1.0) ).xy ;"," gl_Position = vec4( ( v / projectionVector) + center , 0.0, 1.0);"," vTextureCoord = aTextureCoord;"," vColor = aColor;","}"],this.textureCount=0,this.init()},i.PixiFastShader.prototype.constructor=i.PixiFastShader,i.PixiFastShader.prototype.init=function(){var t=this.gl,e=i.compileProgram(t,this.vertexSrc,this.fragmentSrc);t.useProgram(e),this.uSampler=t.getUniformLocation(e,"uSampler"),this.projectionVector=t.getUniformLocation(e,"projectionVector"),this.offsetVector=t.getUniformLocation(e,"offsetVector"),this.dimensions=t.getUniformLocation(e,"dimensions"),this.uMatrix=t.getUniformLocation(e,"uMatrix"),this.aVertexPosition=t.getAttribLocation(e,"aVertexPosition"),this.aPositionCoord=t.getAttribLocation(e,"aPositionCoord"),this.aScale=t.getAttribLocation(e,"aScale"),this.aRotation=t.getAttribLocation(e,"aRotation"),this.aTextureCoord=t.getAttribLocation(e,"aTextureCoord"),this.colorAttribute=t.getAttribLocation(e,"aColor"),-1===this.colorAttribute&&(this.colorAttribute=2),this.attributes=[this.aVertexPosition,this.aPositionCoord,this.aScale,this.aRotation,this.aTextureCoord,this.colorAttribute],this.program=e},i.PixiFastShader.prototype.destroy=function(){this.gl.deleteProgram(this.program),this.uniforms=null,this.gl=null,this.attributes=null},i.StripShader=function(t){this._UID=i._UID++,this.gl=t,this.program=null,this.fragmentSrc=["precision mediump float;","varying vec2 vTextureCoord;","uniform float alpha;","uniform sampler2D uSampler;","void main(void) {"," gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;","}"],this.vertexSrc=["attribute vec2 aVertexPosition;","attribute vec2 aTextureCoord;","uniform mat3 translationMatrix;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","varying vec2 vTextureCoord;","void main(void) {"," vec3 v = translationMatrix * vec3(aVertexPosition , 1.0);"," v -= offsetVector.xyx;"," gl_Position = vec4( v.x / projectionVector.x -1.0, v.y / -projectionVector.y + 1.0 , 0.0, 1.0);"," vTextureCoord = aTextureCoord;","}"],this.init()},i.StripShader.prototype.constructor=i.StripShader,i.StripShader.prototype.init=function(){var t=this.gl,e=i.compileProgram(t,this.vertexSrc,this.fragmentSrc);t.useProgram(e),this.uSampler=t.getUniformLocation(e,"uSampler"),this.projectionVector=t.getUniformLocation(e,"projectionVector"),this.offsetVector=t.getUniformLocation(e,"offsetVector"),this.colorAttribute=t.getAttribLocation(e,"aColor"),this.aVertexPosition=t.getAttribLocation(e,"aVertexPosition"),this.aTextureCoord=t.getAttribLocation(e,"aTextureCoord"),this.attributes=[this.aVertexPosition,this.aTextureCoord],this.translationMatrix=t.getUniformLocation(e,"translationMatrix"),this.alpha=t.getUniformLocation(e,"alpha"),this.program=e},i.StripShader.prototype.destroy=function(){this.gl.deleteProgram(this.program),this.uniforms=null,this.gl=null,this.attribute=null},i.PrimitiveShader=function(t){this._UID=i._UID++,this.gl=t,this.program=null,this.fragmentSrc=["precision mediump float;","varying vec4 vColor;","void main(void) {"," gl_FragColor = vColor;","}"],this.vertexSrc=["attribute vec2 aVertexPosition;","attribute vec4 aColor;","uniform mat3 translationMatrix;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","uniform float alpha;","uniform float flipY;","uniform vec3 tint;","varying vec4 vColor;","void main(void) {"," vec3 v = translationMatrix * vec3(aVertexPosition , 1.0);"," v -= offsetVector.xyx;"," gl_Position = vec4( v.x / projectionVector.x -1.0, (v.y / projectionVector.y * -flipY) + flipY , 0.0, 1.0);"," vColor = aColor * vec4(tint * alpha, alpha);","}"],this.init()},i.PrimitiveShader.prototype.constructor=i.PrimitiveShader,i.PrimitiveShader.prototype.init=function(){var t=this.gl,e=i.compileProgram(t,this.vertexSrc,this.fragmentSrc);t.useProgram(e),this.projectionVector=t.getUniformLocation(e,"projectionVector"),this.offsetVector=t.getUniformLocation(e,"offsetVector"),this.tintColor=t.getUniformLocation(e,"tint"),this.flipY=t.getUniformLocation(e,"flipY"),this.aVertexPosition=t.getAttribLocation(e,"aVertexPosition"),this.colorAttribute=t.getAttribLocation(e,"aColor"),this.attributes=[this.aVertexPosition,this.colorAttribute],this.translationMatrix=t.getUniformLocation(e,"translationMatrix"),this.alpha=t.getUniformLocation(e,"alpha"),this.program=e},i.PrimitiveShader.prototype.destroy=function(){this.gl.deleteProgram(this.program),this.uniforms=null,this.gl=null,this.attributes=null},i.ComplexPrimitiveShader=function(t){this._UID=i._UID++,this.gl=t,this.program=null,this.fragmentSrc=["precision mediump float;","varying vec4 vColor;","void main(void) {"," gl_FragColor = vColor;","}"],this.vertexSrc=["attribute vec2 aVertexPosition;","uniform mat3 translationMatrix;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","uniform vec3 tint;","uniform float alpha;","uniform vec3 color;","uniform float flipY;","varying vec4 vColor;","void main(void) {"," vec3 v = translationMatrix * vec3(aVertexPosition , 1.0);"," v -= offsetVector.xyx;"," gl_Position = vec4( v.x / projectionVector.x -1.0, (v.y / projectionVector.y * -flipY) + flipY , 0.0, 1.0);"," vColor = vec4(color * alpha * tint, alpha);","}"],this.init()},i.ComplexPrimitiveShader.prototype.constructor=i.ComplexPrimitiveShader,i.ComplexPrimitiveShader.prototype.init=function(){var t=this.gl,e=i.compileProgram(t,this.vertexSrc,this.fragmentSrc);t.useProgram(e),this.projectionVector=t.getUniformLocation(e,"projectionVector"),this.offsetVector=t.getUniformLocation(e,"offsetVector"),this.tintColor=t.getUniformLocation(e,"tint"),this.color=t.getUniformLocation(e,"color"),this.flipY=t.getUniformLocation(e,"flipY"),this.aVertexPosition=t.getAttribLocation(e,"aVertexPosition"),this.attributes=[this.aVertexPosition,this.colorAttribute],this.translationMatrix=t.getUniformLocation(e,"translationMatrix"),this.alpha=t.getUniformLocation(e,"alpha"),this.program=e},i.ComplexPrimitiveShader.prototype.destroy=function(){this.gl.deleteProgram(this.program),this.uniforms=null,this.gl=null,this.attribute=null},i.glContexts=[],i.instances=[],i.WebGLRenderer=function(t){this.game=t,i.defaultRenderer||(i.defaultRenderer=this),this.type=i.WEBGL_RENDERER,this.resolution=t.resolution,this.transparent=t.transparent,this.autoResize=!1,this.preserveDrawingBuffer=t.preserveDrawingBuffer,this.clearBeforeRender=t.clearBeforeRender,this.width=t.width,this.height=t.height,this.view=t.canvas,this._contextOptions={alpha:this.transparent,antialias:t.antialias,premultipliedAlpha:this.transparent&&"notMultiplied"!==this.transparent,stencil:!0,preserveDrawingBuffer:this.preserveDrawingBuffer},this.projection=new i.Point,this.offset=new i.Point,this.shaderManager=new i.WebGLShaderManager,this.spriteBatch=new i.WebGLSpriteBatch,this.maskManager=new i.WebGLMaskManager,this.filterManager=new i.WebGLFilterManager,this.stencilManager=new i.WebGLStencilManager,this.blendModeManager=new i.WebGLBlendModeManager,this.renderSession={},this.renderSession.game=this.game,this.renderSession.gl=this.gl,this.renderSession.drawCount=0,this.renderSession.shaderManager=this.shaderManager,this.renderSession.maskManager=this.maskManager,this.renderSession.filterManager=this.filterManager,this.renderSession.blendModeManager=this.blendModeManager,this.renderSession.spriteBatch=this.spriteBatch,this.renderSession.stencilManager=this.stencilManager,this.renderSession.renderer=this,this.renderSession.resolution=this.resolution,this.initContext(),this.mapBlendModes()},i.WebGLRenderer.prototype.constructor=i.WebGLRenderer,i.WebGLRenderer.prototype.initContext=function(){var t=this.view.getContext("webgl",this._contextOptions)||this.view.getContext("experimental-webgl",this._contextOptions);if(this.gl=t,!t)throw new Error("This browser does not support webGL. Try using the canvas renderer");this.glContextId=t.id=i.WebGLRenderer.glContextId++,i.glContexts[this.glContextId]=t,i.instances[this.glContextId]=this,t.disable(t.DEPTH_TEST),t.disable(t.CULL_FACE),t.enable(t.BLEND),this.shaderManager.setContext(t),this.spriteBatch.setContext(t),this.maskManager.setContext(t),this.filterManager.setContext(t),this.blendModeManager.setContext(t),this.stencilManager.setContext(t),this.renderSession.gl=this.gl,this.resize(this.width,this.height)},i.WebGLRenderer.prototype.render=function(t){if(!this.contextLost){var e=this.gl;e.viewport(0,0,this.width,this.height),e.bindFramebuffer(e.FRAMEBUFFER,null),this.game.clearBeforeRender&&(e.clearColor(t._bgColor.r,t._bgColor.g,t._bgColor.b,t._bgColor.a),e.clear(e.COLOR_BUFFER_BIT)),this.offset.x=this.game.camera._shake.x,this.offset.y=this.game.camera._shake.y,this.renderDisplayObject(t,this.projection)}},i.WebGLRenderer.prototype.renderDisplayObject=function(t,e,s,n){this.renderSession.blendModeManager.setBlendMode(i.blendModes.NORMAL),this.renderSession.drawCount=0,this.renderSession.flipY=s?-1:1,this.renderSession.projection=e,this.renderSession.offset=this.offset,this.spriteBatch.begin(this.renderSession),this.filterManager.begin(this.renderSession,s),t._renderWebGL(this.renderSession,n),this.spriteBatch.end()},i.WebGLRenderer.prototype.resize=function(t,e){this.width=t*this.resolution,this.height=e*this.resolution,this.view.width=this.width,this.view.height=this.height,this.autoResize&&(this.view.style.width=this.width/this.resolution+"px",this.view.style.height=this.height/this.resolution+"px"),this.gl.viewport(0,0,this.width,this.height),this.projection.x=this.width/2/this.resolution,this.projection.y=-this.height/2/this.resolution},i.WebGLRenderer.prototype.updateTexture=function(t){if(!t.hasLoaded)return!1;var e=this.gl;return t._glTextures[e.id]||(t._glTextures[e.id]=e.createTexture()),e.bindTexture(e.TEXTURE_2D,t._glTextures[e.id]),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultipliedAlpha),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t.source),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t.scaleMode===i.scaleModes.LINEAR?e.LINEAR:e.NEAREST),t.mipmap&&i.isPowerOfTwo(t.width,t.height)?(e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t.scaleMode===i.scaleModes.LINEAR?e.LINEAR_MIPMAP_LINEAR:e.NEAREST_MIPMAP_NEAREST),e.generateMipmap(e.TEXTURE_2D)):e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t.scaleMode===i.scaleModes.LINEAR?e.LINEAR:e.NEAREST),t._powerOf2?(e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT)):(e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),t._dirty[e.id]=!1,!0},i.WebGLRenderer.prototype.destroy=function(){i.glContexts[this.glContextId]=null,this.projection=null,this.offset=null,this.shaderManager.destroy(),this.spriteBatch.destroy(),this.maskManager.destroy(),this.filterManager.destroy(),this.shaderManager=null,this.spriteBatch=null,this.maskManager=null,this.filterManager=null,this.gl=null,this.renderSession=null,i.CanvasPool.remove(this),i.instances[this.glContextId]=null,i.WebGLRenderer.glContextId--},i.WebGLRenderer.prototype.mapBlendModes=function(){var t=this.gl;if(!i.blendModesWebGL){var e=[],s=i.blendModes;e[s.NORMAL]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.ADD]=[t.SRC_ALPHA,t.DST_ALPHA],e[s.MULTIPLY]=[t.DST_COLOR,t.ONE_MINUS_SRC_ALPHA],e[s.SCREEN]=[t.SRC_ALPHA,t.ONE],e[s.OVERLAY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.DARKEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.LIGHTEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.COLOR_DODGE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.COLOR_BURN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.HARD_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.SOFT_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.DIFFERENCE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.EXCLUSION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.HUE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.SATURATION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.COLOR]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.LUMINOSITY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],i.blendModesWebGL=e}},i.WebGLRenderer.glContextId=0,i.WebGLBlendModeManager=function(){this.currentBlendMode=99999},i.WebGLBlendModeManager.prototype.constructor=i.WebGLBlendModeManager,i.WebGLBlendModeManager.prototype.setContext=function(t){this.gl=t},i.WebGLBlendModeManager.prototype.setBlendMode=function(t){if(this.currentBlendMode===t)return!1;this.currentBlendMode=t;var e=i.blendModesWebGL[this.currentBlendMode];return e&&this.gl.blendFunc(e[0],e[1]),!0},i.WebGLBlendModeManager.prototype.destroy=function(){this.gl=null},i.WebGLMaskManager=function(){},i.WebGLMaskManager.prototype.constructor=i.WebGLMaskManager,i.WebGLMaskManager.prototype.setContext=function(t){this.gl=t},i.WebGLMaskManager.prototype.pushMask=function(t,e){var s=e.gl;t.dirty&&i.WebGLGraphics.updateGraphics(t,s),void 0!==t._webGL[s.id]&&void 0!==t._webGL[s.id].data&&0!==t._webGL[s.id].data.length&&e.stencilManager.pushStencil(t,t._webGL[s.id].data[0],e)},i.WebGLMaskManager.prototype.popMask=function(t,e){var i=this.gl;void 0!==t._webGL[i.id]&&void 0!==t._webGL[i.id].data&&0!==t._webGL[i.id].data.length&&e.stencilManager.popStencil(t,t._webGL[i.id].data[0],e)},i.WebGLMaskManager.prototype.destroy=function(){this.gl=null},i.WebGLStencilManager=function(){this.stencilStack=[],this.reverse=!0,this.count=0},i.WebGLStencilManager.prototype.setContext=function(t){this.gl=t},i.WebGLStencilManager.prototype.pushStencil=function(t,e,i){var s=this.gl;this.bindGraphics(t,e,i),0===this.stencilStack.length&&(s.enable(s.STENCIL_TEST),s.clear(s.STENCIL_BUFFER_BIT),this.reverse=!0,this.count=0),this.stencilStack.push(e);var n=this.count;s.colorMask(!1,!1,!1,!1),s.stencilFunc(s.ALWAYS,0,255),s.stencilOp(s.KEEP,s.KEEP,s.INVERT),1===e.mode?(s.drawElements(s.TRIANGLE_FAN,e.indices.length-4,s.UNSIGNED_SHORT,0),this.reverse?(s.stencilFunc(s.EQUAL,255-n,255),s.stencilOp(s.KEEP,s.KEEP,s.DECR)):(s.stencilFunc(s.EQUAL,n,255),s.stencilOp(s.KEEP,s.KEEP,s.INCR)),s.drawElements(s.TRIANGLE_FAN,4,s.UNSIGNED_SHORT,2*(e.indices.length-4)),this.reverse?s.stencilFunc(s.EQUAL,255-(n+1),255):s.stencilFunc(s.EQUAL,n+1,255),this.reverse=!this.reverse):(this.reverse?(s.stencilFunc(s.EQUAL,n,255),s.stencilOp(s.KEEP,s.KEEP,s.INCR)):(s.stencilFunc(s.EQUAL,255-n,255),s.stencilOp(s.KEEP,s.KEEP,s.DECR)),s.drawElements(s.TRIANGLE_STRIP,e.indices.length,s.UNSIGNED_SHORT,0),this.reverse?s.stencilFunc(s.EQUAL,n+1,255):s.stencilFunc(s.EQUAL,255-(n+1),255)),s.colorMask(!0,!0,!0,!0),s.stencilOp(s.KEEP,s.KEEP,s.KEEP),this.count++},i.WebGLStencilManager.prototype.bindGraphics=function(t,e,s){this._currentGraphics=t;var n,r=this.gl,o=s.projection,a=s.offset;1===e.mode?(n=s.shaderManager.complexPrimitiveShader,s.shaderManager.setShader(n),r.uniform1f(n.flipY,s.flipY),r.uniformMatrix3fv(n.translationMatrix,!1,t.worldTransform.toArray(!0)),r.uniform2f(n.projectionVector,o.x,-o.y),r.uniform2f(n.offsetVector,-a.x,-a.y),r.uniform3fv(n.tintColor,i.hex2rgb(t.tint)),r.uniform3fv(n.color,e.color),r.uniform1f(n.alpha,t.worldAlpha*e.alpha),r.bindBuffer(r.ARRAY_BUFFER,e.buffer),r.vertexAttribPointer(n.aVertexPosition,2,r.FLOAT,!1,8,0),r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,e.indexBuffer)):(n=s.shaderManager.primitiveShader,s.shaderManager.setShader(n),r.uniformMatrix3fv(n.translationMatrix,!1,t.worldTransform.toArray(!0)),r.uniform1f(n.flipY,s.flipY),r.uniform2f(n.projectionVector,o.x,-o.y),r.uniform2f(n.offsetVector,-a.x,-a.y),r.uniform3fv(n.tintColor,i.hex2rgb(t.tint)),r.uniform1f(n.alpha,t.worldAlpha),r.bindBuffer(r.ARRAY_BUFFER,e.buffer),r.vertexAttribPointer(n.aVertexPosition,2,r.FLOAT,!1,24,0),r.vertexAttribPointer(n.colorAttribute,4,r.FLOAT,!1,24,8),r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,e.indexBuffer))},i.WebGLStencilManager.prototype.popStencil=function(t,e,i){var s=this.gl;if(this.stencilStack.pop(),this.count--,0===this.stencilStack.length)s.disable(s.STENCIL_TEST);else{var n=this.count;this.bindGraphics(t,e,i),s.colorMask(!1,!1,!1,!1),1===e.mode?(this.reverse=!this.reverse,this.reverse?(s.stencilFunc(s.EQUAL,255-(n+1),255),s.stencilOp(s.KEEP,s.KEEP,s.INCR)):(s.stencilFunc(s.EQUAL,n+1,255),s.stencilOp(s.KEEP,s.KEEP,s.DECR)),s.drawElements(s.TRIANGLE_FAN,4,s.UNSIGNED_SHORT,2*(e.indices.length-4)),s.stencilFunc(s.ALWAYS,0,255),s.stencilOp(s.KEEP,s.KEEP,s.INVERT),s.drawElements(s.TRIANGLE_FAN,e.indices.length-4,s.UNSIGNED_SHORT,0),this.reverse?s.stencilFunc(s.EQUAL,n,255):s.stencilFunc(s.EQUAL,255-n,255)):(this.reverse?(s.stencilFunc(s.EQUAL,n+1,255),s.stencilOp(s.KEEP,s.KEEP,s.DECR)):(s.stencilFunc(s.EQUAL,255-(n+1),255),s.stencilOp(s.KEEP,s.KEEP,s.INCR)),s.drawElements(s.TRIANGLE_STRIP,e.indices.length,s.UNSIGNED_SHORT,0),this.reverse?s.stencilFunc(s.EQUAL,n,255):s.stencilFunc(s.EQUAL,255-n,255)),s.colorMask(!0,!0,!0,!0),s.stencilOp(s.KEEP,s.KEEP,s.KEEP)}},i.WebGLStencilManager.prototype.destroy=function(){this.stencilStack=null,this.gl=null},i.WebGLShaderManager=function(){this.maxAttibs=10,this.attribState=[],this.tempAttribState=[];for(var t=0;t<this.maxAttibs;t++)this.attribState[t]=!1;this.stack=[]},i.WebGLShaderManager.prototype.constructor=i.WebGLShaderManager,i.WebGLShaderManager.prototype.setContext=function(t){this.gl=t,this.primitiveShader=new i.PrimitiveShader(t),this.complexPrimitiveShader=new i.ComplexPrimitiveShader(t),this.defaultShader=new i.PixiShader(t),this.fastShader=new i.PixiFastShader(t),this.stripShader=new i.StripShader(t),this.setShader(this.defaultShader)},i.WebGLShaderManager.prototype.setAttribs=function(t){var e;for(e=0;e<this.tempAttribState.length;e++)this.tempAttribState[e]=!1;for(e=0;e<t.length;e++){var i=t[e];this.tempAttribState[i]=!0}var s=this.gl;for(e=0;e<this.attribState.length;e++)this.attribState[e]!==this.tempAttribState[e]&&(this.attribState[e]=this.tempAttribState[e],this.tempAttribState[e]?s.enableVertexAttribArray(e):s.disableVertexAttribArray(e))},i.WebGLShaderManager.prototype.setShader=function(t){return this._currentId!==t._UID&&(this._currentId=t._UID,this.currentShader=t,this.gl.useProgram(t.program),this.setAttribs(t.attributes),!0)},i.WebGLShaderManager.prototype.destroy=function(){this.attribState=null,this.tempAttribState=null,this.primitiveShader.destroy(),this.complexPrimitiveShader.destroy(),this.defaultShader.destroy(),this.fastShader.destroy(),this.stripShader.destroy(),this.gl=null},i.WebGLSpriteBatch=function(){this.vertSize=5,this.size=2e3;var t=4*this.size*4*this.vertSize,e=6*this.size;this.vertices=new i.ArrayBuffer(t),this.positions=new i.Float32Array(this.vertices),this.colors=new i.Uint32Array(this.vertices),this.indices=new i.Uint16Array(e),this.lastIndexCount=0;for(var s=0,n=0;s<e;s+=6,n+=4)this.indices[s+0]=n+0,this.indices[s+1]=n+1,this.indices[s+2]=n+2,this.indices[s+3]=n+0,this.indices[s+4]=n+2,this.indices[s+5]=n+3;this.drawing=!1,this.currentBatchSize=0,this.currentBaseTexture=null,this.dirty=!0,this.textures=[],this.blendModes=[],this.shaders=[],this.sprites=[],this.defaultShader=new i.AbstractFilter(["precision lowp float;","varying vec2 vTextureCoord;","varying vec4 vColor;","uniform sampler2D uSampler;","void main(void) {"," gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;","}"])},i.WebGLSpriteBatch.prototype.setContext=function(t){this.gl=t,this.vertexBuffer=t.createBuffer(),this.indexBuffer=t.createBuffer(),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,this.indices,t.STATIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),t.bufferData(t.ARRAY_BUFFER,this.vertices,t.DYNAMIC_DRAW),this.currentBlendMode=99999;var e=new i.PixiShader(t);e.fragmentSrc=this.defaultShader.fragmentSrc,e.uniforms={},e.init(),this.defaultShader.shaders[t.id]=e},i.WebGLSpriteBatch.prototype.begin=function(t){this.renderSession=t,this.shader=this.renderSession.shaderManager.defaultShader,this.start()},i.WebGLSpriteBatch.prototype.end=function(){this.flush()},i.WebGLSpriteBatch.prototype.render=function(t,e){var i=t.texture,s=t.worldTransform;e&&(s=e),this.currentBatchSize>=this.size&&(this.flush(),this.currentBaseTexture=i.baseTexture);var n=i._uvs;if(n){var r,o,a,h,l=t.anchor.x,c=t.anchor.y;if(i.trim){var u=i.trim;o=u.x-l*u.width,r=o+i.crop.width,h=u.y-c*u.height,a=h+i.crop.height}else r=i.frame.width*(1-l),o=i.frame.width*-l,a=i.frame.height*(1-c),h=i.frame.height*-c;var d=4*this.currentBatchSize*this.vertSize,p=i.baseTexture.resolution,f=s.a/p,g=s.b/p,m=s.c/p,y=s.d/p,v=s.tx,b=s.ty,x=this.colors,w=this.positions;this.renderSession.roundPixels?(w[d]=f*o+m*h+v|0,w[d+1]=y*h+g*o+b|0,w[d+5]=f*r+m*h+v|0,w[d+6]=y*h+g*r+b|0,w[d+10]=f*r+m*a+v|0,w[d+11]=y*a+g*r+b|0,w[d+15]=f*o+m*a+v|0,w[d+16]=y*a+g*o+b|0):(w[d]=f*o+m*h+v,w[d+1]=y*h+g*o+b,w[d+5]=f*r+m*h+v,w[d+6]=y*h+g*r+b,w[d+10]=f*r+m*a+v,w[d+11]=y*a+g*r+b,w[d+15]=f*o+m*a+v,w[d+16]=y*a+g*o+b),w[d+2]=n.x0,w[d+3]=n.y0,w[d+7]=n.x1,w[d+8]=n.y1,w[d+12]=n.x2,w[d+13]=n.y2,w[d+17]=n.x3,w[d+18]=n.y3;var _=t.tint;x[d+4]=x[d+9]=x[d+14]=x[d+19]=(_>>16)+(65280&_)+((255&_)<<16)+(255*t.worldAlpha<<24),this.sprites[this.currentBatchSize++]=t}},i.WebGLSpriteBatch.prototype.renderTilingSprite=function(t){var e=t.tilingTexture;this.currentBatchSize>=this.size&&(this.flush(),this.currentBaseTexture=e.baseTexture),t._uvs||(t._uvs=new i.TextureUvs);var s=t._uvs,n=e.baseTexture.width,r=e.baseTexture.height;t.tilePosition.x%=n*t.tileScaleOffset.x,t.tilePosition.y%=r*t.tileScaleOffset.y;var o=t.tilePosition.x/(n*t.tileScaleOffset.x),a=t.tilePosition.y/(r*t.tileScaleOffset.y),h=t.width/n/(t.tileScale.x*t.tileScaleOffset.x),l=t.height/r/(t.tileScale.y*t.tileScaleOffset.y);s.x0=0-o,s.y0=0-a,s.x1=1*h-o,s.y1=0-a,s.x2=1*h-o,s.y2=1*l-a,s.x3=0-o,s.y3=1*l-a;var c=t.tint,u=(c>>16)+(65280&c)+((255&c)<<16)+(255*t.worldAlpha<<24),d=this.positions,p=this.colors,f=t.width,g=t.height,m=t.anchor.x,y=t.anchor.y,v=f*(1-m),b=f*-m,x=g*(1-y),w=g*-y,_=4*this.currentBatchSize*this.vertSize,P=e.baseTexture.resolution,T=t.worldTransform,C=T.a/P,S=T.b/P,A=T.c/P,E=T.d/P,I=T.tx,M=T.ty;d[_++]=C*b+A*w+I,d[_++]=E*w+S*b+M,d[_++]=s.x0,d[_++]=s.y0,p[_++]=u,d[_++]=C*v+A*w+I,d[_++]=E*w+S*v+M,d[_++]=s.x1,d[_++]=s.y1,p[_++]=u,d[_++]=C*v+A*x+I,d[_++]=E*x+S*v+M,d[_++]=s.x2,d[_++]=s.y2,p[_++]=u,d[_++]=C*b+A*x+I,d[_++]=E*x+S*b+M,d[_++]=s.x3,d[_++]=s.y3,p[_++]=u,this.sprites[this.currentBatchSize++]=t},i.WebGLSpriteBatch.prototype.flush=function(){if(0!==this.currentBatchSize){var t,e=this.gl;if(this.dirty){this.dirty=!1,e.activeTexture(e.TEXTURE0),e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer),t=this.defaultShader.shaders[e.id];var s=4*this.vertSize;e.vertexAttribPointer(t.aVertexPosition,2,e.FLOAT,!1,s,0),e.vertexAttribPointer(t.aTextureCoord,2,e.FLOAT,!1,s,8),e.vertexAttribPointer(t.colorAttribute,4,e.UNSIGNED_BYTE,!0,s,16)}if(this.currentBatchSize>.5*this.size)e.bufferSubData(e.ARRAY_BUFFER,0,this.vertices);else{var n=this.positions.subarray(0,4*this.currentBatchSize*this.vertSize);e.bufferSubData(e.ARRAY_BUFFER,0,n)}for(var r,o,a,h,l=0,c=0,u=null,d=this.renderSession.blendModeManager.currentBlendMode,p=null,f=!1,g=!1,m=0,y=this.currentBatchSize;m<y;m++){h=this.sprites[m],r=h.tilingTexture?h.tilingTexture.baseTexture:h.texture.baseTexture,o=h.blendMode,a=h.shader||this.defaultShader,f=d!==o,g=p!==a;var v=r.skipRender;if(v&&h.children.length>0&&(v=!1),(u!==r&&!v||f||g)&&(this.renderBatch(u,l,c),c=m,l=0,u=r,f&&(d=o,this.renderSession.blendModeManager.setBlendMode(d)),g)){p=a,t=p.shaders[e.id],t||(t=new i.PixiShader(e),t.fragmentSrc=p.fragmentSrc,t.uniforms=p.uniforms,t.init(),p.shaders[e.id]=t),this.renderSession.shaderManager.setShader(t),t.dirty&&t.syncUniforms();var b=this.renderSession.projection;e.uniform2f(t.projectionVector,b.x,b.y);var x=this.renderSession.offset;e.uniform2f(t.offsetVector,x.x,x.y)}l++}this.renderBatch(u,l,c),this.currentBatchSize=0}},i.WebGLSpriteBatch.prototype.renderBatch=function(t,e,i){if(0!==e){var s=this.gl;if(t._dirty[s.id]){if(!this.renderSession.renderer.updateTexture(t))return}else s.bindTexture(s.TEXTURE_2D,t._glTextures[s.id]);s.drawElements(s.TRIANGLES,6*e,s.UNSIGNED_SHORT,6*i*2),this.renderSession.drawCount++}},i.WebGLSpriteBatch.prototype.stop=function(){this.flush(),this.dirty=!0},i.WebGLSpriteBatch.prototype.start=function(){this.dirty=!0},i.WebGLSpriteBatch.prototype.destroy=function(){this.vertices=null,this.indices=null,this.gl.deleteBuffer(this.vertexBuffer),this.gl.deleteBuffer(this.indexBuffer),this.currentBaseTexture=null,this.gl=null},i.WebGLFastSpriteBatch=function(t){this.vertSize=10,this.maxSize=6e3,this.size=this.maxSize;var e=4*this.size*this.vertSize,s=6*this.maxSize;this.vertices=new i.Float32Array(e),this.indices=new i.Uint16Array(s),this.vertexBuffer=null,this.indexBuffer=null,this.lastIndexCount=0;for(var n=0,r=0;n<s;n+=6,r+=4)this.indices[n+0]=r+0,this.indices[n+1]=r+1,this.indices[n+2]=r+2,this.indices[n+3]=r+0,this.indices[n+4]=r+2,this.indices[n+5]=r+3;this.drawing=!1,this.currentBatchSize=0,this.currentBaseTexture=null,this.currentBlendMode=0,this.renderSession=null,this.shader=null,this.matrix=null,this.setContext(t)},i.WebGLFastSpriteBatch.prototype.constructor=i.WebGLFastSpriteBatch,i.WebGLFastSpriteBatch.prototype.setContext=function(t){this.gl=t,this.vertexBuffer=t.createBuffer(),this.indexBuffer=t.createBuffer(),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,this.indices,t.STATIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),t.bufferData(t.ARRAY_BUFFER,this.vertices,t.DYNAMIC_DRAW)},i.WebGLFastSpriteBatch.prototype.begin=function(t,e){this.renderSession=e,this.shader=this.renderSession.shaderManager.fastShader,this.matrix=t.worldTransform.toArray(!0),this.start()},i.WebGLFastSpriteBatch.prototype.end=function(){this.flush()},i.WebGLFastSpriteBatch.prototype.render=function(t){var e=t.children,i=e[0];if(i.texture._uvs){this.currentBaseTexture=i.texture.baseTexture,i.blendMode!==this.renderSession.blendModeManager.currentBlendMode&&(this.flush(),this.renderSession.blendModeManager.setBlendMode(i.blendMode));for(var s=0,n=e.length;s<n;s++)this.renderSprite(e[s]);this.flush()}},i.WebGLFastSpriteBatch.prototype.renderSprite=function(t){if(t.visible&&(t.texture.baseTexture===this.currentBaseTexture||t.texture.baseTexture.skipRender||(this.flush(),this.currentBaseTexture=t.texture.baseTexture,t.texture._uvs))){var e,i,s,n,r,o,a=this.vertices;if(e=t.texture._uvs,t.texture.frame.width,t.texture.frame.height,t.texture.trim){var h=t.texture.trim;s=h.x-t.anchor.x*h.width,i=s+t.texture.crop.width,r=h.y-t.anchor.y*h.height,n=r+t.texture.crop.height}else i=t.texture.frame.width*(1-t.anchor.x),s=t.texture.frame.width*-t.anchor.x,n=t.texture.frame.height*(1-t.anchor.y),r=t.texture.frame.height*-t.anchor.y;o=4*this.currentBatchSize*this.vertSize,a[o++]=s,a[o++]=r,a[o++]=t.position.x,a[o++]=t.position.y,a[o++]=t.scale.x,a[o++]=t.scale.y,a[o++]=t.rotation,a[o++]=e.x0,a[o++]=e.y1,a[o++]=t.alpha,a[o++]=i,a[o++]=r,a[o++]=t.position.x,a[o++]=t.position.y,a[o++]=t.scale.x,a[o++]=t.scale.y,a[o++]=t.rotation,a[o++]=e.x1,a[o++]=e.y1,a[o++]=t.alpha,a[o++]=i,a[o++]=n,a[o++]=t.position.x,a[o++]=t.position.y,a[o++]=t.scale.x,a[o++]=t.scale.y,a[o++]=t.rotation,a[o++]=e.x2,a[o++]=e.y2,a[o++]=t.alpha,a[o++]=s,a[o++]=n,a[o++]=t.position.x,a[o++]=t.position.y,a[o++]=t.scale.x,a[o++]=t.scale.y,a[o++]=t.rotation,a[o++]=e.x3,a[o++]=e.y3,a[o++]=t.alpha,this.currentBatchSize++,this.currentBatchSize>=this.size&&this.flush()}},i.WebGLFastSpriteBatch.prototype.flush=function(){if(0!==this.currentBatchSize){var t=this.gl;if(this.currentBaseTexture._glTextures[t.id]||this.renderSession.renderer.updateTexture(this.currentBaseTexture,t),t.bindTexture(t.TEXTURE_2D,this.currentBaseTexture._glTextures[t.id]),this.currentBatchSize>.5*this.size)t.bufferSubData(t.ARRAY_BUFFER,0,this.vertices);else{var e=this.vertices.subarray(0,4*this.currentBatchSize*this.vertSize);t.bufferSubData(t.ARRAY_BUFFER,0,e)}t.drawElements(t.TRIANGLES,6*this.currentBatchSize,t.UNSIGNED_SHORT,0),this.currentBatchSize=0,this.renderSession.drawCount++}},i.WebGLFastSpriteBatch.prototype.stop=function(){this.flush()},i.WebGLFastSpriteBatch.prototype.start=function(){var t=this.gl;t.activeTexture(t.TEXTURE0),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer);var e=this.renderSession.projection;t.uniform2f(this.shader.projectionVector,e.x,e.y),t.uniformMatrix3fv(this.shader.uMatrix,!1,this.matrix);var i=4*this.vertSize;t.vertexAttribPointer(this.shader.aVertexPosition,2,t.FLOAT,!1,i,0),t.vertexAttribPointer(this.shader.aPositionCoord,2,t.FLOAT,!1,i,8),t.vertexAttribPointer(this.shader.aScale,2,t.FLOAT,!1,i,16),t.vertexAttribPointer(this.shader.aRotation,1,t.FLOAT,!1,i,24),t.vertexAttribPointer(this.shader.aTextureCoord,2,t.FLOAT,!1,i,28),t.vertexAttribPointer(this.shader.colorAttribute,1,t.FLOAT,!1,i,36)},i.WebGLFilterManager=function(){this.filterStack=[],this.offsetX=0,this.offsetY=0},i.WebGLFilterManager.prototype.constructor=i.WebGLFilterManager,i.WebGLFilterManager.prototype.setContext=function(t){this.gl=t,this.texturePool=[],this.initShaderBuffers()},i.WebGLFilterManager.prototype.begin=function(t,e){this.renderSession=t,this.defaultShader=t.shaderManager.defaultShader;var i=this.renderSession.projection;this.width=2*i.x,this.height=2*-i.y,this.buffer=e},i.WebGLFilterManager.prototype.pushFilter=function(t){var e=this.gl,s=this.renderSession.projection,n=this.renderSession.offset;t._filterArea=t.target.filterArea||t.target.getBounds(),t._previous_stencil_mgr=this.renderSession.stencilManager,this.renderSession.stencilManager=new i.WebGLStencilManager,this.renderSession.stencilManager.setContext(e),e.disable(e.STENCIL_TEST),this.filterStack.push(t);var r=t.filterPasses[0];this.offsetX+=t._filterArea.x,this.offsetY+=t._filterArea.y;var o=this.texturePool.pop();o?o.resize(this.width*this.renderSession.resolution,this.height*this.renderSession.resolution):o=new i.FilterTexture(this.gl,this.width*this.renderSession.resolution,this.height*this.renderSession.resolution),e.bindTexture(e.TEXTURE_2D,o.texture);var a=t._filterArea,h=r.padding;a.x-=h,a.y-=h,a.width+=2*h,a.height+=2*h,a.x<0&&(a.x=0),a.width>this.width&&(a.width=this.width),a.y<0&&(a.y=0),a.height>this.height&&(a.height=this.height),e.bindFramebuffer(e.FRAMEBUFFER,o.frameBuffer),e.viewport(0,0,a.width*this.renderSession.resolution,a.height*this.renderSession.resolution),s.x=a.width/2,s.y=-a.height/2,n.x=-a.x,n.y=-a.y,e.colorMask(!0,!0,!0,!0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT),t._glFilterTexture=o},i.WebGLFilterManager.prototype.popFilter=function(){var t=this.gl,e=this.filterStack.pop(),s=e._filterArea,n=e._glFilterTexture,r=this.renderSession.projection,o=this.renderSession.offset;if(e.filterPasses.length>1){t.viewport(0,0,s.width*this.renderSession.resolution,s.height*this.renderSession.resolution),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),this.vertexArray[0]=0,this.vertexArray[1]=s.height,this.vertexArray[2]=s.width,this.vertexArray[3]=s.height,this.vertexArray[4]=0,this.vertexArray[5]=0,this.vertexArray[6]=s.width,this.vertexArray[7]=0,t.bufferSubData(t.ARRAY_BUFFER,0,this.vertexArray),t.bindBuffer(t.ARRAY_BUFFER,this.uvBuffer),this.uvArray[2]=s.width/this.width,this.uvArray[5]=s.height/this.height,this.uvArray[6]=s.width/this.width,this.uvArray[7]=s.height/this.height,t.bufferSubData(t.ARRAY_BUFFER,0,this.uvArray);var a=n,h=this.texturePool.pop();h||(h=new i.FilterTexture(this.gl,this.width*this.renderSession.resolution,this.height*this.renderSession.resolution)),h.resize(this.width*this.renderSession.resolution,this.height*this.renderSession.resolution),t.bindFramebuffer(t.FRAMEBUFFER,h.frameBuffer),t.clear(t.COLOR_BUFFER_BIT),t.disable(t.BLEND);for(var l=0;l<e.filterPasses.length-1;l++){var c=e.filterPasses[l];t.bindFramebuffer(t.FRAMEBUFFER,h.frameBuffer),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,a.texture),this.applyFilterPass(c,s,s.width,s.height);var u=a;a=h,h=u}t.enable(t.BLEND),n=a,this.texturePool.push(h)}var d=e.filterPasses[e.filterPasses.length-1];this.offsetX-=s.x,this.offsetY-=s.y;var p=this.width,f=this.height,g=0,m=0,y=this.buffer;if(0===this.filterStack.length)t.colorMask(!0,!0,!0,!0);else{var v=this.filterStack[this.filterStack.length-1];s=v._filterArea,p=s.width,f=s.height,g=s.x,m=s.y,y=v._glFilterTexture.frameBuffer}r.x=p/2,r.y=-f/2,o.x=g,o.y=m,s=e._filterArea;var b=s.x-g,x=s.y-m;t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),this.vertexArray[0]=b,this.vertexArray[1]=x+s.height,this.vertexArray[2]=b+s.width,this.vertexArray[3]=x+s.height,this.vertexArray[4]=b,this.vertexArray[5]=x,this.vertexArray[6]=b+s.width,this.vertexArray[7]=x,t.bufferSubData(t.ARRAY_BUFFER,0,this.vertexArray),t.bindBuffer(t.ARRAY_BUFFER,this.uvBuffer),this.uvArray[2]=s.width/this.width,this.uvArray[5]=s.height/this.height,this.uvArray[6]=s.width/this.width,this.uvArray[7]=s.height/this.height,t.bufferSubData(t.ARRAY_BUFFER,0,this.uvArray),t.viewport(0,0,p*this.renderSession.resolution,f*this.renderSession.resolution),t.bindFramebuffer(t.FRAMEBUFFER,y),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,n.texture),this.renderSession.stencilManager&&this.renderSession.stencilManager.destroy(),this.renderSession.stencilManager=e._previous_stencil_mgr,e._previous_stencil_mgr=null,this.renderSession.stencilManager.count>0?t.enable(t.STENCIL_TEST):t.disable(t.STENCIL_TEST),this.applyFilterPass(d,s,p,f),this.texturePool.push(n),e._glFilterTexture=null},i.WebGLFilterManager.prototype.applyFilterPass=function(t,e,s,n){var r=this.gl,o=t.shaders[r.id];o||(o=new i.PixiShader(r),o.fragmentSrc=t.fragmentSrc,o.uniforms=t.uniforms,o.init(),t.shaders[r.id]=o),this.renderSession.shaderManager.setShader(o),r.uniform2f(o.projectionVector,s/2,-n/2),r.uniform2f(o.offsetVector,0,0),t.uniforms.dimensions&&(t.uniforms.dimensions.value[0]=this.width,t.uniforms.dimensions.value[1]=this.height,t.uniforms.dimensions.value[2]=this.vertexArray[0],t.uniforms.dimensions.value[3]=this.vertexArray[5]),o.syncUniforms(),r.bindBuffer(r.ARRAY_BUFFER,this.vertexBuffer),r.vertexAttribPointer(o.aVertexPosition,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ARRAY_BUFFER,this.uvBuffer),r.vertexAttribPointer(o.aTextureCoord,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ARRAY_BUFFER,this.colorBuffer),r.vertexAttribPointer(o.colorAttribute,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,this.indexBuffer),r.drawElements(r.TRIANGLES,6,r.UNSIGNED_SHORT,0),this.renderSession.drawCount++},i.WebGLFilterManager.prototype.initShaderBuffers=function(){var t=this.gl;this.vertexBuffer=t.createBuffer(),this.uvBuffer=t.createBuffer(),this.colorBuffer=t.createBuffer(),this.indexBuffer=t.createBuffer(),this.vertexArray=new i.Float32Array([0,0,1,0,0,1,1,1]),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),t.bufferData(t.ARRAY_BUFFER,this.vertexArray,t.STATIC_DRAW),this.uvArray=new i.Float32Array([0,0,1,0,0,1,1,1]),t.bindBuffer(t.ARRAY_BUFFER,this.uvBuffer),t.bufferData(t.ARRAY_BUFFER,this.uvArray,t.STATIC_DRAW),this.colorArray=new i.Float32Array([1,16777215,1,16777215,1,16777215,1,16777215]),t.bindBuffer(t.ARRAY_BUFFER,this.colorBuffer),t.bufferData(t.ARRAY_BUFFER,this.colorArray,t.STATIC_DRAW),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,new Uint16Array([0,1,2,1,3,2]),t.STATIC_DRAW)},i.WebGLFilterManager.prototype.destroy=function(){var t=this.gl;this.filterStack=null,this.offsetX=0,this.offsetY=0;for(var e=0;e<this.texturePool.length;e++)this.texturePool[e].destroy();this.texturePool=null,t.deleteBuffer(this.vertexBuffer),t.deleteBuffer(this.uvBuffer),t.deleteBuffer(this.colorBuffer),t.deleteBuffer(this.indexBuffer)},i.FilterTexture=function(t,e,s,n){this.gl=t,this.frameBuffer=t.createFramebuffer(),this.texture=t.createTexture(),n=n||i.scaleModes.DEFAULT,t.bindTexture(t.TEXTURE_2D,this.texture),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,n===i.scaleModes.LINEAR?t.LINEAR:t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,n===i.scaleModes.LINEAR?t.LINEAR:t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.bindFramebuffer(t.FRAMEBUFFER,this.frameBuffer),t.bindFramebuffer(t.FRAMEBUFFER,this.frameBuffer),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,this.texture,0),this.renderBuffer=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,this.renderBuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,this.renderBuffer),this.resize(e,s)},i.FilterTexture.prototype.constructor=i.FilterTexture,i.FilterTexture.prototype.clear=function(){var t=this.gl;t.clearColor(0,0,0,0),t.clear(t.COLOR_BUFFER_BIT)},i.FilterTexture.prototype.resize=function(t,e){if(this.width!==t||this.height!==e){this.width=t,this.height=e;var i=this.gl;i.bindTexture(i.TEXTURE_2D,this.texture),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,t,e,0,i.RGBA,i.UNSIGNED_BYTE,null),i.bindRenderbuffer(i.RENDERBUFFER,this.renderBuffer),i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH_STENCIL,t,e)}},i.FilterTexture.prototype.destroy=function(){var t=this.gl;t.deleteFramebuffer(this.frameBuffer),t.deleteTexture(this.texture),this.frameBuffer=null,this.texture=null},i.CanvasBuffer=function(t,e){this.width=t,this.height=e,this.canvas=i.CanvasPool.create(this,this.width,this.height),this.context=this.canvas.getContext("2d"),this.canvas.width=t,this.canvas.height=e},i.CanvasBuffer.prototype.constructor=i.CanvasBuffer,i.CanvasBuffer.prototype.clear=function(){this.context.setTransform(1,0,0,1,0,0),this.context.clearRect(0,0,this.width,this.height)},i.CanvasBuffer.prototype.resize=function(t,e){this.width=this.canvas.width=t,this.height=this.canvas.height=e},i.CanvasBuffer.prototype.destroy=function(){i.CanvasPool.remove(this)},i.CanvasMaskManager=function(){},i.CanvasMaskManager.prototype.constructor=i.CanvasMaskManager,i.CanvasMaskManager.prototype.pushMask=function(t,e){var s=e.context;s.save();var n=t.alpha,r=t.worldTransform,o=e.resolution;s.setTransform(r.a*o,r.b*o,r.c*o,r.d*o,r.tx*o,r.ty*o),i.CanvasGraphics.renderGraphicsMask(t,s),s.clip(),t.worldAlpha=n},i.CanvasMaskManager.prototype.popMask=function(t){t.context.restore()},i.CanvasTinter=function(){},i.CanvasTinter.getTintedTexture=function(t,e){var s=t.tintedTexture||i.CanvasPool.create(this);return i.CanvasTinter.tintMethod(t.texture,e,s),s},i.CanvasTinter.tintWithMultiply=function(t,e,i){var s=i.getContext("2d"),n=t.crop;i.width===n.width&&i.height===n.height||(i.width=n.width,i.height=n.height),s.clearRect(0,0,n.width,n.height),s.fillStyle="#"+("00000"+(0|e).toString(16)).substr(-6),s.fillRect(0,0,n.width,n.height),s.globalCompositeOperation="multiply",s.drawImage(t.baseTexture.source,n.x,n.y,n.width,n.height,0,0,n.width,n.height),s.globalCompositeOperation="destination-atop",s.drawImage(t.baseTexture.source,n.x,n.y,n.width,n.height,0,0,n.width,n.height)},i.CanvasTinter.tintWithPerPixel=function(t,e,s){var n=s.getContext("2d"),r=t.crop;s.width=r.width,s.height=r.height,n.globalCompositeOperation="copy",n.drawImage(t.baseTexture.source,r.x,r.y,r.width,r.height,0,0,r.width,r.height);for(var o=i.hex2rgb(e),a=o[0],h=o[1],l=o[2],c=n.getImageData(0,0,r.width,r.height),u=c.data,d=0;d<u.length;d+=4)if(u[d+0]*=a,u[d+1]*=h,u[d+2]*=l,!i.CanvasTinter.canHandleAlpha){var p=u[d+3];u[d+0]/=255/p,u[d+1]/=255/p,u[d+2]/=255/p}n.putImageData(c,0,0)},i.CanvasTinter.checkInverseAlpha=function(){var t=new i.CanvasBuffer(2,1);t.context.fillStyle="rgba(10, 20, 30, 0.5)",t.context.fillRect(0,0,1,1);var e=t.context.getImageData(0,0,1,1);if(null===e)return!1;t.context.putImageData(e,1,0);var s=t.context.getImageData(1,0,1,1);return s.data[0]===e.data[0]&&s.data[1]===e.data[1]&&s.data[2]===e.data[2]&&s.data[3]===e.data[3]},i.CanvasTinter.canHandleAlpha=i.CanvasTinter.checkInverseAlpha(),i.CanvasTinter.canUseMultiply=i.canUseNewCanvasBlendModes(),i.CanvasTinter.tintMethod=i.CanvasTinter.canUseMultiply?i.CanvasTinter.tintWithMultiply:i.CanvasTinter.tintWithPerPixel,i.CanvasRenderer=function(t){this.game=t,i.defaultRenderer||(i.defaultRenderer=this),this.type=i.CANVAS_RENDERER,this.resolution=t.resolution,this.clearBeforeRender=t.clearBeforeRender,this.transparent=t.transparent,this.autoResize=!1,this.width=t.width*this.resolution,this.height=t.height*this.resolution,this.view=t.canvas,this.context=this.view.getContext("2d",{alpha:this.transparent}),this.refresh=!0,this.count=0,this.maskManager=new i.CanvasMaskManager,this.renderSession={context:this.context,maskManager:this.maskManager,scaleMode:null,smoothProperty:Phaser.Canvas.getSmoothingPrefix(this.context),roundPixels:!1},this.mapBlendModes(),this.resize(this.width,this.height)},i.CanvasRenderer.prototype.constructor=i.CanvasRenderer,i.CanvasRenderer.prototype.render=function(t){this.context.setTransform(1,0,0,1,0,0),this.context.globalAlpha=1,this.renderSession.currentBlendMode=0,this.renderSession.shakeX=this.game.camera._shake.x,this.renderSession.shakeY=this.game.camera._shake.y,this.context.globalCompositeOperation="source-over",navigator.isCocoonJS&&this.view.screencanvas&&(this.context.fillStyle="black",this.context.clear()),this.clearBeforeRender&&(this.transparent?this.context.clearRect(0,0,this.width,this.height):t._bgColor&&(this.context.fillStyle=t._bgColor.rgba,this.context.fillRect(0,0,this.width,this.height))),this.renderDisplayObject(t)},i.CanvasRenderer.prototype.destroy=function(t){void 0===t&&(t=!0),t&&this.view.parent&&this.view.parent.removeChild(this.view),this.view=null,this.context=null,this.maskManager=null,this.renderSession=null},i.CanvasRenderer.prototype.resize=function(t,e){this.width=t*this.resolution,this.height=e*this.resolution,this.view.width=this.width,this.view.height=this.height,this.autoResize&&(this.view.style.width=this.width/this.resolution+"px",this.view.style.height=this.height/this.resolution+"px"),this.renderSession.smoothProperty&&(this.context[this.renderSession.smoothProperty]=this.renderSession.scaleMode===i.scaleModes.LINEAR)},i.CanvasRenderer.prototype.renderDisplayObject=function(t,e,i){this.renderSession.context=e||this.context,this.renderSession.resolution=this.resolution,t._renderCanvas(this.renderSession,i)},i.CanvasRenderer.prototype.mapBlendModes=function(){if(!i.blendModesCanvas){var t=[],e=i.blendModes,s=i.canUseNewCanvasBlendModes();t[e.NORMAL]="source-over",t[e.ADD]="lighter",t[e.MULTIPLY]=s?"multiply":"source-over",t[e.SCREEN]=s?"screen":"source-over",t[e.OVERLAY]=s?"overlay":"source-over",t[e.DARKEN]=s?"darken":"source-over",t[e.LIGHTEN]=s?"lighten":"source-over",t[e.COLOR_DODGE]=s?"color-dodge":"source-over",t[e.COLOR_BURN]=s?"color-burn":"source-over",t[e.HARD_LIGHT]=s?"hard-light":"source-over",t[e.SOFT_LIGHT]=s?"soft-light":"source-over",t[e.DIFFERENCE]=s?"difference":"source-over",t[e.EXCLUSION]=s?"exclusion":"source-over",t[e.HUE]=s?"hue":"source-over",t[e.SATURATION]=s?"saturation":"source-over",t[e.COLOR]=s?"color":"source-over",t[e.LUMINOSITY]=s?"luminosity":"source-over",i.blendModesCanvas=t}},i.BaseTexture=function(t,e){this.resolution=1,this.width=100,this.height=100,this.scaleMode=e||i.scaleModes.DEFAULT,this.hasLoaded=!1,this.source=t,this.premultipliedAlpha=!0,this._glTextures=[],this.mipmap=!1,this._dirty=[!0,!0,!0,!0],t&&((this.source.complete||this.source.getContext)&&this.source.width&&this.source.height&&(this.hasLoaded=!0,this.width=this.source.naturalWidth||this.source.width,this.height=this.source.naturalHeight||this.source.height,this.dirty()),this.skipRender=!1,this._powerOf2=!1)},i.BaseTexture.prototype.constructor=i.BaseTexture,i.BaseTexture.prototype.forceLoaded=function(t,e){this.hasLoaded=!0,this.width=t,this.height=e,this.dirty()},i.BaseTexture.prototype.destroy=function(){this.source&&i.CanvasPool.removeByCanvas(this.source),this.source=null,this.unloadFromGPU()},i.BaseTexture.prototype.updateSourceImage=function(t){console.warn("PIXI.BaseTexture.updateSourceImage is deprecated. Use Phaser.Sprite.loadTexture instead.")},i.BaseTexture.prototype.dirty=function(){for(var t=0;t<this._glTextures.length;t++)this._dirty[t]=!0},i.BaseTexture.prototype.unloadFromGPU=function(){this.dirty();for(var t=this._glTextures.length-1;t>=0;t--){var e=this._glTextures[t],s=i.glContexts[t];s&&e&&s.deleteTexture(e)}this._glTextures.length=0,this.dirty()},i.BaseTexture.fromCanvas=function(t,e){return 0===t.width&&(t.width=1),0===t.height&&(t.height=1),new i.BaseTexture(t,e)},i.TextureSilentFail=!1,i.Texture=function(t,e,s,n){this.noFrame=!1,e||(this.noFrame=!0,e=new i.Rectangle(0,0,1,1)),t instanceof i.Texture&&(t=t.baseTexture),this.baseTexture=t,this.frame=e,this.trim=n,this.valid=!1,this.isTiling=!1,this.requiresUpdate=!1,this.requiresReTint=!1,this._uvs=null,this.width=0,this.height=0,this.crop=s||new i.Rectangle(0,0,1,1),t.hasLoaded&&(this.noFrame&&(e=new i.Rectangle(0,0,t.width,t.height)),this.setFrame(e))},i.Texture.prototype.constructor=i.Texture,i.Texture.prototype.onBaseTextureLoaded=function(){var t=this.baseTexture;this.noFrame&&(this.frame=new i.Rectangle(0,0,t.width,t.height)),this.setFrame(this.frame)},i.Texture.prototype.destroy=function(t){t&&this.baseTexture.destroy(),this.valid=!1},i.Texture.prototype.setFrame=function(t){if(this.noFrame=!1,this.frame=t,this.width=t.width,this.height=t.height,this.crop.x=t.x,this.crop.y=t.y,this.crop.width=t.width,this.crop.height=t.height,!this.trim&&(t.x+t.width>this.baseTexture.width||t.y+t.height>this.baseTexture.height)){if(!i.TextureSilentFail)throw new Error("Texture Error: frame does not fit inside the base Texture dimensions "+this);return void(this.valid=!1)}this.valid=t&&t.width&&t.height&&this.baseTexture.source&&this.baseTexture.hasLoaded,this.trim&&(this.width=this.trim.width,this.height=this.trim.height,this.frame.width=this.trim.width,this.frame.height=this.trim.height),this.valid&&this._updateUvs()},i.Texture.prototype._updateUvs=function(){this._uvs||(this._uvs=new i.TextureUvs);var t=this.crop,e=this.baseTexture.width,s=this.baseTexture.height;this._uvs.x0=t.x/e,this._uvs.y0=t.y/s,this._uvs.x1=(t.x+t.width)/e,this._uvs.y1=t.y/s,this._uvs.x2=(t.x+t.width)/e,this._uvs.y2=(t.y+t.height)/s,this._uvs.x3=t.x/e,this._uvs.y3=(t.y+t.height)/s},i.Texture.fromCanvas=function(t,e){var s=i.BaseTexture.fromCanvas(t,e);return new i.Texture(s)},i.TextureUvs=function(){this.x0=0,this.y0=0,this.x1=0,this.y1=0,this.x2=0,this.y2=0,this.x3=0,this.y3=0},i.RenderTexture=function(t,e,s,n,r){if(this.width=t||100,this.height=e||100,this.resolution=r||1,this.frame=new i.Rectangle(0,0,this.width*this.resolution,this.height*this.resolution),this.crop=new i.Rectangle(0,0,this.width*this.resolution,this.height*this.resolution),this.baseTexture=new i.BaseTexture,this.baseTexture.width=this.width*this.resolution,this.baseTexture.height=this.height*this.resolution,this.baseTexture._glTextures=[],this.baseTexture.resolution=this.resolution,this.baseTexture.scaleMode=n||i.scaleModes.DEFAULT,this.baseTexture.hasLoaded=!0,i.Texture.call(this,this.baseTexture,new i.Rectangle(0,0,this.width*this.resolution,this.height*this.resolution)),this.renderer=s||i.defaultRenderer,this.renderer.type===i.WEBGL_RENDERER){var o=this.renderer.gl;this.baseTexture._dirty[o.id]=!1,this.textureBuffer=new i.FilterTexture(o,this.width,this.height,this.baseTexture.scaleMode),this.baseTexture._glTextures[o.id]=this.textureBuffer.texture,this.render=this.renderWebGL,this.projection=new i.Point(.5*this.width,.5*-this.height)}else this.render=this.renderCanvas,this.textureBuffer=new i.CanvasBuffer(this.width*this.resolution,this.height*this.resolution),this.baseTexture.source=this.textureBuffer.canvas;this.valid=!0,this.tempMatrix=new Phaser.Matrix,this._updateUvs()},i.RenderTexture.prototype=Object.create(i.Texture.prototype),i.RenderTexture.prototype.constructor=i.RenderTexture,i.RenderTexture.prototype.resize=function(t,e,s){t===this.width&&e===this.height||(this.valid=t>0&&e>0,this.width=t,this.height=e,this.frame.width=this.crop.width=t*this.resolution,this.frame.height=this.crop.height=e*this.resolution,s&&(this.baseTexture.width=this.width*this.resolution,this.baseTexture.height=this.height*this.resolution),this.renderer.type===i.WEBGL_RENDERER&&(this.projection.x=this.width/2,this.projection.y=-this.height/2),this.valid&&this.textureBuffer.resize(this.width,this.height))},i.RenderTexture.prototype.clear=function(){this.valid&&(this.renderer.type===i.WEBGL_RENDERER&&this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER,this.textureBuffer.frameBuffer),this.textureBuffer.clear())},i.RenderTexture.prototype.renderWebGL=function(t,e,i){if(this.valid&&0!==t.alpha){var s=t.worldTransform;s.identity(),s.translate(0,2*this.projection.y),e&&s.append(e),s.scale(1,-1);for(var n=0;n<t.children.length;n++)t.children[n].updateTransform();var r=this.renderer.gl;r.viewport(0,0,this.width*this.resolution,this.height*this.resolution),r.bindFramebuffer(r.FRAMEBUFFER,this.textureBuffer.frameBuffer),i&&this.textureBuffer.clear(),this.renderer.spriteBatch.dirty=!0,this.renderer.renderDisplayObject(t,this.projection,this.textureBuffer.frameBuffer,e),this.renderer.spriteBatch.dirty=!0}},i.RenderTexture.prototype.renderCanvas=function(t,e,i){if(this.valid&&0!==t.alpha){var s=t.worldTransform;s.identity(),e&&s.append(e);for(var n=0;n<t.children.length;n++)t.children[n].updateTransform();i&&this.textureBuffer.clear();var r=this.renderer.resolution;this.renderer.resolution=this.resolution,this.renderer.renderDisplayObject(t,this.textureBuffer.context,e),this.renderer.resolution=r}},i.RenderTexture.prototype.getImage=function(){var t=new Image;return t.src=this.getBase64(),t},i.RenderTexture.prototype.getBase64=function(){return this.getCanvas().toDataURL()},i.RenderTexture.prototype.getCanvas=function(){if(this.renderer.type===i.WEBGL_RENDERER){var t=this.renderer.gl,e=this.textureBuffer.width,s=this.textureBuffer.height,n=new Uint8Array(4*e*s);t.bindFramebuffer(t.FRAMEBUFFER,this.textureBuffer.frameBuffer),t.readPixels(0,0,e,s,t.RGBA,t.UNSIGNED_BYTE,n),t.bindFramebuffer(t.FRAMEBUFFER,null);var r=new i.CanvasBuffer(e,s),o=r.context.getImageData(0,0,e,s);return o.data.set(n),r.context.putImageData(o,0,0),r.canvas}return this.textureBuffer.canvas},i.AbstractFilter=function(t,e){this.passes=[this],this.shaders=[],this.dirty=!0,this.padding=0,this.uniforms=e||{},this.fragmentSrc=t||[]},i.AbstractFilter.prototype.constructor=i.AbstractFilter,i.AbstractFilter.prototype.syncUniforms=function(){for(var t=0,e=this.shaders.length;t<e;t++)this.shaders[t].dirty=!0},i.Strip=function(t){i.DisplayObjectContainer.call(this),this.texture=t,this.uvs=new i.Float32Array([0,1,1,1,1,0,0,1]),this.vertices=new i.Float32Array([0,0,100,0,100,100,0,100]),this.colors=new i.Float32Array([1,1,1,1]),this.indices=new i.Uint16Array([0,1,2,3]),this.dirty=!0,this.blendMode=i.blendModes.NORMAL,this.canvasPadding=0,this.drawMode=i.Strip.DrawModes.TRIANGLE_STRIP},i.Strip.prototype=Object.create(i.DisplayObjectContainer.prototype),i.Strip.prototype.constructor=i.Strip,i.Strip.prototype._renderWebGL=function(t){!this.visible||this.alpha<=0||(t.spriteBatch.stop(),this._vertexBuffer||this._initWebGL(t),t.shaderManager.setShader(t.shaderManager.stripShader),this._renderStrip(t),t.spriteBatch.start())},i.Strip.prototype._initWebGL=function(t){var e=t.gl;this._vertexBuffer=e.createBuffer(),this._indexBuffer=e.createBuffer(),this._uvBuffer=e.createBuffer(),this._colorBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this._vertexBuffer),e.bufferData(e.ARRAY_BUFFER,this.vertices,e.DYNAMIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,this._uvBuffer),e.bufferData(e.ARRAY_BUFFER,this.uvs,e.STATIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,this._colorBuffer),e.bufferData(e.ARRAY_BUFFER,this.colors,e.STATIC_DRAW),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this._indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,this.indices,e.STATIC_DRAW)},i.Strip.prototype._renderStrip=function(t){var e=t.gl,s=t.projection,n=t.offset,r=t.shaderManager.stripShader,o=this.drawMode===i.Strip.DrawModes.TRIANGLE_STRIP?e.TRIANGLE_STRIP:e.TRIANGLES;t.blendModeManager.setBlendMode(this.blendMode),e.uniformMatrix3fv(r.translationMatrix,!1,this.worldTransform.toArray(!0)),e.uniform2f(r.projectionVector,s.x,-s.y),e.uniform2f(r.offsetVector,-n.x,-n.y),e.uniform1f(r.alpha,this.worldAlpha),this.dirty?(this.dirty=!1,e.bindBuffer(e.ARRAY_BUFFER,this._vertexBuffer),e.bufferData(e.ARRAY_BUFFER,this.vertices,e.STATIC_DRAW),e.vertexAttribPointer(r.aVertexPosition,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this._uvBuffer),e.bufferData(e.ARRAY_BUFFER,this.uvs,e.STATIC_DRAW),e.vertexAttribPointer(r.aTextureCoord,2,e.FLOAT,!1,0,0),e.activeTexture(e.TEXTURE0),this.texture.baseTexture._dirty[e.id]?t.renderer.updateTexture(this.texture.baseTexture):e.bindTexture(e.TEXTURE_2D,this.texture.baseTexture._glTextures[e.id]),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this._indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,this.indices,e.STATIC_DRAW)):(e.bindBuffer(e.ARRAY_BUFFER,this._vertexBuffer),e.bufferSubData(e.ARRAY_BUFFER,0,this.vertices),e.vertexAttribPointer(r.aVertexPosition,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this._uvBuffer),e.vertexAttribPointer(r.aTextureCoord,2,e.FLOAT,!1,0,0),e.activeTexture(e.TEXTURE0),this.texture.baseTexture._dirty[e.id]?t.renderer.updateTexture(this.texture.baseTexture):e.bindTexture(e.TEXTURE_2D,this.texture.baseTexture._glTextures[e.id]),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this._indexBuffer)),e.drawElements(o,this.indices.length,e.UNSIGNED_SHORT,0)},i.Strip.prototype._renderCanvas=function(t){var e=t.context,s=this.worldTransform,n=s.tx*t.resolution+t.shakeX,r=s.ty*t.resolution+t.shakeY;t.roundPixels?e.setTransform(s.a,s.b,s.c,s.d,0|n,0|r):e.setTransform(s.a,s.b,s.c,s.d,n,r),this.drawMode===i.Strip.DrawModes.TRIANGLE_STRIP?this._renderCanvasTriangleStrip(e):this._renderCanvasTriangles(e)},i.Strip.prototype._renderCanvasTriangleStrip=function(t){var e=this.vertices,i=this.uvs,s=e.length/2;this.count++;for(var n=0;n<s-2;n++){var r=2*n;this._renderCanvasDrawTriangle(t,e,i,r,r+2,r+4)}},i.Strip.prototype._renderCanvasTriangles=function(t){var e=this.vertices,i=this.uvs,s=this.indices,n=s.length;this.count++;for(var r=0;r<n;r+=3){var o=2*s[r],a=2*s[r+1],h=2*s[r+2];this._renderCanvasDrawTriangle(t,e,i,o,a,h)}},i.Strip.prototype._renderCanvasDrawTriangle=function(t,e,i,s,n,r){var o=this.texture.baseTexture.source,a=this.texture.width,h=this.texture.height,l=e[s],c=e[n],u=e[r],d=e[s+1],p=e[n+1],f=e[r+1],g=i[s]*a,m=i[n]*a,y=i[r]*a,v=i[s+1]*h,b=i[n+1]*h,x=i[r+1]*h;if(this.canvasPadding>0){var w=this.canvasPadding/this.worldTransform.a,_=this.canvasPadding/this.worldTransform.d,P=(l+c+u)/3,T=(d+p+f)/3,C=l-P,S=d-T,A=Math.sqrt(C*C+S*S);l=P+C/A*(A+w),d=T+S/A*(A+_),C=c-P,S=p-T,A=Math.sqrt(C*C+S*S),c=P+C/A*(A+w),p=T+S/A*(A+_),C=u-P,S=f-T,A=Math.sqrt(C*C+S*S),u=P+C/A*(A+w),f=T+S/A*(A+_)}t.save(),t.beginPath(),t.moveTo(l,d),t.lineTo(c,p),t.lineTo(u,f),t.closePath(),t.clip();var E=g*b+v*y+m*x-b*y-v*m-g*x,I=l*b+v*u+c*x-b*u-v*c-l*x,M=g*c+l*y+m*u-c*y-l*m-g*u,R=g*b*u+v*c*y+l*m*x-l*b*y-v*m*u-g*c*x,B=d*b+v*f+p*x-b*f-v*p-d*x,L=g*p+d*y+m*f-p*y-d*m-g*f,k=g*b*f+v*p*y+d*m*x-d*b*y-v*m*f-g*p*x;t.transform(I/E,B/E,M/E,L/E,R/E,k/E),t.drawImage(o,0,0),t.restore()},i.Strip.prototype.renderStripFlat=function(t){var e=this.context,i=t.vertices,s=i.length/2;this.count++,e.beginPath();for(var n=1;n<s-2;n++){var r=2*n,o=i[r],a=i[r+2],h=i[r+4],l=i[r+1],c=i[r+3],u=i[r+5];e.moveTo(o,l),e.lineTo(a,c),e.lineTo(h,u)}e.fillStyle="#FF0000",e.fill(),e.closePath()},i.Strip.prototype.onTextureUpdate=function(){this.updateFrame=!0},i.Strip.prototype.getBounds=function(t){for(var e=t||this.worldTransform,s=e.a,n=e.b,r=e.c,o=e.d,a=e.tx,h=e.ty,l=-1/0,c=-1/0,u=1/0,d=1/0,p=this.vertices,f=0,g=p.length;f<g;f+=2){var m=p[f],y=p[f+1],v=s*m+r*y+a,b=o*y+n*m+h;u=v<u?v:u,d=b<d?b:d,l=v>l?v:l,c=b>c?b:c}if(u===-1/0||c===1/0)return i.EmptyRectangle;var x=this._bounds;return x.x=u,x.width=l-u,x.y=d,x.height=c-d,this._currentBounds=x,x},i.Strip.DrawModes={TRIANGLE_STRIP:0,TRIANGLES:1},i.Rope=function(t,e){i.Strip.call(this,t),this.points=e,this.vertices=new i.Float32Array(4*e.length),this.uvs=new i.Float32Array(4*e.length),this.colors=new i.Float32Array(2*e.length),this.indices=new i.Uint16Array(2*e.length),this.refresh()},i.Rope.prototype=Object.create(i.Strip.prototype),i.Rope.prototype.constructor=i.Rope,i.Rope.prototype.refresh=function(){var t=this.points;if(!(t.length<1)){var e=this.uvs,i=(t[0],this.indices),s=this.colors;this.count-=.2,e[0]=0,e[1]=0,e[2]=0,e[3]=1,s[0]=1,s[1]=1,i[0]=0,i[1]=1;for(var n,r,o,a=t.length,h=1;h<a;h++)n=t[h],r=4*h,o=h/(a-1),e[r]=o,e[r+1]=0,e[r+2]=o,e[r+3]=1,r=2*h,s[r]=1,s[r+1]=1,r=2*h,i[r]=r,i[r+1]=r+1,n}},i.Rope.prototype.updateTransform=function(){var t=this.points;if(!(t.length<1)){var e,s=t[0],n={x:0,y:0};this.count-=.2;for(var r,o,a,h,l,c=this.vertices,u=t.length,d=0;d<u;d++)r=t[d],o=4*d,e=d<t.length-1?t[d+1]:r,n.y=-(e.x-s.x),n.x=e.y-s.y,a=10*(1-d/(u-1)),a>1&&(a=1),h=Math.sqrt(n.x*n.x+n.y*n.y),l=this.texture.height/2,n.x/=h,n.y/=h,n.x*=l,n.y*=l,c[o]=r.x+n.x,c[o+1]=r.y+n.y,c[o+2]=r.x-n.x,c[o+3]=r.y-n.y,s=r;i.DisplayObjectContainer.prototype.updateTransform.call(this)}},i.Rope.prototype.setTexture=function(t){this.texture=t},i.TilingSprite=function(t,e,s){i.Sprite.call(this,t),this._width=e||128,this._height=s||128,this.tileScale=new i.Point(1,1),this.tileScaleOffset=new i.Point(1,1),this.tilePosition=new i.Point,this.renderable=!0,this.tint=16777215,this.textureDebug=!1,this.blendMode=i.blendModes.NORMAL,this.canvasBuffer=null,this.tilingTexture=null,this.tilePattern=null,this.refreshTexture=!0,this.frameWidth=0,this.frameHeight=0},i.TilingSprite.prototype=Object.create(i.Sprite.prototype),i.TilingSprite.prototype.constructor=i.TilingSprite,i.TilingSprite.prototype.setTexture=function(t){this.texture!==t&&(this.texture=t,this.refreshTexture=!0,this.cachedTint=16777215)},i.TilingSprite.prototype._renderWebGL=function(t){if(this.visible&&this.renderable&&0!==this.alpha){if(this._mask&&(t.spriteBatch.stop(),t.maskManager.pushMask(this.mask,t),t.spriteBatch.start()),this._filters&&(t.spriteBatch.flush(),t.filterManager.pushFilter(this._filterBlock)),this.refreshTexture){if(this.generateTilingTexture(!0,t),!this.tilingTexture)return;this.tilingTexture.needsUpdate&&(t.renderer.updateTexture(this.tilingTexture.baseTexture),this.tilingTexture.needsUpdate=!1)}t.spriteBatch.renderTilingSprite(this);for(var e=0;e<this.children.length;e++)this.children[e]._renderWebGL(t);t.spriteBatch.stop(),this._filters&&t.filterManager.popFilter(),this._mask&&t.maskManager.popMask(this._mask,t),t.spriteBatch.start()}},i.TilingSprite.prototype._renderCanvas=function(t){if(this.visible&&this.renderable&&0!==this.alpha){var e=t.context;this._mask&&t.maskManager.pushMask(this._mask,t),e.globalAlpha=this.worldAlpha;var s=this.worldTransform,n=t.resolution,r=s.tx*n+t.shakeX,o=s.ty*n+t.shakeY;if(e.setTransform(s.a*n,s.b*n,s.c*n,s.d*n,r,o),this.refreshTexture){if(this.generateTilingTexture(!1,t),!this.tilingTexture)return;this.tilePattern=e.createPattern(this.tilingTexture.baseTexture.source,"repeat")}var a=t.currentBlendMode;this.blendMode!==t.currentBlendMode&&(t.currentBlendMode=this.blendMode,e.globalCompositeOperation=i.blendModesCanvas[t.currentBlendMode]);var h=this.tilePosition,l=this.tileScale;h.x%=this.tilingTexture.baseTexture.width,h.y%=this.tilingTexture.baseTexture.height,e.scale(l.x,l.y),e.translate(h.x+this.anchor.x*-this._width,h.y+this.anchor.y*-this._height),e.fillStyle=this.tilePattern;var r=-h.x,o=-h.y,c=this._width/l.x,u=this._height/l.y;t.roundPixels&&(r|=0,o|=0,c|=0,u|=0),e.fillRect(r,o,c,u),e.scale(1/l.x,1/l.y),e.translate(-h.x+this.anchor.x*this._width,-h.y+this.anchor.y*this._height),this._mask&&t.maskManager.popMask(t);for(var d=0;d<this.children.length;d++)this.children[d]._renderCanvas(t);a!==this.blendMode&&(t.currentBlendMode=a,e.globalCompositeOperation=i.blendModesCanvas[a])}},i.TilingSprite.prototype.onTextureUpdate=function(){},i.TilingSprite.prototype.generateTilingTexture=function(t,e){if(this.texture.baseTexture.hasLoaded){var s=this.texture,n=s.frame,r=this._frame.sourceSizeW||this._frame.width,o=this._frame.sourceSizeH||this._frame.height,a=0,h=0;this._frame.trimmed&&(a=this._frame.spriteSourceSizeX,h=this._frame.spriteSourceSizeY),t&&(r=i.getNextPowerOfTwo(r),o=i.getNextPowerOfTwo(o)),this.canvasBuffer?(this.canvasBuffer.resize(r,o),this.tilingTexture.baseTexture.width=r,this.tilingTexture.baseTexture.height=o,this.tilingTexture.needsUpdate=!0):(this.canvasBuffer=new i.CanvasBuffer(r,o),this.tilingTexture=i.Texture.fromCanvas(this.canvasBuffer.canvas),this.tilingTexture.isTiling=!0,this.tilingTexture.needsUpdate=!0),this.textureDebug&&(this.canvasBuffer.context.strokeStyle="#00ff00",this.canvasBuffer.context.strokeRect(0,0,r,o));var l=s.crop.width,c=s.crop.height;l===r&&c===o||(l=r,c=o),this.canvasBuffer.context.drawImage(s.baseTexture.source,s.crop.x,s.crop.y,s.crop.width,s.crop.height,a,h,l,c),this.tileScaleOffset.x=n.width/r,this.tileScaleOffset.y=n.height/o,this.refreshTexture=!1,this.tilingTexture.baseTexture._powerOf2=!0}},i.TilingSprite.prototype.getBounds=function(){var t=this._width,e=this._height,i=t*(1-this.anchor.x),s=t*-this.anchor.x,n=e*(1-this.anchor.y),r=e*-this.anchor.y,o=this.worldTransform,a=o.a,h=o.b,l=o.c,c=o.d,u=o.tx,d=o.ty,p=a*s+l*r+u,f=c*r+h*s+d,g=a*i+l*r+u,m=c*r+h*i+d,y=a*i+l*n+u,v=c*n+h*i+d,b=a*s+l*n+u,x=c*n+h*s+d,w=-1/0,_=-1/0,P=1/0,T=1/0;P=p<P?p:P,P=g<P?g:P,P=y<P?y:P,P=b<P?b:P,T=f<T?f:T,T=m<T?m:T,T=v<T?v:T,T=x<T?x:T,w=p>w?p:w,w=g>w?g:w,w=y>w?y:w,w=b>w?b:w,_=f>_?f:_,_=m>_?m:_,_=v>_?v:_,_=x>_?x:_;var C=this._bounds;return C.x=P,C.width=w-P,C.y=T,C.height=_-T,this._currentBounds=C,C},i.TilingSprite.prototype.destroy=function(){i.Sprite.prototype.destroy.call(this),this.canvasBuffer&&(this.canvasBuffer.destroy(),this.canvasBuffer=null),this.tileScale=null,this.tileScaleOffset=null,this.tilePosition=null,this.tilingTexture&&(this.tilingTexture.destroy(!0),this.tilingTexture=null)},Object.defineProperty(i.TilingSprite.prototype,"width",{get:function(){return this._width},set:function(t){this._width=t}}),Object.defineProperty(i.TilingSprite.prototype,"height",{get:function(){return this._height},set:function(t){this._height=t}}),void 0!==t&&t.exports&&(e=t.exports=i),e.PIXI=i,i}).call(this)},,,,,,,,,,function(t,e,i){t.exports=i(33)}],[102]); | public/game.js | webpackJsonp([1],[,function(t,e,i){"use strict";(function(e){function s(t){return"[object Array]"===T.call(t)}function n(t){return void 0!==e&&e.isBuffer&&e.isBuffer(t)}function r(t){return"[object ArrayBuffer]"===T.call(t)}function o(t){return"undefined"!=typeof FormData&&t instanceof FormData}function a(t){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer&&t.buffer instanceof ArrayBuffer}function h(t){return"string"==typeof t}function l(t){return"number"==typeof t}function c(t){return void 0===t}function u(t){return null!==t&&"object"==typeof t}function d(t){return"[object Date]"===T.call(t)}function p(t){return"[object File]"===T.call(t)}function f(t){return"[object Blob]"===T.call(t)}function g(t){return"[object Function]"===T.call(t)}function m(t){return u(t)&&g(t.pipe)}function y(t){return"undefined"!=typeof URLSearchParams&&t instanceof URLSearchParams}function v(t){return t.replace(/^\s*/,"").replace(/\s*$/,"")}function b(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product)&&("undefined"!=typeof window&&"undefined"!=typeof document)}function x(t,e){if(null!==t&&void 0!==t)if("object"==typeof t||s(t)||(t=[t]),s(t))for(var i=0,n=t.length;i<n;i++)e.call(null,t[i],i,t);else for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.call(null,t[r],r,t)}function w(){function t(t,i){"object"==typeof e[i]&&"object"==typeof t?e[i]=w(e[i],t):e[i]=t}for(var e={},i=0,s=arguments.length;i<s;i++)x(arguments[i],t);return e}function _(t,e,i){return x(e,function(e,s){t[s]=i&&"function"==typeof e?P(e,i):e}),t}var P=i(18),T=Object.prototype.toString;t.exports={isArray:s,isArrayBuffer:r,isBuffer:n,isFormData:o,isArrayBufferView:a,isString:h,isNumber:l,isObject:u,isUndefined:c,isDate:d,isFile:p,isBlob:f,isFunction:g,isStream:m,isURLSearchParams:y,isStandardBrowserEnv:b,forEach:x,merge:w,extend:_,trim:v}}).call(e,i(65).Buffer)},,,,function(t,e,i){"use strict";i.d(e,"b",function(){return s}),i.d(e,"a",function(){return r}),i.d(e,"c",function(){return o});var s={BLACK:"#060304",DARKBLUE:"#001440",TEAL:"#427a8b",GREEN:"#39bb8f",YELLOWGREEN:"#e2fda7"},n=function(){var t=!1;return function(e){(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4)))&&(t=!0)}(navigator.userAgent||navigator.vendor||window.opera),t},r={SCREENWIDTH:window.innerWidth*window.devicePixelRatio,SCREENHEIGHT:window.innerHeight*window.devicePixelRatio,SCALERATIO:function(){var t=window.innerWidth/window.innerHeight,e=void 0;return e=t>1?window.innerHeight*window.devicePixelRatio/2048:window.innerWidth*window.devicePixelRatio/2048,n()&&(e+=1),e}(),BRICKSIZE:120},o=n()},,,,function(t,e,i){"use strict";(function(e){function s(t,e){!n.isUndefined(t)&&n.isUndefined(t["Content-Type"])&&(t["Content-Type"]=e)}var n=i(1),r=i(52),o={"Content-Type":"application/x-www-form-urlencoded"},a={adapter:function(){var t;return"undefined"!=typeof XMLHttpRequest?t=i(14):void 0!==e&&(t=i(14)),t}(),transformRequest:[function(t,e){return r(e,"Content-Type"),n.isFormData(t)||n.isArrayBuffer(t)||n.isBuffer(t)||n.isStream(t)||n.isFile(t)||n.isBlob(t)?t:n.isArrayBufferView(t)?t.buffer:n.isURLSearchParams(t)?(s(e,"application/x-www-form-urlencoded;charset=utf-8"),t.toString()):n.isObject(t)?(s(e,"application/json;charset=utf-8"),JSON.stringify(t)):t}],transformResponse:[function(t){if("string"==typeof t)try{t=JSON.parse(t)}catch(t){}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,validateStatus:function(t){return t>=200&&t<300}};a.headers={common:{Accept:"application/json, text/plain, */*"}},n.forEach(["delete","get","head"],function(t){a.headers[t]={}}),n.forEach(["post","put","patch"],function(t){a.headers[t]=n.merge(o)}),t.exports=a}).call(e,i(4))},,,,,function(t,e,i){"use strict";var s=i(1),n=i(44),r=i(47),o=i(53),a=i(51),h=i(17),l="undefined"!=typeof window&&window.btoa&&window.btoa.bind(window)||i(46);t.exports=function(t){return new Promise(function(e,c){var u=t.data,d=t.headers;s.isFormData(u)&&delete d["Content-Type"];var p=new XMLHttpRequest,f="onreadystatechange",g=!1;if("undefined"==typeof window||!window.XDomainRequest||"withCredentials"in p||a(t.url)||(p=new window.XDomainRequest,f="onload",g=!0,p.onprogress=function(){},p.ontimeout=function(){}),t.auth){var m=t.auth.username||"",y=t.auth.password||"";d.Authorization="Basic "+l(m+":"+y)}if(p.open(t.method.toUpperCase(),r(t.url,t.params,t.paramsSerializer),!0),p.timeout=t.timeout,p[f]=function(){if(p&&(4===p.readyState||g)&&(0!==p.status||p.responseURL&&0===p.responseURL.indexOf("file:"))){var i="getAllResponseHeaders"in p?o(p.getAllResponseHeaders()):null,s=t.responseType&&"text"!==t.responseType?p.response:p.responseText,r={data:s,status:1223===p.status?204:p.status,statusText:1223===p.status?"No Content":p.statusText,headers:i,config:t,request:p};n(e,c,r),p=null}},p.onerror=function(){c(h("Network Error",t)),p=null},p.ontimeout=function(){c(h("timeout of "+t.timeout+"ms exceeded",t,"ECONNABORTED")),p=null},s.isStandardBrowserEnv()){var v=i(49),b=(t.withCredentials||a(t.url))&&t.xsrfCookieName?v.read(t.xsrfCookieName):void 0;b&&(d[t.xsrfHeaderName]=b)}if("setRequestHeader"in p&&s.forEach(d,function(t,e){void 0===u&&"content-type"===e.toLowerCase()?delete d[e]:p.setRequestHeader(e,t)}),t.withCredentials&&(p.withCredentials=!0),t.responseType)try{p.responseType=t.responseType}catch(e){if("json"!==t.responseType)throw e}"function"==typeof t.onDownloadProgress&&p.addEventListener("progress",t.onDownloadProgress),"function"==typeof t.onUploadProgress&&p.upload&&p.upload.addEventListener("progress",t.onUploadProgress),t.cancelToken&&t.cancelToken.promise.then(function(t){p&&(p.abort(),c(t),p=null)}),void 0===u&&(u=null),p.send(u)})}},function(t,e,i){"use strict";function s(t){this.message=t}s.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},s.prototype.__CANCEL__=!0,t.exports=s},function(t,e,i){"use strict";t.exports=function(t){return!(!t||!t.__CANCEL__)}},function(t,e,i){"use strict";var s=i(43);t.exports=function(t,e,i,n){var r=new Error(t);return s(r,e,i,n)}},function(t,e,i){"use strict";t.exports=function(t,e){return function(){for(var i=new Array(arguments.length),s=0;s<i.length;s++)i[s]=arguments[s];return t.apply(e,i)}}},function(t,e,i){"use strict";function s(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var n=function(){function t(t,e){for(var i=0;i<e.length;i++){var s=e[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(t,s.key,s)}}return function(e,i,s){return i&&t(e.prototype,i),s&&t(e,s),e}}(),r=function(){function t(e,i,n,r,o){s(this,t),this.game=e,this.scale=i||1,this.color=o,this.x=n,this.y=r,this.sprite=this.game.add.sprite(this.x,this.y,"bricks",this.color),this.sprite.inputEnabled=!0,this.sprite.scale.setTo(this.scale),this.emitter=this.game.add.emitter(0,0,6),this.emitter.makeParticles("bricks",this.color),this.emitter.minParticleScale=this.scale,this.emitter.maxParticleScale=this.scale,this.emitter.gravity=2e3*this.scale}return n(t,[{key:"tweenTo",value:function(t,e){this.game.add.tween(this.sprite).to({x:t,y:e},400,"Bounce",!0)}},{key:"addClickEvent",value:function(t,e){this.sprite.events.onInputDown.add(t,e)}},{key:"enableClickEvents",value:function(){this.sprite.inputEnabled=!0}},{key:"disableClickEvents",value:function(){this.sprite.inputEnabled=!1}},{key:"changePosition",value:function(t){var e=t.x,i=t.y;this.isEmpty()?(this.game.world.sendToBack(this.sprite),this.sprite.x=e||this.sprite.x,this.sprite.y=i||this.sprite.y):this.tweenTo(e,i),this.x=e,this.y=i}},{key:"runDestroyAnim",value:function(){this.game.world.bringToTop(this.emitter),this.emitter.x=this.x+this.sprite.width/2,this.emitter.y=this.y+this.sprite.width/2,this.emitter.start(!1,1e3,1,1)}},{key:"destroy",value:function(){this.runDestroyAnim(),this.sprite.destroy()}},{key:"isEmpty",value:function(){return 7===this.color}}]),t}();e.a=r},,,,,,,,,,,,,,function(t,e,i){"use strict";function s(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function r(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}Object.defineProperty(e,"__esModule",{value:!0});var o=i(79),a=(i.n(o),i(81)),h=(i.n(a),i(80)),l=i.n(h),c=i(60),u=i(5),d=u.a.SCREENWIDTH,p=u.a.SCREENHEIGHT;new(function(t){function e(t,i,r){s(this,e);var o=n(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t,i,r));return o.state.add("Preload",c.a,!1),o.state.add("Main",c.b,!1),o.state.start("Preload"),o}return r(e,t),e}(l.a.Game))(d,p,l.a.CANVAS)},,,,function(t,e,i){t.exports=i(38)},function(t,e,i){"use strict";function s(t){var e=new o(t),i=r(o.prototype.request,e);return n.extend(i,o.prototype,e),n.extend(i,e),i}var n=i(1),r=i(18),o=i(40),a=i(9),h=s(a);h.Axios=o,h.create=function(t){return s(n.merge(a,t))},h.Cancel=i(15),h.CancelToken=i(39),h.isCancel=i(16),h.all=function(t){return Promise.all(t)},h.spread=i(54),t.exports=h,t.exports.default=h},function(t,e,i){"use strict";function s(t){if("function"!=typeof t)throw new TypeError("executor must be a function.");var e;this.promise=new Promise(function(t){e=t});var i=this;t(function(t){i.reason||(i.reason=new n(t),e(i.reason))})}var n=i(15);s.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},s.source=function(){var t;return{token:new s(function(e){t=e}),cancel:t}},t.exports=s},function(t,e,i){"use strict";function s(t){this.defaults=t,this.interceptors={request:new o,response:new o}}var n=i(9),r=i(1),o=i(41),a=i(42),h=i(50),l=i(48);s.prototype.request=function(t){"string"==typeof t&&(t=r.merge({url:arguments[0]},arguments[1])),t=r.merge(n,this.defaults,{method:"get"},t),t.baseURL&&!h(t.url)&&(t.url=l(t.baseURL,t.url));var e=[a,void 0],i=Promise.resolve(t);for(this.interceptors.request.forEach(function(t){e.unshift(t.fulfilled,t.rejected)}),this.interceptors.response.forEach(function(t){e.push(t.fulfilled,t.rejected)});e.length;)i=i.then(e.shift(),e.shift());return i},r.forEach(["delete","get","head","options"],function(t){s.prototype[t]=function(e,i){return this.request(r.merge(i||{},{method:t,url:e}))}}),r.forEach(["post","put","patch"],function(t){s.prototype[t]=function(e,i,s){return this.request(r.merge(s||{},{method:t,url:e,data:i}))}}),t.exports=s},function(t,e,i){"use strict";function s(){this.handlers=[]}var n=i(1);s.prototype.use=function(t,e){return this.handlers.push({fulfilled:t,rejected:e}),this.handlers.length-1},s.prototype.eject=function(t){this.handlers[t]&&(this.handlers[t]=null)},s.prototype.forEach=function(t){n.forEach(this.handlers,function(e){null!==e&&t(e)})},t.exports=s},function(t,e,i){"use strict";function s(t){t.cancelToken&&t.cancelToken.throwIfRequested()}var n=i(1),r=i(45),o=i(16),a=i(9);t.exports=function(t){return s(t),t.headers=t.headers||{},t.data=r(t.data,t.headers,t.transformRequest),t.headers=n.merge(t.headers.common||{},t.headers[t.method]||{},t.headers||{}),n.forEach(["delete","get","head","post","put","patch","common"],function(e){delete t.headers[e]}),(t.adapter||a.adapter)(t).then(function(e){return s(t),e.data=r(e.data,e.headers,t.transformResponse),e},function(e){return o(e)||(s(t),e&&e.response&&(e.response.data=r(e.response.data,e.response.headers,t.transformResponse))),Promise.reject(e)})}},function(t,e,i){"use strict";t.exports=function(t,e,i,s){return t.config=e,i&&(t.code=i),t.response=s,t}},function(t,e,i){"use strict";var s=i(17);t.exports=function(t,e,i){var n=i.config.validateStatus;i.status&&n&&!n(i.status)?e(s("Request failed with status code "+i.status,i.config,null,i)):t(i)}},function(t,e,i){"use strict";var s=i(1);t.exports=function(t,e,i){return s.forEach(i,function(i){t=i(t,e)}),t}},function(t,e,i){"use strict";function s(){this.message="String contains an invalid character"}function n(t){for(var e,i,n=String(t),o="",a=0,h=r;n.charAt(0|a)||(h="=",a%1);o+=h.charAt(63&e>>8-a%1*8)){if((i=n.charCodeAt(a+=.75))>255)throw new s;e=e<<8|i}return o}var r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";s.prototype=new Error,s.prototype.code=5,s.prototype.name="InvalidCharacterError",t.exports=n},function(t,e,i){"use strict";function s(t){return encodeURIComponent(t).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var n=i(1);t.exports=function(t,e,i){if(!e)return t;var r;if(i)r=i(e);else if(n.isURLSearchParams(e))r=e.toString();else{var o=[];n.forEach(e,function(t,e){null!==t&&void 0!==t&&(n.isArray(t)&&(e+="[]"),n.isArray(t)||(t=[t]),n.forEach(t,function(t){n.isDate(t)?t=t.toISOString():n.isObject(t)&&(t=JSON.stringify(t)),o.push(s(e)+"="+s(t))}))}),r=o.join("&")}return r&&(t+=(-1===t.indexOf("?")?"?":"&")+r),t}},function(t,e,i){"use strict";t.exports=function(t,e){return e?t.replace(/\/+$/,"")+"/"+e.replace(/^\/+/,""):t}},function(t,e,i){"use strict";var s=i(1);t.exports=s.isStandardBrowserEnv()?function(){return{write:function(t,e,i,n,r,o){var a=[];a.push(t+"="+encodeURIComponent(e)),s.isNumber(i)&&a.push("expires="+new Date(i).toGMTString()),s.isString(n)&&a.push("path="+n),s.isString(r)&&a.push("domain="+r),!0===o&&a.push("secure"),document.cookie=a.join("; ")},read:function(t){var e=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove:function(t){this.write(t,"",Date.now()-864e5)}}}():function(){return{write:function(){},read:function(){return null},remove:function(){}}}()},function(t,e,i){"use strict";t.exports=function(t){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(t)}},function(t,e,i){"use strict";var s=i(1);t.exports=s.isStandardBrowserEnv()?function(){function t(t){var e=t;return i&&(n.setAttribute("href",e),e=n.href),n.setAttribute("href",e),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:"/"===n.pathname.charAt(0)?n.pathname:"/"+n.pathname}}var e,i=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");return e=t(window.location.href),function(i){var n=s.isString(i)?t(i):i;return n.protocol===e.protocol&&n.host===e.host}}():function(){return function(){return!0}}()},function(t,e,i){"use strict";var s=i(1);t.exports=function(t,e){s.forEach(t,function(i,s){s!==e&&s.toUpperCase()===e.toUpperCase()&&(t[e]=i,delete t[s])})}},function(t,e,i){"use strict";var s=i(1);t.exports=function(t){var e,i,n,r={};return t?(s.forEach(t.split("\n"),function(t){n=t.indexOf(":"),e=s.trim(t.substr(0,n)).toLowerCase(),i=s.trim(t.substr(n+1)),e&&(r[e]=r[e]?r[e]+", "+i:i)}),r):r}},function(t,e,i){"use strict";t.exports=function(t){return function(e){return t.apply(null,e)}}},function(t,e,i){"use strict";function s(t){function e(i,s,n){var r=n||[];return 0==s||t.boardRows[s][i].isEmpty()||(r.push(t.boardRows[s][i]),e(i,s-1,r)),r}var i=t.getBrickLocation(this),s=i.x,n=(i.y,e(s,t.boardRows.length-1)),r=n.length;t.deleteGroup(n),t.addScore(r)}function n(t){for(var e=t.getBrickLocation(this),i=(e.x,e.y),s=[],n=0;n<t.boardRows[i].length;n++)t.boardRows[i][n].isEmpty()||s.push(t.boardRows[i][n]);var r=s.length;t.deleteGroup(s),t.addScore(r)}function r(t){var e=t.getBrickLocation(this),i=e.x,s=e.y,n=[];n.push(t.boardRows[s][i]),i!==t.boardRows[s].length-1&&n.push(t.boardRows[s][i+1]),i!==t.boardRows[s].length-1&&s!==t.boardRows.length-1&&n.push(t.boardRows[s+1][i+1]),i!==t.boardRows[s].length-1&&0!==s&&n.push(t.boardRows[s-1][i+1]),0!==i&&n.push(t.boardRows[s][i-1]),0!==i&&0!==s&&n.push(t.boardRows[s-1][i-1]),0!==i&&s!==t.boardRows.length-1&&n.push(t.boardRows[s+1][i-1]),0!==s&&n.push(t.boardRows[s-1][i]),s!==t.boardRows.length-1&&n.push(t.boardRows[s+1][i]);for(var r=n.length-1;r>0;r--)n[r].isEmpty()&&n.splice(r,1);var o=n.length;t.deleteGroup(n),t.addScore(o)}function o(t){return a[t]}e.a=o;var a={8:s,9:n,10:r}},function(t,e,i){"use strict";function s(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var n=i(19),r=i(57),o=i(5),a=i(37),h=i.n(a),l=function(){function t(t,e){for(var i=0;i<e.length;i++){var s=e[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(t,s.key,s)}}return function(e,i,s){return i&&t(e.prototype,i),s&&t(e,s),e}}(),c=o.a.BRICKSIZE,u=function(){function t(e,i,n,r){s(this,t),this.game=e,this.boardRows=[],this.brickSize=c,this.brickScale=i,this.brickOffset=this.brickSize*this.brickScale,this.boardWidth=8*this.brickOffset,this.boardHeight=12*this.brickOffset,this.boardOffsetW=this.boardWidth/2,this.boardOffsetH=this.boardHeight/2,this.posX=n-this.boardOffsetW,this.posY=r-this.boardOffsetH,this.moves=0,this.numOfColors=5,this.playerScore=0,this.destroyBrickSound=this.game.add.audio("brickDestroy"),this.destroyBrickSound.volume=1.5,this.gameMusic=this.game.add.audio("gameMusic"),this.gameMusic.loop=!0,this.gameMusic.volume=.5,o.c||(this.background=this.makeBackground(),this.background.start(!1,5e3,250,0)),this.scoreBoard=this.game.add.text(this.posX,this.posY-100*this.brickScale,"Score: "+this.playerScore,{fill:"#fff",fontSize:60*this.brickScale}),this.settings={},this.settings.music=!0,this.settings.sound=!0,this.settingsIcon=this.game.add.sprite(this.boardWidth+this.posX-90*this.brickScale,this.posY-90*this.brickScale,"settingsIcon"),this.settingsIcon.width=75*this.brickScale,this.settingsIcon.height=75*this.brickScale,this.settingsIcon.inputEnabled=!0,this.settingsIcon.events.onInputDown.add(this.openSettingsModal,this),this.createBoard(),this.gameMusic.play()}return l(t,[{key:"createSettingsModal",value:function(){var t=this.game.add.graphics(0,0);t.beginFill(3783567),t.drawRect(this.game.world.centerX-150,this.game.world.centerY-200,300,400),t.endFill(),t.beginFill(16777215),t.drawRect(this.game.world.centerX-150+5,this.game.world.centerY-200+5,290,390),t.endFill(),this.disableBoardInput()}},{key:"openSettingsModal",value:function(){}},{key:"makeBackground",value:function(){var t=this.game.add.emitter(this.game.world.centerX,-100,50);return t.width=this.game.world.width,t.minParticleScale=.25*this.brickScale,t.maxParticleScale=.8*this.brickScale,t.makeParticles("bricks",[0,1,2,3,4,5]),t.setYSpeed(50*this.brickScale,150*this.brickScale),t.setXSpeed(0,0),t.minRotation=0,t.maxRotation=0,t}},{key:"brickClickHandler",value:function(t){if(7!==t.frame){var e=this.getBrickLocation(t),i=e.x,s=e.y,n=this.findColorGroup(s,i,t.frame),r=n.length;if(this.deleteGroup(n),2===++this.moves)if(this.isGameOver())this.gameOver();else{var o=this.posX+this.brickOffset,a=this.posY+this.brickOffset;this.boardRows[0]=this.createColorRow(o,a),this.moves=0}this.dropColumns(),this.addScore(r)}}},{key:"powerUpClickHandler",value:function(t){var e=this.getBrickLocation(t),i=e.x,s=e.y;if(this.boardRows[s][i].applyEffect(this),2==++this.moves)if(this.isGameOver())this.gameOver();else{var n=this.posX+this.brickOffset,r=this.posY+this.brickOffset;this.boardRows[0]=this.createColorRow(n,r),this.moves=0}this.dropColumns()}},{key:"runScoreAnim",value:function(t){var e=this,i=this.game.add.text(this.game.input.x,this.game.input.y-50*this.brickScale,"+"+t,{fill:"#fff",fontSize:60*this.brickScale});this.game.world.bringToTop(i);var s=this.game.add.tween(i).to({y:i.y-50*this.brickScale},300,"Quad.easeOut",!0),n=function(){e.game.add.tween(i).to({alpha:0},400,"Quad.easeOut",!0).onComplete.add(function(){return i.destroy()})};s.onComplete.add(n)}},{key:"addScore",value:function(t){var e=Math.floor(t+t/1.5);this.runScoreAnim(e),this.playerScore+=e,this.updateScoreBoard()}},{key:"updateScoreBoard",value:function(){this.scoreBoard.text="Score: "+this.playerScore}},{key:"findColorGroup",value:function(t,e,i,s){var n=s||[],r=function(t){return n.includes(t)};return r(this.boardRows[t][e])||n.push(this.boardRows[t][e]),0!=e&&this.boardRows[t][e-1].color===i&&(r(this.boardRows[t][e-1])||(n.push(this.boardRows[t][e-1]),this.findColorGroup(t,e-1,i,n))),e!=this.boardRows[t].length-1&&this.boardRows[t][e+1].color===i&&(r(this.boardRows[t][e+1])||(n.push(this.boardRows[t][e+1]),this.findColorGroup(t,e+1,i,n))),0!=t&&this.boardRows[t-1][e].color===i&&(r(this.boardRows[t-1][e])||(n.push(this.boardRows[t-1][e]),this.findColorGroup(t-1,e,i,n))),t!=this.boardRows.length-1&&this.boardRows[t+1][e].color===i&&(r(this.boardRows[t+1][e])||(n.push(this.boardRows[t+1][e]),this.findColorGroup(t+1,e,i,n))),n}},{key:"createBoard",value:function(){this.createBoardBackground();for(var t=this.posX+this.brickOffset,e=this.posY+this.brickOffset,i=0;i<10;i++){var s=this.brickOffset*i;i<4?this.boardRows.push(this.createColorRow(t,e+s,7)):this.boardRows.push(this.createColorRow(t,e+s))}}},{key:"renderBoard",value:function(){for(var t=0;t<this.boardRows.length;t++)for(var e=0;e<this.boardRows[t].length;e++){var i=this.posX+this.brickOffset+this.brickOffset*e,s=this.posY+this.brickOffset+this.brickOffset*t;this.boardRows[t][e].changePosition({x:i,y:s})}}},{key:"createBoardBackground",value:function(){for(var t=0;t<12;t++)for(var e=0;e<8;e++){var i=this.brickOffset*e,s=this.brickOffset*t,r=6;e>0&&e<7&&t>0&&t<11&&(r=7),new n.a(this.game,this.brickScale,this.posX+i,this.posY+s,r)}}},{key:"createEmptyBrick",value:function(t,e){var i=this.getBrickLocation(this.boardRows[t][e]),s=i.x,r=i.y;return new n.a(this.game,this.brickScale,s,r,7)}},{key:"createColorRow",value:function(t,e,i){for(var s=[],o=void 0,a=0;a<6;a++){var h=void 0;Math.floor(100*Math.random())<96?(o=i||Math.floor(Math.random()*this.numOfColors),h=new n.a(this.game,this.brickScale,t+this.brickOffset*a,e,o),h.addClickEvent(this.brickClickHandler,this)):(o=i||Math.floor(3*Math.random())+8,h=new r.a(this.game,this.brickScale,t+this.brickOffset*a,e,o),h.addClickEvent(this.powerUpClickHandler,this)),s.push(h)}return s}},{key:"dropColumns",value:function(){for(var t=[[],[],[],[],[],[]],e=0;e<t.length;e++){for(var i=0;i<10;i++)t[e].push(this.boardRows[i][e]);this.moveEmptyTop(t[e])}for(var s=0;s<t.length;s++)for(var n=0;n<t[s].length;n++)this.boardRows[n][s]=t[s][n];this.renderBoard()}},{key:"moveEmptyTop",value:function(t){for(var e=0;e<t.length;e++)if(t[e].isEmpty()){var i=t.splice(e,1)[0];t.unshift(i)}}},{key:"getBrickLocation",value:function(t){return{x:(t.x-this.posX)/this.brickOffset-1,y:(t.y-this.posY)/this.brickOffset-1}}},{key:"deleteBrick",value:function(t,e){var i=this.createEmptyBrick(t,e);this.boardRows[t][e].destroy(),this.boardRows[t].splice(e,1,i)}},{key:"deleteGroup",value:function(t){for(var e=0;e<t.length;e++){var i=this.getBrickLocation(t[e]),s=i.x,n=i.y;this.deleteBrick(n,s)}this.destroyBrickSound.play()}},{key:"isGameOver",value:function(){for(var t=!1,e=0;e<this.boardRows[0].length;e++)if(!this.boardRows[0][e].isEmpty()){t=!0;break}return t}},{key:"disableBoardInput",value:function(){this.boardRows.map(function(t){t.map(function(t){t.disableClickEvents()})})}},{key:"enableBoardInput",value:function(){this.boardRows.map(function(t){t.map(function(t){t.enableClickEvents()})})}},{key:"gameOver",value:function(){this.disableBoardInput(),this.scoreBoard.text="Game Over\nFinal Score: "+this.playerScore,h.a.post("/user/score/new",{score:this.playerScore}).then(function(t){alert("Thanks for playing!"),window.location.replace("/profile")}).catch(function(t){console.log(t)})}}]),t}();e.a=u},function(t,e,i){"use strict";function s(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function r(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}var o=i(19),a=i(55),h=function(){function t(t,e){for(var i=0;i<e.length;i++){var s=e[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(t,s.key,s)}}return function(e,i,s){return i&&t(e.prototype,i),s&&t(e,s),e}}(),l=function(t){function e(t,r,o,h,l){s(this,e);var c=n(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t,r,o,h,l));return c.effect=i.i(a.a)(c.color),c}return r(e,t),h(e,[{key:"applyEffect",value:function(t){this.effect(t)}}]),e}(o.a);e.a=l},function(t,e,i){"use strict";function s(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function r(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}var o=i(5),a=i(56),h=function(){function t(t,e){for(var i=0;i<e.length;i++){var s=e[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(t,s.key,s)}}return function(e,i,s){return i&&t(e.prototype,i),s&&t(e,s),e}}(),l=(o.a.SCREENWIDTH,o.a.SCREENHEIGHT,o.a.SCALERATIO),c=function(t){function e(){return s(this,e),n(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return r(e,t),h(e,[{key:"create",value:function(){this.game.scale.fullScreenScaleMode=Phaser.ScaleManager.SHOW_ALL,this.game.scale.scaleMode=Phaser.ScaleManager.SHOW_ALL,this.game.scale.refresh(),this.game.forceSingleUpdate=!0,this.myBoard=new a.a(this.game,l,this.game.world.centerX,this.game.world.centerY)}}]),e}(Phaser.State);e.a=c},function(t,e,i){"use strict";function s(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function r(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}var o=i(5),a=i(84),h=i.n(a),l=i(82),c=i.n(l),u=i(83),d=i.n(u),p=i(85),f=i.n(p),g=function(){function t(t,e){for(var i=0;i<e.length;i++){var s=e[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(t,s.key,s)}}return function(e,i,s){return i&&t(e.prototype,i),s&&t(e,s),e}}(),m=function(t){function e(){return s(this,e),n(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return r(e,t),g(e,[{key:"preload",value:function(){var t=this;this.load.onLoadComplete.addOnce(function(){return t.ready=!0}),this.loadResources()}},{key:"create",value:function(){this.stage.backgroundColor=o.b.DARKBLUE,this.game.add.text(this.game.world.centerX,this.game.world.centerY,"Loading ...",{fill:"#fff",align:"center",fontSize:50*o.a.SCALERATIO}).anchor.set(.5)}},{key:"loadResources",value:function(){this.game.load.spritesheet("bricks",h.a,o.a.BRICKSIZE,o.a.BRICKSIZE,11),this.game.load.image("settingsIcon",f.a),this.game.load.audio("brickDestroy",c.a),this.game.load.audio("gameMusic",d.a)}},{key:"update",value:function(){this.ready&&this.game.state.start("Main")}}]),e}(Phaser.State);e.a=m},function(t,e,i){"use strict";var s=i(58),n=i(59);i.d(e,"b",function(){return s.a}),i.d(e,"a",function(){return n.a})},,,function(t,e,i){"use strict";function s(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===t[e-2]?2:"="===t[e-1]?1:0}function n(t){return 3*t.length/4-s(t)}function r(t){var e,i,n,r,o,a,h=t.length;o=s(t),a=new u(3*h/4-o),n=o>0?h-4:h;var l=0;for(e=0,i=0;e<n;e+=4,i+=3)r=c[t.charCodeAt(e)]<<18|c[t.charCodeAt(e+1)]<<12|c[t.charCodeAt(e+2)]<<6|c[t.charCodeAt(e+3)],a[l++]=r>>16&255,a[l++]=r>>8&255,a[l++]=255&r;return 2===o?(r=c[t.charCodeAt(e)]<<2|c[t.charCodeAt(e+1)]>>4,a[l++]=255&r):1===o&&(r=c[t.charCodeAt(e)]<<10|c[t.charCodeAt(e+1)]<<4|c[t.charCodeAt(e+2)]>>2,a[l++]=r>>8&255,a[l++]=255&r),a}function o(t){return l[t>>18&63]+l[t>>12&63]+l[t>>6&63]+l[63&t]}function a(t,e,i){for(var s,n=[],r=e;r<i;r+=3)s=(t[r]<<16)+(t[r+1]<<8)+t[r+2],n.push(o(s));return n.join("")}function h(t){for(var e,i=t.length,s=i%3,n="",r=[],o=0,h=i-s;o<h;o+=16383)r.push(a(t,o,o+16383>h?h:o+16383));return 1===s?(e=t[i-1],n+=l[e>>2],n+=l[e<<4&63],n+="=="):2===s&&(e=(t[i-2]<<8)+t[i-1],n+=l[e>>10],n+=l[e>>4&63],n+=l[e<<2&63],n+="="),r.push(n),r.join("")}e.byteLength=n,e.toByteArray=r,e.fromByteArray=h;for(var l=[],c=[],u="undefined"!=typeof Uint8Array?Uint8Array:Array,d="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",p=0,f=d.length;p<f;++p)l[p]=d[p],c[d.charCodeAt(p)]=p;c["-".charCodeAt(0)]=62,c["_".charCodeAt(0)]=63},,function(t,e,i){"use strict";(function(t){function s(){return r.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function n(t,e){if(s()<e)throw new RangeError("Invalid typed array length");return r.TYPED_ARRAY_SUPPORT?(t=new Uint8Array(e),t.__proto__=r.prototype):(null===t&&(t=new r(e)),t.length=e),t}function r(t,e,i){if(!(r.TYPED_ARRAY_SUPPORT||this instanceof r))return new r(t,e,i);if("number"==typeof t){if("string"==typeof e)throw new Error("If encoding is specified then the first argument must be a string");return l(this,t)}return o(this,t,e,i)}function o(t,e,i,s){if("number"==typeof e)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer?d(t,e,i,s):"string"==typeof e?c(t,e,i):p(t,e)}function a(t){if("number"!=typeof t)throw new TypeError('"size" argument must be a number');if(t<0)throw new RangeError('"size" argument must not be negative')}function h(t,e,i,s){return a(e),e<=0?n(t,e):void 0!==i?"string"==typeof s?n(t,e).fill(i,s):n(t,e).fill(i):n(t,e)}function l(t,e){if(a(e),t=n(t,e<0?0:0|f(e)),!r.TYPED_ARRAY_SUPPORT)for(var i=0;i<e;++i)t[i]=0;return t}function c(t,e,i){if("string"==typeof i&&""!==i||(i="utf8"),!r.isEncoding(i))throw new TypeError('"encoding" must be a valid string encoding');var s=0|m(e,i);t=n(t,s);var o=t.write(e,i);return o!==s&&(t=t.slice(0,o)),t}function u(t,e){var i=e.length<0?0:0|f(e.length);t=n(t,i);for(var s=0;s<i;s+=1)t[s]=255&e[s];return t}function d(t,e,i,s){if(e.byteLength,i<0||e.byteLength<i)throw new RangeError("'offset' is out of bounds");if(e.byteLength<i+(s||0))throw new RangeError("'length' is out of bounds");return e=void 0===i&&void 0===s?new Uint8Array(e):void 0===s?new Uint8Array(e,i):new Uint8Array(e,i,s),r.TYPED_ARRAY_SUPPORT?(t=e,t.__proto__=r.prototype):t=u(t,e),t}function p(t,e){if(r.isBuffer(e)){var i=0|f(e.length);return t=n(t,i),0===t.length?t:(e.copy(t,0,0,i),t)}if(e){if("undefined"!=typeof ArrayBuffer&&e.buffer instanceof ArrayBuffer||"length"in e)return"number"!=typeof e.length||K(e.length)?n(t,0):u(t,e);if("Buffer"===e.type&&Z(e.data))return u(t,e.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}function f(t){if(t>=s())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s().toString(16)+" bytes");return 0|t}function g(t){return+t!=t&&(t=0),r.alloc(+t)}function m(t,e){if(r.isBuffer(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var i=t.length;if(0===i)return 0;for(var s=!1;;)switch(e){case"ascii":case"latin1":case"binary":return i;case"utf8":case"utf-8":case void 0:return V(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*i;case"hex":return i>>>1;case"base64":return Y(t).length;default:if(s)return V(t).length;e=(""+e).toLowerCase(),s=!0}}function y(t,e,i){var s=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===i||i>this.length)&&(i=this.length),i<=0)return"";if(i>>>=0,e>>>=0,i<=e)return"";for(t||(t="utf8");;)switch(t){case"hex":return B(this,e,i);case"utf8":case"utf-8":return E(this,e,i);case"ascii":return M(this,e,i);case"latin1":case"binary":return R(this,e,i);case"base64":return A(this,e,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return L(this,e,i);default:if(s)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),s=!0}}function v(t,e,i){var s=t[e];t[e]=t[i],t[i]=s}function b(t,e,i,s,n){if(0===t.length)return-1;if("string"==typeof i?(s=i,i=0):i>2147483647?i=2147483647:i<-2147483648&&(i=-2147483648),i=+i,isNaN(i)&&(i=n?0:t.length-1),i<0&&(i=t.length+i),i>=t.length){if(n)return-1;i=t.length-1}else if(i<0){if(!n)return-1;i=0}if("string"==typeof e&&(e=r.from(e,s)),r.isBuffer(e))return 0===e.length?-1:x(t,e,i,s,n);if("number"==typeof e)return e&=255,r.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?n?Uint8Array.prototype.indexOf.call(t,e,i):Uint8Array.prototype.lastIndexOf.call(t,e,i):x(t,[e],i,s,n);throw new TypeError("val must be string, number or Buffer")}function x(t,e,i,s,n){function r(t,e){return 1===o?t[e]:t.readUInt16BE(e*o)}var o=1,a=t.length,h=e.length;if(void 0!==s&&("ucs2"===(s=String(s).toLowerCase())||"ucs-2"===s||"utf16le"===s||"utf-16le"===s)){if(t.length<2||e.length<2)return-1;o=2,a/=2,h/=2,i/=2}var l;if(n){var c=-1;for(l=i;l<a;l++)if(r(t,l)===r(e,-1===c?0:l-c)){if(-1===c&&(c=l),l-c+1===h)return c*o}else-1!==c&&(l-=l-c),c=-1}else for(i+h>a&&(i=a-h),l=i;l>=0;l--){for(var u=!0,d=0;d<h;d++)if(r(t,l+d)!==r(e,d)){u=!1;break}if(u)return l}return-1}function w(t,e,i,s){i=Number(i)||0;var n=t.length-i;s?(s=Number(s))>n&&(s=n):s=n;var r=e.length;if(r%2!=0)throw new TypeError("Invalid hex string");s>r/2&&(s=r/2);for(var o=0;o<s;++o){var a=parseInt(e.substr(2*o,2),16);if(isNaN(a))return o;t[i+o]=a}return o}function _(t,e,i,s){return z(V(e,t.length-i),t,i,s)}function P(t,e,i,s){return z(q(e),t,i,s)}function T(t,e,i,s){return P(t,e,i,s)}function C(t,e,i,s){return z(Y(e),t,i,s)}function S(t,e,i,s){return z(H(e,t.length-i),t,i,s)}function A(t,e,i){return 0===e&&i===t.length?J.fromByteArray(t):J.fromByteArray(t.slice(e,i))}function E(t,e,i){i=Math.min(t.length,i);for(var s=[],n=e;n<i;){var r=t[n],o=null,a=r>239?4:r>223?3:r>191?2:1;if(n+a<=i){var h,l,c,u;switch(a){case 1:r<128&&(o=r);break;case 2:h=t[n+1],128==(192&h)&&(u=(31&r)<<6|63&h)>127&&(o=u);break;case 3:h=t[n+1],l=t[n+2],128==(192&h)&&128==(192&l)&&(u=(15&r)<<12|(63&h)<<6|63&l)>2047&&(u<55296||u>57343)&&(o=u);break;case 4:h=t[n+1],l=t[n+2],c=t[n+3],128==(192&h)&&128==(192&l)&&128==(192&c)&&(u=(15&r)<<18|(63&h)<<12|(63&l)<<6|63&c)>65535&&u<1114112&&(o=u)}}null===o?(o=65533,a=1):o>65535&&(o-=65536,s.push(o>>>10&1023|55296),o=56320|1023&o),s.push(o),n+=a}return I(s)}function I(t){var e=t.length;if(e<=$)return String.fromCharCode.apply(String,t);for(var i="",s=0;s<e;)i+=String.fromCharCode.apply(String,t.slice(s,s+=$));return i}function M(t,e,i){var s="";i=Math.min(t.length,i);for(var n=e;n<i;++n)s+=String.fromCharCode(127&t[n]);return s}function R(t,e,i){var s="";i=Math.min(t.length,i);for(var n=e;n<i;++n)s+=String.fromCharCode(t[n]);return s}function B(t,e,i){var s=t.length;(!e||e<0)&&(e=0),(!i||i<0||i>s)&&(i=s);for(var n="",r=e;r<i;++r)n+=j(t[r]);return n}function L(t,e,i){for(var s=t.slice(e,i),n="",r=0;r<s.length;r+=2)n+=String.fromCharCode(s[r]+256*s[r+1]);return n}function O(t,e,i){if(t%1!=0||t<0)throw new RangeError("offset is not uint");if(t+e>i)throw new RangeError("Trying to access beyond buffer length")}function k(t,e,i,s,n,o){if(!r.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>n||e<o)throw new RangeError('"value" argument is out of bounds');if(i+s>t.length)throw new RangeError("Index out of range")}function F(t,e,i,s){e<0&&(e=65535+e+1);for(var n=0,r=Math.min(t.length-i,2);n<r;++n)t[i+n]=(e&255<<8*(s?n:1-n))>>>8*(s?n:1-n)}function D(t,e,i,s){e<0&&(e=4294967295+e+1);for(var n=0,r=Math.min(t.length-i,4);n<r;++n)t[i+n]=e>>>8*(s?n:3-n)&255}function U(t,e,i,s,n,r){if(i+s>t.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("Index out of range")}function G(t,e,i,s,n){return n||U(t,e,i,4,3.4028234663852886e38,-3.4028234663852886e38),Q.write(t,e,i,s,23,4),i+4}function N(t,e,i,s,n){return n||U(t,e,i,8,1.7976931348623157e308,-1.7976931348623157e308),Q.write(t,e,i,s,52,8),i+8}function X(t){if(t=W(t).replace(tt,""),t.length<2)return"";for(;t.length%4!=0;)t+="=";return t}function W(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function j(t){return t<16?"0"+t.toString(16):t.toString(16)}function V(t,e){e=e||1/0;for(var i,s=t.length,n=null,r=[],o=0;o<s;++o){if((i=t.charCodeAt(o))>55295&&i<57344){if(!n){if(i>56319){(e-=3)>-1&&r.push(239,191,189);continue}if(o+1===s){(e-=3)>-1&&r.push(239,191,189);continue}n=i;continue}if(i<56320){(e-=3)>-1&&r.push(239,191,189),n=i;continue}i=65536+(n-55296<<10|i-56320)}else n&&(e-=3)>-1&&r.push(239,191,189);if(n=null,i<128){if((e-=1)<0)break;r.push(i)}else if(i<2048){if((e-=2)<0)break;r.push(i>>6|192,63&i|128)}else if(i<65536){if((e-=3)<0)break;r.push(i>>12|224,i>>6&63|128,63&i|128)}else{if(!(i<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;r.push(i>>18|240,i>>12&63|128,i>>6&63|128,63&i|128)}}return r}function q(t){for(var e=[],i=0;i<t.length;++i)e.push(255&t.charCodeAt(i));return e}function H(t,e){for(var i,s,n,r=[],o=0;o<t.length&&!((e-=2)<0);++o)i=t.charCodeAt(o),s=i>>8,n=i%256,r.push(n),r.push(s);return r}function Y(t){return J.toByteArray(X(t))}function z(t,e,i,s){for(var n=0;n<s&&!(n+i>=e.length||n>=t.length);++n)e[n+i]=t[n];return n}function K(t){return t!==t}/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <[email protected]> <http://feross.org>
* @license MIT
*/
var J=i(63),Q=i(87),Z=i(66);e.Buffer=r,e.SlowBuffer=g,e.INSPECT_MAX_BYTES=50,r.TYPED_ARRAY_SUPPORT=void 0!==t.TYPED_ARRAY_SUPPORT?t.TYPED_ARRAY_SUPPORT:function(){try{var t=new Uint8Array(1);return t.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===t.foo()&&"function"==typeof t.subarray&&0===t.subarray(1,1).byteLength}catch(t){return!1}}(),e.kMaxLength=s(),r.poolSize=8192,r._augment=function(t){return t.__proto__=r.prototype,t},r.from=function(t,e,i){return o(null,t,e,i)},r.TYPED_ARRAY_SUPPORT&&(r.prototype.__proto__=Uint8Array.prototype,r.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&r[Symbol.species]===r&&Object.defineProperty(r,Symbol.species,{value:null,configurable:!0})),r.alloc=function(t,e,i){return h(null,t,e,i)},r.allocUnsafe=function(t){return l(null,t)},r.allocUnsafeSlow=function(t){return l(null,t)},r.isBuffer=function(t){return!(null==t||!t._isBuffer)},r.compare=function(t,e){if(!r.isBuffer(t)||!r.isBuffer(e))throw new TypeError("Arguments must be Buffers");if(t===e)return 0;for(var i=t.length,s=e.length,n=0,o=Math.min(i,s);n<o;++n)if(t[n]!==e[n]){i=t[n],s=e[n];break}return i<s?-1:s<i?1:0},r.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},r.concat=function(t,e){if(!Z(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return r.alloc(0);var i;if(void 0===e)for(e=0,i=0;i<t.length;++i)e+=t[i].length;var s=r.allocUnsafe(e),n=0;for(i=0;i<t.length;++i){var o=t[i];if(!r.isBuffer(o))throw new TypeError('"list" argument must be an Array of Buffers');o.copy(s,n),n+=o.length}return s},r.byteLength=m,r.prototype._isBuffer=!0,r.prototype.swap16=function(){var t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var e=0;e<t;e+=2)v(this,e,e+1);return this},r.prototype.swap32=function(){var t=this.length;if(t%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var e=0;e<t;e+=4)v(this,e,e+3),v(this,e+1,e+2);return this},r.prototype.swap64=function(){var t=this.length;if(t%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var e=0;e<t;e+=8)v(this,e,e+7),v(this,e+1,e+6),v(this,e+2,e+5),v(this,e+3,e+4);return this},r.prototype.toString=function(){var t=0|this.length;return 0===t?"":0===arguments.length?E(this,0,t):y.apply(this,arguments)},r.prototype.equals=function(t){if(!r.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===r.compare(this,t)},r.prototype.inspect=function(){var t="",i=e.INSPECT_MAX_BYTES;return this.length>0&&(t=this.toString("hex",0,i).match(/.{2}/g).join(" "),this.length>i&&(t+=" ... ")),"<Buffer "+t+">"},r.prototype.compare=function(t,e,i,s,n){if(!r.isBuffer(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===i&&(i=t?t.length:0),void 0===s&&(s=0),void 0===n&&(n=this.length),e<0||i>t.length||s<0||n>this.length)throw new RangeError("out of range index");if(s>=n&&e>=i)return 0;if(s>=n)return-1;if(e>=i)return 1;if(e>>>=0,i>>>=0,s>>>=0,n>>>=0,this===t)return 0;for(var o=n-s,a=i-e,h=Math.min(o,a),l=this.slice(s,n),c=t.slice(e,i),u=0;u<h;++u)if(l[u]!==c[u]){o=l[u],a=c[u];break}return o<a?-1:a<o?1:0},r.prototype.includes=function(t,e,i){return-1!==this.indexOf(t,e,i)},r.prototype.indexOf=function(t,e,i){return b(this,t,e,i,!0)},r.prototype.lastIndexOf=function(t,e,i){return b(this,t,e,i,!1)},r.prototype.write=function(t,e,i,s){if(void 0===e)s="utf8",i=this.length,e=0;else if(void 0===i&&"string"==typeof e)s=e,i=this.length,e=0;else{if(!isFinite(e))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");e|=0,isFinite(i)?(i|=0,void 0===s&&(s="utf8")):(s=i,i=void 0)}var n=this.length-e;if((void 0===i||i>n)&&(i=n),t.length>0&&(i<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");s||(s="utf8");for(var r=!1;;)switch(s){case"hex":return w(this,t,e,i);case"utf8":case"utf-8":return _(this,t,e,i);case"ascii":return P(this,t,e,i);case"latin1":case"binary":return T(this,t,e,i);case"base64":return C(this,t,e,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,t,e,i);default:if(r)throw new TypeError("Unknown encoding: "+s);s=(""+s).toLowerCase(),r=!0}},r.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var $=4096;r.prototype.slice=function(t,e){var i=this.length;t=~~t,e=void 0===e?i:~~e,t<0?(t+=i)<0&&(t=0):t>i&&(t=i),e<0?(e+=i)<0&&(e=0):e>i&&(e=i),e<t&&(e=t);var s;if(r.TYPED_ARRAY_SUPPORT)s=this.subarray(t,e),s.__proto__=r.prototype;else{var n=e-t;s=new r(n,void 0);for(var o=0;o<n;++o)s[o]=this[o+t]}return s},r.prototype.readUIntLE=function(t,e,i){t|=0,e|=0,i||O(t,e,this.length);for(var s=this[t],n=1,r=0;++r<e&&(n*=256);)s+=this[t+r]*n;return s},r.prototype.readUIntBE=function(t,e,i){t|=0,e|=0,i||O(t,e,this.length);for(var s=this[t+--e],n=1;e>0&&(n*=256);)s+=this[t+--e]*n;return s},r.prototype.readUInt8=function(t,e){return e||O(t,1,this.length),this[t]},r.prototype.readUInt16LE=function(t,e){return e||O(t,2,this.length),this[t]|this[t+1]<<8},r.prototype.readUInt16BE=function(t,e){return e||O(t,2,this.length),this[t]<<8|this[t+1]},r.prototype.readUInt32LE=function(t,e){return e||O(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},r.prototype.readUInt32BE=function(t,e){return e||O(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},r.prototype.readIntLE=function(t,e,i){t|=0,e|=0,i||O(t,e,this.length);for(var s=this[t],n=1,r=0;++r<e&&(n*=256);)s+=this[t+r]*n;return n*=128,s>=n&&(s-=Math.pow(2,8*e)),s},r.prototype.readIntBE=function(t,e,i){t|=0,e|=0,i||O(t,e,this.length);for(var s=e,n=1,r=this[t+--s];s>0&&(n*=256);)r+=this[t+--s]*n;return n*=128,r>=n&&(r-=Math.pow(2,8*e)),r},r.prototype.readInt8=function(t,e){return e||O(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},r.prototype.readInt16LE=function(t,e){e||O(t,2,this.length);var i=this[t]|this[t+1]<<8;return 32768&i?4294901760|i:i},r.prototype.readInt16BE=function(t,e){e||O(t,2,this.length);var i=this[t+1]|this[t]<<8;return 32768&i?4294901760|i:i},r.prototype.readInt32LE=function(t,e){return e||O(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},r.prototype.readInt32BE=function(t,e){return e||O(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},r.prototype.readFloatLE=function(t,e){return e||O(t,4,this.length),Q.read(this,t,!0,23,4)},r.prototype.readFloatBE=function(t,e){return e||O(t,4,this.length),Q.read(this,t,!1,23,4)},r.prototype.readDoubleLE=function(t,e){return e||O(t,8,this.length),Q.read(this,t,!0,52,8)},r.prototype.readDoubleBE=function(t,e){return e||O(t,8,this.length),Q.read(this,t,!1,52,8)},r.prototype.writeUIntLE=function(t,e,i,s){if(t=+t,e|=0,i|=0,!s){k(this,t,e,i,Math.pow(2,8*i)-1,0)}var n=1,r=0;for(this[e]=255&t;++r<i&&(n*=256);)this[e+r]=t/n&255;return e+i},r.prototype.writeUIntBE=function(t,e,i,s){if(t=+t,e|=0,i|=0,!s){k(this,t,e,i,Math.pow(2,8*i)-1,0)}var n=i-1,r=1;for(this[e+n]=255&t;--n>=0&&(r*=256);)this[e+n]=t/r&255;return e+i},r.prototype.writeUInt8=function(t,e,i){return t=+t,e|=0,i||k(this,t,e,1,255,0),r.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},r.prototype.writeUInt16LE=function(t,e,i){return t=+t,e|=0,i||k(this,t,e,2,65535,0),r.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):F(this,t,e,!0),e+2},r.prototype.writeUInt16BE=function(t,e,i){return t=+t,e|=0,i||k(this,t,e,2,65535,0),r.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):F(this,t,e,!1),e+2},r.prototype.writeUInt32LE=function(t,e,i){return t=+t,e|=0,i||k(this,t,e,4,4294967295,0),r.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):D(this,t,e,!0),e+4},r.prototype.writeUInt32BE=function(t,e,i){return t=+t,e|=0,i||k(this,t,e,4,4294967295,0),r.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):D(this,t,e,!1),e+4},r.prototype.writeIntLE=function(t,e,i,s){if(t=+t,e|=0,!s){var n=Math.pow(2,8*i-1);k(this,t,e,i,n-1,-n)}var r=0,o=1,a=0;for(this[e]=255&t;++r<i&&(o*=256);)t<0&&0===a&&0!==this[e+r-1]&&(a=1),this[e+r]=(t/o>>0)-a&255;return e+i},r.prototype.writeIntBE=function(t,e,i,s){if(t=+t,e|=0,!s){var n=Math.pow(2,8*i-1);k(this,t,e,i,n-1,-n)}var r=i-1,o=1,a=0;for(this[e+r]=255&t;--r>=0&&(o*=256);)t<0&&0===a&&0!==this[e+r+1]&&(a=1),this[e+r]=(t/o>>0)-a&255;return e+i},r.prototype.writeInt8=function(t,e,i){return t=+t,e|=0,i||k(this,t,e,1,127,-128),r.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[e]=255&t,e+1},r.prototype.writeInt16LE=function(t,e,i){return t=+t,e|=0,i||k(this,t,e,2,32767,-32768),r.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):F(this,t,e,!0),e+2},r.prototype.writeInt16BE=function(t,e,i){return t=+t,e|=0,i||k(this,t,e,2,32767,-32768),r.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):F(this,t,e,!1),e+2},r.prototype.writeInt32LE=function(t,e,i){return t=+t,e|=0,i||k(this,t,e,4,2147483647,-2147483648),r.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):D(this,t,e,!0),e+4},r.prototype.writeInt32BE=function(t,e,i){return t=+t,e|=0,i||k(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),r.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):D(this,t,e,!1),e+4},r.prototype.writeFloatLE=function(t,e,i){return G(this,t,e,!0,i)},r.prototype.writeFloatBE=function(t,e,i){return G(this,t,e,!1,i)},r.prototype.writeDoubleLE=function(t,e,i){return N(this,t,e,!0,i)},r.prototype.writeDoubleBE=function(t,e,i){return N(this,t,e,!1,i)},r.prototype.copy=function(t,e,i,s){if(i||(i=0),s||0===s||(s=this.length),e>=t.length&&(e=t.length),e||(e=0),s>0&&s<i&&(s=i),s===i)return 0;if(0===t.length||0===this.length)return 0;if(e<0)throw new RangeError("targetStart out of bounds");if(i<0||i>=this.length)throw new RangeError("sourceStart out of bounds");if(s<0)throw new RangeError("sourceEnd out of bounds");s>this.length&&(s=this.length),t.length-e<s-i&&(s=t.length-e+i);var n,o=s-i;if(this===t&&i<e&&e<s)for(n=o-1;n>=0;--n)t[n+e]=this[n+i];else if(o<1e3||!r.TYPED_ARRAY_SUPPORT)for(n=0;n<o;++n)t[n+e]=this[n+i];else Uint8Array.prototype.set.call(t,this.subarray(i,i+o),e);return o},r.prototype.fill=function(t,e,i,s){if("string"==typeof t){if("string"==typeof e?(s=e,e=0,i=this.length):"string"==typeof i&&(s=i,i=this.length),1===t.length){var n=t.charCodeAt(0);n<256&&(t=n)}if(void 0!==s&&"string"!=typeof s)throw new TypeError("encoding must be a string");if("string"==typeof s&&!r.isEncoding(s))throw new TypeError("Unknown encoding: "+s)}else"number"==typeof t&&(t&=255);if(e<0||this.length<e||this.length<i)throw new RangeError("Out of range index");if(i<=e)return this;e>>>=0,i=void 0===i?this.length:i>>>0,t||(t=0);var o;if("number"==typeof t)for(o=e;o<i;++o)this[o]=t;else{var a=r.isBuffer(t)?t:V(new r(t,s).toString()),h=a.length;for(o=0;o<i-e;++o)this[o+e]=a[o%h]}return this};var tt=/[^+\/0-9A-Za-z-_]/g}).call(e,i(0))},function(t,e){var i={}.toString;t.exports=Array.isArray||function(t){return"[object Array]"==i.call(t)}},,,,,,,,,,,,,function(t,e,i){(function(e){t.exports=e.PIXI=i(92)}).call(e,i(0))},function(t,e,i){(function(e){t.exports=e.Phaser=i(91)}).call(e,i(0))},function(t,e,i){(function(e){t.exports=e.p2=i(90)}).call(e,i(0))},function(t,e,i){t.exports=i.p+"js/game/src/assets/sounds/brick_destroy.wav"},function(t,e,i){t.exports=i.p+"js/game/src/assets/sounds/game_music.wav"},function(t,e,i){t.exports=i.p+"js/game/src/assets/sprites/bricksScaled720X240.png"},function(t,e,i){t.exports=i.p+"js/game/src/assets/sprites/settings-50.png"},,function(t,e){e.read=function(t,e,i,s,n){var r,o,a=8*n-s-1,h=(1<<a)-1,l=h>>1,c=-7,u=i?n-1:0,d=i?-1:1,p=t[e+u];for(u+=d,r=p&(1<<-c)-1,p>>=-c,c+=a;c>0;r=256*r+t[e+u],u+=d,c-=8);for(o=r&(1<<-c)-1,r>>=-c,c+=s;c>0;o=256*o+t[e+u],u+=d,c-=8);if(0===r)r=1-l;else{if(r===h)return o?NaN:1/0*(p?-1:1);o+=Math.pow(2,s),r-=l}return(p?-1:1)*o*Math.pow(2,r-s)},e.write=function(t,e,i,s,n,r){var o,a,h,l=8*r-n-1,c=(1<<l)-1,u=c>>1,d=23===n?Math.pow(2,-24)-Math.pow(2,-77):0,p=s?0:r-1,f=s?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=c):(o=Math.floor(Math.log(e)/Math.LN2),e*(h=Math.pow(2,-o))<1&&(o--,h*=2),e+=o+u>=1?d/h:d*Math.pow(2,1-u),e*h>=2&&(o++,h/=2),o+u>=c?(a=0,o=c):o+u>=1?(a=(e*h-1)*Math.pow(2,n),o+=u):(a=e*Math.pow(2,u-1)*Math.pow(2,n),o=0));n>=8;t[i+p]=255&a,p+=f,a/=256,n-=8);for(o=o<<n|a,l+=n;l>0;t[i+p]=255&o,p+=f,o/=256,l-=8);t[i+p-f]|=128*g}},,,function(t,e,i){var s,s;!function(e){t.exports=e()}(function(){return function t(e,i,n){function r(a,h){if(!i[a]){if(!e[a]){var l="function"==typeof s&&s;if(!h&&l)return s(a,!0);if(o)return s(a,!0);throw new Error("Cannot find module '"+a+"'")}var c=i[a]={exports:{}};e[a][0].call(c.exports,function(t){var i=e[a][1][t];return r(i||t)},c,c.exports,t,e,i,n)}return i[a].exports}for(var o="function"==typeof s&&s,a=0;a<n.length;a++)r(n[a]);return r}({1:[function(t,e,i){function s(){}var n=t("./Scalar");e.exports=s,s.lineInt=function(t,e,i){i=i||0;var s,r,o,a,h,l,c,u=[0,0];return s=t[1][1]-t[0][1],r=t[0][0]-t[1][0],o=s*t[0][0]+r*t[0][1],a=e[1][1]-e[0][1],h=e[0][0]-e[1][0],l=a*e[0][0]+h*e[0][1],c=s*h-a*r,n.eq(c,0,i)||(u[0]=(h*o-r*l)/c,u[1]=(s*l-a*o)/c),u},s.segmentsIntersect=function(t,e,i,s){var n=e[0]-t[0],r=e[1]-t[1],o=s[0]-i[0],a=s[1]-i[1];if(o*r-a*n==0)return!1;var h=(n*(i[1]-t[1])+r*(t[0]-i[0]))/(o*r-a*n),l=(o*(t[1]-i[1])+a*(i[0]-t[0]))/(a*n-o*r);return h>=0&&h<=1&&l>=0&&l<=1}},{"./Scalar":4}],2:[function(t,e,i){function s(){}e.exports=s,s.area=function(t,e,i){return(e[0]-t[0])*(i[1]-t[1])-(i[0]-t[0])*(e[1]-t[1])},s.left=function(t,e,i){return s.area(t,e,i)>0},s.leftOn=function(t,e,i){return s.area(t,e,i)>=0},s.right=function(t,e,i){return s.area(t,e,i)<0},s.rightOn=function(t,e,i){return s.area(t,e,i)<=0};var n=[],r=[];s.collinear=function(t,e,i,o){if(o){var a=n,h=r;a[0]=e[0]-t[0],a[1]=e[1]-t[1],h[0]=i[0]-e[0],h[1]=i[1]-e[1];var l=a[0]*h[0]+a[1]*h[1],c=Math.sqrt(a[0]*a[0]+a[1]*a[1]),u=Math.sqrt(h[0]*h[0]+h[1]*h[1]);return Math.acos(l/(c*u))<o}return 0==s.area(t,e,i)},s.sqdist=function(t,e){var i=e[0]-t[0],s=e[1]-t[1];return i*i+s*s}},{}],3:[function(t,e,i){function s(){this.vertices=[]}function n(t,e,i,s,n){n=n||0;var r=e[1]-t[1],o=t[0]-e[0],h=r*t[0]+o*t[1],l=s[1]-i[1],c=i[0]-s[0],u=l*i[0]+c*i[1],d=r*c-l*o;return a.eq(d,0,n)?[0,0]:[(c*h-o*u)/d,(r*u-l*h)/d]}var r=t("./Line"),o=t("./Point"),a=t("./Scalar");e.exports=s,s.prototype.at=function(t){var e=this.vertices,i=e.length;return e[t<0?t%i+i:t%i]},s.prototype.first=function(){return this.vertices[0]},s.prototype.last=function(){return this.vertices[this.vertices.length-1]},s.prototype.clear=function(){this.vertices.length=0},s.prototype.append=function(t,e,i){if(void 0===e)throw new Error("From is not given!");if(void 0===i)throw new Error("To is not given!");if(i-1<e)throw new Error("lol1");if(i>t.vertices.length)throw new Error("lol2");if(e<0)throw new Error("lol3");for(var s=e;s<i;s++)this.vertices.push(t.vertices[s])},s.prototype.makeCCW=function(){for(var t=0,e=this.vertices,i=1;i<this.vertices.length;++i)(e[i][1]<e[t][1]||e[i][1]==e[t][1]&&e[i][0]>e[t][0])&&(t=i);o.left(this.at(t-1),this.at(t),this.at(t+1))||this.reverse()},s.prototype.reverse=function(){for(var t=[],e=0,i=this.vertices.length;e!==i;e++)t.push(this.vertices.pop());this.vertices=t},s.prototype.isReflex=function(t){return o.right(this.at(t-1),this.at(t),this.at(t+1))};var h=[],l=[];s.prototype.canSee=function(t,e){var i,s,n=h,a=l;if(o.leftOn(this.at(t+1),this.at(t),this.at(e))&&o.rightOn(this.at(t-1),this.at(t),this.at(e)))return!1;s=o.sqdist(this.at(t),this.at(e));for(var c=0;c!==this.vertices.length;++c)if((c+1)%this.vertices.length!==t&&c!==t&&o.leftOn(this.at(t),this.at(e),this.at(c+1))&&o.rightOn(this.at(t),this.at(e),this.at(c))&&(n[0]=this.at(t),n[1]=this.at(e),a[0]=this.at(c),a[1]=this.at(c+1),i=r.lineInt(n,a),o.sqdist(this.at(t),i)<s))return!1;return!0},s.prototype.copy=function(t,e,i){var n=i||new s;if(n.clear(),t<e)for(var r=t;r<=e;r++)n.vertices.push(this.vertices[r]);else{for(var r=0;r<=e;r++)n.vertices.push(this.vertices[r]);for(var r=t;r<this.vertices.length;r++)n.vertices.push(this.vertices[r])}return n},s.prototype.getCutEdges=function(){for(var t=[],e=[],i=[],n=new s,r=Number.MAX_VALUE,o=0;o<this.vertices.length;++o)if(this.isReflex(o))for(var a=0;a<this.vertices.length;++a)if(this.canSee(o,a)){e=this.copy(o,a,n).getCutEdges(),i=this.copy(a,o,n).getCutEdges();for(var h=0;h<i.length;h++)e.push(i[h]);e.length<r&&(t=e,r=e.length,t.push([this.at(o),this.at(a)]))}return t},s.prototype.decomp=function(){var t=this.getCutEdges();return t.length>0?this.slice(t):[this]},s.prototype.slice=function(t){if(0==t.length)return[this];if(t instanceof Array&&t.length&&t[0]instanceof Array&&2==t[0].length&&t[0][0]instanceof Array){for(var e=[this],i=0;i<t.length;i++)for(var s=t[i],n=0;n<e.length;n++){var r=e[n],o=r.slice(s);if(o){e.splice(n,1),e.push(o[0],o[1]);break}}return e}var s=t,i=this.vertices.indexOf(s[0]),n=this.vertices.indexOf(s[1]);return-1!=i&&-1!=n&&[this.copy(i,n),this.copy(n,i)]},s.prototype.isSimple=function(){for(var t=this.vertices,e=0;e<t.length-1;e++)for(var i=0;i<e-1;i++)if(r.segmentsIntersect(t[e],t[e+1],t[i],t[i+1]))return!1;for(var e=1;e<t.length-2;e++)if(r.segmentsIntersect(t[0],t[t.length-1],t[e],t[e+1]))return!1;return!0},s.prototype.quickDecomp=function(t,e,i,r,a,h){a=a||100,h=h||0,r=r||25,t=void 0!==t?t:[],e=e||[],i=i||[];var l=[0,0],c=[0,0],u=[0,0],d=0,p=0,f=0,g=0,m=0,y=0,v=0,b=new s,x=new s,w=this,_=this.vertices;if(_.length<3)return t;if(++h>a)return console.warn("quickDecomp: max level ("+a+") reached."),t;for(var P=0;P<this.vertices.length;++P)if(w.isReflex(P)){e.push(w.vertices[P]),d=p=Number.MAX_VALUE;for(var T=0;T<this.vertices.length;++T)o.left(w.at(P-1),w.at(P),w.at(T))&&o.rightOn(w.at(P-1),w.at(P),w.at(T-1))&&(u=n(w.at(P-1),w.at(P),w.at(T),w.at(T-1)),o.right(w.at(P+1),w.at(P),u)&&(f=o.sqdist(w.vertices[P],u))<p&&(p=f,c=u,y=T)),o.left(w.at(P+1),w.at(P),w.at(T+1))&&o.rightOn(w.at(P+1),w.at(P),w.at(T))&&(u=n(w.at(P+1),w.at(P),w.at(T),w.at(T+1)),o.left(w.at(P-1),w.at(P),u)&&(f=o.sqdist(w.vertices[P],u))<d&&(d=f,l=u,m=T));if(y==(m+1)%this.vertices.length)u[0]=(c[0]+l[0])/2,u[1]=(c[1]+l[1])/2,i.push(u),P<m?(b.append(w,P,m+1),b.vertices.push(u),x.vertices.push(u),0!=y&&x.append(w,y,w.vertices.length),x.append(w,0,P+1)):(0!=P&&b.append(w,P,w.vertices.length),b.append(w,0,m+1),b.vertices.push(u),x.vertices.push(u),x.append(w,y,P+1));else{if(y>m&&(m+=this.vertices.length),g=Number.MAX_VALUE,m<y)return t;for(var T=y;T<=m;++T)o.leftOn(w.at(P-1),w.at(P),w.at(T))&&o.rightOn(w.at(P+1),w.at(P),w.at(T))&&(f=o.sqdist(w.at(P),w.at(T)))<g&&(g=f,v=T%this.vertices.length);P<v?(b.append(w,P,v+1),0!=v&&x.append(w,v,_.length),x.append(w,0,P+1)):(0!=P&&b.append(w,P,_.length),b.append(w,0,v+1),x.append(w,v,P+1))}return b.vertices.length<x.vertices.length?(b.quickDecomp(t,e,i,r,a,h),x.quickDecomp(t,e,i,r,a,h)):(x.quickDecomp(t,e,i,r,a,h),b.quickDecomp(t,e,i,r,a,h)),t}return t.push(this),t},s.prototype.removeCollinearPoints=function(t){for(var e=0,i=this.vertices.length-1;this.vertices.length>3&&i>=0;--i)o.collinear(this.at(i-1),this.at(i),this.at(i+1),t)&&(this.vertices.splice(i%this.vertices.length,1),i--,e++);return e}},{"./Line":1,"./Point":2,"./Scalar":4}],4:[function(t,e,i){function s(){}e.exports=s,s.eq=function(t,e,i){return i=i||0,Math.abs(t-e)<i}},{}],5:[function(t,e,i){e.exports={Polygon:t("./Polygon"),Point:t("./Point")}},{"./Point":2,"./Polygon":3}],6:[function(t,e,i){e.exports={name:"p2",version:"0.7.0",description:"A JavaScript 2D physics engine.",author:"Stefan Hedman <[email protected]> (http://steffe.se)",keywords:["p2.js","p2","physics","engine","2d"],main:"./src/p2.js",engines:{node:"*"},repository:{type:"git",url:"https://github.com/schteppe/p2.js.git"},bugs:{url:"https://github.com/schteppe/p2.js/issues"},licenses:[{type:"MIT"}],devDependencies:{grunt:"^0.4.5","grunt-contrib-jshint":"^0.11.2","grunt-contrib-nodeunit":"^0.4.1","grunt-contrib-uglify":"~0.4.0","grunt-contrib-watch":"~0.5.0","grunt-browserify":"~2.0.1","grunt-contrib-concat":"^0.4.0"},dependencies:{"poly-decomp":"0.1.0"}}},{}],7:[function(t,e,i){function s(t){this.lowerBound=n.create(),t&&t.lowerBound&&n.copy(this.lowerBound,t.lowerBound),this.upperBound=n.create(),t&&t.upperBound&&n.copy(this.upperBound,t.upperBound)}var n=t("../math/vec2");t("../utils/Utils");e.exports=s;var r=n.create();s.prototype.setFromPoints=function(t,e,i,s){var o=this.lowerBound,a=this.upperBound;"number"!=typeof i&&(i=0),0!==i?n.rotate(o,t[0],i):n.copy(o,t[0]),n.copy(a,o);for(var h=Math.cos(i),l=Math.sin(i),c=1;c<t.length;c++){var u=t[c];if(0!==i){var d=u[0],p=u[1];r[0]=h*d-l*p,r[1]=l*d+h*p,u=r}for(var f=0;f<2;f++)u[f]>a[f]&&(a[f]=u[f]),u[f]<o[f]&&(o[f]=u[f])}e&&(n.add(this.lowerBound,this.lowerBound,e),n.add(this.upperBound,this.upperBound,e)),s&&(this.lowerBound[0]-=s,this.lowerBound[1]-=s,this.upperBound[0]+=s,this.upperBound[1]+=s)},s.prototype.copy=function(t){n.copy(this.lowerBound,t.lowerBound),n.copy(this.upperBound,t.upperBound)},s.prototype.extend=function(t){for(var e=2;e--;){var i=t.lowerBound[e];this.lowerBound[e]>i&&(this.lowerBound[e]=i);var s=t.upperBound[e];this.upperBound[e]<s&&(this.upperBound[e]=s)}},s.prototype.overlaps=function(t){var e=this.lowerBound,i=this.upperBound,s=t.lowerBound,n=t.upperBound;return(s[0]<=i[0]&&i[0]<=n[0]||e[0]<=n[0]&&n[0]<=i[0])&&(s[1]<=i[1]&&i[1]<=n[1]||e[1]<=n[1]&&n[1]<=i[1])},s.prototype.containsPoint=function(t){var e=this.lowerBound,i=this.upperBound;return e[0]<=t[0]&&t[0]<=i[0]&&e[1]<=t[1]&&t[1]<=i[1]},s.prototype.overlapsRay=function(t){var e=1/t.direction[0],i=1/t.direction[1],s=(this.lowerBound[0]-t.from[0])*e,n=(this.upperBound[0]-t.from[0])*e,r=(this.lowerBound[1]-t.from[1])*i,o=(this.upperBound[1]-t.from[1])*i,a=Math.max(Math.max(Math.min(s,n),Math.min(r,o))),h=Math.min(Math.min(Math.max(s,n),Math.max(r,o)));return h<0?-1:a>h?-1:a}},{"../math/vec2":30,"../utils/Utils":57}],8:[function(t,e,i){function s(t){this.type=t,this.result=[],this.world=null,this.boundingVolumeType=s.AABB}var n=t("../math/vec2"),r=t("../objects/Body");e.exports=s,s.AABB=1,s.BOUNDING_CIRCLE=2,s.prototype.setWorld=function(t){this.world=t},s.prototype.getCollisionPairs=function(t){};var o=n.create();s.boundingRadiusCheck=function(t,e){n.sub(o,t.position,e.position);var i=n.squaredLength(o),s=t.boundingRadius+e.boundingRadius;return i<=s*s},s.aabbCheck=function(t,e){return t.getAABB().overlaps(e.getAABB())},s.prototype.boundingVolumeCheck=function(t,e){var i;switch(this.boundingVolumeType){case s.BOUNDING_CIRCLE:i=s.boundingRadiusCheck(t,e);break;case s.AABB:i=s.aabbCheck(t,e);break;default:throw new Error("Bounding volume type not recognized: "+this.boundingVolumeType)}return i},s.canCollide=function(t,e){var i=r.KINEMATIC,s=r.STATIC;return(t.type!==s||e.type!==s)&&(!(t.type===i&&e.type===s||t.type===s&&e.type===i)&&((t.type!==i||e.type!==i)&&((t.sleepState!==r.SLEEPING||e.sleepState!==r.SLEEPING)&&!(t.sleepState===r.SLEEPING&&e.type===s||e.sleepState===r.SLEEPING&&t.type===s))))},s.NAIVE=1,s.SAP=2},{"../math/vec2":30,"../objects/Body":31}],9:[function(t,e,i){function s(){n.call(this,n.NAIVE)}var n=(t("../shapes/Circle"),t("../shapes/Plane"),t("../shapes/Shape"),t("../shapes/Particle"),t("../collision/Broadphase"));t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.getCollisionPairs=function(t){var e=t.bodies,i=this.result;i.length=0;for(var s=0,r=e.length;s!==r;s++)for(var o=e[s],a=0;a<s;a++){var h=e[a];n.canCollide(o,h)&&this.boundingVolumeCheck(o,h)&&i.push(o,h)}return i},s.prototype.aabbQuery=function(t,e,i){i=i||[];for(var s=t.bodies,n=0;n<s.length;n++){var r=s[n];r.aabbNeedsUpdate&&r.updateAABB(),r.aabb.overlaps(e)&&i.push(r)}return i}},{"../collision/Broadphase":8,"../math/vec2":30,"../shapes/Circle":39,"../shapes/Particle":43,"../shapes/Plane":44,"../shapes/Shape":45}],10:[function(t,e,i){function s(){this.contactEquations=[],this.frictionEquations=[],this.enableFriction=!0,this.enabledEquations=!0,this.slipForce=10,this.frictionCoefficient=.3,this.surfaceVelocity=0,this.contactEquationPool=new c({size:32}),this.frictionEquationPool=new u({size:64}),this.restitution=0,this.stiffness=p.DEFAULT_STIFFNESS,this.relaxation=p.DEFAULT_RELAXATION,this.frictionStiffness=p.DEFAULT_STIFFNESS,this.frictionRelaxation=p.DEFAULT_RELAXATION,this.enableFrictionReduction=!0,this.collidingBodiesLastStep=new d,this.contactSkinSize=.01}function n(t,e){o.set(t.vertices[0],.5*-e.length,-e.radius),o.set(t.vertices[1],.5*e.length,-e.radius),o.set(t.vertices[2],.5*e.length,e.radius),o.set(t.vertices[3],.5*-e.length,e.radius)}function r(t,e,i,s){for(var n=q,r=H,l=Y,c=z,u=t,d=e.vertices,p=null,f=0;f!==d.length+1;f++){var g=d[f%d.length],m=d[(f+1)%d.length];o.rotate(n,g,s),o.rotate(r,m,s),h(n,n,i),h(r,r,i),a(l,n,u),a(c,r,u);var y=o.crossLength(l,c);if(null===p&&(p=y),y*p<=0)return!1;p=y}return!0}var o=t("../math/vec2"),a=o.sub,h=o.add,l=o.dot,c=(t("../utils/Utils"),t("../utils/ContactEquationPool")),u=t("../utils/FrictionEquationPool"),d=t("../utils/TupleDictionary"),p=t("../equations/Equation"),f=(t("../equations/ContactEquation"),t("../equations/FrictionEquation"),t("../shapes/Circle")),g=t("../shapes/Convex"),m=t("../shapes/Shape"),y=(t("../objects/Body"),t("../shapes/Box"));e.exports=s;var v=o.fromValues(0,1),b=o.fromValues(0,0),x=o.fromValues(0,0),w=o.fromValues(0,0),_=o.fromValues(0,0),P=o.fromValues(0,0),T=o.fromValues(0,0),C=o.fromValues(0,0),S=o.fromValues(0,0),A=o.fromValues(0,0),E=o.fromValues(0,0),I=o.fromValues(0,0),M=o.fromValues(0,0),R=o.fromValues(0,0),B=o.fromValues(0,0),L=o.fromValues(0,0),O=o.fromValues(0,0),k=o.fromValues(0,0),F=o.fromValues(0,0),D=[],U=o.create(),G=o.create();s.prototype.bodiesOverlap=function(t,e){for(var i=U,s=G,n=0,r=t.shapes.length;n!==r;n++){var o=t.shapes[n];t.toWorldFrame(i,o.position);for(var a=0,h=e.shapes.length;a!==h;a++){var l=e.shapes[a];if(e.toWorldFrame(s,l.position),this[o.type|l.type](t,o,i,o.angle+t.angle,e,l,s,l.angle+e.angle,!0))return!0}}return!1},s.prototype.collidedLastStep=function(t,e){var i=0|t.id,s=0|e.id;return!!this.collidingBodiesLastStep.get(i,s)},s.prototype.reset=function(){this.collidingBodiesLastStep.reset();for(var t=this.contactEquations,e=t.length;e--;){var i=t[e],s=i.bodyA.id,n=i.bodyB.id;this.collidingBodiesLastStep.set(s,n,!0)}for(var r=this.contactEquations,o=this.frictionEquations,a=0;a<r.length;a++)this.contactEquationPool.release(r[a]);for(var a=0;a<o.length;a++)this.frictionEquationPool.release(o[a]);this.contactEquations.length=this.frictionEquations.length=0},s.prototype.createContactEquation=function(t,e,i,s){var n=this.contactEquationPool.get();return n.bodyA=t,n.bodyB=e,n.shapeA=i,n.shapeB=s,n.restitution=this.restitution,n.firstImpact=!this.collidedLastStep(t,e),n.stiffness=this.stiffness,n.relaxation=this.relaxation,n.needsUpdate=!0,n.enabled=this.enabledEquations,n.offset=this.contactSkinSize,n},s.prototype.createFrictionEquation=function(t,e,i,s){var n=this.frictionEquationPool.get();return n.bodyA=t,n.bodyB=e,n.shapeA=i,n.shapeB=s,n.setSlipForce(this.slipForce),n.frictionCoefficient=this.frictionCoefficient,n.relativeVelocity=this.surfaceVelocity,n.enabled=this.enabledEquations,n.needsUpdate=!0,n.stiffness=this.frictionStiffness,n.relaxation=this.frictionRelaxation,n.contactEquations.length=0,n},s.prototype.createFrictionFromContact=function(t){var e=this.createFrictionEquation(t.bodyA,t.bodyB,t.shapeA,t.shapeB);return o.copy(e.contactPointA,t.contactPointA),o.copy(e.contactPointB,t.contactPointB),o.rotate90cw(e.t,t.normalA),e.contactEquations.push(t),e},s.prototype.createFrictionFromAverage=function(t){var e=this.contactEquations[this.contactEquations.length-1],i=this.createFrictionEquation(e.bodyA,e.bodyB,e.shapeA,e.shapeB),s=e.bodyA;e.bodyB;o.set(i.contactPointA,0,0),o.set(i.contactPointB,0,0),o.set(i.t,0,0);for(var n=0;n!==t;n++)e=this.contactEquations[this.contactEquations.length-1-n],e.bodyA===s?(o.add(i.t,i.t,e.normalA),o.add(i.contactPointA,i.contactPointA,e.contactPointA),o.add(i.contactPointB,i.contactPointB,e.contactPointB)):(o.sub(i.t,i.t,e.normalA),o.add(i.contactPointA,i.contactPointA,e.contactPointB),o.add(i.contactPointB,i.contactPointB,e.contactPointA)),i.contactEquations.push(e);var r=1/t;return o.scale(i.contactPointA,i.contactPointA,r),o.scale(i.contactPointB,i.contactPointB,r),o.normalize(i.t,i.t),o.rotate90cw(i.t,i.t),i},s.prototype[m.LINE|m.CONVEX]=s.prototype.convexLine=function(t,e,i,s,n,r,o,a,h){return!h&&0},s.prototype[m.LINE|m.BOX]=s.prototype.lineBox=function(t,e,i,s,n,r,o,a,h){return!h&&0};var N=new y({width:1,height:1}),X=o.create();s.prototype[m.CAPSULE|m.CONVEX]=s.prototype[m.CAPSULE|m.BOX]=s.prototype.convexCapsule=function(t,e,i,s,r,a,h,l,c){var u=X;o.set(u,a.length/2,0),o.rotate(u,u,l),o.add(u,u,h);var d=this.circleConvex(r,a,u,l,t,e,i,s,c,a.radius);o.set(u,-a.length/2,0),o.rotate(u,u,l),o.add(u,u,h);var p=this.circleConvex(r,a,u,l,t,e,i,s,c,a.radius);if(c&&(d||p))return!0;var f=N;return n(f,a),this.convexConvex(t,e,i,s,r,f,h,l,c)+d+p},s.prototype[m.CAPSULE|m.LINE]=s.prototype.lineCapsule=function(t,e,i,s,n,r,o,a,h){return!h&&0};var W=o.create(),j=o.create(),V=new y({width:1,height:1});s.prototype[m.CAPSULE|m.CAPSULE]=s.prototype.capsuleCapsule=function(t,e,i,s,r,a,h,l,c){for(var u,d=W,p=j,f=0,g=0;g<2;g++){o.set(d,(0===g?-1:1)*e.length/2,0),o.rotate(d,d,s),o.add(d,d,i);for(var m=0;m<2;m++){o.set(p,(0===m?-1:1)*a.length/2,0),o.rotate(p,p,l),o.add(p,p,h),this.enableFrictionReduction&&(u=this.enableFriction,this.enableFriction=!1);var y=this.circleCircle(t,e,d,s,r,a,p,l,c,e.radius,a.radius);if(this.enableFrictionReduction&&(this.enableFriction=u),c&&y)return!0;f+=y}}this.enableFrictionReduction&&(u=this.enableFriction,this.enableFriction=!1);var v=V;n(v,e);var b=this.convexCapsule(t,v,i,s,r,a,h,l,c);if(this.enableFrictionReduction&&(this.enableFriction=u),c&&b)return!0;if(f+=b,this.enableFrictionReduction){var u=this.enableFriction;this.enableFriction=!1}n(v,a);var x=this.convexCapsule(r,v,h,l,t,e,i,s,c);return this.enableFrictionReduction&&(this.enableFriction=u),!(!c||!x)||(f+=x,this.enableFrictionReduction&&f&&this.enableFriction&&this.frictionEquations.push(this.createFrictionFromAverage(f)),f)},s.prototype[m.LINE|m.LINE]=s.prototype.lineLine=function(t,e,i,s,n,r,o,a,h){return!h&&0},s.prototype[m.PLANE|m.LINE]=s.prototype.planeLine=function(t,e,i,s,n,r,c,u,d){var p=b,f=x,g=w,m=_,y=P,E=T,I=C,M=S,R=A,B=D,L=0;o.set(p,-r.length/2,0),o.set(f,r.length/2,0),o.rotate(g,p,u),o.rotate(m,f,u),h(g,g,c),h(m,m,c),o.copy(p,g),o.copy(f,m),a(y,f,p),o.normalize(E,y),o.rotate90cw(R,E),o.rotate(M,v,s),B[0]=p,B[1]=f;for(var O=0;O<B.length;O++){var k=B[O];a(I,k,i);var F=l(I,M);if(F<0){if(d)return!0;var U=this.createContactEquation(t,n,e,r);L++,o.copy(U.normalA,M),o.normalize(U.normalA,U.normalA),o.scale(I,M,F),a(U.contactPointA,k,I),a(U.contactPointA,U.contactPointA,t.position),a(U.contactPointB,k,c),h(U.contactPointB,U.contactPointB,c),a(U.contactPointB,U.contactPointB,n.position),this.contactEquations.push(U),this.enableFrictionReduction||this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(U))}}return!d&&(this.enableFrictionReduction||L&&this.enableFriction&&this.frictionEquations.push(this.createFrictionFromAverage(L)),L)},s.prototype[m.PARTICLE|m.CAPSULE]=s.prototype.particleCapsule=function(t,e,i,s,n,r,o,a,h){return this.circleLine(t,e,i,s,n,r,o,a,h,r.radius,0)},s.prototype[m.CIRCLE|m.LINE]=s.prototype.circleLine=function(t,e,i,s,n,r,c,u,d,p,f){var p=p||0,f=void 0!==f?f:e.radius,g=b,m=x,y=w,v=_,L=P,O=T,k=C,F=S,U=A,G=E,N=I,X=M,W=R,j=B,V=D;o.set(F,-r.length/2,0),o.set(U,r.length/2,0),o.rotate(G,F,u),o.rotate(N,U,u),h(G,G,c),h(N,N,c),o.copy(F,G),o.copy(U,N),a(O,U,F),o.normalize(k,O),o.rotate90cw(L,k),a(X,i,F);var q=l(X,L);a(v,F,c),a(W,i,c);var H=f+p;if(Math.abs(q)<H){o.scale(g,L,q),a(y,i,g),o.scale(m,L,l(L,W)),o.normalize(m,m),o.scale(m,m,p),h(y,y,m);var Y=l(k,y),z=l(k,F),K=l(k,U);if(Y>z&&Y<K){if(d)return!0;var J=this.createContactEquation(t,n,e,r);return o.scale(J.normalA,g,-1),o.normalize(J.normalA,J.normalA),o.scale(J.contactPointA,J.normalA,f),h(J.contactPointA,J.contactPointA,i),a(J.contactPointA,J.contactPointA,t.position),a(J.contactPointB,y,c),h(J.contactPointB,J.contactPointB,c),a(J.contactPointB,J.contactPointB,n.position),this.contactEquations.push(J),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(J)),1}}V[0]=F,V[1]=U;for(var Q=0;Q<V.length;Q++){var Z=V[Q];if(a(X,Z,i),o.squaredLength(X)<Math.pow(H,2)){if(d)return!0;var J=this.createContactEquation(t,n,e,r);return o.copy(J.normalA,X),o.normalize(J.normalA,J.normalA),o.scale(J.contactPointA,J.normalA,f),h(J.contactPointA,J.contactPointA,i),a(J.contactPointA,J.contactPointA,t.position),a(J.contactPointB,Z,c),o.scale(j,J.normalA,-p),h(J.contactPointB,J.contactPointB,j),h(J.contactPointB,J.contactPointB,c),a(J.contactPointB,J.contactPointB,n.position),this.contactEquations.push(J),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(J)),1}}return 0},s.prototype[m.CIRCLE|m.CAPSULE]=s.prototype.circleCapsule=function(t,e,i,s,n,r,o,a,h){return this.circleLine(t,e,i,s,n,r,o,a,h,r.radius)},s.prototype[m.CIRCLE|m.CONVEX]=s.prototype[m.CIRCLE|m.BOX]=s.prototype.circleConvex=function(t,e,i,s,n,l,c,u,d,p){for(var p="number"==typeof p?p:e.radius,f=b,g=x,m=w,y=_,v=P,T=E,C=I,S=R,A=B,M=L,k=O,F=!1,D=Number.MAX_VALUE,U=l.vertices,G=0;G!==U.length+1;G++){var N=U[G%U.length],X=U[(G+1)%U.length];if(o.rotate(f,N,u),o.rotate(g,X,u),h(f,f,c),h(g,g,c),a(m,g,f),o.normalize(y,m),o.rotate90cw(v,y),o.scale(A,v,-e.radius),h(A,A,i),r(A,l,c,u)){o.sub(M,f,A);var W=Math.abs(o.dot(M,v));W<D&&(o.copy(k,A),D=W,o.scale(S,v,W),o.add(S,S,A),F=!0)}}if(F){if(d)return!0;var j=this.createContactEquation(t,n,e,l);return o.sub(j.normalA,k,i),o.normalize(j.normalA,j.normalA),o.scale(j.contactPointA,j.normalA,p),h(j.contactPointA,j.contactPointA,i),a(j.contactPointA,j.contactPointA,t.position),a(j.contactPointB,S,c),h(j.contactPointB,j.contactPointB,c),a(j.contactPointB,j.contactPointB,n.position),this.contactEquations.push(j),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(j)),1}if(p>0)for(var G=0;G<U.length;G++){var V=U[G];if(o.rotate(C,V,u),h(C,C,c),a(T,C,i),o.squaredLength(T)<Math.pow(p,2)){if(d)return!0;var j=this.createContactEquation(t,n,e,l);return o.copy(j.normalA,T),o.normalize(j.normalA,j.normalA),o.scale(j.contactPointA,j.normalA,p),h(j.contactPointA,j.contactPointA,i),a(j.contactPointA,j.contactPointA,t.position),a(j.contactPointB,C,c),h(j.contactPointB,j.contactPointB,c),a(j.contactPointB,j.contactPointB,n.position),this.contactEquations.push(j),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(j)),1}}return 0};var q=o.create(),H=o.create(),Y=o.create(),z=o.create();s.prototype[m.PARTICLE|m.CONVEX]=s.prototype[m.PARTICLE|m.BOX]=s.prototype.particleConvex=function(t,e,i,s,n,c,u,d,p){var f=b,g=x,m=w,y=_,v=P,S=T,A=C,I=E,M=R,B=k,L=F,O=Number.MAX_VALUE,D=!1,U=c.vertices;if(!r(i,c,u,d))return 0;if(p)return!0;for(var G=0;G!==U.length+1;G++){var N=U[G%U.length],X=U[(G+1)%U.length];o.rotate(f,N,d),o.rotate(g,X,d),h(f,f,u),h(g,g,u),a(m,g,f),o.normalize(y,m),o.rotate90cw(v,y),a(I,i,f);l(I,v);a(S,f,u),a(A,i,u),o.sub(B,f,i);var W=Math.abs(o.dot(B,v));W<O&&(O=W,o.scale(M,v,W),o.add(M,M,i),o.copy(L,v),D=!0)}if(D){var j=this.createContactEquation(t,n,e,c);return o.scale(j.normalA,L,-1),o.normalize(j.normalA,j.normalA),o.set(j.contactPointA,0,0),h(j.contactPointA,j.contactPointA,i),a(j.contactPointA,j.contactPointA,t.position),a(j.contactPointB,M,u),h(j.contactPointB,j.contactPointB,u),a(j.contactPointB,j.contactPointB,n.position),this.contactEquations.push(j),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(j)),1}return 0},s.prototype[m.CIRCLE]=s.prototype.circleCircle=function(t,e,i,s,n,r,l,c,u,d,p){var f=b,d=d||e.radius,p=p||r.radius;a(f,i,l);var g=d+p;if(o.squaredLength(f)>Math.pow(g,2))return 0;if(u)return!0;var m=this.createContactEquation(t,n,e,r);return a(m.normalA,l,i),o.normalize(m.normalA,m.normalA),o.scale(m.contactPointA,m.normalA,d),o.scale(m.contactPointB,m.normalA,-p),h(m.contactPointA,m.contactPointA,i),a(m.contactPointA,m.contactPointA,t.position),h(m.contactPointB,m.contactPointB,l),a(m.contactPointB,m.contactPointB,n.position),this.contactEquations.push(m),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(m)),1},s.prototype[m.PLANE|m.CONVEX]=s.prototype[m.PLANE|m.BOX]=s.prototype.planeConvex=function(t,e,i,s,n,r,c,u,d){var p=b,f=x,g=w,m=0;o.rotate(f,v,s);for(var y=0;y!==r.vertices.length;y++){var _=r.vertices[y];if(o.rotate(p,_,u),h(p,p,c),a(g,p,i),l(g,f)<=0){if(d)return!0;m++;var P=this.createContactEquation(t,n,e,r);a(g,p,i),o.copy(P.normalA,f);var T=l(g,P.normalA);o.scale(g,P.normalA,T),a(P.contactPointB,p,n.position),a(P.contactPointA,p,g),a(P.contactPointA,P.contactPointA,t.position),this.contactEquations.push(P),this.enableFrictionReduction||this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(P))}}return this.enableFrictionReduction&&this.enableFriction&&m&&this.frictionEquations.push(this.createFrictionFromAverage(m)),m},s.prototype[m.PARTICLE|m.PLANE]=s.prototype.particlePlane=function(t,e,i,s,n,r,h,c,u){var d=b,p=x;c=c||0,a(d,i,h),o.rotate(p,v,c);var f=l(d,p);if(f>0)return 0;if(u)return!0;var g=this.createContactEquation(n,t,r,e);return o.copy(g.normalA,p),o.scale(d,g.normalA,f),a(g.contactPointA,i,d),a(g.contactPointA,g.contactPointA,n.position),a(g.contactPointB,i,t.position),this.contactEquations.push(g),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(g)),1},s.prototype[m.CIRCLE|m.PARTICLE]=s.prototype.circleParticle=function(t,e,i,s,n,r,l,c,u){var d=b;if(a(d,l,i),o.squaredLength(d)>Math.pow(e.radius,2))return 0;if(u)return!0;var p=this.createContactEquation(t,n,e,r);return o.copy(p.normalA,d),o.normalize(p.normalA,p.normalA),o.scale(p.contactPointA,p.normalA,e.radius),h(p.contactPointA,p.contactPointA,i),a(p.contactPointA,p.contactPointA,t.position),a(p.contactPointB,l,n.position),this.contactEquations.push(p),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(p)),1};var K=new f({radius:1}),J=o.create(),Q=o.create();o.create();s.prototype[m.PLANE|m.CAPSULE]=s.prototype.planeCapsule=function(t,e,i,s,n,r,a,l,c){var u=J,d=Q,p=K;o.set(u,-r.length/2,0),o.rotate(u,u,l),h(u,u,a),o.set(d,r.length/2,0),o.rotate(d,d,l),h(d,d,a),p.radius=r.radius;var f;this.enableFrictionReduction&&(f=this.enableFriction,this.enableFriction=!1);var g=this.circlePlane(n,p,u,0,t,e,i,s,c),m=this.circlePlane(n,p,d,0,t,e,i,s,c);if(this.enableFrictionReduction&&(this.enableFriction=f),c)return g||m;var y=g+m;return this.enableFrictionReduction&&y&&this.frictionEquations.push(this.createFrictionFromAverage(y)),y},s.prototype[m.CIRCLE|m.PLANE]=s.prototype.circlePlane=function(t,e,i,s,n,r,c,u,d){var p=t,f=e,g=i,m=n,y=c,_=u;_=_||0;var P=b,T=x,C=w;a(P,g,y),o.rotate(T,v,_);var S=l(T,P);if(S>f.radius)return 0;if(d)return!0;var A=this.createContactEquation(m,p,r,e);return o.copy(A.normalA,T),o.scale(A.contactPointB,A.normalA,-f.radius),h(A.contactPointB,A.contactPointB,g),a(A.contactPointB,A.contactPointB,p.position),o.scale(C,A.normalA,S),a(A.contactPointA,P,C),h(A.contactPointA,A.contactPointA,y),a(A.contactPointA,A.contactPointA,m.position),this.contactEquations.push(A),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(A)),1},s.prototype[m.CONVEX]=s.prototype[m.CONVEX|m.BOX]=s.prototype[m.BOX]=s.prototype.convexConvex=function(t,e,i,n,r,c,u,d,p,f){var g=b,m=x,y=w,v=_,T=P,E=C,I=S,M=A,R=0,f="number"==typeof f?f:0;if(!s.findSeparatingAxis(e,i,n,c,u,d,g))return 0;a(I,u,i),l(g,I)>0&&o.scale(g,g,-1);var B=s.getClosestEdge(e,n,g,!0),L=s.getClosestEdge(c,d,g);if(-1===B||-1===L)return 0;for(var O=0;O<2;O++){var k=B,F=L,D=e,U=c,G=i,N=u,X=n,W=d,j=t,V=r;if(0===O){var q;q=k,k=F,F=q,q=D,D=U,U=q,q=G,G=N,N=q,q=X,X=W,W=q,q=j,j=V,V=q}for(var H=F;H<F+2;H++){var Y=U.vertices[(H+U.vertices.length)%U.vertices.length];o.rotate(m,Y,W),h(m,m,N);for(var z=0,K=k-1;K<k+2;K++){var J=D.vertices[(K+D.vertices.length)%D.vertices.length],Q=D.vertices[(K+1+D.vertices.length)%D.vertices.length];o.rotate(y,J,X),o.rotate(v,Q,X),h(y,y,G),h(v,v,G),a(T,v,y),o.rotate90cw(M,T),o.normalize(M,M),a(I,m,y);var Z=l(M,I);(K===k&&Z<=f||K!==k&&Z<=0)&&z++}if(z>=3){if(p)return!0;var $=this.createContactEquation(j,V,D,U);R++;var J=D.vertices[k%D.vertices.length],Q=D.vertices[(k+1)%D.vertices.length];o.rotate(y,J,X),o.rotate(v,Q,X),h(y,y,G),h(v,v,G),a(T,v,y),o.rotate90cw($.normalA,T),o.normalize($.normalA,$.normalA),a(I,m,y);var Z=l($.normalA,I);o.scale(E,$.normalA,Z),a($.contactPointA,m,G),a($.contactPointA,$.contactPointA,E),h($.contactPointA,$.contactPointA,G),a($.contactPointA,$.contactPointA,j.position),a($.contactPointB,m,N),h($.contactPointB,$.contactPointB,N),a($.contactPointB,$.contactPointB,V.position),this.contactEquations.push($),this.enableFrictionReduction||this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact($))}}}return this.enableFrictionReduction&&this.enableFriction&&R&&this.frictionEquations.push(this.createFrictionFromAverage(R)),R};var Z=o.fromValues(0,0);s.projectConvexOntoAxis=function(t,e,i,s,n){var r,a,h=null,c=null,u=Z;o.rotate(u,s,-i);for(var d=0;d<t.vertices.length;d++)r=t.vertices[d],a=l(r,u),(null===h||a>h)&&(h=a),(null===c||a<c)&&(c=a);if(c>h){var p=c;c=h,h=p}var f=l(e,s);o.set(n,c+f,h+f)};var $=o.fromValues(0,0),tt=o.fromValues(0,0),et=o.fromValues(0,0),it=o.fromValues(0,0),st=o.fromValues(0,0),nt=o.fromValues(0,0);s.findSeparatingAxis=function(t,e,i,n,r,h,l){var c=null,u=!1,d=!1,p=$,f=tt,g=et,m=it,v=st,b=nt;if(t instanceof y&&n instanceof y)for(var x=0;2!==x;x++){var w=t,_=i;1===x&&(w=n,_=h);for(var P=0;2!==P;P++){0===P?o.set(m,0,1):1===P&&o.set(m,1,0),0!==_&&o.rotate(m,m,_),s.projectConvexOntoAxis(t,e,i,m,v),s.projectConvexOntoAxis(n,r,h,m,b);var T=v,C=b;v[0]>b[0]&&(C=v,T=b,!0);var S=C[0]-T[1];u=S<=0,(null===c||S>c)&&(o.copy(l,m),c=S,d=u)}}else for(var x=0;2!==x;x++){var w=t,_=i;1===x&&(w=n,_=h);for(var P=0;P!==w.vertices.length;P++){o.rotate(f,w.vertices[P],_),o.rotate(g,w.vertices[(P+1)%w.vertices.length],_),a(p,g,f),o.rotate90cw(m,p),o.normalize(m,m),s.projectConvexOntoAxis(t,e,i,m,v),s.projectConvexOntoAxis(n,r,h,m,b);var T=v,C=b;v[0]>b[0]&&(C=v,T=b,!0);var S=C[0]-T[1];u=S<=0,(null===c||S>c)&&(o.copy(l,m),c=S,d=u)}}return d};var rt=o.fromValues(0,0),ot=o.fromValues(0,0),at=o.fromValues(0,0);s.getClosestEdge=function(t,e,i,s){var n=rt,r=ot,h=at;o.rotate(n,i,-e),s&&o.scale(n,n,-1);for(var c=-1,u=t.vertices.length,d=-1,p=0;p!==u;p++){a(r,t.vertices[(p+1)%u],t.vertices[p%u]),o.rotate90cw(h,r),o.normalize(h,h);var f=l(h,n);(-1===c||f>d)&&(c=p%u,d=f)}return c};var ht=o.create(),lt=o.create(),ct=o.create(),ut=o.create(),dt=o.create(),pt=o.create(),ft=o.create();s.prototype[m.CIRCLE|m.HEIGHTFIELD]=s.prototype.circleHeightfield=function(t,e,i,s,n,r,l,c,u,d){var p=r.heights,d=d||e.radius,f=r.elementWidth,g=lt,m=ht,y=dt,v=ft,b=pt,x=ct,w=ut,_=Math.floor((i[0]-d-l[0])/f),P=Math.ceil((i[0]+d-l[0])/f);_<0&&(_=0),P>=p.length&&(P=p.length-1);for(var T=p[_],C=p[P],S=_;S<P;S++)p[S]<C&&(C=p[S]),p[S]>T&&(T=p[S]);if(i[1]-d>T)return!u&&0;for(var A=!1,S=_;S<P;S++){o.set(x,S*f,p[S]),o.set(w,(S+1)*f,p[S+1]),o.add(x,x,l),o.add(w,w,l),o.sub(b,w,x),o.rotate(b,b,Math.PI/2),o.normalize(b,b),o.scale(m,b,-d),o.add(m,m,i),o.sub(g,m,x);var E=o.dot(g,b);if(m[0]>=x[0]&&m[0]<w[0]&&E<=0){if(u)return!0;A=!0,o.scale(g,b,-E),o.add(y,m,g),o.copy(v,b);var I=this.createContactEquation(n,t,r,e);o.copy(I.normalA,v),o.scale(I.contactPointB,I.normalA,-d),h(I.contactPointB,I.contactPointB,i),a(I.contactPointB,I.contactPointB,t.position),o.copy(I.contactPointA,y),o.sub(I.contactPointA,I.contactPointA,n.position),this.contactEquations.push(I),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(I))}}if(A=!1,d>0)for(var S=_;S<=P;S++)if(o.set(x,S*f,p[S]),o.add(x,x,l),o.sub(g,i,x),o.squaredLength(g)<Math.pow(d,2)){if(u)return!0;A=!0;var I=this.createContactEquation(n,t,r,e);o.copy(I.normalA,g),o.normalize(I.normalA,I.normalA),o.scale(I.contactPointB,I.normalA,-d),h(I.contactPointB,I.contactPointB,i),a(I.contactPointB,I.contactPointB,t.position),a(I.contactPointA,x,l),h(I.contactPointA,I.contactPointA,l),a(I.contactPointA,I.contactPointA,n.position),this.contactEquations.push(I),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(I))}return A?1:0};var gt=o.create(),mt=o.create(),yt=o.create(),vt=new g({vertices:[o.create(),o.create(),o.create(),o.create()]});s.prototype[m.BOX|m.HEIGHTFIELD]=s.prototype[m.CONVEX|m.HEIGHTFIELD]=s.prototype.convexHeightfield=function(t,e,i,s,n,r,a,h,l){var c=r.heights,u=r.elementWidth,d=gt,p=mt,f=yt,g=vt,m=Math.floor((t.aabb.lowerBound[0]-a[0])/u),y=Math.ceil((t.aabb.upperBound[0]-a[0])/u);m<0&&(m=0),y>=c.length&&(y=c.length-1);for(var v=c[m],b=c[y],x=m;x<y;x++)c[x]<b&&(b=c[x]),c[x]>v&&(v=c[x]);if(t.aabb.lowerBound[1]>v)return!l&&0;for(var w=0,x=m;x<y;x++){o.set(d,x*u,c[x]),o.set(p,(x+1)*u,c[x+1]),o.add(d,d,a),o.add(p,p,a);o.set(f,.5*(p[0]+d[0]),.5*(p[1]+d[1]-100)),o.sub(g.vertices[0],p,f),o.sub(g.vertices[1],d,f),o.copy(g.vertices[2],g.vertices[1]),o.copy(g.vertices[3],g.vertices[0]),g.vertices[2][1]-=100,g.vertices[3][1]-=100,w+=this.convexConvex(t,e,i,s,n,g,f,0,l)}return w}},{"../equations/ContactEquation":21,"../equations/Equation":22,"../equations/FrictionEquation":23,"../math/vec2":30,"../objects/Body":31,"../shapes/Box":37,"../shapes/Circle":39,"../shapes/Convex":40,"../shapes/Shape":45,"../utils/ContactEquationPool":48,"../utils/FrictionEquationPool":49,"../utils/TupleDictionary":56,"../utils/Utils":57}],11:[function(t,e,i){function s(t){t=t||{},this.from=t.from?r.fromValues(t.from[0],t.from[1]):r.create(),this.to=t.to?r.fromValues(t.to[0],t.to[1]):r.create(),this.checkCollisionResponse=void 0===t.checkCollisionResponse||t.checkCollisionResponse,this.skipBackfaces=!!t.skipBackfaces,this.collisionMask=void 0!==t.collisionMask?t.collisionMask:-1,this.collisionGroup=void 0!==t.collisionGroup?t.collisionGroup:-1,this.mode=void 0!==t.mode?t.mode:s.ANY,this.callback=t.callback||function(t){},this.direction=r.create(),this.length=1,this.update()}function n(t,e,i){r.sub(a,i,t);var s=r.dot(a,e);return r.scale(h,e,s),r.add(h,h,t),r.squaredDistance(i,h)}e.exports=s;var r=t("../math/vec2");t("../collision/RaycastResult"),t("../shapes/Shape"),t("../collision/AABB");s.prototype.constructor=s,s.CLOSEST=1,s.ANY=2,s.ALL=4,s.prototype.update=function(){var t=this.direction;r.sub(t,this.to,this.from),this.length=r.length(t),r.normalize(t,t)},s.prototype.intersectBodies=function(t,e){for(var i=0,s=e.length;!t.shouldStop(this)&&i<s;i++){var n=e[i],r=n.getAABB();(r.overlapsRay(this)>=0||r.containsPoint(this.from))&&this.intersectBody(t,n)}};var o=r.create();s.prototype.intersectBody=function(t,e){var i=this.checkCollisionResponse;if(!i||e.collisionResponse)for(var s=o,n=0,a=e.shapes.length;n<a;n++){var h=e.shapes[n];if((!i||h.collisionResponse)&&(0!=(this.collisionGroup&h.collisionMask)&&0!=(h.collisionGroup&this.collisionMask))){r.rotate(s,h.position,e.angle),r.add(s,s,e.position);var l=h.angle+e.angle;if(this.intersectShape(t,h,l,s,e),t.shouldStop(this))break}}},s.prototype.intersectShape=function(t,e,i,s,r){n(this.from,this.direction,s)>e.boundingRadius*e.boundingRadius||(this._currentBody=r,this._currentShape=e,e.raycast(t,this,s,i),this._currentBody=this._currentShape=null)},s.prototype.getAABB=function(t){var e=this.to,i=this.from;r.set(t.lowerBound,Math.min(e[0],i[0]),Math.min(e[1],i[1])),r.set(t.upperBound,Math.max(e[0],i[0]),Math.max(e[1],i[1]))};r.create();s.prototype.reportIntersection=function(t,e,i,n){var o=(this.from,this.to,this._currentShape),a=this._currentBody;if(!(this.skipBackfaces&&r.dot(i,this.direction)>0))switch(this.mode){case s.ALL:t.set(i,o,a,e,n),this.callback(t);break;case s.CLOSEST:(e<t.fraction||!t.hasHit())&&t.set(i,o,a,e,n);break;case s.ANY:t.set(i,o,a,e,n)}};var a=r.create(),h=r.create()},{"../collision/AABB":7,"../collision/RaycastResult":12,"../math/vec2":30,"../shapes/Shape":45}],12:[function(t,e,i){function s(){this.normal=n.create(),this.shape=null,this.body=null,this.faceIndex=-1,this.fraction=-1,this.isStopped=!1}var n=t("../math/vec2"),r=t("../collision/Ray");e.exports=s,s.prototype.reset=function(){n.set(this.normal,0,0),this.shape=null,this.body=null,this.faceIndex=-1,this.fraction=-1,this.isStopped=!1},s.prototype.getHitDistance=function(t){return n.distance(t.from,t.to)*this.fraction},s.prototype.hasHit=function(){return-1!==this.fraction},s.prototype.getHitPoint=function(t,e){n.lerp(t,e.from,e.to,this.fraction)},s.prototype.stop=function(){this.isStopped=!0},s.prototype.shouldStop=function(t){return this.isStopped||-1!==this.fraction&&t.mode===r.ANY},s.prototype.set=function(t,e,i,s,r){n.copy(this.normal,t),this.shape=e,this.body=i,this.fraction=s,this.faceIndex=r}},{"../collision/Ray":11,"../math/vec2":30}],13:[function(t,e,i){function s(){r.call(this,r.SAP),this.axisList=[],this.axisIndex=0;var t=this;this._addBodyHandler=function(e){t.axisList.push(e.body)},this._removeBodyHandler=function(e){var i=t.axisList.indexOf(e.body);-1!==i&&t.axisList.splice(i,1)}}var n=t("../utils/Utils"),r=t("../collision/Broadphase");e.exports=s,s.prototype=new r,s.prototype.constructor=s,s.prototype.setWorld=function(t){this.axisList.length=0,n.appendArray(this.axisList,t.bodies),t.off("addBody",this._addBodyHandler).off("removeBody",this._removeBodyHandler),t.on("addBody",this._addBodyHandler).on("removeBody",this._removeBodyHandler),this.world=t},s.sortAxisList=function(t,e){e|=0;for(var i=1,s=t.length;i<s;i++){for(var n=t[i],r=i-1;r>=0&&!(t[r].aabb.lowerBound[e]<=n.aabb.lowerBound[e]);r--)t[r+1]=t[r];t[r+1]=n}return t},s.prototype.sortList=function(){var t=this.axisList,e=this.axisIndex;s.sortAxisList(t,e)},s.prototype.getCollisionPairs=function(t){var e=this.axisList,i=this.result,s=this.axisIndex;i.length=0;for(var n=e.length;n--;){var o=e[n];o.aabbNeedsUpdate&&o.updateAABB()}this.sortList();for(var a=0,h=0|e.length;a!==h;a++)for(var l=e[a],c=a+1;c<h;c++){var u=e[c],d=u.aabb.lowerBound[s]<=l.aabb.upperBound[s];if(!d)break;r.canCollide(l,u)&&this.boundingVolumeCheck(l,u)&&i.push(l,u)}return i},s.prototype.aabbQuery=function(t,e,i){i=i||[],this.sortList();var s=this.axisIndex,n="x";1===s&&(n="y"),2===s&&(n="z");for(var r=this.axisList,o=(e.lowerBound[n],e.upperBound[n],0);o<r.length;o++){var a=r[o];a.aabbNeedsUpdate&&a.updateAABB(),a.aabb.overlaps(e)&&i.push(a)}return i}},{"../collision/Broadphase":8,"../utils/Utils":57}],14:[function(t,e,i){function s(t,e,i,s){this.type=i,s=n.defaults(s,{collideConnected:!0,wakeUpBodies:!0}),this.equations=[],this.bodyA=t,this.bodyB=e,this.collideConnected=s.collideConnected,s.wakeUpBodies&&(t&&t.wakeUp(),e&&e.wakeUp())}e.exports=s;var n=t("../utils/Utils");s.prototype.update=function(){throw new Error("method update() not implmemented in this Constraint subclass!")},s.DISTANCE=1,s.GEAR=2,s.LOCK=3,s.PRISMATIC=4,s.REVOLUTE=5,s.prototype.setStiffness=function(t){for(var e=this.equations,i=0;i!==e.length;i++){var s=e[i];s.stiffness=t,s.needsUpdate=!0}},s.prototype.setRelaxation=function(t){for(var e=this.equations,i=0;i!==e.length;i++){var s=e[i];s.relaxation=t,s.needsUpdate=!0}}},{"../utils/Utils":57}],15:[function(t,e,i){function s(t,e,i){i=a.defaults(i,{localAnchorA:[0,0],localAnchorB:[0,0]}),n.call(this,t,e,n.DISTANCE,i),this.localAnchorA=o.fromValues(i.localAnchorA[0],i.localAnchorA[1]),this.localAnchorB=o.fromValues(i.localAnchorB[0],i.localAnchorB[1]);var s=this.localAnchorA,h=this.localAnchorB;if(this.distance=0,"number"==typeof i.distance)this.distance=i.distance;else{var l=o.create(),c=o.create(),u=o.create();o.rotate(l,s,t.angle),o.rotate(c,h,e.angle),o.add(u,e.position,c),o.sub(u,u,l),o.sub(u,u,t.position),this.distance=o.length(u)}var d;d=void 0===i.maxForce?Number.MAX_VALUE:i.maxForce;var p=new r(t,e,-d,d);this.equations=[p],this.maxForce=d;var u=o.create(),f=o.create(),g=o.create(),m=this;p.computeGq=function(){var t=this.bodyA,e=this.bodyB,i=t.position,n=e.position;return o.rotate(f,s,t.angle),o.rotate(g,h,e.angle),o.add(u,n,g),o.sub(u,u,f),o.sub(u,u,i),o.length(u)-m.distance},this.setMaxForce(d),this.upperLimitEnabled=!1,this.upperLimit=1,this.lowerLimitEnabled=!1,this.lowerLimit=0,this.position=0}var n=t("./Constraint"),r=t("../equations/Equation"),o=t("../math/vec2"),a=t("../utils/Utils");e.exports=s,s.prototype=new n,s.prototype.constructor=s;var h=o.create(),l=o.create(),c=o.create();s.prototype.update=function(){var t=this.equations[0],e=this.bodyA,i=this.bodyB,s=(this.distance,e.position),n=i.position,r=this.equations[0],a=t.G;o.rotate(l,this.localAnchorA,e.angle),o.rotate(c,this.localAnchorB,i.angle),o.add(h,n,c),o.sub(h,h,l),o.sub(h,h,s),this.position=o.length(h);var u=!1;if(this.upperLimitEnabled&&this.position>this.upperLimit&&(r.maxForce=0,r.minForce=-this.maxForce,this.distance=this.upperLimit,u=!0),this.lowerLimitEnabled&&this.position<this.lowerLimit&&(r.maxForce=this.maxForce,r.minForce=0,this.distance=this.lowerLimit,u=!0),(this.lowerLimitEnabled||this.upperLimitEnabled)&&!u)return void(r.enabled=!1);r.enabled=!0,o.normalize(h,h);var d=o.crossLength(l,h),p=o.crossLength(c,h);a[0]=-h[0],a[1]=-h[1],a[2]=-d,a[3]=h[0],a[4]=h[1],a[5]=p},s.prototype.setMaxForce=function(t){var e=this.equations[0];e.minForce=-t,e.maxForce=t},s.prototype.getMaxForce=function(){return this.equations[0].maxForce}},{"../equations/Equation":22,"../math/vec2":30,"../utils/Utils":57,"./Constraint":14}],16:[function(t,e,i){function s(t,e,i){i=i||{},n.call(this,t,e,n.GEAR,i),this.ratio=void 0!==i.ratio?i.ratio:1,this.angle=void 0!==i.angle?i.angle:e.angle-this.ratio*t.angle,i.angle=this.angle,i.ratio=this.ratio,this.equations=[new r(t,e,i)],void 0!==i.maxTorque&&this.setMaxTorque(i.maxTorque)}var n=t("./Constraint"),r=(t("../equations/Equation"),t("../equations/AngleLockEquation"));t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.update=function(){var t=this.equations[0];t.ratio!==this.ratio&&t.setRatio(this.ratio),t.angle=this.angle},s.prototype.setMaxTorque=function(t){this.equations[0].setMaxTorque(t)},s.prototype.getMaxTorque=function(t){return this.equations[0].maxForce}},{"../equations/AngleLockEquation":20,"../equations/Equation":22,"../math/vec2":30,"./Constraint":14}],17:[function(t,e,i){function s(t,e,i){i=i||{},n.call(this,t,e,n.LOCK,i);var s=void 0===i.maxForce?Number.MAX_VALUE:i.maxForce,a=(i.localAngleB,new o(t,e,-s,s)),h=new o(t,e,-s,s),l=new o(t,e,-s,s),c=r.create(),u=r.create(),d=this;a.computeGq=function(){return r.rotate(c,d.localOffsetB,t.angle),r.sub(u,e.position,t.position),r.sub(u,u,c),u[0]},h.computeGq=function(){return r.rotate(c,d.localOffsetB,t.angle),r.sub(u,e.position,t.position),r.sub(u,u,c),u[1]};var p=r.create(),f=r.create();l.computeGq=function(){return r.rotate(p,d.localOffsetB,e.angle-d.localAngleB),r.scale(p,p,-1),r.sub(u,t.position,e.position),r.add(u,u,p),r.rotate(f,p,-Math.PI/2),r.normalize(f,f),r.dot(u,f)},this.localOffsetB=r.create(),i.localOffsetB?r.copy(this.localOffsetB,i.localOffsetB):(r.sub(this.localOffsetB,e.position,t.position),r.rotate(this.localOffsetB,this.localOffsetB,-t.angle)),this.localAngleB=0,"number"==typeof i.localAngleB?this.localAngleB=i.localAngleB:this.localAngleB=e.angle-t.angle,this.equations.push(a,h,l),this.setMaxForce(s)}var n=t("./Constraint"),r=t("../math/vec2"),o=t("../equations/Equation");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.setMaxForce=function(t){for(var e=this.equations,i=0;i<this.equations.length;i++)e[i].maxForce=t,e[i].minForce=-t},s.prototype.getMaxForce=function(){return this.equations[0].maxForce};var a=r.create(),h=r.create(),l=r.create(),c=r.fromValues(1,0),u=r.fromValues(0,1);s.prototype.update=function(){var t=this.equations[0],e=this.equations[1],i=this.equations[2],s=this.bodyA,n=this.bodyB;r.rotate(a,this.localOffsetB,s.angle),r.rotate(h,this.localOffsetB,n.angle-this.localAngleB),r.scale(h,h,-1),r.rotate(l,h,Math.PI/2),r.normalize(l,l),t.G[0]=-1,t.G[1]=0,t.G[2]=-r.crossLength(a,c),t.G[3]=1,e.G[0]=0,e.G[1]=-1,e.G[2]=-r.crossLength(a,u),e.G[4]=1,i.G[0]=-l[0],i.G[1]=-l[1],i.G[3]=l[0],i.G[4]=l[1],i.G[5]=r.crossLength(h,l)}},{"../equations/Equation":22,"../math/vec2":30,"./Constraint":14}],18:[function(t,e,i){function s(t,e,i){i=i||{},n.call(this,t,e,n.PRISMATIC,i);var s=a.fromValues(0,0),l=a.fromValues(1,0),c=a.fromValues(0,0);i.localAnchorA&&a.copy(s,i.localAnchorA),i.localAxisA&&a.copy(l,i.localAxisA),i.localAnchorB&&a.copy(c,i.localAnchorB),this.localAnchorA=s,this.localAnchorB=c,this.localAxisA=l;var u=this.maxForce=void 0!==i.maxForce?i.maxForce:Number.MAX_VALUE,d=new o(t,e,-u,u),p=new a.create,f=new a.create,g=new a.create,m=new a.create;if(d.computeGq=function(){return a.dot(g,m)},d.updateJacobian=function(){var i=this.G,n=t.position,r=e.position;a.rotate(p,s,t.angle),a.rotate(f,c,e.angle),a.add(g,r,f),a.sub(g,g,n),a.sub(g,g,p),a.rotate(m,l,t.angle+Math.PI/2),i[0]=-m[0],i[1]=-m[1],i[2]=-a.crossLength(p,m)+a.crossLength(m,g),i[3]=m[0],i[4]=m[1],i[5]=a.crossLength(f,m)},this.equations.push(d),!i.disableRotationalLock){var y=new h(t,e,-u,u);this.equations.push(y)}this.position=0,this.velocity=0,this.lowerLimitEnabled=void 0!==i.lowerLimit,this.upperLimitEnabled=void 0!==i.upperLimit,this.lowerLimit=void 0!==i.lowerLimit?i.lowerLimit:0,this.upperLimit=void 0!==i.upperLimit?i.upperLimit:1,this.upperLimitEquation=new r(t,e),this.lowerLimitEquation=new r(t,e),this.upperLimitEquation.minForce=this.lowerLimitEquation.minForce=0,this.upperLimitEquation.maxForce=this.lowerLimitEquation.maxForce=u,this.motorEquation=new o(t,e),this.motorEnabled=!1,this.motorSpeed=0;var v=this,b=this.motorEquation;b.computeGW;b.computeGq=function(){return 0},b.computeGW=function(){var t=this.G,e=this.bodyA,i=this.bodyB,s=e.velocity,n=i.velocity,r=e.angularVelocity,o=i.angularVelocity;return this.gmult(t,s,r,n,o)+v.motorSpeed}}var n=t("./Constraint"),r=t("../equations/ContactEquation"),o=t("../equations/Equation"),a=t("../math/vec2"),h=t("../equations/RotationalLockEquation");e.exports=s,s.prototype=new n,s.prototype.constructor=s;var l=a.create(),c=a.create(),u=a.create(),d=a.create(),p=a.create(),f=a.create();s.prototype.update=function(){var t=this.equations,e=t[0],i=this.upperLimit,s=this.lowerLimit,n=this.upperLimitEquation,r=this.lowerLimitEquation,o=this.bodyA,h=this.bodyB,g=this.localAxisA,m=this.localAnchorA,y=this.localAnchorB;e.updateJacobian(),a.rotate(l,g,o.angle),a.rotate(d,m,o.angle),a.add(c,d,o.position),a.rotate(p,y,h.angle),a.add(u,p,h.position);var v=this.position=a.dot(u,l)-a.dot(c,l);if(this.motorEnabled){var b=this.motorEquation.G;b[0]=l[0],b[1]=l[1],b[2]=a.crossLength(l,p),b[3]=-l[0],b[4]=-l[1],b[5]=-a.crossLength(l,d)}if(this.upperLimitEnabled&&v>i)a.scale(n.normalA,l,-1),a.sub(n.contactPointA,c,o.position),a.sub(n.contactPointB,u,h.position),a.scale(f,l,i),a.add(n.contactPointA,n.contactPointA,f),-1===t.indexOf(n)&&t.push(n);else{var x=t.indexOf(n);-1!==x&&t.splice(x,1)}if(this.lowerLimitEnabled&&v<s)a.scale(r.normalA,l,1),a.sub(r.contactPointA,c,o.position),a.sub(r.contactPointB,u,h.position),a.scale(f,l,s),a.sub(r.contactPointB,r.contactPointB,f),-1===t.indexOf(r)&&t.push(r);else{var x=t.indexOf(r);-1!==x&&t.splice(x,1)}},s.prototype.enableMotor=function(){this.motorEnabled||(this.equations.push(this.motorEquation),this.motorEnabled=!0)},s.prototype.disableMotor=function(){if(this.motorEnabled){var t=this.equations.indexOf(this.motorEquation);this.equations.splice(t,1),this.motorEnabled=!1}},s.prototype.setLimits=function(t,e){"number"==typeof t?(this.lowerLimit=t,this.lowerLimitEnabled=!0):(this.lowerLimit=t,this.lowerLimitEnabled=!1),"number"==typeof e?(this.upperLimit=e,this.upperLimitEnabled=!0):(this.upperLimit=e,this.upperLimitEnabled=!1)}},{"../equations/ContactEquation":21,"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../math/vec2":30,"./Constraint":14}],19:[function(t,e,i){function s(t,e,i){i=i||{},n.call(this,t,e,n.REVOLUTE,i);var s=this.maxForce=void 0!==i.maxForce?i.maxForce:Number.MAX_VALUE;this.pivotA=h.create(),this.pivotB=h.create(),i.worldPivot?(h.sub(this.pivotA,i.worldPivot,t.position),h.sub(this.pivotB,i.worldPivot,e.position),h.rotate(this.pivotA,this.pivotA,-t.angle),h.rotate(this.pivotB,this.pivotB,-e.angle)):(h.copy(this.pivotA,i.localPivotA),h.copy(this.pivotB,i.localPivotB));var f=this.equations=[new r(t,e,-s,s),new r(t,e,-s,s)],g=f[0],m=f[1],y=this;g.computeGq=function(){return h.rotate(l,y.pivotA,t.angle),h.rotate(c,y.pivotB,e.angle),h.add(p,e.position,c),h.sub(p,p,t.position),h.sub(p,p,l),h.dot(p,u)},m.computeGq=function(){return h.rotate(l,y.pivotA,t.angle),h.rotate(c,y.pivotB,e.angle),h.add(p,e.position,c),h.sub(p,p,t.position),h.sub(p,p,l),h.dot(p,d)},m.minForce=g.minForce=-s,m.maxForce=g.maxForce=s,this.motorEquation=new o(t,e),this.motorEnabled=!1,this.angle=0,this.lowerLimitEnabled=!1,this.upperLimitEnabled=!1,this.lowerLimit=0,this.upperLimit=0,this.upperLimitEquation=new a(t,e),this.lowerLimitEquation=new a(t,e),this.upperLimitEquation.minForce=0,this.lowerLimitEquation.maxForce=0}var n=t("./Constraint"),r=t("../equations/Equation"),o=t("../equations/RotationalVelocityEquation"),a=t("../equations/RotationalLockEquation"),h=t("../math/vec2");e.exports=s;var l=h.create(),c=h.create(),u=h.fromValues(1,0),d=h.fromValues(0,1),p=h.create();s.prototype=new n,s.prototype.constructor=s,s.prototype.setLimits=function(t,e){"number"==typeof t?(this.lowerLimit=t,this.lowerLimitEnabled=!0):(this.lowerLimit=t,this.lowerLimitEnabled=!1),"number"==typeof e?(this.upperLimit=e,this.upperLimitEnabled=!0):(this.upperLimit=e,this.upperLimitEnabled=!1)},s.prototype.update=function(){var t=this.bodyA,e=this.bodyB,i=this.pivotA,s=this.pivotB,n=this.equations,r=(n[0],n[1],n[0]),o=n[1],a=this.upperLimit,p=this.lowerLimit,f=this.upperLimitEquation,g=this.lowerLimitEquation,m=this.angle=e.angle-t.angle;if(this.upperLimitEnabled&&m>a)f.angle=a,-1===n.indexOf(f)&&n.push(f);else{var y=n.indexOf(f);-1!==y&&n.splice(y,1)}if(this.lowerLimitEnabled&&m<p)g.angle=p,-1===n.indexOf(g)&&n.push(g);else{var y=n.indexOf(g);-1!==y&&n.splice(y,1)}h.rotate(l,i,t.angle),h.rotate(c,s,e.angle),r.G[0]=-1,r.G[1]=0,r.G[2]=-h.crossLength(l,u),r.G[3]=1,r.G[4]=0,r.G[5]=h.crossLength(c,u),o.G[0]=0,o.G[1]=-1,o.G[2]=-h.crossLength(l,d),o.G[3]=0,o.G[4]=1,o.G[5]=h.crossLength(c,d)},s.prototype.enableMotor=function(){this.motorEnabled||(this.equations.push(this.motorEquation),this.motorEnabled=!0)},s.prototype.disableMotor=function(){if(this.motorEnabled){var t=this.equations.indexOf(this.motorEquation);this.equations.splice(t,1),this.motorEnabled=!1}},s.prototype.motorIsEnabled=function(){return!!this.motorEnabled},s.prototype.setMotorSpeed=function(t){if(this.motorEnabled){var e=this.equations.indexOf(this.motorEquation);this.equations[e].relativeVelocity=t}},s.prototype.getMotorSpeed=function(){return!!this.motorEnabled&&this.motorEquation.relativeVelocity}},{"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../equations/RotationalVelocityEquation":25,"../math/vec2":30,"./Constraint":14}],20:[function(t,e,i){function s(t,e,i){i=i||{},n.call(this,t,e,-Number.MAX_VALUE,Number.MAX_VALUE),this.angle=i.angle||0,this.ratio="number"==typeof i.ratio?i.ratio:1,this.setRatio(this.ratio)}var n=t("./Equation");t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.computeGq=function(){return this.ratio*this.bodyA.angle-this.bodyB.angle+this.angle},s.prototype.setRatio=function(t){var e=this.G;e[2]=t,e[5]=-1,this.ratio=t},s.prototype.setMaxTorque=function(t){this.maxForce=t,this.minForce=-t}},{"../math/vec2":30,"./Equation":22}],21:[function(t,e,i){function s(t,e){n.call(this,t,e,0,Number.MAX_VALUE),this.contactPointA=r.create(),this.penetrationVec=r.create(),this.contactPointB=r.create(),this.normalA=r.create(),this.restitution=0,this.firstImpact=!1,this.shapeA=null,this.shapeB=null}var n=t("./Equation"),r=t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.computeB=function(t,e,i){var s=this.bodyA,n=this.bodyB,o=this.contactPointA,a=this.contactPointB,h=s.position,l=n.position,c=this.penetrationVec,u=this.normalA,d=this.G,p=r.crossLength(o,u),f=r.crossLength(a,u);d[0]=-u[0],d[1]=-u[1],d[2]=-p,d[3]=u[0],d[4]=u[1],d[5]=f,r.add(c,l,a),r.sub(c,c,h),r.sub(c,c,o);var g,m;return this.firstImpact&&0!==this.restitution?(m=0,g=1/e*(1+this.restitution)*this.computeGW()):(m=r.dot(u,c)+this.offset,g=this.computeGW()),-m*t-g*e-i*this.computeGiMf()}},{"../math/vec2":30,"./Equation":22}],22:[function(t,e,i){function s(t,e,i,n){this.minForce=void 0===i?-Number.MAX_VALUE:i,this.maxForce=void 0===n?Number.MAX_VALUE:n,this.bodyA=t,this.bodyB=e,this.stiffness=s.DEFAULT_STIFFNESS,this.relaxation=s.DEFAULT_RELAXATION,this.G=new r.ARRAY_TYPE(6);for(var o=0;o<6;o++)this.G[o]=0;this.offset=0,this.a=0,this.b=0,this.epsilon=0,this.timeStep=1/60,this.needsUpdate=!0,this.multiplier=0,this.relativeVelocity=0,this.enabled=!0}e.exports=s;var n=t("../math/vec2"),r=t("../utils/Utils");t("../objects/Body");s.prototype.constructor=s,s.DEFAULT_STIFFNESS=1e6,s.DEFAULT_RELAXATION=4,s.prototype.update=function(){var t=this.stiffness,e=this.relaxation,i=this.timeStep;this.a=4/(i*(1+4*e)),this.b=4*e/(1+4*e),this.epsilon=4/(i*i*t*(1+4*e)),this.needsUpdate=!1},s.prototype.gmult=function(t,e,i,s,n){return t[0]*e[0]+t[1]*e[1]+t[2]*i+t[3]*s[0]+t[4]*s[1]+t[5]*n},s.prototype.computeB=function(t,e,i){var s=this.computeGW();return-this.computeGq()*t-s*e-this.computeGiMf()*i};var o=n.create(),a=n.create();s.prototype.computeGq=function(){var t=this.G,e=this.bodyA,i=this.bodyB,s=(e.position,i.position,e.angle),n=i.angle;return this.gmult(t,o,s,a,n)+this.offset},s.prototype.computeGW=function(){var t=this.G,e=this.bodyA,i=this.bodyB,s=e.velocity,n=i.velocity,r=e.angularVelocity,o=i.angularVelocity;return this.gmult(t,s,r,n,o)+this.relativeVelocity},s.prototype.computeGWlambda=function(){var t=this.G,e=this.bodyA,i=this.bodyB,s=e.vlambda,n=i.vlambda,r=e.wlambda,o=i.wlambda;return this.gmult(t,s,r,n,o)};var h=n.create(),l=n.create();s.prototype.computeGiMf=function(){var t=this.bodyA,e=this.bodyB,i=t.force,s=t.angularForce,r=e.force,o=e.angularForce,a=t.invMassSolve,c=e.invMassSolve,u=t.invInertiaSolve,d=e.invInertiaSolve,p=this.G;return n.scale(h,i,a),n.multiply(h,t.massMultiplier,h),n.scale(l,r,c),n.multiply(l,e.massMultiplier,l),this.gmult(p,h,s*u,l,o*d)},s.prototype.computeGiMGt=function(){var t=this.bodyA,e=this.bodyB,i=t.invMassSolve,s=e.invMassSolve,n=t.invInertiaSolve,r=e.invInertiaSolve,o=this.G;return o[0]*o[0]*i*t.massMultiplier[0]+o[1]*o[1]*i*t.massMultiplier[1]+o[2]*o[2]*n+o[3]*o[3]*s*e.massMultiplier[0]+o[4]*o[4]*s*e.massMultiplier[1]+o[5]*o[5]*r};var c=n.create(),u=n.create(),d=n.create();n.create(),n.create(),n.create();s.prototype.addToWlambda=function(t){var e=this.bodyA,i=this.bodyB,s=c,r=u,o=d,a=e.invMassSolve,h=i.invMassSolve,l=e.invInertiaSolve,p=i.invInertiaSolve,f=this.G;r[0]=f[0],r[1]=f[1],o[0]=f[3],o[1]=f[4],n.scale(s,r,a*t),n.multiply(s,s,e.massMultiplier),n.add(e.vlambda,e.vlambda,s),e.wlambda+=l*f[2]*t,n.scale(s,o,h*t),n.multiply(s,s,i.massMultiplier),n.add(i.vlambda,i.vlambda,s),i.wlambda+=p*f[5]*t},s.prototype.computeInvC=function(t){return 1/(this.computeGiMGt()+t)}},{"../math/vec2":30,"../objects/Body":31,"../utils/Utils":57}],23:[function(t,e,i){function s(t,e,i){r.call(this,t,e,-i,i),this.contactPointA=n.create(),this.contactPointB=n.create(),this.t=n.create(),this.contactEquations=[],this.shapeA=null,this.shapeB=null,this.frictionCoefficient=.3}var n=t("../math/vec2"),r=t("./Equation");t("../utils/Utils");e.exports=s,s.prototype=new r,s.prototype.constructor=s,s.prototype.setSlipForce=function(t){this.maxForce=t,this.minForce=-t},s.prototype.getSlipForce=function(){return this.maxForce},s.prototype.computeB=function(t,e,i){var s=(this.bodyA,this.bodyB,this.contactPointA),r=this.contactPointB,o=this.t,a=this.G;return a[0]=-o[0],a[1]=-o[1],a[2]=-n.crossLength(s,o),a[3]=o[0],a[4]=o[1],a[5]=n.crossLength(r,o),-this.computeGW()*e-i*this.computeGiMf()}},{"../math/vec2":30,"../utils/Utils":57,"./Equation":22}],24:[function(t,e,i){function s(t,e,i){i=i||{},n.call(this,t,e,-Number.MAX_VALUE,Number.MAX_VALUE),this.angle=i.angle||0;var s=this.G;s[2]=1,s[5]=-1}var n=t("./Equation"),r=t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s;var o=r.create(),a=r.create(),h=r.fromValues(1,0),l=r.fromValues(0,1);s.prototype.computeGq=function(){return r.rotate(o,h,this.bodyA.angle+this.angle),r.rotate(a,l,this.bodyB.angle),r.dot(o,a)}},{"../math/vec2":30,"./Equation":22}],25:[function(t,e,i){function s(t,e){n.call(this,t,e,-Number.MAX_VALUE,Number.MAX_VALUE),this.relativeVelocity=1,this.ratio=1}var n=t("./Equation");t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.computeB=function(t,e,i){var s=this.G;s[2]=-1,s[5]=this.ratio;var n=this.computeGiMf();return-this.computeGW()*e-i*n}},{"../math/vec2":30,"./Equation":22}],26:[function(t,e,i){var s=function(){};e.exports=s,s.prototype={constructor:s,on:function(t,e,i){e.context=i||this,void 0===this._listeners&&(this._listeners={});var s=this._listeners;return void 0===s[t]&&(s[t]=[]),-1===s[t].indexOf(e)&&s[t].push(e),this},has:function(t,e){if(void 0===this._listeners)return!1;var i=this._listeners;if(e){if(void 0!==i[t]&&-1!==i[t].indexOf(e))return!0}else if(void 0!==i[t])return!0;return!1},off:function(t,e){if(void 0===this._listeners)return this;var i=this._listeners,s=i[t].indexOf(e);return-1!==s&&i[t].splice(s,1),this},emit:function(t){if(void 0===this._listeners)return this;var e=this._listeners,i=e[t.type];if(void 0!==i){t.target=this;for(var s=0,n=i.length;s<n;s++){var r=i[s];r.call(r.context,t)}}return this}}},{}],27:[function(t,e,i){function s(t,e,i){if(i=i||{},!(t instanceof n&&e instanceof n))throw new Error("First two arguments must be Material instances.");this.id=s.idCounter++,this.materialA=t,this.materialB=e,this.friction=void 0!==i.friction?Number(i.friction):.3,this.restitution=void 0!==i.restitution?Number(i.restitution):0,this.stiffness=void 0!==i.stiffness?Number(i.stiffness):r.DEFAULT_STIFFNESS,this.relaxation=void 0!==i.relaxation?Number(i.relaxation):r.DEFAULT_RELAXATION,this.frictionStiffness=void 0!==i.frictionStiffness?Number(i.frictionStiffness):r.DEFAULT_STIFFNESS,this.frictionRelaxation=void 0!==i.frictionRelaxation?Number(i.frictionRelaxation):r.DEFAULT_RELAXATION,this.surfaceVelocity=void 0!==i.surfaceVelocity?Number(i.surfaceVelocity):0,this.contactSkinSize=.005}var n=t("./Material"),r=t("../equations/Equation");e.exports=s,s.idCounter=0},{"../equations/Equation":22,"./Material":28}],28:[function(t,e,i){function s(t){this.id=t||s.idCounter++}e.exports=s,s.idCounter=0},{}],29:[function(t,e,i){var s={};s.GetArea=function(t){if(t.length<6)return 0;for(var e=t.length-2,i=0,s=0;s<e;s+=2)i+=(t[s+2]-t[s])*(t[s+1]+t[s+3]);return.5*-(i+=(t[0]-t[e])*(t[e+1]+t[1]))},s.Triangulate=function(t){var e=t.length>>1;if(e<3)return[];for(var i=[],n=[],r=0;r<e;r++)n.push(r);for(var r=0,o=e;o>3;){var a=n[(r+0)%o],h=n[(r+1)%o],l=n[(r+2)%o],c=t[2*a],u=t[2*a+1],d=t[2*h],p=t[2*h+1],f=t[2*l],g=t[2*l+1],m=!1;if(s._convex(c,u,d,p,f,g)){m=!0;for(var y=0;y<o;y++){var v=n[y];if(v!=a&&v!=h&&v!=l&&s._PointInTriangle(t[2*v],t[2*v+1],c,u,d,p,f,g)){m=!1;break}}}if(m)i.push(a,h,l),n.splice((r+1)%o,1),o--,r=0;else if(r++>3*o)break}return i.push(n[0],n[1],n[2]),i},s._PointInTriangle=function(t,e,i,s,n,r,o,a){var h=o-i,l=a-s,c=n-i,u=r-s,d=t-i,p=e-s,f=h*h+l*l,g=h*c+l*u,m=h*d+l*p,y=c*c+u*u,v=c*d+u*p,b=1/(f*y-g*g),x=(y*m-g*v)*b,w=(f*v-g*m)*b;return x>=0&&w>=0&&x+w<1},s._convex=function(t,e,i,s,n,r){return(e-s)*(n-i)+(i-t)*(r-s)>=0},e.exports=s},{}],30:[function(t,e,i){var s=e.exports={},n=t("../utils/Utils");s.crossLength=function(t,e){return t[0]*e[1]-t[1]*e[0]},s.crossVZ=function(t,e,i){return s.rotate(t,e,-Math.PI/2),s.scale(t,t,i),t},s.crossZV=function(t,e,i){return s.rotate(t,i,Math.PI/2),s.scale(t,t,e),t},s.rotate=function(t,e,i){if(0!==i){var s=Math.cos(i),n=Math.sin(i),r=e[0],o=e[1];t[0]=s*r-n*o,t[1]=n*r+s*o}else t[0]=e[0],t[1]=e[1]},s.rotate90cw=function(t,e){var i=e[0],s=e[1];t[0]=s,t[1]=-i},s.toLocalFrame=function(t,e,i,n){s.copy(t,e),s.sub(t,t,i),s.rotate(t,t,-n)},s.toGlobalFrame=function(t,e,i,n){s.copy(t,e),s.rotate(t,t,n),s.add(t,t,i)},s.vectorToLocalFrame=function(t,e,i){s.rotate(t,e,-i)},s.vectorToGlobalFrame=function(t,e,i){s.rotate(t,e,i)},s.centroid=function(t,e,i,n){return s.add(t,e,i),s.add(t,t,n),s.scale(t,t,1/3),t},s.create=function(){var t=new n.ARRAY_TYPE(2);return t[0]=0,t[1]=0,t},s.clone=function(t){var e=new n.ARRAY_TYPE(2);return e[0]=t[0],e[1]=t[1],e},s.fromValues=function(t,e){var i=new n.ARRAY_TYPE(2);return i[0]=t,i[1]=e,i},s.copy=function(t,e){return t[0]=e[0],t[1]=e[1],t},s.set=function(t,e,i){return t[0]=e,t[1]=i,t},s.add=function(t,e,i){return t[0]=e[0]+i[0],t[1]=e[1]+i[1],t},s.subtract=function(t,e,i){return t[0]=e[0]-i[0],t[1]=e[1]-i[1],t},s.sub=s.subtract,s.multiply=function(t,e,i){return t[0]=e[0]*i[0],t[1]=e[1]*i[1],t},s.mul=s.multiply,s.divide=function(t,e,i){return t[0]=e[0]/i[0],t[1]=e[1]/i[1],t},s.div=s.divide,s.scale=function(t,e,i){return t[0]=e[0]*i,t[1]=e[1]*i,t},s.distance=function(t,e){var i=e[0]-t[0],s=e[1]-t[1];return Math.sqrt(i*i+s*s)},s.dist=s.distance,s.squaredDistance=function(t,e){var i=e[0]-t[0],s=e[1]-t[1];return i*i+s*s},s.sqrDist=s.squaredDistance,s.length=function(t){var e=t[0],i=t[1];return Math.sqrt(e*e+i*i)},s.len=s.length,s.squaredLength=function(t){var e=t[0],i=t[1];return e*e+i*i},s.sqrLen=s.squaredLength,s.negate=function(t,e){return t[0]=-e[0],t[1]=-e[1],t},s.normalize=function(t,e){var i=e[0],s=e[1],n=i*i+s*s;return n>0&&(n=1/Math.sqrt(n),t[0]=e[0]*n,t[1]=e[1]*n),t},s.dot=function(t,e){return t[0]*e[0]+t[1]*e[1]},s.str=function(t){return"vec2("+t[0]+", "+t[1]+")"},s.lerp=function(t,e,i,s){var n=e[0],r=e[1];return t[0]=n+s*(i[0]-n),t[1]=r+s*(i[1]-r),t},s.reflect=function(t,e,i){var s=e[0]*i[0]+e[1]*i[1];t[0]=e[0]-2*i[0]*s,t[1]=e[1]-2*i[1]*s},s.getLineSegmentsIntersection=function(t,e,i,n,r){var o=s.getLineSegmentsIntersectionFraction(e,i,n,r);return!(o<0)&&(t[0]=e[0]+o*(i[0]-e[0]),t[1]=e[1]+o*(i[1]-e[1]),!0)},s.getLineSegmentsIntersectionFraction=function(t,e,i,s){var n,r,o=e[0]-t[0],a=e[1]-t[1],h=s[0]-i[0],l=s[1]-i[1];return n=(-a*(t[0]-i[0])+o*(t[1]-i[1]))/(-h*a+o*l),r=(h*(t[1]-i[1])-l*(t[0]-i[0]))/(-h*a+o*l),n>=0&&n<=1&&r>=0&&r<=1?r:-1}},{"../utils/Utils":57}],31:[function(t,e,i){function s(t){t=t||{},c.call(this),this.id=t.id||++s._idCounter,this.world=null,this.shapes=[],this.mass=t.mass||0,this.invMass=0,this.inertia=0,this.invInertia=0,this.invMassSolve=0,this.invInertiaSolve=0,this.fixedRotation=!!t.fixedRotation,this.fixedX=!!t.fixedX,this.fixedY=!!t.fixedY,this.massMultiplier=n.create(),this.position=n.fromValues(0,0),t.position&&n.copy(this.position,t.position),this.interpolatedPosition=n.fromValues(0,0),this.interpolatedAngle=0,this.previousPosition=n.fromValues(0,0),this.previousAngle=0,this.velocity=n.fromValues(0,0),t.velocity&&n.copy(this.velocity,t.velocity),this.vlambda=n.fromValues(0,0),this.wlambda=0,this.angle=t.angle||0,this.angularVelocity=t.angularVelocity||0,this.force=n.create(),t.force&&n.copy(this.force,t.force),this.angularForce=t.angularForce||0,this.damping="number"==typeof t.damping?t.damping:.1,this.angularDamping="number"==typeof t.angularDamping?t.angularDamping:.1,this.type=s.STATIC,void 0!==t.type?this.type=t.type:t.mass?this.type=s.DYNAMIC:this.type=s.STATIC,this.boundingRadius=0,this.aabb=new l,this.aabbNeedsUpdate=!0,this.allowSleep=void 0===t.allowSleep||t.allowSleep,this.wantsToSleep=!1,this.sleepState=s.AWAKE,this.sleepSpeedLimit=void 0!==t.sleepSpeedLimit?t.sleepSpeedLimit:.2,this.sleepTimeLimit=void 0!==t.sleepTimeLimit?t.sleepTimeLimit:1,this.gravityScale=void 0!==t.gravityScale?t.gravityScale:1,this.collisionResponse=void 0===t.collisionResponse||t.collisionResponse,this.idleTime=0,this.timeLastSleepy=0,this.ccdSpeedThreshold=void 0!==t.ccdSpeedThreshold?t.ccdSpeedThreshold:-1,this.ccdIterations=void 0!==t.ccdIterations?t.ccdIterations:10,this.concavePath=null,this._wakeUpAfterNarrowphase=!1,this.updateMassProperties()}var n=t("../math/vec2"),r=t("poly-decomp"),o=t("../shapes/Convex"),a=t("../collision/RaycastResult"),h=t("../collision/Ray"),l=t("../collision/AABB"),c=t("../events/EventEmitter");e.exports=s,s.prototype=new c,s.prototype.constructor=s,s._idCounter=0,s.prototype.updateSolveMassProperties=function(){this.sleepState===s.SLEEPING||this.type===s.KINEMATIC?(this.invMassSolve=0,this.invInertiaSolve=0):(this.invMassSolve=this.invMass,this.invInertiaSolve=this.invInertia)},s.prototype.setDensity=function(t){var e=this.getArea();this.mass=e*t,this.updateMassProperties()},s.prototype.getArea=function(){for(var t=0,e=0;e<this.shapes.length;e++)t+=this.shapes[e].area;return t},s.prototype.getAABB=function(){return this.aabbNeedsUpdate&&this.updateAABB(),this.aabb};var u=new l,d=n.create();s.prototype.updateAABB=function(){for(var t=this.shapes,e=t.length,i=d,s=this.angle,r=0;r!==e;r++){var o=t[r],a=o.angle+s;n.rotate(i,o.position,s),n.add(i,i,this.position),o.computeAABB(u,i,a),0===r?this.aabb.copy(u):this.aabb.extend(u)}this.aabbNeedsUpdate=!1},s.prototype.updateBoundingRadius=function(){for(var t=this.shapes,e=t.length,i=0,s=0;s!==e;s++){var r=t[s],o=n.length(r.position),a=r.boundingRadius;o+a>i&&(i=o+a)}this.boundingRadius=i},s.prototype.addShape=function(t,e,i){if(t.body)throw new Error("A shape can only be added to one body.");t.body=this,e?n.copy(t.position,e):n.set(t.position,0,0),t.angle=i||0,this.shapes.push(t),this.updateMassProperties(),this.updateBoundingRadius(),this.aabbNeedsUpdate=!0},s.prototype.removeShape=function(t){var e=this.shapes.indexOf(t);return-1!==e&&(this.shapes.splice(e,1),this.aabbNeedsUpdate=!0,t.body=null,!0)},s.prototype.updateMassProperties=function(){if(this.type===s.STATIC||this.type===s.KINEMATIC)this.mass=Number.MAX_VALUE,this.invMass=0,this.inertia=Number.MAX_VALUE,this.invInertia=0;else{var t=this.shapes,e=t.length,i=this.mass/e,r=0;if(this.fixedRotation)this.inertia=Number.MAX_VALUE,this.invInertia=0;else{for(var o=0;o<e;o++){var a=t[o],h=n.squaredLength(a.position);r+=a.computeMomentOfInertia(i)+i*h}this.inertia=r,this.invInertia=r>0?1/r:0}this.invMass=1/this.mass,n.set(this.massMultiplier,this.fixedX?0:1,this.fixedY?0:1)}};n.create();s.prototype.applyForce=function(t,e){if(n.add(this.force,this.force,t),e){var i=n.crossLength(e,t);this.angularForce+=i}};var p=n.create(),f=n.create(),g=n.create();s.prototype.applyForceLocal=function(t,e){e=e||g;var i=p,s=f;this.vectorToWorldFrame(i,t),this.vectorToWorldFrame(s,e),this.applyForce(i,s)};var m=n.create();s.prototype.applyImpulse=function(t,e){if(this.type===s.DYNAMIC){var i=m;if(n.scale(i,t,this.invMass),n.multiply(i,this.massMultiplier,i),n.add(this.velocity,i,this.velocity),e){var r=n.crossLength(e,t);r*=this.invInertia,this.angularVelocity+=r}}};var y=n.create(),v=n.create(),b=n.create();s.prototype.applyImpulseLocal=function(t,e){e=e||b;var i=y,s=v;this.vectorToWorldFrame(i,t),this.vectorToWorldFrame(s,e),this.applyImpulse(i,s)},s.prototype.toLocalFrame=function(t,e){n.toLocalFrame(t,e,this.position,this.angle)},s.prototype.toWorldFrame=function(t,e){n.toGlobalFrame(t,e,this.position,this.angle)},s.prototype.vectorToLocalFrame=function(t,e){n.vectorToLocalFrame(t,e,this.angle)},s.prototype.vectorToWorldFrame=function(t,e){n.vectorToGlobalFrame(t,e,this.angle)},s.prototype.fromPolygon=function(t,e){e=e||{};for(var i=this.shapes.length;i>=0;--i)this.removeShape(this.shapes[i]);var s=new r.Polygon;if(s.vertices=t,s.makeCCW(),"number"==typeof e.removeCollinearPoints&&s.removeCollinearPoints(e.removeCollinearPoints),void 0===e.skipSimpleCheck&&!s.isSimple())return!1;this.concavePath=s.vertices.slice(0);for(var i=0;i<this.concavePath.length;i++){var a=[0,0];n.copy(a,this.concavePath[i]),this.concavePath[i]=a}var h;h=e.optimalDecomp?s.decomp():s.quickDecomp();for(var l=n.create(),i=0;i!==h.length;i++){for(var c=new o({vertices:h[i].vertices}),u=0;u!==c.vertices.length;u++){var a=c.vertices[u];n.sub(a,a,c.centerOfMass)}n.scale(l,c.centerOfMass,1),c.updateTriangles(),c.updateCenterOfMass(),c.updateBoundingRadius(),this.addShape(c,l)}return this.adjustCenterOfMass(),this.aabbNeedsUpdate=!0,!0};var x=(n.fromValues(0,0),n.fromValues(0,0)),w=n.fromValues(0,0),_=n.fromValues(0,0);s.prototype.adjustCenterOfMass=function(){var t=x,e=w,i=_,s=0;n.set(e,0,0);for(var r=0;r!==this.shapes.length;r++){var o=this.shapes[r];n.scale(t,o.position,o.area),n.add(e,e,t),s+=o.area}n.scale(i,e,1/s);for(var r=0;r!==this.shapes.length;r++){var o=this.shapes[r];n.sub(o.position,o.position,i)}n.add(this.position,this.position,i);for(var r=0;this.concavePath&&r<this.concavePath.length;r++)n.sub(this.concavePath[r],this.concavePath[r],i);this.updateMassProperties(),this.updateBoundingRadius()},s.prototype.setZeroForce=function(){n.set(this.force,0,0),this.angularForce=0},s.prototype.resetConstraintVelocity=function(){var t=this,e=t.vlambda;n.set(e,0,0),t.wlambda=0},s.prototype.addConstraintVelocity=function(){var t=this,e=t.velocity;n.add(e,e,t.vlambda),t.angularVelocity+=t.wlambda},s.prototype.applyDamping=function(t){if(this.type===s.DYNAMIC){var e=this.velocity;n.scale(e,e,Math.pow(1-this.damping,t)),this.angularVelocity*=Math.pow(1-this.angularDamping,t)}},s.prototype.wakeUp=function(){var t=this.sleepState;this.sleepState=s.AWAKE,this.idleTime=0,t!==s.AWAKE&&this.emit(s.wakeUpEvent)},s.prototype.sleep=function(){this.sleepState=s.SLEEPING,this.angularVelocity=0,this.angularForce=0,n.set(this.velocity,0,0),n.set(this.force,0,0),this.emit(s.sleepEvent)},s.prototype.sleepTick=function(t,e,i){if(this.allowSleep&&this.type!==s.SLEEPING){this.wantsToSleep=!1;this.sleepState;n.squaredLength(this.velocity)+Math.pow(this.angularVelocity,2)>=Math.pow(this.sleepSpeedLimit,2)?(this.idleTime=0,this.sleepState=s.AWAKE):(this.idleTime+=i,this.sleepState=s.SLEEPY),this.idleTime>this.sleepTimeLimit&&(e?this.wantsToSleep=!0:this.sleep())}},s.prototype.overlaps=function(t){return this.world.overlapKeeper.bodiesAreOverlapping(this,t)};var P=n.create(),T=n.create();s.prototype.integrate=function(t){var e=this.invMass,i=this.force,s=this.position,r=this.velocity;n.copy(this.previousPosition,this.position),this.previousAngle=this.angle,this.fixedRotation||(this.angularVelocity+=this.angularForce*this.invInertia*t),n.scale(P,i,t*e),n.multiply(P,this.massMultiplier,P),n.add(r,P,r),this.integrateToTimeOfImpact(t)||(n.scale(T,r,t),n.add(s,s,T),this.fixedRotation||(this.angle+=this.angularVelocity*t)),this.aabbNeedsUpdate=!0};var C=new a,S=new h({mode:h.ALL}),A=n.create(),E=n.create(),I=n.create(),M=n.create();s.prototype.integrateToTimeOfImpact=function(t){if(this.ccdSpeedThreshold<0||n.squaredLength(this.velocity)<Math.pow(this.ccdSpeedThreshold,2))return!1;n.normalize(A,this.velocity),n.scale(E,this.velocity,t),n.add(E,E,this.position),n.sub(I,E,this.position);var e,i=this.angularVelocity*t,s=n.length(I),r=1,o=this;if(C.reset(),S.callback=function(t){t.body!==o&&(e=t.body,t.getHitPoint(E,S),n.sub(I,E,o.position),r=n.length(I)/s,t.stop())},n.copy(S.from,this.position),n.copy(S.to,E),S.update(),this.world.raycast(C,S),!e)return!1;var a=this.angle;n.copy(M,this.position);for(var h=0,l=0,c=0,u=r;u>=l&&h<this.ccdIterations;){h++,c=(u-l)/2,n.scale(T,I,r),n.add(this.position,M,T),this.angle=a+i*r,this.updateAABB();this.aabb.overlaps(e.aabb)&&this.world.narrowphase.bodiesOverlap(this,e)?l=c:u=c}return r=c,n.copy(this.position,M),this.angle=a,n.scale(T,I,r),n.add(this.position,this.position,T),this.fixedRotation||(this.angle+=i*r),!0},s.prototype.getVelocityAtPoint=function(t,e){return n.crossVZ(t,e,this.angularVelocity),n.subtract(t,this.velocity,t),t},s.sleepyEvent={type:"sleepy"},s.sleepEvent={type:"sleep"},s.wakeUpEvent={type:"wakeup"},s.DYNAMIC=1,s.STATIC=2,s.KINEMATIC=4,s.AWAKE=0,s.SLEEPY=1,s.SLEEPING=2},{"../collision/AABB":7,"../collision/Ray":11,"../collision/RaycastResult":12,"../events/EventEmitter":26,"../math/vec2":30,"../shapes/Convex":40,"poly-decomp":5}],32:[function(t,e,i){function s(t,e,i){i=i||{},r.call(this,t,e,i),this.localAnchorA=n.fromValues(0,0),this.localAnchorB=n.fromValues(0,0),i.localAnchorA&&n.copy(this.localAnchorA,i.localAnchorA),i.localAnchorB&&n.copy(this.localAnchorB,i.localAnchorB),i.worldAnchorA&&this.setWorldAnchorA(i.worldAnchorA),i.worldAnchorB&&this.setWorldAnchorB(i.worldAnchorB);var s=n.create(),o=n.create();this.getWorldAnchorA(s),this.getWorldAnchorB(o);var a=n.distance(s,o);this.restLength="number"==typeof i.restLength?i.restLength:a}var n=t("../math/vec2"),r=t("./Spring");t("../utils/Utils");e.exports=s,s.prototype=new r,s.prototype.constructor=s,s.prototype.setWorldAnchorA=function(t){this.bodyA.toLocalFrame(this.localAnchorA,t)},s.prototype.setWorldAnchorB=function(t){this.bodyB.toLocalFrame(this.localAnchorB,t)},s.prototype.getWorldAnchorA=function(t){this.bodyA.toWorldFrame(t,this.localAnchorA)},s.prototype.getWorldAnchorB=function(t){this.bodyB.toWorldFrame(t,this.localAnchorB)};var o=n.create(),a=n.create(),h=n.create(),l=n.create(),c=n.create(),u=n.create(),d=n.create(),p=n.create(),f=n.create();s.prototype.applyForce=function(){var t=this.stiffness,e=this.damping,i=this.restLength,s=this.bodyA,r=this.bodyB,g=o,m=a,y=h,v=l,b=f,x=c,w=u,_=d,P=p;this.getWorldAnchorA(x),this.getWorldAnchorB(w),n.sub(_,x,s.position),n.sub(P,w,r.position),n.sub(g,w,x);var T=n.len(g);n.normalize(m,g),n.sub(y,r.velocity,s.velocity),n.crossZV(b,r.angularVelocity,P),n.add(y,y,b),n.crossZV(b,s.angularVelocity,_),n.sub(y,y,b),n.scale(v,m,-t*(T-i)-e*n.dot(y,m)),n.sub(s.force,s.force,v),n.add(r.force,r.force,v);var C=n.crossLength(_,v),S=n.crossLength(P,v);s.angularForce-=C,r.angularForce+=S}},{"../math/vec2":30,"../utils/Utils":57,"./Spring":34}],33:[function(t,e,i){function s(t,e,i){i=i||{},n.call(this,t,e,i),this.restAngle="number"==typeof i.restAngle?i.restAngle:e.angle-t.angle}var n=(t("../math/vec2"),t("./Spring"));e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.applyForce=function(){var t=this.stiffness,e=this.damping,i=this.restAngle,s=this.bodyA,n=this.bodyB,r=n.angle-s.angle,o=n.angularVelocity-s.angularVelocity,a=-t*(r-i)-e*o*0;s.angularForce-=a,n.angularForce+=a}},{"../math/vec2":30,"./Spring":34}],34:[function(t,e,i){function s(t,e,i){i=n.defaults(i,{stiffness:100,damping:1}),this.stiffness=i.stiffness,this.damping=i.damping,this.bodyA=t,this.bodyB=e}var n=(t("../math/vec2"),t("../utils/Utils"));e.exports=s,s.prototype.applyForce=function(){}},{"../math/vec2":30,"../utils/Utils":57}],35:[function(t,e,i){function s(t,e){e=e||{},this.chassisBody=t,this.wheels=[],this.groundBody=new h({mass:0}),this.world=null;var i=this;this.preStepCallback=function(){i.update()}}function n(t,e){e=e||{},this.vehicle=t,this.forwardEquation=new a(t.chassisBody,t.groundBody),this.sideEquation=new a(t.chassisBody,t.groundBody),this.steerValue=0,this.engineForce=0,this.setSideFriction(void 0!==e.sideFriction?e.sideFriction:5),this.localForwardVector=r.fromValues(0,1),e.localForwardVector&&r.copy(this.localForwardVector,e.localForwardVector),this.localPosition=r.fromValues(0,0),e.localPosition&&r.copy(this.localPosition,e.localPosition),o.apply(this,t.chassisBody,t.groundBody),this.equations.push(this.forwardEquation,this.sideEquation),this.setBrakeForce(0)}var r=t("../math/vec2"),o=(t("../utils/Utils"),t("../constraints/Constraint")),a=t("../equations/FrictionEquation"),h=t("../objects/Body");e.exports=s,s.prototype.addToWorld=function(t){this.world=t,t.addBody(this.groundBody),t.on("preStep",this.preStepCallback);for(var e=0;e<this.wheels.length;e++){var i=this.wheels[e];t.addConstraint(i)}},s.prototype.removeFromWorld=function(){var t=this.world;t.removeBody(this.groundBody),t.off("preStep",this.preStepCallback);for(var e=0;e<this.wheels.length;e++){var i=this.wheels[e];t.removeConstraint(i)}this.world=null},s.prototype.addWheel=function(t){var e=new n(this,t);return this.wheels.push(e),e},s.prototype.update=function(){for(var t=0;t<this.wheels.length;t++)this.wheels[t].update()},n.prototype=new o,n.prototype.setBrakeForce=function(t){this.forwardEquation.setSlipForce(t)},n.prototype.setSideFriction=function(t){this.sideEquation.setSlipForce(t)};var l=r.create(),c=r.create();n.prototype.getSpeed=function(){return this.vehicle.chassisBody.vectorToWorldFrame(c,this.localForwardVector),this.vehicle.chassisBody.getVelocityAtPoint(l,c),r.dot(l,c)};var u=r.create();n.prototype.update=function(){this.vehicle.chassisBody.vectorToWorldFrame(this.forwardEquation.t,this.localForwardVector),r.rotate(this.sideEquation.t,this.localForwardVector,Math.PI/2),this.vehicle.chassisBody.vectorToWorldFrame(this.sideEquation.t,this.sideEquation.t),r.rotate(this.forwardEquation.t,this.forwardEquation.t,this.steerValue),r.rotate(this.sideEquation.t,this.sideEquation.t,this.steerValue),this.vehicle.chassisBody.toWorldFrame(this.forwardEquation.contactPointB,this.localPosition),r.copy(this.sideEquation.contactPointB,this.forwardEquation.contactPointB),this.vehicle.chassisBody.vectorToWorldFrame(this.forwardEquation.contactPointA,this.localPosition),r.copy(this.sideEquation.contactPointA,this.forwardEquation.contactPointA),r.normalize(u,this.forwardEquation.t),r.scale(u,u,this.engineForce),this.vehicle.chassisBody.applyForce(u,this.forwardEquation.contactPointA)}},{"../constraints/Constraint":14,"../equations/FrictionEquation":23,"../math/vec2":30,"../objects/Body":31,"../utils/Utils":57}],36:[function(t,e,i){var s=e.exports={AABB:t("./collision/AABB"),AngleLockEquation:t("./equations/AngleLockEquation"),Body:t("./objects/Body"),Broadphase:t("./collision/Broadphase"),Capsule:t("./shapes/Capsule"),Circle:t("./shapes/Circle"),Constraint:t("./constraints/Constraint"),ContactEquation:t("./equations/ContactEquation"),ContactEquationPool:t("./utils/ContactEquationPool"),ContactMaterial:t("./material/ContactMaterial"),Convex:t("./shapes/Convex"),DistanceConstraint:t("./constraints/DistanceConstraint"),Equation:t("./equations/Equation"),EventEmitter:t("./events/EventEmitter"),FrictionEquation:t("./equations/FrictionEquation"),FrictionEquationPool:t("./utils/FrictionEquationPool"),GearConstraint:t("./constraints/GearConstraint"),GSSolver:t("./solver/GSSolver"),Heightfield:t("./shapes/Heightfield"),Line:t("./shapes/Line"),LockConstraint:t("./constraints/LockConstraint"),Material:t("./material/Material"),Narrowphase:t("./collision/Narrowphase"),NaiveBroadphase:t("./collision/NaiveBroadphase"),Particle:t("./shapes/Particle"),Plane:t("./shapes/Plane"),Pool:t("./utils/Pool"),RevoluteConstraint:t("./constraints/RevoluteConstraint"),PrismaticConstraint:t("./constraints/PrismaticConstraint"),Ray:t("./collision/Ray"),RaycastResult:t("./collision/RaycastResult"),Box:t("./shapes/Box"),RotationalVelocityEquation:t("./equations/RotationalVelocityEquation"),SAPBroadphase:t("./collision/SAPBroadphase"),Shape:t("./shapes/Shape"),Solver:t("./solver/Solver"),Spring:t("./objects/Spring"),TopDownVehicle:t("./objects/TopDownVehicle"),LinearSpring:t("./objects/LinearSpring"),RotationalSpring:t("./objects/RotationalSpring"),Utils:t("./utils/Utils"),World:t("./world/World"),vec2:t("./math/vec2"),version:t("../package.json").version};Object.defineProperty(s,"Rectangle",{get:function(){return console.warn("The Rectangle class has been renamed to Box."),this.Box}})},{"../package.json":6,"./collision/AABB":7,"./collision/Broadphase":8,"./collision/NaiveBroadphase":9,"./collision/Narrowphase":10,"./collision/Ray":11,"./collision/RaycastResult":12,"./collision/SAPBroadphase":13,"./constraints/Constraint":14,"./constraints/DistanceConstraint":15,"./constraints/GearConstraint":16,"./constraints/LockConstraint":17,"./constraints/PrismaticConstraint":18,"./constraints/RevoluteConstraint":19,"./equations/AngleLockEquation":20,"./equations/ContactEquation":21,"./equations/Equation":22,"./equations/FrictionEquation":23,"./equations/RotationalVelocityEquation":25,"./events/EventEmitter":26,"./material/ContactMaterial":27,"./material/Material":28,"./math/vec2":30,"./objects/Body":31,"./objects/LinearSpring":32,"./objects/RotationalSpring":33,"./objects/Spring":34,"./objects/TopDownVehicle":35,"./shapes/Box":37,"./shapes/Capsule":38,"./shapes/Circle":39,"./shapes/Convex":40,"./shapes/Heightfield":41,"./shapes/Line":42,"./shapes/Particle":43,"./shapes/Plane":44,"./shapes/Shape":45,"./solver/GSSolver":46,"./solver/Solver":47,"./utils/ContactEquationPool":48,"./utils/FrictionEquationPool":49,"./utils/Pool":55,"./utils/Utils":57,"./world/World":61}],37:[function(t,e,i){function s(t){"number"==typeof arguments[0]&&"number"==typeof arguments[1]&&(t={width:arguments[0],height:arguments[1]},console.warn("The Rectangle has been renamed to Box and its constructor signature has changed. Please use the following format: new Box({ width: 1, height: 1, ... })")),t=t||{};var e=this.width=t.width||1,i=this.height=t.height||1,s=[n.fromValues(-e/2,-i/2),n.fromValues(e/2,-i/2),n.fromValues(e/2,i/2),n.fromValues(-e/2,i/2)],a=[n.fromValues(1,0),n.fromValues(0,1)];t.vertices=s,t.axes=a,t.type=r.BOX,o.call(this,t)}var n=t("../math/vec2"),r=t("./Shape"),o=t("./Convex");e.exports=s,s.prototype=new o,s.prototype.constructor=s,s.prototype.computeMomentOfInertia=function(t){var e=this.width,i=this.height;return t*(i*i+e*e)/12},s.prototype.updateBoundingRadius=function(){var t=this.width,e=this.height;this.boundingRadius=Math.sqrt(t*t+e*e)/2};n.create(),n.create(),n.create(),n.create();s.prototype.computeAABB=function(t,e,i){t.setFromPoints(this.vertices,e,i,0)},s.prototype.updateArea=function(){this.area=this.width*this.height}},{"../math/vec2":30,"./Convex":40,"./Shape":45}],38:[function(t,e,i){function s(t){"number"==typeof arguments[0]&&"number"==typeof arguments[1]&&(t={length:arguments[0],radius:arguments[1]},console.warn("The Capsule constructor signature has changed. Please use the following format: new Capsule({ radius: 1, length: 1 })")),t=t||{},this.length=t.length||1,this.radius=t.radius||1,t.type=n.CAPSULE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.computeMomentOfInertia=function(t){var e=this.radius,i=this.length+e,s=2*e;return t*(s*s+i*i)/12},s.prototype.updateBoundingRadius=function(){this.boundingRadius=this.radius+this.length/2},s.prototype.updateArea=function(){this.area=Math.PI*this.radius*this.radius+2*this.radius*this.length};var o=r.create();s.prototype.computeAABB=function(t,e,i){var s=this.radius;r.set(o,this.length/2,0),0!==i&&r.rotate(o,o,i),r.set(t.upperBound,Math.max(o[0]+s,-o[0]+s),Math.max(o[1]+s,-o[1]+s)),r.set(t.lowerBound,Math.min(o[0]-s,-o[0]-s),Math.min(o[1]-s,-o[1]-s)),r.add(t.lowerBound,t.lowerBound,e),r.add(t.upperBound,t.upperBound,e)};var a=r.create(),h=r.create(),l=r.create(),c=r.create(),u=r.fromValues(0,1);s.prototype.raycast=function(t,e,i,s){for(var n=e.from,o=e.to,d=(e.direction,a),p=h,f=l,g=c,m=this.length/2,y=0;y<2;y++){var v=this.radius*(2*y-1);r.set(f,-m,v),r.set(g,m,v),r.toGlobalFrame(f,f,i,s),r.toGlobalFrame(g,g,i,s);var b=r.getLineSegmentsIntersectionFraction(n,o,f,g);if(b>=0&&(r.rotate(p,u,s),r.scale(p,p,2*y-1),e.reportIntersection(t,b,p,-1),t.shouldStop(e)))return}for(var x=Math.pow(this.radius,2)+Math.pow(m,2),y=0;y<2;y++){r.set(f,m*(2*y-1),0),r.toGlobalFrame(f,f,i,s);var w=Math.pow(o[0]-n[0],2)+Math.pow(o[1]-n[1],2),_=2*((o[0]-n[0])*(n[0]-f[0])+(o[1]-n[1])*(n[1]-f[1])),P=Math.pow(n[0]-f[0],2)+Math.pow(n[1]-f[1],2)-Math.pow(this.radius,2),b=Math.pow(_,2)-4*w*P;if(!(b<0))if(0===b){if(r.lerp(d,n,o,b),r.squaredDistance(d,i)>x&&(r.sub(p,d,f),r.normalize(p,p),e.reportIntersection(t,b,p,-1),t.shouldStop(e)))return}else{var T=Math.sqrt(b),C=1/(2*w),S=(-_-T)*C,A=(-_+T)*C;if(S>=0&&S<=1&&(r.lerp(d,n,o,S),r.squaredDistance(d,i)>x&&(r.sub(p,d,f),r.normalize(p,p),e.reportIntersection(t,S,p,-1),t.shouldStop(e))))return;if(A>=0&&A<=1&&(r.lerp(d,n,o,A),r.squaredDistance(d,i)>x&&(r.sub(p,d,f),r.normalize(p,p),e.reportIntersection(t,A,p,-1),t.shouldStop(e))))return}}}},{"../math/vec2":30,"./Shape":45}],39:[function(t,e,i){function s(t){"number"==typeof arguments[0]&&(t={radius:arguments[0]},console.warn("The Circle constructor signature has changed. Please use the following format: new Circle({ radius: 1 })")),t=t||{},this.radius=t.radius||1,t.type=n.CIRCLE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.computeMomentOfInertia=function(t){var e=this.radius;return t*e*e/2},s.prototype.updateBoundingRadius=function(){this.boundingRadius=this.radius},s.prototype.updateArea=function(){this.area=Math.PI*this.radius*this.radius},s.prototype.computeAABB=function(t,e,i){var s=this.radius;r.set(t.upperBound,s,s),r.set(t.lowerBound,-s,-s),e&&(r.add(t.lowerBound,t.lowerBound,e),r.add(t.upperBound,t.upperBound,e))};var o=r.create(),a=r.create();s.prototype.raycast=function(t,e,i,s){var n=e.from,h=e.to,l=this.radius,c=Math.pow(h[0]-n[0],2)+Math.pow(h[1]-n[1],2),u=2*((h[0]-n[0])*(n[0]-i[0])+(h[1]-n[1])*(n[1]-i[1])),d=Math.pow(n[0]-i[0],2)+Math.pow(n[1]-i[1],2)-Math.pow(l,2),p=Math.pow(u,2)-4*c*d,f=o,g=a;if(!(p<0))if(0===p)r.lerp(f,n,h,p),r.sub(g,f,i),r.normalize(g,g),e.reportIntersection(t,p,g,-1);else{var m=Math.sqrt(p),y=1/(2*c),v=(-u-m)*y,b=(-u+m)*y;if(v>=0&&v<=1&&(r.lerp(f,n,h,v),r.sub(g,f,i),r.normalize(g,g),e.reportIntersection(t,v,g,-1),t.shouldStop(e)))return;b>=0&&b<=1&&(r.lerp(f,n,h,b),r.sub(g,f,i),r.normalize(g,g),e.reportIntersection(t,b,g,-1))}}},{"../math/vec2":30,"./Shape":45}],40:[function(t,e,i){function s(t){Array.isArray(arguments[0])&&(t={vertices:arguments[0],axes:arguments[1]},console.warn("The Convex constructor signature has changed. Please use the following format: new Convex({ vertices: [...], ... })")),t=t||{},this.vertices=[];for(var e=void 0!==t.vertices?t.vertices:[],i=0;i<e.length;i++){var s=r.create();r.copy(s,e[i]),this.vertices.push(s)}if(this.axes=[],t.axes)for(var i=0;i<t.axes.length;i++){var o=r.create();r.copy(o,t.axes[i]),this.axes.push(o)}else for(var i=0;i<this.vertices.length;i++){var a=this.vertices[i],h=this.vertices[(i+1)%this.vertices.length],l=r.create();r.sub(l,h,a),r.rotate90cw(l,l),r.normalize(l,l),this.axes.push(l)}if(this.centerOfMass=r.fromValues(0,0),this.triangles=[],this.vertices.length&&(this.updateTriangles(),this.updateCenterOfMass()),this.boundingRadius=0,t.type=n.CONVEX,n.call(this,t),this.updateBoundingRadius(),this.updateArea(),this.area<0)throw new Error("Convex vertices must be given in conter-clockwise winding.")}var n=t("./Shape"),r=t("../math/vec2"),o=t("../math/polyk");t("poly-decomp");e.exports=s,s.prototype=new n,s.prototype.constructor=s;var a=r.create(),h=r.create();s.prototype.projectOntoLocalAxis=function(t,e){for(var i,s,n=null,o=null,t=a,h=0;h<this.vertices.length;h++)i=this.vertices[h],s=r.dot(i,t),(null===n||s>n)&&(n=s),(null===o||s<o)&&(o=s);if(o>n){var l=o;o=n,n=l}r.set(e,o,n)},s.prototype.projectOntoWorldAxis=function(t,e,i,s){var n=h;this.projectOntoLocalAxis(t,s),0!==i?r.rotate(n,t,i):n=t;var o=r.dot(e,n);r.set(s,s[0]+o,s[1]+o)},s.prototype.updateTriangles=function(){this.triangles.length=0;for(var t=[],e=0;e<this.vertices.length;e++){var i=this.vertices[e];t.push(i[0],i[1])}for(var s=o.Triangulate(t),e=0;e<s.length;e+=3){var n=s[e],r=s[e+1],a=s[e+2];this.triangles.push([n,r,a])}};var l=r.create(),c=r.create(),u=r.create(),d=r.create(),p=r.create();r.create(),r.create(),r.create(),r.create();s.prototype.updateCenterOfMass=function(){var t=this.triangles,e=this.vertices,i=this.centerOfMass,n=l,o=u,a=d,h=p,f=c;r.set(i,0,0);for(var g=0,m=0;m!==t.length;m++){var y=t[m],o=e[y[0]],a=e[y[1]],h=e[y[2]];r.centroid(n,o,a,h);var v=s.triangleArea(o,a,h);g+=v,r.scale(f,n,v),r.add(i,i,f)}r.scale(i,i,1/g)},s.prototype.computeMomentOfInertia=function(t){for(var e=0,i=0,s=this.vertices.length,n=s-1,o=0;o<s;n=o,o++){var a=this.vertices[n],h=this.vertices[o],l=Math.abs(r.crossLength(a,h));e+=l*(r.dot(h,h)+r.dot(h,a)+r.dot(a,a)),i+=l}return t/6*(e/i)},s.prototype.updateBoundingRadius=function(){for(var t=this.vertices,e=0,i=0;i!==t.length;i++){var s=r.squaredLength(t[i]);s>e&&(e=s)}this.boundingRadius=Math.sqrt(e)},s.triangleArea=function(t,e,i){return.5*((e[0]-t[0])*(i[1]-t[1])-(i[0]-t[0])*(e[1]-t[1]))},s.prototype.updateArea=function(){this.updateTriangles(),this.area=0;for(var t=this.triangles,e=this.vertices,i=0;i!==t.length;i++){var n=t[i],r=e[n[0]],o=e[n[1]],a=e[n[2]],h=s.triangleArea(r,o,a);this.area+=h}},s.prototype.computeAABB=function(t,e,i){t.setFromPoints(this.vertices,e,i,0)};var f=r.create(),g=r.create(),m=r.create();s.prototype.raycast=function(t,e,i,s){var n=f,o=g,a=m,h=this.vertices;r.toLocalFrame(n,e.from,i,s),r.toLocalFrame(o,e.to,i,s);for(var l=h.length,c=0;c<l&&!t.shouldStop(e);c++){var u=h[c],d=h[(c+1)%l],p=r.getLineSegmentsIntersectionFraction(n,o,u,d);p>=0&&(r.sub(a,d,u),r.rotate(a,a,-Math.PI/2+s),r.normalize(a,a),e.reportIntersection(t,p,a,c))}}},{"../math/polyk":29,"../math/vec2":30,"./Shape":45,"poly-decomp":5}],41:[function(t,e,i){function s(t){if(Array.isArray(arguments[0])){if(t={heights:arguments[0]},"object"==typeof arguments[1])for(var e in arguments[1])t[e]=arguments[1][e];console.warn("The Heightfield constructor signature has changed. Please use the following format: new Heightfield({ heights: [...], ... })")}t=t||{},this.heights=t.heights?t.heights.slice(0):[],this.maxValue=t.maxValue||null,this.minValue=t.minValue||null,this.elementWidth=t.elementWidth||.1,void 0!==t.maxValue&&void 0!==t.minValue||this.updateMaxMinValues(),t.type=n.HEIGHTFIELD,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");t("../utils/Utils");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.updateMaxMinValues=function(){for(var t=this.heights,e=t[0],i=t[0],s=0;s!==t.length;s++){var n=t[s];n>e&&(e=n),n<i&&(i=n)}this.maxValue=e,this.minValue=i},s.prototype.computeMomentOfInertia=function(t){return Number.MAX_VALUE},s.prototype.updateBoundingRadius=function(){this.boundingRadius=Number.MAX_VALUE},s.prototype.updateArea=function(){for(var t=this.heights,e=0,i=0;i<t.length-1;i++)e+=(t[i]+t[i+1])/2*this.elementWidth;this.area=e};var o=[r.create(),r.create(),r.create(),r.create()];s.prototype.computeAABB=function(t,e,i){r.set(o[0],0,this.maxValue),r.set(o[1],this.elementWidth*this.heights.length,this.maxValue),r.set(o[2],this.elementWidth*this.heights.length,this.minValue),r.set(o[3],0,this.minValue),t.setFromPoints(o,e,i)},s.prototype.getLineSegment=function(t,e,i){var s=this.heights,n=this.elementWidth;r.set(t,i*n,s[i]),r.set(e,(i+1)*n,s[i+1])},s.prototype.getSegmentIndex=function(t){return Math.floor(t[0]/this.elementWidth)},s.prototype.getClampedSegmentIndex=function(t){var e=this.getSegmentIndex(t);return e=Math.min(this.heights.length,Math.max(e,0))};var a=(r.create(),r.create()),h=r.create(),l=r.create(),c=r.create(),u=r.create();r.fromValues(0,1);s.prototype.raycast=function(t,e,i,s){var n=e.from,o=e.to,d=(e.direction,a),p=h,f=l,g=c,m=u;r.toLocalFrame(g,n,i,s),r.toLocalFrame(m,o,i,s);var y=this.getClampedSegmentIndex(g),v=this.getClampedSegmentIndex(m);if(y>v){var b=y;y=v,v=b}for(var x=0;x<this.heights.length-1;x++){this.getLineSegment(p,f,x);var w=r.getLineSegmentsIntersectionFraction(g,m,p,f);if(w>=0&&(r.sub(d,f,p),r.rotate(d,d,s+Math.PI/2),r.normalize(d,d),e.reportIntersection(t,w,d,-1),t.shouldStop(e)))return}}},{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],42:[function(t,e,i){function s(t){"number"==typeof arguments[0]&&(t={length:arguments[0]},console.warn("The Line constructor signature has changed. Please use the following format: new Line({ length: 1, ... })")),t=t||{},this.length=t.length||1,t.type=n.LINE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.computeMomentOfInertia=function(t){return t*Math.pow(this.length,2)/12},s.prototype.updateBoundingRadius=function(){this.boundingRadius=this.length/2};var o=[r.create(),r.create()];s.prototype.computeAABB=function(t,e,i){var s=this.length/2;r.set(o[0],-s,0),r.set(o[1],s,0),t.setFromPoints(o,e,i,0)};var a=(r.create(),r.create()),h=r.create(),l=r.create(),c=r.fromValues(0,1);s.prototype.raycast=function(t,e,i,s){var n=e.from,o=e.to,u=h,d=l,p=this.length/2;r.set(u,-p,0),r.set(d,p,0),r.toGlobalFrame(u,u,i,s),r.toGlobalFrame(d,d,i,s);var f=r.getLineSegmentsIntersectionFraction(u,d,n,o);if(f>=0){var g=a;r.rotate(g,c,s),e.reportIntersection(t,f,g,-1)}}},{"../math/vec2":30,"./Shape":45}],43:[function(t,e,i){function s(t){t=t||{},t.type=n.PARTICLE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.computeMomentOfInertia=function(t){return 0},s.prototype.updateBoundingRadius=function(){this.boundingRadius=0},s.prototype.computeAABB=function(t,e,i){r.copy(t.lowerBound,e),r.copy(t.upperBound,e)}},{"../math/vec2":30,"./Shape":45}],44:[function(t,e,i){function s(t){t=t||{},t.type=n.PLANE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");t("../utils/Utils");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.computeMomentOfInertia=function(t){return 0},s.prototype.updateBoundingRadius=function(){this.boundingRadius=Number.MAX_VALUE},s.prototype.computeAABB=function(t,e,i){var s=i%(2*Math.PI),n=r.set,o=Number.MAX_VALUE,a=t.lowerBound,h=t.upperBound;0===s?(n(a,-o,-o),n(h,o,0)):s===Math.PI/2?(n(a,0,-o),n(h,o,o)):s===Math.PI?(n(a,-o,0),n(h,o,o)):s===3*Math.PI/2?(n(a,-o,-o),n(h,0,o)):(n(a,-o,-o),n(h,o,o)),r.add(a,a,e),r.add(h,h,e)},s.prototype.updateArea=function(){this.area=Number.MAX_VALUE};var o=r.create(),a=(r.create(),r.create(),r.create()),h=r.create();s.prototype.raycast=function(t,e,i,s){var n=e.from,l=e.to,c=e.direction,u=o,d=a,p=h;r.set(d,0,1),r.rotate(d,d,s),r.sub(p,n,i);var f=r.dot(p,d);if(r.sub(p,l,i),!(f*r.dot(p,d)>0||r.squaredDistance(n,l)<f*f)){var g=r.dot(d,c);r.sub(u,n,i);var m=-r.dot(d,u)/g/e.length;e.reportIntersection(t,m,d,-1)}}},{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],45:[function(t,e,i){function s(t){t=t||{},this.body=null,this.position=n.fromValues(0,0),t.position&&n.copy(this.position,t.position),this.angle=t.angle||0,this.type=t.type||0,this.id=s.idCounter++,this.boundingRadius=0,this.collisionGroup=void 0!==t.collisionGroup?t.collisionGroup:1,this.collisionResponse=void 0===t.collisionResponse||t.collisionResponse,this.collisionMask=void 0!==t.collisionMask?t.collisionMask:1,this.material=t.material||null,this.area=0,this.sensor=void 0!==t.sensor&&t.sensor,this.type&&this.updateBoundingRadius(),this.updateArea()}e.exports=s;var n=t("../math/vec2");s.idCounter=0,s.CIRCLE=1,s.PARTICLE=2,s.PLANE=4,s.CONVEX=8,s.LINE=16,s.BOX=32,Object.defineProperty(s,"RECTANGLE",{get:function(){return console.warn("Shape.RECTANGLE is deprecated, use Shape.BOX instead."),s.BOX}}),s.CAPSULE=64,s.HEIGHTFIELD=128,s.prototype.computeMomentOfInertia=function(t){},s.prototype.updateBoundingRadius=function(){},s.prototype.updateArea=function(){},s.prototype.computeAABB=function(t,e,i){},s.prototype.raycast=function(t,e,i,s){}},{"../math/vec2":30}],46:[function(t,e,i){function s(t){o.call(this,t,o.GS),t=t||{},this.iterations=t.iterations||10,this.tolerance=t.tolerance||1e-7,this.arrayStep=30,this.lambda=new a.ARRAY_TYPE(this.arrayStep),this.Bs=new a.ARRAY_TYPE(this.arrayStep),this.invCs=new a.ARRAY_TYPE(this.arrayStep),this.useZeroRHS=!1,this.frictionIterations=0,this.usedIterations=0}function n(t){for(var e=t.length;e--;)t[e]=0}var r=t("../math/vec2"),o=t("./Solver"),a=t("../utils/Utils"),h=t("../equations/FrictionEquation");e.exports=s,s.prototype=new o,s.prototype.constructor=s,s.prototype.solve=function(t,e){this.sortEquations();var i=0,o=this.iterations,l=this.frictionIterations,c=this.equations,u=c.length,d=Math.pow(this.tolerance*u,2),p=e.bodies,f=e.bodies.length,g=(r.add,r.set,this.useZeroRHS),m=this.lambda;if(this.usedIterations=0,u)for(var y=0;y!==f;y++){var v=p[y];v.updateSolveMassProperties()}m.length<u&&(m=this.lambda=new a.ARRAY_TYPE(u+this.arrayStep),this.Bs=new a.ARRAY_TYPE(u+this.arrayStep),this.invCs=new a.ARRAY_TYPE(u+this.arrayStep)),n(m);for(var b=this.invCs,x=this.Bs,m=this.lambda,y=0;y!==c.length;y++){var w=c[y];(w.timeStep!==t||w.needsUpdate)&&(w.timeStep=t,w.update()),x[y]=w.computeB(w.a,w.b,t),b[y]=w.computeInvC(w.epsilon)}var w,_,y,P;if(0!==u){for(y=0;y!==f;y++){var v=p[y];v.resetConstraintVelocity()}if(l){for(i=0;i!==l;i++){for(_=0,P=0;P!==u;P++){w=c[P];var T=s.iterateEquation(P,w,w.epsilon,x,b,m,g,t,i);_+=Math.abs(T)}if(this.usedIterations++,_*_<=d)break}for(s.updateMultipliers(c,m,1/t),P=0;P!==u;P++){var C=c[P];if(C instanceof h){for(var S=0,A=0;A!==C.contactEquations.length;A++)S+=C.contactEquations[A].multiplier;S*=C.frictionCoefficient/C.contactEquations.length,C.maxForce=S,C.minForce=-S}}}for(i=0;i!==o;i++){for(_=0,P=0;P!==u;P++){w=c[P];var T=s.iterateEquation(P,w,w.epsilon,x,b,m,g,t,i);_+=Math.abs(T)}if(this.usedIterations++,_*_<=d)break}for(y=0;y!==f;y++)p[y].addConstraintVelocity();s.updateMultipliers(c,m,1/t)}},s.updateMultipliers=function(t,e,i){for(var s=t.length;s--;)t[s].multiplier=e[s]*i},s.iterateEquation=function(t,e,i,s,n,r,o,a,h){var l=s[t],c=n[t],u=r[t],d=e.computeGWlambda(),p=e.maxForce,f=e.minForce;o&&(l=0);var g=c*(l-d-i*u),m=u+g;return m<f*a?g=f*a-u:m>p*a&&(g=p*a-u),r[t]+=g,e.addToWlambda(g),g}},{"../equations/FrictionEquation":23,"../math/vec2":30,"../utils/Utils":57,"./Solver":47}],47:[function(t,e,i){function s(t,e){t=t||{},n.call(this),this.type=e,this.equations=[],this.equationSortFunction=t.equationSortFunction||!1}var n=(t("../utils/Utils"),t("../events/EventEmitter"));e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.solve=function(t,e){throw new Error("Solver.solve should be implemented by subclasses!")};var r={bodies:[]};s.prototype.solveIsland=function(t,e){this.removeAllEquations(),e.equations.length&&(this.addEquations(e.equations),r.bodies.length=0,e.getBodies(r.bodies),r.bodies.length&&this.solve(t,r))},s.prototype.sortEquations=function(){this.equationSortFunction&&this.equations.sort(this.equationSortFunction)},s.prototype.addEquation=function(t){t.enabled&&this.equations.push(t)},s.prototype.addEquations=function(t){for(var e=0,i=t.length;e!==i;e++){var s=t[e];s.enabled&&this.equations.push(s)}},s.prototype.removeEquation=function(t){var e=this.equations.indexOf(t);-1!==e&&this.equations.splice(e,1)},s.prototype.removeAllEquations=function(){this.equations.length=0},s.GS=1,s.ISLAND=2},{"../events/EventEmitter":26,"../utils/Utils":57}],48:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../equations/ContactEquation"),r=t("./Pool");e.exports=s,s.prototype=new r,s.prototype.constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.bodyA=t.bodyB=null,this}},{"../equations/ContactEquation":21,"./Pool":55}],49:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../equations/FrictionEquation"),r=t("./Pool");e.exports=s,s.prototype=new r,s.prototype.constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.bodyA=t.bodyB=null,this}},{"../equations/FrictionEquation":23,"./Pool":55}],50:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../world/IslandNode"),r=t("./Pool");e.exports=s,s.prototype=new r,s.prototype.constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.reset(),this}},{"../world/IslandNode":60,"./Pool":55}],51:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../world/Island"),r=t("./Pool");e.exports=s,s.prototype=new r,s.prototype.constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.reset(),this}},{"../world/Island":58,"./Pool":55}],52:[function(t,e,i){function s(){this.overlappingShapesLastState=new n,this.overlappingShapesCurrentState=new n,this.recordPool=new r({size:16}),this.tmpDict=new n,this.tmpArray1=[]}var n=t("./TupleDictionary"),r=(t("./OverlapKeeperRecord"),t("./OverlapKeeperRecordPool"));t("./Utils");e.exports=s,s.prototype.tick=function(){for(var t=this.overlappingShapesLastState,e=this.overlappingShapesCurrentState,i=t.keys.length;i--;){var s=t.keys[i],n=t.getByKey(s);e.getByKey(s);n&&this.recordPool.release(n)}t.reset(),t.copy(e),e.reset()},s.prototype.setOverlapping=function(t,e,i,s){var n=(this.overlappingShapesLastState,this.overlappingShapesCurrentState);if(!n.get(e.id,s.id)){var r=this.recordPool.get();r.set(t,e,i,s),n.set(e.id,s.id,r)}},s.prototype.getNewOverlaps=function(t){return this.getDiff(this.overlappingShapesLastState,this.overlappingShapesCurrentState,t)},s.prototype.getEndOverlaps=function(t){return this.getDiff(this.overlappingShapesCurrentState,this.overlappingShapesLastState,t)},s.prototype.bodiesAreOverlapping=function(t,e){for(var i=this.overlappingShapesCurrentState,s=i.keys.length;s--;){var n=i.keys[s],r=i.data[n];if(r.bodyA===t&&r.bodyB===e||r.bodyA===e&&r.bodyB===t)return!0}return!1},s.prototype.getDiff=function(t,e,i){var i=i||[],s=t,n=e;i.length=0;for(var r=n.keys.length;r--;){var o=n.keys[r],a=n.data[o];if(!a)throw new Error("Key "+o+" had no data!");s.data[o]||i.push(a)}return i},s.prototype.isNewOverlap=function(t,e){var i=0|t.id,s=0|e.id,n=this.overlappingShapesLastState,r=this.overlappingShapesCurrentState;return!n.get(i,s)&&!!r.get(i,s)},s.prototype.getNewBodyOverlaps=function(t){this.tmpArray1.length=0;var e=this.getNewOverlaps(this.tmpArray1);return this.getBodyDiff(e,t)},s.prototype.getEndBodyOverlaps=function(t){this.tmpArray1.length=0;var e=this.getEndOverlaps(this.tmpArray1);return this.getBodyDiff(e,t)},s.prototype.getBodyDiff=function(t,e){e=e||[];for(var i=this.tmpDict,s=t.length;s--;){var n=t[s];i.set(0|n.bodyA.id,0|n.bodyB.id,n)}for(s=i.keys.length;s--;){var n=i.getByKey(i.keys[s]);n&&e.push(n.bodyA,n.bodyB)}return i.reset(),e}},{"./OverlapKeeperRecord":53,"./OverlapKeeperRecordPool":54,"./TupleDictionary":56,"./Utils":57}],53:[function(t,e,i){function s(t,e,i,s){this.shapeA=e,this.shapeB=s,this.bodyA=t,this.bodyB=i}e.exports=s,s.prototype.set=function(t,e,i,n){s.call(this,t,e,i,n)}},{}],54:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("./OverlapKeeperRecord"),r=t("./Pool");e.exports=s,s.prototype=new r,s.prototype.constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.bodyA=t.bodyB=t.shapeA=t.shapeB=null,this}},{"./OverlapKeeperRecord":53,"./Pool":55}],55:[function(t,e,i){function s(t){t=t||{},this.objects=[],void 0!==t.size&&this.resize(t.size)}e.exports=s,s.prototype.resize=function(t){for(var e=this.objects;e.length>t;)e.pop();for(;e.length<t;)e.push(this.create());return this},s.prototype.get=function(){var t=this.objects;return t.length?t.pop():this.create()},s.prototype.release=function(t){return this.destroy(t),this.objects.push(t),this}},{}],56:[function(t,e,i){function s(){this.data={},this.keys=[]}var n=t("./Utils");e.exports=s,s.prototype.getKey=function(t,e){return t|=0,e|=0,(0|t)==(0|e)?-1:0|((0|t)>(0|e)?t<<16|65535&e:e<<16|65535&t)},s.prototype.getByKey=function(t){return t|=0,this.data[t]},s.prototype.get=function(t,e){return this.data[this.getKey(t,e)]},s.prototype.set=function(t,e,i){if(!i)throw new Error("No data!");var s=this.getKey(t,e);return this.data[s]||this.keys.push(s),this.data[s]=i,s},s.prototype.reset=function(){for(var t=this.data,e=this.keys,i=e.length;i--;)delete t[e[i]];e.length=0},s.prototype.copy=function(t){this.reset(),n.appendArray(this.keys,t.keys);for(var e=t.keys.length;e--;){var i=t.keys[e];this.data[i]=t.data[i]}}},{"./Utils":57}],57:[function(t,e,i){function s(){}e.exports=s,s.appendArray=function(t,e){if(e.length<15e4)t.push.apply(t,e);else for(var i=0,s=e.length;i!==s;++i)t.push(e[i])},s.splice=function(t,e,i){i=i||1;for(var s=e,n=t.length-i;s<n;s++)t[s]=t[s+i];t.length=n},"undefined"!=typeof P2_ARRAY_TYPE?s.ARRAY_TYPE=P2_ARRAY_TYPE:"undefined"!=typeof Float32Array?s.ARRAY_TYPE=Float32Array:s.ARRAY_TYPE=Array,s.extend=function(t,e){for(var i in e)t[i]=e[i]},s.defaults=function(t,e){t=t||{};for(var i in e)i in t||(t[i]=e[i]);return t}},{}],58:[function(t,e,i){function s(){this.equations=[],this.bodies=[]}var n=t("../objects/Body");e.exports=s,s.prototype.reset=function(){this.equations.length=this.bodies.length=0};var r=[];s.prototype.getBodies=function(t){var e=t||[],i=this.equations;r.length=0;for(var s=0;s!==i.length;s++){var n=i[s];-1===r.indexOf(n.bodyA.id)&&(e.push(n.bodyA),r.push(n.bodyA.id)),-1===r.indexOf(n.bodyB.id)&&(e.push(n.bodyB),r.push(n.bodyB.id))}return e},s.prototype.wantsToSleep=function(){for(var t=0;t<this.bodies.length;t++){var e=this.bodies[t];if(e.type===n.DYNAMIC&&!e.wantsToSleep)return!1}return!0},s.prototype.sleep=function(){for(var t=0;t<this.bodies.length;t++){this.bodies[t].sleep()}return!0}},{"../objects/Body":31}],59:[function(t,e,i){function s(t){this.nodePool=new n({size:16}),this.islandPool=new r({size:8}),this.equations=[],this.islands=[],this.nodes=[],this.queue=[]}var n=(t("../math/vec2"),t("./Island"),t("./IslandNode"),t("./../utils/IslandNodePool")),r=t("./../utils/IslandPool"),o=t("../objects/Body");e.exports=s,s.getUnvisitedNode=function(t){for(var e=t.length,i=0;i!==e;i++){var s=t[i];if(!s.visited&&s.body.type===o.DYNAMIC)return s}return!1},s.prototype.visit=function(t,e,i){e.push(t.body);for(var s=t.equations.length,n=0;n!==s;n++){var r=t.equations[n];-1===i.indexOf(r)&&i.push(r)}},s.prototype.bfs=function(t,e,i){var n=this.queue;for(n.length=0,n.push(t),t.visited=!0,this.visit(t,e,i);n.length;)for(var r,a=n.pop();r=s.getUnvisitedNode(a.neighbors);)r.visited=!0,this.visit(r,e,i),r.body.type===o.DYNAMIC&&n.push(r)},s.prototype.split=function(t){for(var e=t.bodies,i=this.nodes,n=this.equations;i.length;)this.nodePool.release(i.pop());for(var r=0;r!==e.length;r++){var o=this.nodePool.get();o.body=e[r],i.push(o)}for(var a=0;a!==n.length;a++){var h=n[a],r=e.indexOf(h.bodyA),l=e.indexOf(h.bodyB),c=i[r],u=i[l];c.neighbors.push(u),u.neighbors.push(c),c.equations.push(h),u.equations.push(h)}for(var d=this.islands,r=0;r<d.length;r++)this.islandPool.release(d[r]);d.length=0;for(var p;p=s.getUnvisitedNode(i);){var f=this.islandPool.get();this.bfs(p,f.bodies,f.equations),d.push(f)}return d}},{"../math/vec2":30,"../objects/Body":31,"./../utils/IslandNodePool":50,"./../utils/IslandPool":51,"./Island":58,"./IslandNode":60}],60:[function(t,e,i){function s(t){this.body=t,this.neighbors=[],this.equations=[],this.visited=!1}e.exports=s,s.prototype.reset=function(){this.equations.length=0,this.neighbors.length=0,this.visited=!1,this.body=null}},{}],61:[function(t,e,i){function s(t){u.apply(this),t=t||{},this.springs=[],this.bodies=[],this.disabledBodyCollisionPairs=[],this.solver=t.solver||new n,this.narrowphase=new y(this),this.islandManager=new x,this.gravity=r.fromValues(0,-9.78),t.gravity&&r.copy(this.gravity,t.gravity),this.frictionGravity=r.length(this.gravity)||10,this.useWorldGravityAsFrictionGravity=!0,this.useFrictionGravityOnZeroGravity=!0,this.broadphase=t.broadphase||new m,this.broadphase.setWorld(this),this.constraints=[],this.defaultMaterial=new p,this.defaultContactMaterial=new f(this.defaultMaterial,this.defaultMaterial),this.lastTimeStep=1/60,this.applySpringForces=!0,this.applyDamping=!0,this.applyGravity=!0,this.solveConstraints=!0,this.contactMaterials=[],this.time=0,this.accumulator=0,this.stepping=!1,this.bodiesToBeRemoved=[],this.islandSplit=void 0===t.islandSplit||!!t.islandSplit,this.emitImpactEvent=!0,this._constraintIdCounter=0,this._bodyIdCounter=0,this.postStepEvent={type:"postStep"},this.addBodyEvent={type:"addBody",body:null},this.removeBodyEvent={type:"removeBody",body:null},this.addSpringEvent={type:"addSpring",spring:null},this.impactEvent={type:"impact",bodyA:null,bodyB:null,shapeA:null,shapeB:null,contactEquation:null},this.postBroadphaseEvent={type:"postBroadphase",pairs:null},this.sleepMode=s.NO_SLEEPING,this.beginContactEvent={type:"beginContact",shapeA:null,shapeB:null,bodyA:null,bodyB:null,contactEquations:[]},this.endContactEvent={type:"endContact",shapeA:null,shapeB:null,bodyA:null,bodyB:null},this.preSolveEvent={type:"preSolve",contactEquations:null,frictionEquations:null},this.overlappingShapesLastState={keys:[]},this.overlappingShapesCurrentState={keys:[]},this.overlapKeeper=new b}var n=t("../solver/GSSolver"),r=(t("../solver/Solver"),t("../collision/Ray"),t("../math/vec2")),o=t("../shapes/Circle"),a=t("../shapes/Convex"),h=(t("../shapes/Line"),t("../shapes/Plane")),l=t("../shapes/Capsule"),c=t("../shapes/Particle"),u=t("../events/EventEmitter"),d=t("../objects/Body"),p=(t("../shapes/Shape"),t("../objects/LinearSpring"),t("../material/Material")),f=t("../material/ContactMaterial"),g=(t("../constraints/DistanceConstraint"),t("../constraints/Constraint"),t("../constraints/LockConstraint"),t("../constraints/RevoluteConstraint"),t("../constraints/PrismaticConstraint"),t("../constraints/GearConstraint"),t("../../package.json"),t("../collision/Broadphase"),t("../collision/AABB")),m=t("../collision/SAPBroadphase"),y=t("../collision/Narrowphase"),v=t("../utils/Utils"),b=t("../utils/OverlapKeeper"),x=t("./IslandManager");t("../objects/RotationalSpring");e.exports=s,s.prototype=new Object(u.prototype),s.prototype.constructor=s,s.NO_SLEEPING=1,s.BODY_SLEEPING=2,s.ISLAND_SLEEPING=4,s.prototype.addConstraint=function(t){this.constraints.push(t)},s.prototype.addContactMaterial=function(t){this.contactMaterials.push(t)},s.prototype.removeContactMaterial=function(t){var e=this.contactMaterials.indexOf(t);-1!==e&&v.splice(this.contactMaterials,e,1)},s.prototype.getContactMaterial=function(t,e){for(var i=this.contactMaterials,s=0,n=i.length;s!==n;s++){var r=i[s];if(r.materialA.id===t.id&&r.materialB.id===e.id||r.materialA.id===e.id&&r.materialB.id===t.id)return r}return!1},s.prototype.removeConstraint=function(t){var e=this.constraints.indexOf(t);-1!==e&&v.splice(this.constraints,e,1)};var w=(r.create(),r.create(),r.create(),r.create(),r.create(),r.create(),r.create()),_=r.fromValues(0,0),P=r.fromValues(0,0);r.fromValues(0,0),r.fromValues(0,0);s.prototype.step=function(t,e,i){if(i=i||10,0===(e=e||0))this.internalStep(t),this.time+=t;else{this.accumulator+=e;for(var s=0;this.accumulator>=t&&s<i;)this.internalStep(t),this.time+=t,this.accumulator-=t,s++;for(var n=this.accumulator%t/t,o=0;o!==this.bodies.length;o++){var a=this.bodies[o];r.lerp(a.interpolatedPosition,a.previousPosition,a.position,n),a.interpolatedAngle=a.previousAngle+n*(a.angle-a.previousAngle)}}};var T=[];s.prototype.internalStep=function(t){this.stepping=!0;var e=this.springs.length,i=this.springs,n=this.bodies,o=this.gravity,a=this.solver,h=this.bodies.length,l=this.broadphase,c=this.narrowphase,u=this.constraints,p=w,f=(r.scale,r.add),g=(r.rotate,this.islandManager);if(this.overlapKeeper.tick(),this.lastTimeStep=t,this.useWorldGravityAsFrictionGravity){var m=r.length(this.gravity);0===m&&this.useFrictionGravityOnZeroGravity||(this.frictionGravity=m)}if(this.applyGravity)for(var y=0;y!==h;y++){var b=n[y],x=b.force;b.type===d.DYNAMIC&&b.sleepState!==d.SLEEPING&&(r.scale(p,o,b.mass*b.gravityScale),f(x,x,p))}if(this.applySpringForces)for(var y=0;y!==e;y++){var _=i[y];_.applyForce()}if(this.applyDamping)for(var y=0;y!==h;y++){var b=n[y];b.type===d.DYNAMIC&&b.applyDamping(t)}for(var P=l.getCollisionPairs(this),C=this.disabledBodyCollisionPairs,y=C.length-2;y>=0;y-=2)for(var S=P.length-2;S>=0;S-=2)(C[y]===P[S]&&C[y+1]===P[S+1]||C[y+1]===P[S]&&C[y]===P[S+1])&&P.splice(S,2);var A=u.length;for(y=0;y!==A;y++){var E=u[y];if(!E.collideConnected)for(var S=P.length-2;S>=0;S-=2)(E.bodyA===P[S]&&E.bodyB===P[S+1]||E.bodyB===P[S]&&E.bodyA===P[S+1])&&P.splice(S,2)}this.postBroadphaseEvent.pairs=P,this.emit(this.postBroadphaseEvent),this.postBroadphaseEvent.pairs=null,c.reset(this);for(var y=0,I=P.length;y!==I;y+=2)for(var M=P[y],R=P[y+1],B=0,L=M.shapes.length;B!==L;B++)for(var O=M.shapes[B],k=O.position,F=O.angle,D=0,U=R.shapes.length;D!==U;D++){var G=R.shapes[D],N=G.position,X=G.angle,W=this.defaultContactMaterial;if(O.material&&G.material){var j=this.getContactMaterial(O.material,G.material);j&&(W=j)}this.runNarrowphase(c,M,O,k,F,R,G,N,X,W,this.frictionGravity)}for(var y=0;y!==h;y++){var V=n[y];V._wakeUpAfterNarrowphase&&(V.wakeUp(),V._wakeUpAfterNarrowphase=!1)}if(this.has("endContact")){this.overlapKeeper.getEndOverlaps(T);for(var q=this.endContactEvent,D=T.length;D--;){var H=T[D];q.shapeA=H.shapeA,q.shapeB=H.shapeB,q.bodyA=H.bodyA,q.bodyB=H.bodyB,this.emit(q)}T.length=0}var Y=this.preSolveEvent;Y.contactEquations=c.contactEquations,Y.frictionEquations=c.frictionEquations,this.emit(Y),Y.contactEquations=Y.frictionEquations=null;var A=u.length;for(y=0;y!==A;y++)u[y].update();if(c.contactEquations.length||c.frictionEquations.length||A)if(this.islandSplit){for(g.equations.length=0,v.appendArray(g.equations,c.contactEquations),v.appendArray(g.equations,c.frictionEquations),y=0;y!==A;y++)v.appendArray(g.equations,u[y].equations);g.split(this);for(var y=0;y!==g.islands.length;y++){var z=g.islands[y];z.equations.length&&a.solveIsland(t,z)}}else{for(a.addEquations(c.contactEquations),a.addEquations(c.frictionEquations),y=0;y!==A;y++)a.addEquations(u[y].equations);this.solveConstraints&&a.solve(t,this),a.removeAllEquations()}for(var y=0;y!==h;y++){var V=n[y];V.integrate(t)}for(var y=0;y!==h;y++)n[y].setZeroForce();if(this.emitImpactEvent&&this.has("impact"))for(var K=this.impactEvent,y=0;y!==c.contactEquations.length;y++){var J=c.contactEquations[y];J.firstImpact&&(K.bodyA=J.bodyA,K.bodyB=J.bodyB,K.shapeA=J.shapeA,K.shapeB=J.shapeB,K.contactEquation=J,this.emit(K))}if(this.sleepMode===s.BODY_SLEEPING)for(y=0;y!==h;y++)n[y].sleepTick(this.time,!1,t);else if(this.sleepMode===s.ISLAND_SLEEPING&&this.islandSplit){for(y=0;y!==h;y++)n[y].sleepTick(this.time,!0,t);for(var y=0;y<this.islandManager.islands.length;y++){var z=this.islandManager.islands[y];z.wantsToSleep()&&z.sleep()}}this.stepping=!1;for(var Q=this.bodiesToBeRemoved,y=0;y!==Q.length;y++)this.removeBody(Q[y]);Q.length=0,this.emit(this.postStepEvent)},s.prototype.runNarrowphase=function(t,e,i,s,n,o,a,h,l,c,u){if(0!=(i.collisionGroup&a.collisionMask)&&0!=(a.collisionGroup&i.collisionMask)){r.rotate(_,s,e.angle),r.rotate(P,h,o.angle),r.add(_,_,e.position),r.add(P,P,o.position);var p=n+e.angle,f=l+o.angle;t.enableFriction=c.friction>0,t.frictionCoefficient=c.friction;var g;g=e.type===d.STATIC||e.type===d.KINEMATIC?o.mass:o.type===d.STATIC||o.type===d.KINEMATIC?e.mass:e.mass*o.mass/(e.mass+o.mass),t.slipForce=c.friction*u*g,t.restitution=c.restitution,t.surfaceVelocity=c.surfaceVelocity,t.frictionStiffness=c.frictionStiffness,t.frictionRelaxation=c.frictionRelaxation,t.stiffness=c.stiffness,t.relaxation=c.relaxation,t.contactSkinSize=c.contactSkinSize,t.enabledEquations=e.collisionResponse&&o.collisionResponse&&i.collisionResponse&&a.collisionResponse;var m=t[i.type|a.type],y=0;if(m){var v=i.sensor||a.sensor,b=t.frictionEquations.length;y=i.type<a.type?m.call(t,e,i,_,p,o,a,P,f,v):m.call(t,o,a,P,f,e,i,_,p,v);var x=t.frictionEquations.length-b;if(y){if(e.allowSleep&&e.type===d.DYNAMIC&&e.sleepState===d.SLEEPING&&o.sleepState===d.AWAKE&&o.type!==d.STATIC){r.squaredLength(o.velocity)+Math.pow(o.angularVelocity,2)>=2*Math.pow(o.sleepSpeedLimit,2)&&(e._wakeUpAfterNarrowphase=!0)}if(o.allowSleep&&o.type===d.DYNAMIC&&o.sleepState===d.SLEEPING&&e.sleepState===d.AWAKE&&e.type!==d.STATIC){r.squaredLength(e.velocity)+Math.pow(e.angularVelocity,2)>=2*Math.pow(e.sleepSpeedLimit,2)&&(o._wakeUpAfterNarrowphase=!0)}if(this.overlapKeeper.setOverlapping(e,i,o,a),this.has("beginContact")&&this.overlapKeeper.isNewOverlap(i,a)){var w=this.beginContactEvent;if(w.shapeA=i,w.shapeB=a,w.bodyA=e,w.bodyB=o,w.contactEquations.length=0,"number"==typeof y)for(var T=t.contactEquations.length-y;T<t.contactEquations.length;T++)w.contactEquations.push(t.contactEquations[T]);this.emit(w)}if("number"==typeof y&&x>1)for(var T=t.frictionEquations.length-x;T<t.frictionEquations.length;T++){var C=t.frictionEquations[T];C.setSlipForce(C.getSlipForce()/x)}}}}},s.prototype.addSpring=function(t){this.springs.push(t);var e=this.addSpringEvent;e.spring=t,this.emit(e),e.spring=null},s.prototype.removeSpring=function(t){var e=this.springs.indexOf(t);-1!==e&&v.splice(this.springs,e,1)},s.prototype.addBody=function(t){if(-1===this.bodies.indexOf(t)){this.bodies.push(t),t.world=this;var e=this.addBodyEvent;e.body=t,this.emit(e),e.body=null}},s.prototype.removeBody=function(t){if(this.stepping)this.bodiesToBeRemoved.push(t);else{t.world=null;var e=this.bodies.indexOf(t);-1!==e&&(v.splice(this.bodies,e,1),this.removeBodyEvent.body=t,t.resetConstraintVelocity(),this.emit(this.removeBodyEvent),this.removeBodyEvent.body=null)}},s.prototype.getBodyById=function(t){for(var e=this.bodies,i=0;i<e.length;i++){var s=e[i];if(s.id===t)return s}return!1},s.prototype.disableBodyCollision=function(t,e){this.disabledBodyCollisionPairs.push(t,e)},s.prototype.enableBodyCollision=function(t,e){for(var i=this.disabledBodyCollisionPairs,s=0;s<i.length;s+=2)if(i[s]===t&&i[s+1]===e||i[s+1]===t&&i[s]===e)return void i.splice(s,2)},s.prototype.clear=function(){this.time=0,this.solver&&this.solver.equations.length&&this.solver.removeAllEquations();for(var t=this.constraints,e=t.length-1;e>=0;e--)this.removeConstraint(t[e]);for(var i=this.bodies,e=i.length-1;e>=0;e--)this.removeBody(i[e]);for(var n=this.springs,e=n.length-1;e>=0;e--)this.removeSpring(n[e]);for(var r=this.contactMaterials,e=r.length-1;e>=0;e--)this.removeContactMaterial(r[e]);s.apply(this)};var C=r.create(),S=(r.fromValues(0,0),r.fromValues(0,0));s.prototype.hitTest=function(t,e,i){i=i||0;var s=new d({position:t}),n=new c,u=t,p=C,f=S;s.addShape(n);for(var g=this.narrowphase,m=[],y=0,v=e.length;y!==v;y++)for(var b=e[y],x=0,w=b.shapes.length;x!==w;x++){var _=b.shapes[x];r.rotate(p,_.position,b.angle),r.add(p,p,b.position);var P=_.angle+b.angle;(_ instanceof o&&g.circleParticle(b,_,p,P,s,n,u,0,!0)||_ instanceof a&&g.particleConvex(s,n,u,0,b,_,p,P,!0)||_ instanceof h&&g.particlePlane(s,n,u,0,b,_,p,P,!0)||_ instanceof l&&g.particleCapsule(s,n,u,0,b,_,p,P,!0)||_ instanceof c&&r.squaredLength(r.sub(f,p,t))<i*i)&&m.push(b)}return m},s.prototype.setGlobalStiffness=function(t){for(var e=this.constraints,i=0;i!==e.length;i++)for(var s=e[i],n=0;n!==s.equations.length;n++){var r=s.equations[n];r.stiffness=t,r.needsUpdate=!0}for(var o=this.contactMaterials,i=0;i!==o.length;i++){var s=o[i];s.stiffness=s.frictionStiffness=t}var s=this.defaultContactMaterial;s.stiffness=s.frictionStiffness=t},s.prototype.setGlobalRelaxation=function(t){for(var e=0;e!==this.constraints.length;e++)for(var i=this.constraints[e],s=0;s!==i.equations.length;s++){var n=i.equations[s];n.relaxation=t,n.needsUpdate=!0}for(var e=0;e!==this.contactMaterials.length;e++){var i=this.contactMaterials[e];i.relaxation=i.frictionRelaxation=t}var i=this.defaultContactMaterial;i.relaxation=i.frictionRelaxation=t};var A=new g,E=[];s.prototype.raycast=function(t,e){return e.getAABB(A),this.broadphase.aabbQuery(this,A,E),e.intersectBodies(t,E),E.length=0,t.hasHit()}},{"../../package.json":6,"../collision/AABB":7,"../collision/Broadphase":8,"../collision/Narrowphase":10,"../collision/Ray":11,"../collision/SAPBroadphase":13,"../constraints/Constraint":14,"../constraints/DistanceConstraint":15,"../constraints/GearConstraint":16,"../constraints/LockConstraint":17,"../constraints/PrismaticConstraint":18,"../constraints/RevoluteConstraint":19,"../events/EventEmitter":26,"../material/ContactMaterial":27,"../material/Material":28,"../math/vec2":30,"../objects/Body":31,"../objects/LinearSpring":32,"../objects/RotationalSpring":33,"../shapes/Capsule":38,"../shapes/Circle":39,"../shapes/Convex":40,"../shapes/Line":42,"../shapes/Particle":43,"../shapes/Plane":44,"../shapes/Shape":45,"../solver/GSSolver":46,"../solver/Solver":47,"../utils/OverlapKeeper":52,"../utils/Utils":57,"./IslandManager":59}]},{},[36])(36)})},function(t,e,i){(function(i){/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*
* @overview
*
* Phaser - http://phaser.io
*
* v2.6.2 "Kore Springs" - Built: Fri Aug 26 2016 01:03:19
*
* By Richard Davey http://www.photonstorm.com @photonstorm
*
* Phaser is a fun, free and fast 2D game framework for making HTML5 games
* for desktop and mobile web browsers, supporting Canvas and WebGL rendering.
*
* Phaser uses Pixi.js for rendering, created by Mat Groves http://matgroves.com @Doormat23
* Phaser uses p2.js for full-body physics, created by Stefan Hedman https://github.com/schteppe/p2.js @schteppe
* Phaser contains a port of N+ Physics, converted by Richard Davey, original by http://www.metanetsoftware.com
*
* Many thanks to Adam Saltsman (@ADAMATOMIC) for releasing Flixel, from which both Phaser and my love of framework development originate.
*
* Follow development at http://phaser.io and on our forum
*
* "If you want your children to be intelligent, read them fairy tales."
* "If you want them to be more intelligent, read them more fairy tales."
* -- Albert Einstein
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
(function(){function s(t,e){this._scaleFactor=t,this._deltaMode=e,this.originalEvent=null}var n=n||{VERSION:"2.6.2",GAMES:[],AUTO:0,CANVAS:1,WEBGL:2,HEADLESS:3,NONE:0,LEFT:1,RIGHT:2,UP:3,DOWN:4,SPRITE:0,BUTTON:1,IMAGE:2,GRAPHICS:3,TEXT:4,TILESPRITE:5,BITMAPTEXT:6,GROUP:7,RENDERTEXTURE:8,TILEMAP:9,TILEMAPLAYER:10,EMITTER:11,POLYGON:12,BITMAPDATA:13,CANVAS_FILTER:14,WEBGL_FILTER:15,ELLIPSE:16,SPRITEBATCH:17,RETROFONT:18,POINTER:19,ROPE:20,CIRCLE:21,RECTANGLE:22,LINE:23,MATRIX:24,POINT:25,ROUNDEDRECTANGLE:26,CREATURE:27,VIDEO:28,PENDING_ATLAS:-1,HORIZONTAL:0,VERTICAL:1,LANDSCAPE:0,PORTRAIT:1,ANGLE_UP:270,ANGLE_DOWN:90,ANGLE_LEFT:180,ANGLE_RIGHT:0,ANGLE_NORTH_EAST:315,ANGLE_NORTH_WEST:225,ANGLE_SOUTH_EAST:45,ANGLE_SOUTH_WEST:135,TOP_LEFT:0,TOP_CENTER:1,TOP_RIGHT:2,LEFT_TOP:3,LEFT_CENTER:4,LEFT_BOTTOM:5,CENTER:6,RIGHT_TOP:7,RIGHT_CENTER:8,RIGHT_BOTTOM:9,BOTTOM_LEFT:10,BOTTOM_CENTER:11,BOTTOM_RIGHT:12,blendModes:{NORMAL:0,ADD:1,MULTIPLY:2,SCREEN:3,OVERLAY:4,DARKEN:5,LIGHTEN:6,COLOR_DODGE:7,COLOR_BURN:8,HARD_LIGHT:9,SOFT_LIGHT:10,DIFFERENCE:11,EXCLUSION:12,HUE:13,SATURATION:14,COLOR:15,LUMINOSITY:16},scaleModes:{DEFAULT:0,LINEAR:0,NEAREST:1},PIXI:PIXI||{}};if(/**
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
Math.trunc||(Math.trunc=function(t){return t<0?Math.ceil(t):Math.floor(t)}),Function.prototype.bind||(Function.prototype.bind=function(){var t=Array.prototype.slice;return function(e){function i(){var r=n.concat(t.call(arguments));s.apply(this instanceof i?this:e,r)}var s=this,n=t.call(arguments,1);if("function"!=typeof s)throw new TypeError;return i.prototype=function t(e){if(e&&(t.prototype=e),!(this instanceof t))return new t}(s.prototype),i}}()),Array.isArray||(Array.isArray=function(t){return"[object Array]"===Object.prototype.toString.call(t)}),Array.prototype.forEach||(Array.prototype.forEach=function(t){"use strict";if(void 0===this||null===this)throw new TypeError;var e=Object(this),i=e.length>>>0;if("function"!=typeof t)throw new TypeError;for(var s=arguments.length>=2?arguments[1]:void 0,n=0;n<i;n++)n in e&&t.call(s,e[n],n,e)}),"function"!=typeof window.Uint32Array&&"object"!=typeof window.Uint32Array){var r=function(t){var e=new Array;window[t]=function(t){if("number"==typeof t){Array.call(this,t),this.length=t;for(var e=0;e<this.length;e++)this[e]=0}else{Array.call(this,t.length),this.length=t.length;for(var e=0;e<this.length;e++)this[e]=t[e]}},window[t].prototype=e,window[t].constructor=window[t]};r("Uint32Array"),r("Int16Array")}window.console||(window.console={},window.console.log=window.console.assert=function(){},window.console.warn=window.console.assert=function(){}),/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Utils={reverseString:function(t){return t.split("").reverse().join("")},getProperty:function(t,e){for(var i=e.split("."),s=i.pop(),n=i.length,r=1,o=i[0];r<n&&(t=t[o]);)o=i[r],r++;return t?t[s]:null},setProperty:function(t,e,i){for(var s=e.split("."),n=s.pop(),r=s.length,o=1,a=s[0];o<r&&(t=t[a]);)a=s[o],o++;return t&&(t[n]=i),t},chanceRoll:function(t){return void 0===t&&(t=50),t>0&&100*Math.random()<=t},randomChoice:function(t,e){return Math.random()<.5?t:e},parseDimension:function(t,e){var i=0,s=0;return"string"==typeof t?"%"===t.substr(-1)?(i=parseInt(t,10)/100,s=0===e?window.innerWidth*i:window.innerHeight*i):s=parseInt(t,10):s=t,s},pad:function(t,e,i,s){if(void 0===e)var e=0;if(void 0===i)var i=" ";if(void 0===s)var s=3;t=t.toString();var n=0;if(e+1>=t.length)switch(s){case 1:t=new Array(e+1-t.length).join(i)+t;break;case 3:var r=Math.ceil((n=e-t.length)/2),o=n-r;t=new Array(o+1).join(i)+t+new Array(r+1).join(i);break;default:t+=new Array(e+1-t.length).join(i)}return t},isPlainObject:function(t){if("object"!=typeof t||t.nodeType||t===t.window)return!1;try{if(t.constructor&&!{}.hasOwnProperty.call(t.constructor.prototype,"isPrototypeOf"))return!1}catch(t){return!1}return!0},extend:function(){var t,e,i,s,r,o,a=arguments[0]||{},h=1,l=arguments.length,c=!1;for("boolean"==typeof a&&(c=a,a=arguments[1]||{},h=2),l===h&&(a=this,--h);h<l;h++)if(null!=(t=arguments[h]))for(e in t)i=a[e],s=t[e],a!==s&&(c&&s&&(n.Utils.isPlainObject(s)||(r=Array.isArray(s)))?(r?(r=!1,o=i&&Array.isArray(i)?i:[]):o=i&&n.Utils.isPlainObject(i)?i:{},a[e]=n.Utils.extend(c,o,s)):void 0!==s&&(a[e]=s));return a},mixinPrototype:function(t,e,i){void 0===i&&(i=!1);for(var s=Object.keys(e),n=0;n<s.length;n++){var r=s[n],o=e[r];!i&&r in t||(!o||"function"!=typeof o.get&&"function"!=typeof o.set?t[r]=o:"function"==typeof o.clone?t[r]=o.clone():Object.defineProperty(t,r,o))}},mixin:function(t,e){if(!t||"object"!=typeof t)return e;for(var i in t){var s=t[i];if(!s.childNodes&&!s.cloneNode){var r=typeof t[i];t[i]&&"object"===r?typeof e[i]===r?e[i]=n.Utils.mixin(t[i],e[i]):e[i]=n.Utils.mixin(t[i],new s.constructor):e[i]=t[i]}}return e}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Circle=function(t,e,i){t=t||0,e=e||0,i=i||0,this.x=t,this.y=e,this._diameter=i,this._radius=0,i>0&&(this._radius=.5*i),this.type=n.CIRCLE},n.Circle.prototype={circumference:function(){return Math.PI*this._radius*2},random:function(t){void 0===t&&(t=new n.Point);var e=2*Math.PI*Math.random(),i=Math.random()+Math.random(),s=i>1?2-i:i,r=s*Math.cos(e),o=s*Math.sin(e);return t.x=this.x+r*this.radius,t.y=this.y+o*this.radius,t},getBounds:function(){return new n.Rectangle(this.x-this.radius,this.y-this.radius,this.diameter,this.diameter)},setTo:function(t,e,i){return this.x=t,this.y=e,this._diameter=i,this._radius=.5*i,this},copyFrom:function(t){return this.setTo(t.x,t.y,t.diameter)},copyTo:function(t){return t.x=this.x,t.y=this.y,t.diameter=this._diameter,t},distance:function(t,e){var i=n.Math.distance(this.x,this.y,t.x,t.y);return e?Math.round(i):i},clone:function(t){return void 0===t||null===t?t=new n.Circle(this.x,this.y,this.diameter):t.setTo(this.x,this.y,this.diameter),t},contains:function(t,e){return n.Circle.contains(this,t,e)},circumferencePoint:function(t,e,i){return n.Circle.circumferencePoint(this,t,e,i)},offset:function(t,e){return this.x+=t,this.y+=e,this},offsetPoint:function(t){return this.offset(t.x,t.y)},toString:function(){return"[{Phaser.Circle (x="+this.x+" y="+this.y+" diameter="+this.diameter+" radius="+this.radius+")}]"}},n.Circle.prototype.constructor=n.Circle,Object.defineProperty(n.Circle.prototype,"diameter",{get:function(){return this._diameter},set:function(t){t>0&&(this._diameter=t,this._radius=.5*t)}}),Object.defineProperty(n.Circle.prototype,"radius",{get:function(){return this._radius},set:function(t){t>0&&(this._radius=t,this._diameter=2*t)}}),Object.defineProperty(n.Circle.prototype,"left",{get:function(){return this.x-this._radius},set:function(t){t>this.x?(this._radius=0,this._diameter=0):this.radius=this.x-t}}),Object.defineProperty(n.Circle.prototype,"right",{get:function(){return this.x+this._radius},set:function(t){t<this.x?(this._radius=0,this._diameter=0):this.radius=t-this.x}}),Object.defineProperty(n.Circle.prototype,"top",{get:function(){return this.y-this._radius},set:function(t){t>this.y?(this._radius=0,this._diameter=0):this.radius=this.y-t}}),Object.defineProperty(n.Circle.prototype,"bottom",{get:function(){return this.y+this._radius},set:function(t){t<this.y?(this._radius=0,this._diameter=0):this.radius=t-this.y}}),Object.defineProperty(n.Circle.prototype,"area",{get:function(){return this._radius>0?Math.PI*this._radius*this._radius:0}}),Object.defineProperty(n.Circle.prototype,"empty",{get:function(){return 0===this._diameter},set:function(t){!0===t&&this.setTo(0,0,0)}}),n.Circle.contains=function(t,e,i){if(t.radius>0&&e>=t.left&&e<=t.right&&i>=t.top&&i<=t.bottom){return(t.x-e)*(t.x-e)+(t.y-i)*(t.y-i)<=t.radius*t.radius}return!1},n.Circle.equals=function(t,e){return t.x===e.x&&t.y===e.y&&t.diameter===e.diameter},n.Circle.intersects=function(t,e){return n.Math.distance(t.x,t.y,e.x,e.y)<=t.radius+e.radius},n.Circle.circumferencePoint=function(t,e,i,s){return void 0===i&&(i=!1),void 0===s&&(s=new n.Point),!0===i&&(e=n.Math.degToRad(e)),s.x=t.x+t.radius*Math.cos(e),s.y=t.y+t.radius*Math.sin(e),s},n.Circle.intersectsRectangle=function(t,e){var i=Math.abs(t.x-e.x-e.halfWidth);if(i>e.halfWidth+t.radius)return!1;var s=Math.abs(t.y-e.y-e.halfHeight);if(s>e.halfHeight+t.radius)return!1;if(i<=e.halfWidth||s<=e.halfHeight)return!0;var n=i-e.halfWidth,r=s-e.halfHeight;return n*n+r*r<=t.radius*t.radius},PIXI.Circle=n.Circle,/**
* @author Richard Davey <[email protected]>
* @author Chad Engler <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Ellipse=function(t,e,i,s){t=t||0,e=e||0,i=i||0,s=s||0,this.x=t,this.y=e,this.width=i,this.height=s,this.type=n.ELLIPSE},n.Ellipse.prototype={setTo:function(t,e,i,s){return this.x=t,this.y=e,this.width=i,this.height=s,this},getBounds:function(){return new n.Rectangle(this.x-this.width,this.y-this.height,this.width,this.height)},copyFrom:function(t){return this.setTo(t.x,t.y,t.width,t.height)},copyTo:function(t){return t.x=this.x,t.y=this.y,t.width=this.width,t.height=this.height,t},clone:function(t){return void 0===t||null===t?t=new n.Ellipse(this.x,this.y,this.width,this.height):t.setTo(this.x,this.y,this.width,this.height),t},contains:function(t,e){return n.Ellipse.contains(this,t,e)},random:function(t){void 0===t&&(t=new n.Point);var e=Math.random()*Math.PI*2,i=Math.random();return t.x=Math.sqrt(i)*Math.cos(e),t.y=Math.sqrt(i)*Math.sin(e),t.x=this.x+t.x*this.width/2,t.y=this.y+t.y*this.height/2,t},toString:function(){return"[{Phaser.Ellipse (x="+this.x+" y="+this.y+" width="+this.width+" height="+this.height+")}]"}},n.Ellipse.prototype.constructor=n.Ellipse,Object.defineProperty(n.Ellipse.prototype,"left",{get:function(){return this.x},set:function(t){this.x=t}}),Object.defineProperty(n.Ellipse.prototype,"right",{get:function(){return this.x+this.width},set:function(t){t<this.x?this.width=0:this.width=t-this.x}}),Object.defineProperty(n.Ellipse.prototype,"top",{get:function(){return this.y},set:function(t){this.y=t}}),Object.defineProperty(n.Ellipse.prototype,"bottom",{get:function(){return this.y+this.height},set:function(t){t<this.y?this.height=0:this.height=t-this.y}}),Object.defineProperty(n.Ellipse.prototype,"empty",{get:function(){return 0===this.width||0===this.height},set:function(t){!0===t&&this.setTo(0,0,0,0)}}),n.Ellipse.contains=function(t,e,i){if(t.width<=0||t.height<=0)return!1;var s=(e-t.x)/t.width-.5,n=(i-t.y)/t.height-.5;return s*=s,n*=n,s+n<.25},PIXI.Ellipse=n.Ellipse,/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Line=function(t,e,i,s){t=t||0,e=e||0,i=i||0,s=s||0,this.start=new n.Point(t,e),this.end=new n.Point(i,s),this.type=n.LINE},n.Line.prototype={setTo:function(t,e,i,s){return this.start.setTo(t,e),this.end.setTo(i,s),this},fromSprite:function(t,e,i){return void 0===i&&(i=!1),i?this.setTo(t.center.x,t.center.y,e.center.x,e.center.y):this.setTo(t.x,t.y,e.x,e.y)},fromAngle:function(t,e,i,s){return this.start.setTo(t,e),this.end.setTo(t+Math.cos(i)*s,e+Math.sin(i)*s),this},rotate:function(t,e){var i=(this.start.x+this.end.x)/2,s=(this.start.y+this.end.y)/2;return this.start.rotate(i,s,t,e),this.end.rotate(i,s,t,e),this},rotateAround:function(t,e,i,s){return this.start.rotate(t,e,i,s),this.end.rotate(t,e,i,s),this},intersects:function(t,e,i){return n.Line.intersectsPoints(this.start,this.end,t.start,t.end,e,i)},reflect:function(t){return n.Line.reflect(this,t)},midPoint:function(t){return void 0===t&&(t=new n.Point),t.x=(this.start.x+this.end.x)/2,t.y=(this.start.y+this.end.y)/2,t},centerOn:function(t,e){var i=(this.start.x+this.end.x)/2,s=(this.start.y+this.end.y)/2,n=t-i,r=e-s;this.start.add(n,r),this.end.add(n,r)},pointOnLine:function(t,e){return(t-this.start.x)*(this.end.y-this.start.y)==(this.end.x-this.start.x)*(e-this.start.y)},pointOnSegment:function(t,e){var i=Math.min(this.start.x,this.end.x),s=Math.max(this.start.x,this.end.x),n=Math.min(this.start.y,this.end.y),r=Math.max(this.start.y,this.end.y);return this.pointOnLine(t,e)&&t>=i&&t<=s&&e>=n&&e<=r},random:function(t){void 0===t&&(t=new n.Point);var e=Math.random();return t.x=this.start.x+e*(this.end.x-this.start.x),t.y=this.start.y+e*(this.end.y-this.start.y),t},coordinatesOnLine:function(t,e){void 0===t&&(t=1),void 0===e&&(e=[]);var i=Math.round(this.start.x),s=Math.round(this.start.y),n=Math.round(this.end.x),r=Math.round(this.end.y),o=Math.abs(n-i),a=Math.abs(r-s),h=i<n?1:-1,l=s<r?1:-1,c=o-a;e.push([i,s]);for(var u=1;i!==n||s!==r;){var d=c<<1;d>-a&&(c-=a,i+=h),d<o&&(c+=o,s+=l),u%t==0&&e.push([i,s]),u++}return e},clone:function(t){return void 0===t||null===t?t=new n.Line(this.start.x,this.start.y,this.end.x,this.end.y):t.setTo(this.start.x,this.start.y,this.end.x,this.end.y),t}},Object.defineProperty(n.Line.prototype,"length",{get:function(){return Math.sqrt((this.end.x-this.start.x)*(this.end.x-this.start.x)+(this.end.y-this.start.y)*(this.end.y-this.start.y))}}),Object.defineProperty(n.Line.prototype,"angle",{get:function(){return Math.atan2(this.end.y-this.start.y,this.end.x-this.start.x)}}),Object.defineProperty(n.Line.prototype,"slope",{get:function(){return(this.end.y-this.start.y)/(this.end.x-this.start.x)}}),Object.defineProperty(n.Line.prototype,"perpSlope",{get:function(){return-(this.end.x-this.start.x)/(this.end.y-this.start.y)}}),Object.defineProperty(n.Line.prototype,"x",{get:function(){return Math.min(this.start.x,this.end.x)}}),Object.defineProperty(n.Line.prototype,"y",{get:function(){return Math.min(this.start.y,this.end.y)}}),Object.defineProperty(n.Line.prototype,"left",{get:function(){return Math.min(this.start.x,this.end.x)}}),Object.defineProperty(n.Line.prototype,"right",{get:function(){return Math.max(this.start.x,this.end.x)}}),Object.defineProperty(n.Line.prototype,"top",{get:function(){return Math.min(this.start.y,this.end.y)}}),Object.defineProperty(n.Line.prototype,"bottom",{get:function(){return Math.max(this.start.y,this.end.y)}}),Object.defineProperty(n.Line.prototype,"width",{get:function(){return Math.abs(this.start.x-this.end.x)}}),Object.defineProperty(n.Line.prototype,"height",{get:function(){return Math.abs(this.start.y-this.end.y)}}),Object.defineProperty(n.Line.prototype,"normalX",{get:function(){return Math.cos(this.angle-1.5707963267948966)}}),Object.defineProperty(n.Line.prototype,"normalY",{get:function(){return Math.sin(this.angle-1.5707963267948966)}}),Object.defineProperty(n.Line.prototype,"normalAngle",{get:function(){return n.Math.wrap(this.angle-1.5707963267948966,-Math.PI,Math.PI)}}),n.Line.intersectsPoints=function(t,e,i,s,r,o){void 0===r&&(r=!0),void 0===o&&(o=new n.Point);var a=e.y-t.y,h=s.y-i.y,l=t.x-e.x,c=i.x-s.x,u=e.x*t.y-t.x*e.y,d=s.x*i.y-i.x*s.y,p=a*c-h*l;if(0===p)return null;if(o.x=(l*d-c*u)/p,o.y=(h*u-a*d)/p,r){var f=(s.y-i.y)*(e.x-t.x)-(s.x-i.x)*(e.y-t.y),g=((s.x-i.x)*(t.y-i.y)-(s.y-i.y)*(t.x-i.x))/f,m=((e.x-t.x)*(t.y-i.y)-(e.y-t.y)*(t.x-i.x))/f;return g>=0&&g<=1&&m>=0&&m<=1?o:null}return o},n.Line.intersects=function(t,e,i,s){return n.Line.intersectsPoints(t.start,t.end,e.start,e.end,i,s)},n.Line.intersectsRectangle=function(t,e){if(!n.Rectangle.intersects(t,e))return!1;var i=t.start.x,s=t.start.y,r=t.end.x,o=t.end.y,a=e.x,h=e.y,l=e.right,c=e.bottom,u=0;if(i>=a&&i<=l&&s>=h&&s<=c||r>=a&&r<=l&&o>=h&&o<=c)return!0;if(i<a&&r>=a){if((u=s+(o-s)*(a-i)/(r-i))>h&&u<=c)return!0}else if(i>l&&r<=l&&(u=s+(o-s)*(l-i)/(r-i))>=h&&u<=c)return!0;if(s<h&&o>=h){if((u=i+(r-i)*(h-s)/(o-s))>=a&&u<=l)return!0}else if(s>c&&o<=c&&(u=i+(r-i)*(c-s)/(o-s))>=a&&u<=l)return!0;return!1},n.Line.reflect=function(t,e){return 2*e.normalAngle-3.141592653589793-t.angle},/**
* @author Mat Groves http://matgroves.com/ @Doormat23
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Matrix=function(t,e,i,s,r,o){void 0!==t&&null!==t||(t=1),void 0!==e&&null!==e||(e=0),void 0!==i&&null!==i||(i=0),void 0!==s&&null!==s||(s=1),void 0!==r&&null!==r||(r=0),void 0!==o&&null!==o||(o=0),this.a=t,this.b=e,this.c=i,this.d=s,this.tx=r,this.ty=o,this.type=n.MATRIX},n.Matrix.prototype={fromArray:function(t){return this.setTo(t[0],t[1],t[3],t[4],t[2],t[5])},setTo:function(t,e,i,s,n,r){return this.a=t,this.b=e,this.c=i,this.d=s,this.tx=n,this.ty=r,this},clone:function(t){return void 0===t||null===t?t=new n.Matrix(this.a,this.b,this.c,this.d,this.tx,this.ty):(t.a=this.a,t.b=this.b,t.c=this.c,t.d=this.d,t.tx=this.tx,t.ty=this.ty),t},copyTo:function(t){return t.copyFrom(this),t},copyFrom:function(t){return this.a=t.a,this.b=t.b,this.c=t.c,this.d=t.d,this.tx=t.tx,this.ty=t.ty,this},toArray:function(t,e){return void 0===e&&(e=new PIXI.Float32Array(9)),t?(e[0]=this.a,e[1]=this.b,e[2]=0,e[3]=this.c,e[4]=this.d,e[5]=0,e[6]=this.tx,e[7]=this.ty,e[8]=1):(e[0]=this.a,e[1]=this.c,e[2]=this.tx,e[3]=this.b,e[4]=this.d,e[5]=this.ty,e[6]=0,e[7]=0,e[8]=1),e},apply:function(t,e){return void 0===e&&(e=new n.Point),e.x=this.a*t.x+this.c*t.y+this.tx,e.y=this.b*t.x+this.d*t.y+this.ty,e},applyInverse:function(t,e){void 0===e&&(e=new n.Point);var i=1/(this.a*this.d+this.c*-this.b),s=t.x,r=t.y;return e.x=this.d*i*s+-this.c*i*r+(this.ty*this.c-this.tx*this.d)*i,e.y=this.a*i*r+-this.b*i*s+(-this.ty*this.a+this.tx*this.b)*i,e},translate:function(t,e){return this.tx+=t,this.ty+=e,this},scale:function(t,e){return this.a*=t,this.d*=e,this.c*=t,this.b*=e,this.tx*=t,this.ty*=e,this},rotate:function(t){var e=Math.cos(t),i=Math.sin(t),s=this.a,n=this.c,r=this.tx;return this.a=s*e-this.b*i,this.b=s*i+this.b*e,this.c=n*e-this.d*i,this.d=n*i+this.d*e,this.tx=r*e-this.ty*i,this.ty=r*i+this.ty*e,this},append:function(t){var e=this.a,i=this.b,s=this.c,n=this.d;return this.a=t.a*e+t.b*s,this.b=t.a*i+t.b*n,this.c=t.c*e+t.d*s,this.d=t.c*i+t.d*n,this.tx=t.tx*e+t.ty*s+this.tx,this.ty=t.tx*i+t.ty*n+this.ty,this},identity:function(){return this.setTo(1,0,0,1,0,0)}},n.identityMatrix=new n.Matrix,PIXI.Matrix=n.Matrix,PIXI.identityMatrix=n.identityMatrix,/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Point=function(t,e){t=t||0,e=e||0,this.x=t,this.y=e,this.type=n.POINT},n.Point.prototype={copyFrom:function(t){return this.setTo(t.x,t.y)},invert:function(){return this.setTo(this.y,this.x)},setTo:function(t,e){return this.x=t||0,this.y=e||(0!==e?this.x:0),this},set:function(t,e){return this.x=t||0,this.y=e||(0!==e?this.x:0),this},add:function(t,e){return this.x+=t,this.y+=e,this},subtract:function(t,e){return this.x-=t,this.y-=e,this},multiply:function(t,e){return this.x*=t,this.y*=e,this},divide:function(t,e){return this.x/=t,this.y/=e,this},clampX:function(t,e){return this.x=n.Math.clamp(this.x,t,e),this},clampY:function(t,e){return this.y=n.Math.clamp(this.y,t,e),this},clamp:function(t,e){return this.x=n.Math.clamp(this.x,t,e),this.y=n.Math.clamp(this.y,t,e),this},clone:function(t){return void 0===t||null===t?t=new n.Point(this.x,this.y):t.setTo(this.x,this.y),t},copyTo:function(t){return t.x=this.x,t.y=this.y,t},distance:function(t,e){return n.Point.distance(this,t,e)},equals:function(t){return t.x===this.x&&t.y===this.y},angle:function(t,e){return void 0===e&&(e=!1),e?n.Math.radToDeg(Math.atan2(t.y-this.y,t.x-this.x)):Math.atan2(t.y-this.y,t.x-this.x)},rotate:function(t,e,i,s,r){return n.Point.rotate(this,t,e,i,s,r)},getMagnitude:function(){return Math.sqrt(this.x*this.x+this.y*this.y)},getMagnitudeSq:function(){return this.x*this.x+this.y*this.y},setMagnitude:function(t){return this.normalize().multiply(t,t)},normalize:function(){if(!this.isZero()){var t=this.getMagnitude();this.x/=t,this.y/=t}return this},isZero:function(){return 0===this.x&&0===this.y},dot:function(t){return this.x*t.x+this.y*t.y},cross:function(t){return this.x*t.y-this.y*t.x},perp:function(){return this.setTo(-this.y,this.x)},rperp:function(){return this.setTo(this.y,-this.x)},normalRightHand:function(){return this.setTo(-1*this.y,this.x)},floor:function(){return this.setTo(Math.floor(this.x),Math.floor(this.y))},ceil:function(){return this.setTo(Math.ceil(this.x),Math.ceil(this.y))},toString:function(){return"[{Point (x="+this.x+" y="+this.y+")}]"}},n.Point.prototype.constructor=n.Point,n.Point.add=function(t,e,i){return void 0===i&&(i=new n.Point),i.x=t.x+e.x,i.y=t.y+e.y,i},n.Point.subtract=function(t,e,i){return void 0===i&&(i=new n.Point),i.x=t.x-e.x,i.y=t.y-e.y,i},n.Point.multiply=function(t,e,i){return void 0===i&&(i=new n.Point),i.x=t.x*e.x,i.y=t.y*e.y,i},n.Point.divide=function(t,e,i){return void 0===i&&(i=new n.Point),i.x=t.x/e.x,i.y=t.y/e.y,i},n.Point.equals=function(t,e){return t.x===e.x&&t.y===e.y},n.Point.angle=function(t,e){return Math.atan2(t.y-e.y,t.x-e.x)},n.Point.negative=function(t,e){return void 0===e&&(e=new n.Point),e.setTo(-t.x,-t.y)},n.Point.multiplyAdd=function(t,e,i,s){return void 0===s&&(s=new n.Point),s.setTo(t.x+e.x*i,t.y+e.y*i)},n.Point.interpolate=function(t,e,i,s){return void 0===s&&(s=new n.Point),s.setTo(t.x+(e.x-t.x)*i,t.y+(e.y-t.y)*i)},n.Point.perp=function(t,e){return void 0===e&&(e=new n.Point),e.setTo(-t.y,t.x)},n.Point.rperp=function(t,e){return void 0===e&&(e=new n.Point),e.setTo(t.y,-t.x)},n.Point.distance=function(t,e,i){var s=n.Math.distance(t.x,t.y,e.x,e.y);return i?Math.round(s):s},n.Point.project=function(t,e,i){void 0===i&&(i=new n.Point);var s=t.dot(e)/e.getMagnitudeSq();return 0!==s&&i.setTo(s*e.x,s*e.y),i},n.Point.projectUnit=function(t,e,i){void 0===i&&(i=new n.Point);var s=t.dot(e);return 0!==s&&i.setTo(s*e.x,s*e.y),i},n.Point.normalRightHand=function(t,e){return void 0===e&&(e=new n.Point),e.setTo(-1*t.y,t.x)},n.Point.normalize=function(t,e){void 0===e&&(e=new n.Point);var i=t.getMagnitude();return 0!==i&&e.setTo(t.x/i,t.y/i),e},n.Point.rotate=function(t,e,i,s,r,o){if(r&&(s=n.Math.degToRad(s)),void 0===o){t.subtract(e,i);var a=Math.sin(s),h=Math.cos(s),l=h*t.x-a*t.y,c=a*t.x+h*t.y;t.x=l+e,t.y=c+i}else{var u=s+Math.atan2(t.y-i,t.x-e);t.x=e+o*Math.cos(u),t.y=i+o*Math.sin(u)}return t},n.Point.centroid=function(t,e){if(void 0===e&&(e=new n.Point),"[object Array]"!==Object.prototype.toString.call(t))throw new Error("Phaser.Point. Parameter 'points' must be an array");var i=t.length;if(i<1)throw new Error("Phaser.Point. Parameter 'points' array must not be empty");if(1===i)return e.copyFrom(t[0]),e;for(var s=0;s<i;s++)n.Point.add(e,t[s],e);return e.divide(i,i),e},n.Point.parse=function(t,e,i){e=e||"x",i=i||"y";var s=new n.Point;return t[e]&&(s.x=parseInt(t[e],10)),t[i]&&(s.y=parseInt(t[i],10)),s},PIXI.Point=n.Point,/**
* @author Richard Davey <[email protected]>
* @author Adrien Brault <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Polygon=function(){this.area=0,this._points=[],arguments.length>0&&this.setTo.apply(this,arguments),this.closed=!0,this.flattened=!1,this.type=n.POLYGON},n.Polygon.prototype={toNumberArray:function(t){void 0===t&&(t=[]);for(var e=0;e<this._points.length;e++)"number"==typeof this._points[e]?(t.push(this._points[e]),t.push(this._points[e+1]),e++):(t.push(this._points[e].x),t.push(this._points[e].y));return t},flatten:function(){return this._points=this.toNumberArray(),this.flattened=!0,this},clone:function(t){var e=this._points.slice();return void 0===t||null===t?t=new n.Polygon(e):t.setTo(e),t},contains:function(t,e){var i=!1;if(this.flattened)for(var s=-2,n=this._points.length-2;(s+=2)<this._points.length;n=s){var r=this._points[s],o=this._points[s+1],a=this._points[n],h=this._points[n+1];(o<=e&&e<h||h<=e&&e<o)&&t<(a-r)*(e-o)/(h-o)+r&&(i=!i)}else for(var s=-1,n=this._points.length-1;++s<this._points.length;n=s){var r=this._points[s].x,o=this._points[s].y,a=this._points[n].x,h=this._points[n].y;(o<=e&&e<h||h<=e&&e<o)&&t<(a-r)*(e-o)/(h-o)+r&&(i=!i)}return i},setTo:function(t){if(this.area=0,this._points=[],arguments.length>0){Array.isArray(t)||(t=Array.prototype.slice.call(arguments));for(var e=Number.MAX_VALUE,i=0,s=t.length;i<s;i++){if("number"==typeof t[i]){var n=new PIXI.Point(t[i],t[i+1]);i++}else if(Array.isArray(t[i]))var n=new PIXI.Point(t[i][0],t[i][1]);else var n=new PIXI.Point(t[i].x,t[i].y);this._points.push(n),n.y<e&&(e=n.y)}this.calculateArea(e)}return this},calculateArea:function(t){for(var e,i,s,n,r=0,o=this._points.length;r<o;r++)e=this._points[r],i=r===o-1?this._points[0]:this._points[r+1],s=(e.y-t+(i.y-t))/2,n=e.x-i.x,this.area+=s*n;return this.area}},n.Polygon.prototype.constructor=n.Polygon,Object.defineProperty(n.Polygon.prototype,"points",{get:function(){return this._points},set:function(t){null!=t?this.setTo(t):this.setTo()}}),PIXI.Polygon=n.Polygon,/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Rectangle=function(t,e,i,s){t=t||0,e=e||0,i=i||0,s=s||0,this.x=t,this.y=e,this.width=i,this.height=s,this.type=n.RECTANGLE},n.Rectangle.prototype={offset:function(t,e){return this.x+=t,this.y+=e,this},offsetPoint:function(t){return this.offset(t.x,t.y)},setTo:function(t,e,i,s){return this.x=t,this.y=e,this.width=i,this.height=s,this},scale:function(t,e){return void 0===e&&(e=t),this.width*=t,this.height*=e,this},centerOn:function(t,e){return this.centerX=t,this.centerY=e,this},floor:function(){this.x=Math.floor(this.x),this.y=Math.floor(this.y)},floorAll:function(){this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.width=Math.floor(this.width),this.height=Math.floor(this.height)},ceil:function(){this.x=Math.ceil(this.x),this.y=Math.ceil(this.y)},ceilAll:function(){this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.width=Math.ceil(this.width),this.height=Math.ceil(this.height)},copyFrom:function(t){return this.setTo(t.x,t.y,t.width,t.height)},copyTo:function(t){return t.x=this.x,t.y=this.y,t.width=this.width,t.height=this.height,t},inflate:function(t,e){return n.Rectangle.inflate(this,t,e)},size:function(t){return n.Rectangle.size(this,t)},resize:function(t,e){return this.width=t,this.height=e,this},clone:function(t){return n.Rectangle.clone(this,t)},contains:function(t,e){return n.Rectangle.contains(this,t,e)},containsRect:function(t){return n.Rectangle.containsRect(t,this)},equals:function(t){return n.Rectangle.equals(this,t)},intersection:function(t,e){return n.Rectangle.intersection(this,t,e)},intersects:function(t){return n.Rectangle.intersects(this,t)},intersectsRaw:function(t,e,i,s,r){return n.Rectangle.intersectsRaw(this,t,e,i,s,r)},union:function(t,e){return n.Rectangle.union(this,t,e)},random:function(t){return void 0===t&&(t=new n.Point),t.x=this.randomX,t.y=this.randomY,t},getPoint:function(t,e){switch(void 0===e&&(e=new n.Point),t){default:case n.TOP_LEFT:return e.set(this.x,this.y);case n.TOP_CENTER:return e.set(this.centerX,this.y);case n.TOP_RIGHT:return e.set(this.right,this.y);case n.LEFT_CENTER:return e.set(this.x,this.centerY);case n.CENTER:return e.set(this.centerX,this.centerY);case n.RIGHT_CENTER:return e.set(this.right,this.centerY);case n.BOTTOM_LEFT:return e.set(this.x,this.bottom);case n.BOTTOM_CENTER:return e.set(this.centerX,this.bottom);case n.BOTTOM_RIGHT:return e.set(this.right,this.bottom)}},toString:function(){return"[{Rectangle (x="+this.x+" y="+this.y+" width="+this.width+" height="+this.height+" empty="+this.empty+")}]"}},Object.defineProperty(n.Rectangle.prototype,"halfWidth",{get:function(){return Math.round(this.width/2)}}),Object.defineProperty(n.Rectangle.prototype,"halfHeight",{get:function(){return Math.round(this.height/2)}}),Object.defineProperty(n.Rectangle.prototype,"bottom",{get:function(){return this.y+this.height},set:function(t){t<=this.y?this.height=0:this.height=t-this.y}}),Object.defineProperty(n.Rectangle.prototype,"bottomLeft",{get:function(){return new n.Point(this.x,this.bottom)},set:function(t){this.x=t.x,this.bottom=t.y}}),Object.defineProperty(n.Rectangle.prototype,"bottomRight",{get:function(){return new n.Point(this.right,this.bottom)},set:function(t){this.right=t.x,this.bottom=t.y}}),Object.defineProperty(n.Rectangle.prototype,"left",{get:function(){return this.x},set:function(t){t>=this.right?this.width=0:this.width=this.right-t,this.x=t}}),Object.defineProperty(n.Rectangle.prototype,"right",{get:function(){return this.x+this.width},set:function(t){t<=this.x?this.width=0:this.width=t-this.x}}),Object.defineProperty(n.Rectangle.prototype,"volume",{get:function(){return this.width*this.height}}),Object.defineProperty(n.Rectangle.prototype,"perimeter",{get:function(){return 2*this.width+2*this.height}}),Object.defineProperty(n.Rectangle.prototype,"centerX",{get:function(){return this.x+this.halfWidth},set:function(t){this.x=t-this.halfWidth}}),Object.defineProperty(n.Rectangle.prototype,"centerY",{get:function(){return this.y+this.halfHeight},set:function(t){this.y=t-this.halfHeight}}),Object.defineProperty(n.Rectangle.prototype,"randomX",{get:function(){return this.x+Math.random()*this.width}}),Object.defineProperty(n.Rectangle.prototype,"randomY",{get:function(){return this.y+Math.random()*this.height}}),Object.defineProperty(n.Rectangle.prototype,"top",{get:function(){return this.y},set:function(t){t>=this.bottom?(this.height=0,this.y=t):this.height=this.bottom-t}}),Object.defineProperty(n.Rectangle.prototype,"topLeft",{get:function(){return new n.Point(this.x,this.y)},set:function(t){this.x=t.x,this.y=t.y}}),Object.defineProperty(n.Rectangle.prototype,"topRight",{get:function(){return new n.Point(this.x+this.width,this.y)},set:function(t){this.right=t.x,this.y=t.y}}),Object.defineProperty(n.Rectangle.prototype,"empty",{get:function(){return!this.width||!this.height},set:function(t){!0===t&&this.setTo(0,0,0,0)}}),n.Rectangle.prototype.constructor=n.Rectangle,n.Rectangle.inflate=function(t,e,i){return t.x-=e,t.width+=2*e,t.y-=i,t.height+=2*i,t},n.Rectangle.inflatePoint=function(t,e){return n.Rectangle.inflate(t,e.x,e.y)},n.Rectangle.size=function(t,e){return void 0===e||null===e?e=new n.Point(t.width,t.height):e.setTo(t.width,t.height),e},n.Rectangle.clone=function(t,e){return void 0===e||null===e?e=new n.Rectangle(t.x,t.y,t.width,t.height):e.setTo(t.x,t.y,t.width,t.height),e},n.Rectangle.contains=function(t,e,i){return!(t.width<=0||t.height<=0)&&(e>=t.x&&e<t.right&&i>=t.y&&i<t.bottom)},n.Rectangle.containsRaw=function(t,e,i,s,n,r){return n>=t&&n<t+i&&r>=e&&r<e+s},n.Rectangle.containsPoint=function(t,e){return n.Rectangle.contains(t,e.x,e.y)},n.Rectangle.containsRect=function(t,e){return!(t.volume>e.volume)&&(t.x>=e.x&&t.y>=e.y&&t.right<e.right&&t.bottom<e.bottom)},n.Rectangle.equals=function(t,e){return t.x===e.x&&t.y===e.y&&t.width===e.width&&t.height===e.height},n.Rectangle.sameDimensions=function(t,e){return t.width===e.width&&t.height===e.height},n.Rectangle.intersection=function(t,e,i){return void 0===i&&(i=new n.Rectangle),n.Rectangle.intersects(t,e)&&(i.x=Math.max(t.x,e.x),i.y=Math.max(t.y,e.y),i.width=Math.min(t.right,e.right)-i.x,i.height=Math.min(t.bottom,e.bottom)-i.y),i},n.Rectangle.intersects=function(t,e){return!(t.width<=0||t.height<=0||e.width<=0||e.height<=0)&&!(t.right<e.x||t.bottom<e.y||t.x>e.right||t.y>e.bottom)},n.Rectangle.intersectsRaw=function(t,e,i,s,n,r){return void 0===r&&(r=0),!(e>t.right+r||i<t.left-r||s>t.bottom+r||n<t.top-r)},n.Rectangle.union=function(t,e,i){return void 0===i&&(i=new n.Rectangle),i.setTo(Math.min(t.x,e.x),Math.min(t.y,e.y),Math.max(t.right,e.right)-Math.min(t.left,e.left),Math.max(t.bottom,e.bottom)-Math.min(t.top,e.top))},n.Rectangle.aabb=function(t,e){void 0===e&&(e=new n.Rectangle);var i=Number.NEGATIVE_INFINITY,s=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY,o=Number.POSITIVE_INFINITY;return t.forEach(function(t){t.x>i&&(i=t.x),t.x<s&&(s=t.x),t.y>r&&(r=t.y),t.y<o&&(o=t.y)}),e.setTo(s,o,i-s,r-o),e},PIXI.Rectangle=n.Rectangle,PIXI.EmptyRectangle=new n.Rectangle(0,0,0,0),/**
* @author Mat Groves http://matgroves.com/
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.RoundedRectangle=function(t,e,i,s,r){void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=0),void 0===s&&(s=0),void 0===r&&(r=20),this.x=t,this.y=e,this.width=i,this.height=s,this.radius=r||20,this.type=n.ROUNDEDRECTANGLE},n.RoundedRectangle.prototype={clone:function(){return new n.RoundedRectangle(this.x,this.y,this.width,this.height,this.radius)},contains:function(t,e){if(this.width<=0||this.height<=0)return!1;var i=this.x;if(t>=i&&t<=i+this.width){var s=this.y;if(e>=s&&e<=s+this.height)return!0}return!1}},n.RoundedRectangle.prototype.constructor=n.RoundedRectangle,PIXI.RoundedRectangle=n.RoundedRectangle,/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Camera=function(t,e,i,s,r,o){this.game=t,this.world=t.world,this.id=0,this.view=new n.Rectangle(i,s,r,o),this.bounds=new n.Rectangle(i,s,r,o),this.deadzone=null,this.visible=!0,this.roundPx=!0,this.atLimit={x:!1,y:!1},this.target=null,this.displayObject=null,this.scale=null,this.totalInView=0,this.lerp=new n.Point(1,1),this.onShakeComplete=new n.Signal,this.onFlashComplete=new n.Signal,this.onFadeComplete=new n.Signal,this.fx=null,this._targetPosition=new n.Point,this._edge=0,this._position=new n.Point,this._shake={intensity:0,duration:0,horizontal:!1,vertical:!1,shakeBounds:!0,x:0,y:0},this._fxDuration=0,this._fxType=0},n.Camera.FOLLOW_LOCKON=0,n.Camera.FOLLOW_PLATFORMER=1,n.Camera.FOLLOW_TOPDOWN=2,n.Camera.FOLLOW_TOPDOWN_TIGHT=3,n.Camera.SHAKE_BOTH=4,n.Camera.SHAKE_HORIZONTAL=5,n.Camera.SHAKE_VERTICAL=6,n.Camera.ENABLE_FX=!0,n.Camera.prototype={boot:function(){this.displayObject=this.game.world,this.scale=this.game.world.scale,this.game.camera=this,n.Graphics&&n.Camera.ENABLE_FX&&(this.fx=new n.Graphics(this.game),this.game.stage.addChild(this.fx))},preUpdate:function(){this.totalInView=0},follow:function(t,e,i,s){void 0===e&&(e=n.Camera.FOLLOW_LOCKON),void 0===i&&(i=1),void 0===s&&(s=1),this.target=t,this.lerp.set(i,s);var r;switch(e){case n.Camera.FOLLOW_PLATFORMER:var o=this.width/8,a=this.height/3;this.deadzone=new n.Rectangle((this.width-o)/2,(this.height-a)/2-.25*a,o,a);break;case n.Camera.FOLLOW_TOPDOWN:r=Math.max(this.width,this.height)/4,this.deadzone=new n.Rectangle((this.width-r)/2,(this.height-r)/2,r,r);break;case n.Camera.FOLLOW_TOPDOWN_TIGHT:r=Math.max(this.width,this.height)/8,this.deadzone=new n.Rectangle((this.width-r)/2,(this.height-r)/2,r,r);break;case n.Camera.FOLLOW_LOCKON:default:this.deadzone=null}},unfollow:function(){this.target=null},focusOn:function(t){this.setPosition(Math.round(t.x-this.view.halfWidth),Math.round(t.y-this.view.halfHeight))},focusOnXY:function(t,e){this.setPosition(Math.round(t-this.view.halfWidth),Math.round(e-this.view.halfHeight))},shake:function(t,e,i,s,r){return void 0===t&&(t=.05),void 0===e&&(e=500),void 0===i&&(i=!0),void 0===s&&(s=n.Camera.SHAKE_BOTH),void 0===r&&(r=!0),!(!i&&this._shake.duration>0)&&(this._shake.intensity=t,this._shake.duration=e,this._shake.shakeBounds=r,this._shake.x=0,this._shake.y=0,this._shake.horizontal=s===n.Camera.SHAKE_BOTH||s===n.Camera.SHAKE_HORIZONTAL,this._shake.vertical=s===n.Camera.SHAKE_BOTH||s===n.Camera.SHAKE_VERTICAL,!0)},flash:function(t,e,i){return void 0===t&&(t=16777215),void 0===e&&(e=500),void 0===i&&(i=!1),!(!this.fx||!i&&this._fxDuration>0)&&(this.fx.clear(),this.fx.beginFill(t),this.fx.drawRect(0,0,this.width,this.height),this.fx.endFill(),this.fx.alpha=1,this._fxDuration=e,this._fxType=0,!0)},fade:function(t,e,i){return void 0===t&&(t=0),void 0===e&&(e=500),void 0===i&&(i=!1),!(!this.fx||!i&&this._fxDuration>0)&&(this.fx.clear(),this.fx.beginFill(t),this.fx.drawRect(0,0,this.width,this.height),this.fx.endFill(),this.fx.alpha=0,this._fxDuration=e,this._fxType=1,!0)},update:function(){this._fxDuration>0&&this.updateFX(),this._shake.duration>0&&this.updateShake(),this.bounds&&this.checkBounds(),this.roundPx&&(this.view.floor(),this._shake.x=Math.floor(this._shake.x),this._shake.y=Math.floor(this._shake.y)),this.displayObject.position.x=-this.view.x,this.displayObject.position.y=-this.view.y},updateFX:function(){0===this._fxType?(this.fx.alpha-=this.game.time.elapsedMS/this._fxDuration,this.fx.alpha<=0&&(this._fxDuration=0,this.fx.alpha=0,this.onFlashComplete.dispatch())):(this.fx.alpha+=this.game.time.elapsedMS/this._fxDuration,this.fx.alpha>=1&&(this._fxDuration=0,this.fx.alpha=1,this.onFadeComplete.dispatch()))},updateShake:function(){this._shake.duration-=this.game.time.elapsedMS,this._shake.duration<=0?(this.onShakeComplete.dispatch(),this._shake.x=0,this._shake.y=0):(this._shake.horizontal&&(this._shake.x=this.game.rnd.frac()*this._shake.intensity*this.view.width*2-this._shake.intensity*this.view.width),this._shake.vertical&&(this._shake.y=this.game.rnd.frac()*this._shake.intensity*this.view.height*2-this._shake.intensity*this.view.height))},updateTarget:function(){this._targetPosition.x=this.view.x+this.target.worldPosition.x,this._targetPosition.y=this.view.y+this.target.worldPosition.y,this.deadzone?(this._edge=this._targetPosition.x-this.view.x,this._edge<this.deadzone.left?this.view.x=this.game.math.linear(this.view.x,this._targetPosition.x-this.deadzone.left,this.lerp.x):this._edge>this.deadzone.right&&(this.view.x=this.game.math.linear(this.view.x,this._targetPosition.x-this.deadzone.right,this.lerp.x)),this._edge=this._targetPosition.y-this.view.y,this._edge<this.deadzone.top?this.view.y=this.game.math.linear(this.view.y,this._targetPosition.y-this.deadzone.top,this.lerp.y):this._edge>this.deadzone.bottom&&(this.view.y=this.game.math.linear(this.view.y,this._targetPosition.y-this.deadzone.bottom,this.lerp.y))):(this.view.x=this.game.math.linear(this.view.x,this._targetPosition.x-this.view.halfWidth,this.lerp.x),this.view.y=this.game.math.linear(this.view.y,this._targetPosition.y-this.view.halfHeight,this.lerp.y)),this.bounds&&this.checkBounds(),this.roundPx&&this.view.floor(),this.displayObject.position.x=-this.view.x,this.displayObject.position.y=-this.view.y},setBoundsToWorld:function(){this.bounds&&this.bounds.copyFrom(this.game.world.bounds)},checkBounds:function(){this.atLimit.x=!1,this.atLimit.y=!1;var t=this.view.x+this._shake.x,e=this.view.right+this._shake.x,i=this.view.y+this._shake.y,s=this.view.bottom+this._shake.y;t<=this.bounds.x*this.scale.x&&(this.atLimit.x=!0,this.view.x=this.bounds.x*this.scale.x,this._shake.shakeBounds||(this._shake.x=0)),e>=this.bounds.right*this.scale.x&&(this.atLimit.x=!0,this.view.x=this.bounds.right*this.scale.x-this.width,this._shake.shakeBounds||(this._shake.x=0)),i<=this.bounds.top*this.scale.y&&(this.atLimit.y=!0,this.view.y=this.bounds.top*this.scale.y,this._shake.shakeBounds||(this._shake.y=0)),s>=this.bounds.bottom*this.scale.y&&(this.atLimit.y=!0,this.view.y=this.bounds.bottom*this.scale.y-this.height,this._shake.shakeBounds||(this._shake.y=0))},setPosition:function(t,e){this.view.x=t,this.view.y=e,this.bounds&&this.checkBounds()},setSize:function(t,e){this.view.width=t,this.view.height=e},reset:function(){this.target=null,this.view.x=0,this.view.y=0,this._shake.duration=0,this.resetFX()},resetFX:function(){this.fx.clear(),this.fx.alpha=0,this._fxDuration=0}},n.Camera.prototype.constructor=n.Camera,Object.defineProperty(n.Camera.prototype,"x",{get:function(){return this.view.x},set:function(t){this.view.x=t,this.bounds&&this.checkBounds()}}),Object.defineProperty(n.Camera.prototype,"y",{get:function(){return this.view.y},set:function(t){this.view.y=t,this.bounds&&this.checkBounds()}}),Object.defineProperty(n.Camera.prototype,"position",{get:function(){return this._position.set(this.view.x,this.view.y),this._position},set:function(t){void 0!==t.x&&(this.view.x=t.x),void 0!==t.y&&(this.view.y=t.y),this.bounds&&this.checkBounds()}}),Object.defineProperty(n.Camera.prototype,"width",{get:function(){return this.view.width},set:function(t){this.view.width=t}}),Object.defineProperty(n.Camera.prototype,"height",{get:function(){return this.view.height},set:function(t){this.view.height=t}}),Object.defineProperty(n.Camera.prototype,"shakeIntensity",{get:function(){return this._shake.intensity},set:function(t){this._shake.intensity=t}}),/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.State=function(){this.game=null,this.key="",this.add=null,this.make=null,this.camera=null,this.cache=null,this.input=null,this.load=null,this.math=null,this.sound=null,this.scale=null,this.stage=null,this.state=null,this.time=null,this.tweens=null,this.world=null,this.particles=null,this.physics=null,this.rnd=null},n.State.prototype={init:function(){},preload:function(){},loadUpdate:function(){},loadRender:function(){},create:function(){},update:function(){},preRender:function(){},render:function(){},resize:function(){},paused:function(){},resumed:function(){},pauseUpdate:function(){},shutdown:function(){}},n.State.prototype.constructor=n.State,/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.StateManager=function(t,e){this.game=t,this.states={},this._pendingState=null,void 0!==e&&null!==e&&(this._pendingState=e),this._clearWorld=!1,this._clearCache=!1,this._created=!1,this._args=[],this.current="",this.onStateChange=new n.Signal,this.onInitCallback=null,this.onPreloadCallback=null,this.onCreateCallback=null,this.onUpdateCallback=null,this.onRenderCallback=null,this.onResizeCallback=null,this.onPreRenderCallback=null,this.onLoadUpdateCallback=null,this.onLoadRenderCallback=null,this.onPausedCallback=null,this.onResumedCallback=null,this.onPauseUpdateCallback=null,this.onShutDownCallback=null},n.StateManager.prototype={boot:function(){this.game.onPause.add(this.pause,this),this.game.onResume.add(this.resume,this),null!==this._pendingState&&"string"!=typeof this._pendingState&&this.add("default",this._pendingState,!0)},add:function(t,e,i){void 0===i&&(i=!1);var s;return e instanceof n.State?s=e:"object"==typeof e?(s=e,s.game=this.game):"function"==typeof e&&(s=new e(this.game)),this.states[t]=s,i&&(this.game.isBooted?this.start(t):this._pendingState=t),s},remove:function(t){this.current===t&&(this.callbackContext=null,this.onInitCallback=null,this.onShutDownCallback=null,this.onPreloadCallback=null,this.onLoadRenderCallback=null,this.onLoadUpdateCallback=null,this.onCreateCallback=null,this.onUpdateCallback=null,this.onPreRenderCallback=null,this.onRenderCallback=null,this.onResizeCallback=null,this.onPausedCallback=null,this.onResumedCallback=null,this.onPauseUpdateCallback=null),delete this.states[t]},start:function(t,e,i){void 0===e&&(e=!0),void 0===i&&(i=!1),this.checkState(t)&&(this._pendingState=t,this._clearWorld=e,this._clearCache=i,arguments.length>3&&(this._args=Array.prototype.splice.call(arguments,3)))},restart:function(t,e){void 0===t&&(t=!0),void 0===e&&(e=!1),this._pendingState=this.current,this._clearWorld=t,this._clearCache=e,arguments.length>2&&(this._args=Array.prototype.slice.call(arguments,2))},dummy:function(){},preUpdate:function(){if(this._pendingState&&this.game.isBooted){var t=this.current;if(this.clearCurrentState(),this.setCurrentState(this._pendingState),this.onStateChange.dispatch(this.current,t),this.current!==this._pendingState)return;this._pendingState=null,this.onPreloadCallback?(this.game.load.reset(!0),this.onPreloadCallback.call(this.callbackContext,this.game),0===this.game.load.totalQueuedFiles()&&0===this.game.load.totalQueuedPacks()?this.loadComplete():this.game.load.start()):this.loadComplete()}},clearCurrentState:function(){this.current&&(this.onShutDownCallback&&this.onShutDownCallback.call(this.callbackContext,this.game),this.game.tweens.removeAll(),this.game.camera.reset(),this.game.input.reset(!0),this.game.physics.clear(),this.game.time.removeAll(),this.game.scale.reset(this._clearWorld),this.game.debug&&this.game.debug.reset(),this._clearWorld&&(this.game.world.shutdown(),this._clearCache&&this.game.cache.destroy()))},checkState:function(t){return this.states[t]?!!(this.states[t].preload||this.states[t].create||this.states[t].update||this.states[t].render)||(console.warn("Invalid Phaser State object given. Must contain at least a one of the required functions: preload, create, update or render"),!1):(console.warn("Phaser.StateManager - No state found with the key: "+t),!1)},link:function(t){this.states[t].game=this.game,this.states[t].add=this.game.add,this.states[t].make=this.game.make,this.states[t].camera=this.game.camera,this.states[t].cache=this.game.cache,this.states[t].input=this.game.input,this.states[t].load=this.game.load,this.states[t].math=this.game.math,this.states[t].sound=this.game.sound,this.states[t].scale=this.game.scale,this.states[t].state=this,this.states[t].stage=this.game.stage,this.states[t].time=this.game.time,this.states[t].tweens=this.game.tweens,this.states[t].world=this.game.world,this.states[t].particles=this.game.particles,this.states[t].rnd=this.game.rnd,this.states[t].physics=this.game.physics,this.states[t].key=t},unlink:function(t){this.states[t]&&(this.states[t].game=null,this.states[t].add=null,this.states[t].make=null,this.states[t].camera=null,this.states[t].cache=null,this.states[t].input=null,this.states[t].load=null,this.states[t].math=null,this.states[t].sound=null,this.states[t].scale=null,this.states[t].state=null,this.states[t].stage=null,this.states[t].time=null,this.states[t].tweens=null,this.states[t].world=null,this.states[t].particles=null,this.states[t].rnd=null,this.states[t].physics=null)},setCurrentState:function(t){this.callbackContext=this.states[t],this.link(t),this.onInitCallback=this.states[t].init||this.dummy,this.onPreloadCallback=this.states[t].preload||null,this.onLoadRenderCallback=this.states[t].loadRender||null,this.onLoadUpdateCallback=this.states[t].loadUpdate||null,this.onCreateCallback=this.states[t].create||null,this.onUpdateCallback=this.states[t].update||null,this.onPreRenderCallback=this.states[t].preRender||null,this.onRenderCallback=this.states[t].render||null,this.onResizeCallback=this.states[t].resize||null,this.onPausedCallback=this.states[t].paused||null,this.onResumedCallback=this.states[t].resumed||null,this.onPauseUpdateCallback=this.states[t].pauseUpdate||null,this.onShutDownCallback=this.states[t].shutdown||this.dummy,""!==this.current&&this.game.physics.reset(),this.current=t,this._created=!1,this.onInitCallback.apply(this.callbackContext,this._args),t===this._pendingState&&(this._args=[]),this.game._kickstart=!0},getCurrentState:function(){return this.states[this.current]},loadComplete:function(){!1===this._created&&this.onLoadUpdateCallback&&this.onLoadUpdateCallback.call(this.callbackContext,this.game),!1===this._created&&this.onCreateCallback?(this._created=!0,this.onCreateCallback.call(this.callbackContext,this.game)):this._created=!0},pause:function(){this._created&&this.onPausedCallback&&this.onPausedCallback.call(this.callbackContext,this.game)},resume:function(){this._created&&this.onResumedCallback&&this.onResumedCallback.call(this.callbackContext,this.game)},update:function(){this._created?this.onUpdateCallback&&this.onUpdateCallback.call(this.callbackContext,this.game):this.onLoadUpdateCallback&&this.onLoadUpdateCallback.call(this.callbackContext,this.game)},pauseUpdate:function(){this._created?this.onPauseUpdateCallback&&this.onPauseUpdateCallback.call(this.callbackContext,this.game):this.onLoadUpdateCallback&&this.onLoadUpdateCallback.call(this.callbackContext,this.game)},preRender:function(t){this._created&&this.onPreRenderCallback&&this.onPreRenderCallback.call(this.callbackContext,this.game,t)},resize:function(t,e){this.onResizeCallback&&this.onResizeCallback.call(this.callbackContext,t,e)},render:function(){this._created?this.onRenderCallback&&(this.game.renderType===n.CANVAS?(this.game.context.save(),this.game.context.setTransform(1,0,0,1,0,0),this.onRenderCallback.call(this.callbackContext,this.game),this.game.context.restore()):this.onRenderCallback.call(this.callbackContext,this.game)):this.onLoadRenderCallback&&this.onLoadRenderCallback.call(this.callbackContext,this.game)},destroy:function(){this._clearWorld=!0,this._clearCache=!0,this.clearCurrentState(),this.callbackContext=null,this.onInitCallback=null,this.onShutDownCallback=null,this.onPreloadCallback=null,this.onLoadRenderCallback=null,this.onLoadUpdateCallback=null,this.onCreateCallback=null,this.onUpdateCallback=null,this.onRenderCallback=null,this.onPausedCallback=null,this.onResumedCallback=null,this.onPauseUpdateCallback=null,this.game=null,this.states={},this._pendingState=null,this.current=""}},n.StateManager.prototype.constructor=n.StateManager,Object.defineProperty(n.StateManager.prototype,"created",{get:function(){return this._created}}),/**
* @author Miller Medeiros http://millermedeiros.github.com/js-signals/
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Signal=function(){},n.Signal.prototype={_bindings:null,_prevParams:null,memorize:!1,_shouldPropagate:!0,active:!0,_boundDispatch:!1,validateListener:function(t,e){if("function"!=typeof t)throw new Error("Phaser.Signal: listener is a required param of {fn}() and should be a Function.".replace("{fn}",e))},_registerListener:function(t,e,i,s,r){var o,a=this._indexOfListener(t,i);if(-1!==a){if(o=this._bindings[a],o.isOnce()!==e)throw new Error("You cannot add"+(e?"":"Once")+"() then add"+(e?"Once":"")+"() the same listener without removing the relationship first.")}else o=new n.SignalBinding(this,t,e,i,s,r),this._addBinding(o);return this.memorize&&this._prevParams&&o.execute(this._prevParams),o},_addBinding:function(t){this._bindings||(this._bindings=[]);var e=this._bindings.length;do{e--}while(this._bindings[e]&&t._priority<=this._bindings[e]._priority);this._bindings.splice(e+1,0,t)},_indexOfListener:function(t,e){if(!this._bindings)return-1;void 0===e&&(e=null);for(var i,s=this._bindings.length;s--;)if(i=this._bindings[s],i._listener===t&&i.context===e)return s;return-1},has:function(t,e){return-1!==this._indexOfListener(t,e)},add:function(t,e,i){this.validateListener(t,"add");var s=[];if(arguments.length>3)for(var n=3;n<arguments.length;n++)s.push(arguments[n]);return this._registerListener(t,!1,e,i,s)},addOnce:function(t,e,i){this.validateListener(t,"addOnce");var s=[];if(arguments.length>3)for(var n=3;n<arguments.length;n++)s.push(arguments[n]);return this._registerListener(t,!0,e,i,s)},remove:function(t,e){this.validateListener(t,"remove");var i=this._indexOfListener(t,e);return-1!==i&&(this._bindings[i]._destroy(),this._bindings.splice(i,1)),t},removeAll:function(t){if(void 0===t&&(t=null),this._bindings){for(var e=this._bindings.length;e--;)t?this._bindings[e].context===t&&(this._bindings[e]._destroy(),this._bindings.splice(e,1)):this._bindings[e]._destroy();t||(this._bindings.length=0)}},getNumListeners:function(){return this._bindings?this._bindings.length:0},halt:function(){this._shouldPropagate=!1},dispatch:function(){if(this.active&&this._bindings){var t,e=Array.prototype.slice.call(arguments),i=this._bindings.length;if(this.memorize&&(this._prevParams=e),i){t=this._bindings.slice(),this._shouldPropagate=!0;do{i--}while(t[i]&&this._shouldPropagate&&!1!==t[i].execute(e))}}},forget:function(){this._prevParams&&(this._prevParams=null)},dispose:function(){this.removeAll(),this._bindings=null,this._prevParams&&(this._prevParams=null)},toString:function(){return"[Phaser.Signal active:"+this.active+" numListeners:"+this.getNumListeners()+"]"}},Object.defineProperty(n.Signal.prototype,"boundDispatch",{get:function(){var t=this;return this._boundDispatch||(this._boundDispatch=function(){return t.dispatch.apply(t,arguments)})}}),n.Signal.prototype.constructor=n.Signal,/**
* @author Miller Medeiros http://millermedeiros.github.com/js-signals/
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.SignalBinding=function(t,e,i,s,n,r){this._listener=e,i&&(this._isOnce=!0),null!=s&&(this.context=s),this._signal=t,n&&(this._priority=n),r&&r.length&&(this._args=r)},n.SignalBinding.prototype={context:null,_isOnce:!1,_priority:0,_args:null,callCount:0,active:!0,params:null,execute:function(t){var e,i;return this.active&&this._listener&&(i=this.params?this.params.concat(t):t,this._args&&(i=i.concat(this._args)),e=this._listener.apply(this.context,i),this.callCount++,this._isOnce&&this.detach()),e},detach:function(){return this.isBound()?this._signal.remove(this._listener,this.context):null},isBound:function(){return!!this._signal&&!!this._listener},isOnce:function(){return this._isOnce},getListener:function(){return this._listener},getSignal:function(){return this._signal},_destroy:function(){delete this._signal,delete this._listener,delete this.context},toString:function(){return"[Phaser.SignalBinding isOnce:"+this._isOnce+", isBound:"+this.isBound()+", active:"+this.active+"]"}},n.SignalBinding.prototype.constructor=n.SignalBinding,/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Filter=function(t,e,i){this.game=t,this.type=n.WEBGL_FILTER,this.passes=[this],this.shaders=[],this.dirty=!0,this.padding=0,this.prevPoint=new n.Point;var s=new Date;if(this.uniforms={resolution:{type:"2f",value:{x:256,y:256}},time:{type:"1f",value:0},mouse:{type:"2f",value:{x:0,y:0}},date:{type:"4fv",value:[s.getFullYear(),s.getMonth(),s.getDate(),60*s.getHours()*60+60*s.getMinutes()+s.getSeconds()]},sampleRate:{type:"1f",value:44100},iChannel0:{type:"sampler2D",value:null,textureData:{repeat:!0}},iChannel1:{type:"sampler2D",value:null,textureData:{repeat:!0}},iChannel2:{type:"sampler2D",value:null,textureData:{repeat:!0}},iChannel3:{type:"sampler2D",value:null,textureData:{repeat:!0}}},e)for(var r in e)this.uniforms[r]=e[r];this.fragmentSrc=i||""},n.Filter.prototype={init:function(){},setResolution:function(t,e){this.uniforms.resolution.value.x=t,this.uniforms.resolution.value.y=e},update:function(t){if(void 0!==t){var e=t.x/this.game.width,i=1-t.y/this.game.height;e===this.prevPoint.x&&i===this.prevPoint.y||(this.uniforms.mouse.value.x=e.toFixed(2),this.uniforms.mouse.value.y=i.toFixed(2),this.prevPoint.set(e,i))}this.uniforms.time.value=this.game.time.totalElapsedSeconds()},addToWorld:function(t,e,i,s,n,r){void 0===n&&(n=0),void 0===r&&(r=0),void 0!==i&&null!==i?this.width=i:i=this.width,void 0!==s&&null!==s?this.height=s:s=this.height;var o=this.game.add.image(t,e,"__default");return o.width=i,o.height=s,o.anchor.set(n,r),o.filters=[this],o},destroy:function(){this.game=null}},n.Filter.prototype.constructor=n.Filter,Object.defineProperty(n.Filter.prototype,"width",{get:function(){return this.uniforms.resolution.value.x},set:function(t){this.uniforms.resolution.value.x=t}}),Object.defineProperty(n.Filter.prototype,"height",{get:function(){return this.uniforms.resolution.value.y},set:function(t){this.uniforms.resolution.value.y=t}}),/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Plugin=function(t,e){void 0===e&&(e=null),this.game=t,this.parent=e,this.active=!1,this.visible=!1,this.hasPreUpdate=!1,this.hasUpdate=!1,this.hasPostUpdate=!1,this.hasRender=!1,this.hasPostRender=!1},n.Plugin.prototype={preUpdate:function(){},update:function(){},render:function(){},postRender:function(){},destroy:function(){this.game=null,this.parent=null,this.active=!1,this.visible=!1}},n.Plugin.prototype.constructor=n.Plugin,/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.PluginManager=function(t){this.game=t,this.plugins=[],this._len=0,this._i=0},n.PluginManager.prototype={add:function(t){var e=Array.prototype.slice.call(arguments,1),i=!1;return"function"==typeof t?t=new t(this.game,this):(t.game=this.game,t.parent=this),"function"==typeof t.preUpdate&&(t.hasPreUpdate=!0,i=!0),"function"==typeof t.update&&(t.hasUpdate=!0,i=!0),"function"==typeof t.postUpdate&&(t.hasPostUpdate=!0,i=!0),"function"==typeof t.render&&(t.hasRender=!0,i=!0),"function"==typeof t.postRender&&(t.hasPostRender=!0,i=!0),i?((t.hasPreUpdate||t.hasUpdate||t.hasPostUpdate)&&(t.active=!0),(t.hasRender||t.hasPostRender)&&(t.visible=!0),this._len=this.plugins.push(t),"function"==typeof t.init&&t.init.apply(t,e),t):null},remove:function(t,e){for(void 0===e&&(e=!0),this._i=this._len;this._i--;)if(this.plugins[this._i]===t)return e&&t.destroy(),this.plugins.splice(this._i,1),void this._len--},removeAll:function(){for(this._i=this._len;this._i--;)this.plugins[this._i].destroy();this.plugins.length=0,this._len=0},preUpdate:function(){for(this._i=this._len;this._i--;)this.plugins[this._i].active&&this.plugins[this._i].hasPreUpdate&&this.plugins[this._i].preUpdate()},update:function(){for(this._i=this._len;this._i--;)this.plugins[this._i].active&&this.plugins[this._i].hasUpdate&&this.plugins[this._i].update()},postUpdate:function(){for(this._i=this._len;this._i--;)this.plugins[this._i].active&&this.plugins[this._i].hasPostUpdate&&this.plugins[this._i].postUpdate()},render:function(){for(this._i=this._len;this._i--;)this.plugins[this._i].visible&&this.plugins[this._i].hasRender&&this.plugins[this._i].render()},postRender:function(){for(this._i=this._len;this._i--;)this.plugins[this._i].visible&&this.plugins[this._i].hasPostRender&&this.plugins[this._i].postRender()},destroy:function(){this.removeAll(),this.game=null}},n.PluginManager.prototype.constructor=n.PluginManager,/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Stage=function(t){this.game=t,PIXI.DisplayObjectContainer.call(this),this.name="_stage_root",this.disableVisibilityChange=!1,this.exists=!0,this.worldTransform=new PIXI.Matrix,this.stage=this,this.currentRenderOrderID=0,this._hiddenVar="hidden",this._onChange=null,this._bgColor={r:0,g:0,b:0,a:0,color:0,rgba:"#000000"},this.game.transparent||(this._bgColor.a=1),t.config&&this.parseConfig(t.config)},n.Stage.prototype=Object.create(PIXI.DisplayObjectContainer.prototype),n.Stage.prototype.constructor=n.Stage,n.Stage.prototype.parseConfig=function(t){t.disableVisibilityChange&&(this.disableVisibilityChange=t.disableVisibilityChange),t.backgroundColor&&this.setBackgroundColor(t.backgroundColor)},n.Stage.prototype.boot=function(){n.DOM.getOffset(this.game.canvas,this.offset),n.Canvas.setUserSelect(this.game.canvas,"none"),n.Canvas.setTouchAction(this.game.canvas,"none"),this.checkVisibility()},n.Stage.prototype.preUpdate=function(){this.currentRenderOrderID=0;for(var t=0;t<this.children.length;t++)this.children[t].preUpdate()},n.Stage.prototype.update=function(){for(var t=this.children.length;t--;)this.children[t].update()},n.Stage.prototype.postUpdate=function(){this.game.camera.update(),this.game.camera.target&&(this.game.camera.target.postUpdate(),this.updateTransform(),this.game.camera.updateTarget());for(var t=0;t<this.children.length;t++)this.children[t].postUpdate();this.updateTransform()},n.Stage.prototype.updateTransform=function(){this.worldAlpha=1;for(var t=0;t<this.children.length;t++)this.children[t].updateTransform()},n.Stage.prototype.checkVisibility=function(){void 0!==document.hidden?this._hiddenVar="visibilitychange":void 0!==document.webkitHidden?this._hiddenVar="webkitvisibilitychange":void 0!==document.mozHidden?this._hiddenVar="mozvisibilitychange":void 0!==document.msHidden?this._hiddenVar="msvisibilitychange":this._hiddenVar=null;var t=this;this._onChange=function(e){return t.visibilityChange(e)},this._hiddenVar&&document.addEventListener(this._hiddenVar,this._onChange,!1),window.onblur=this._onChange,window.onfocus=this._onChange,window.onpagehide=this._onChange,window.onpageshow=this._onChange,this.game.device.cocoonJSApp&&(CocoonJS.App.onSuspended.addEventListener(function(){n.Stage.prototype.visibilityChange.call(t,{type:"pause"})}),CocoonJS.App.onActivated.addEventListener(function(){n.Stage.prototype.visibilityChange.call(t,{type:"resume"})}))},n.Stage.prototype.visibilityChange=function(t){if("pagehide"===t.type||"blur"===t.type||"pageshow"===t.type||"focus"===t.type)return void("pagehide"===t.type||"blur"===t.type?this.game.focusLoss(t):"pageshow"!==t.type&&"focus"!==t.type||this.game.focusGain(t));this.disableVisibilityChange||(document.hidden||document.mozHidden||document.msHidden||document.webkitHidden||"pause"===t.type?this.game.gamePaused(t):this.game.gameResumed(t))},n.Stage.prototype.setBackgroundColor=function(t){this.game.transparent||(n.Color.valueToColor(t,this._bgColor),n.Color.updateColor(this._bgColor),this._bgColor.r/=255,this._bgColor.g/=255,this._bgColor.b/=255,this._bgColor.a=1)},n.Stage.prototype.destroy=function(){this._hiddenVar&&document.removeEventListener(this._hiddenVar,this._onChange,!1),window.onpagehide=null,window.onpageshow=null,window.onblur=null,window.onfocus=null},Object.defineProperty(n.Stage.prototype,"backgroundColor",{get:function(){return this._bgColor.color},set:function(t){this.setBackgroundColor(t)}}),Object.defineProperty(n.Stage.prototype,"smoothed",{get:function(){return PIXI.scaleModes.DEFAULT===PIXI.scaleModes.LINEAR},set:function(t){PIXI.scaleModes.DEFAULT=t?PIXI.scaleModes.LINEAR:PIXI.scaleModes.NEAREST}}),/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Group=function(t,e,i,s,r,o){void 0===s&&(s=!1),void 0===r&&(r=!1),void 0===o&&(o=n.Physics.ARCADE),this.game=t,void 0===e&&(e=t.world),this.name=i||"group",this.z=0,PIXI.DisplayObjectContainer.call(this),s?(this.game.stage.addChild(this),this.z=this.game.stage.children.length):e&&(e.addChild(this),this.z=e.children.length),this.type=n.GROUP,this.physicsType=n.GROUP,this.alive=!0,this.exists=!0,this.ignoreDestroy=!1,this.pendingDestroy=!1,this.classType=n.Sprite,this.cursor=null,this.inputEnableChildren=!1,this.onChildInputDown=new n.Signal,this.onChildInputUp=new n.Signal,this.onChildInputOver=new n.Signal,this.onChildInputOut=new n.Signal,this.enableBody=r,this.enableBodyDebug=!1,this.physicsBodyType=o,this.physicsSortDirection=null,this.onDestroy=new n.Signal,this.cursorIndex=0,this.fixedToCamera=!1,this.cameraOffset=new n.Point,this.hash=[],this._sortProperty="z"},n.Group.prototype=Object.create(PIXI.DisplayObjectContainer.prototype),n.Group.prototype.constructor=n.Group,n.Group.RETURN_NONE=0,n.Group.RETURN_TOTAL=1,n.Group.RETURN_CHILD=2,n.Group.RETURN_ALL=3,n.Group.SORT_ASCENDING=-1,n.Group.SORT_DESCENDING=1,n.Group.prototype.add=function(t,e,i){return void 0===e&&(e=!1),t.parent===this?t:(t.body&&t.parent&&t.parent.hash&&t.parent.removeFromHash(t),void 0===i?(t.z=this.children.length,this.addChild(t)):(this.addChildAt(t,i),this.updateZ()),this.enableBody&&t.hasOwnProperty("body")&&null===t.body?this.game.physics.enable(t,this.physicsBodyType):t.body&&this.addToHash(t),!this.inputEnableChildren||t.input&&!t.inputEnabled||(t.inputEnabled=!0),!e&&t.events&&t.events.onAddedToGroup$dispatch(t,this),null===this.cursor&&(this.cursor=t),t)},n.Group.prototype.addAt=function(t,e,i){this.add(t,i,e)},n.Group.prototype.addToHash=function(t){if(t.parent===this){if(-1===this.hash.indexOf(t))return this.hash.push(t),!0}return!1},n.Group.prototype.removeFromHash=function(t){if(t){var e=this.hash.indexOf(t);if(-1!==e)return this.hash.splice(e,1),!0}return!1},n.Group.prototype.addMultiple=function(t,e){if(t instanceof n.Group)t.moveAll(this,e);else if(Array.isArray(t))for(var i=0;i<t.length;i++)this.add(t[i],e);return t},n.Group.prototype.getAt=function(t){return t<0||t>=this.children.length?-1:this.getChildAt(t)},n.Group.prototype.create=function(t,e,i,s,n,r){void 0===n&&(n=!0);var o=new this.classType(this.game,t,e,i,s);return o.exists=n,o.visible=n,o.alive=n,this.add(o,!1,r)},n.Group.prototype.createMultiple=function(t,e,i,s){void 0===i&&(i=0),void 0===s&&(s=!1),Array.isArray(e)||(e=[e]),Array.isArray(i)||(i=[i]);var n=this,r=[];return e.forEach(function(e){i.forEach(function(i){for(var o=0;o<t;o++)r.push(n.create(0,0,e,i,s))})}),r},n.Group.prototype.updateZ=function(){for(var t=this.children.length;t--;)this.children[t].z=t},n.Group.prototype.align=function(t,e,i,s,r,o){if(void 0===r&&(r=n.TOP_LEFT),void 0===o&&(o=0),0===this.children.length||o>this.children.length||-1===t&&-1===e)return!1;for(var a=new n.Rectangle(0,0,i,s),h=t*i,l=e*s,c=o;c<this.children.length;c++){var u=this.children[c];if(u.alignIn)if(u.alignIn(a,r),-1===t)a.y+=s,a.y===l&&(a.x+=i,a.y=0);else if(-1===e)a.x+=i,a.x===h&&(a.x=0,a.y+=s);else if(a.x+=i,a.x===h&&(a.x=0,a.y+=s,a.y===l))return!0}return!0};n.Group.prototype.resetCursor=function(t){if(void 0===t&&(t=0),t>this.children.length-1&&(t=0),this.cursor)return this.cursorIndex=t,this.cursor=this.children[this.cursorIndex],this.cursor},n.Group.prototype.next=function(){if(this.cursor)return this.cursorIndex>=this.children.length-1?this.cursorIndex=0:this.cursorIndex++,this.cursor=this.children[this.cursorIndex],this.cursor},n.Group.prototype.previous=function(){if(this.cursor)return 0===this.cursorIndex?this.cursorIndex=this.children.length-1:this.cursorIndex--,this.cursor=this.children[this.cursorIndex],this.cursor},n.Group.prototype.swap=function(t,e){this.swapChildren(t,e),this.updateZ()},n.Group.prototype.bringToTop=function(t){return t.parent===this&&this.getIndex(t)<this.children.length&&(this.remove(t,!1,!0),this.add(t,!0)),t},n.Group.prototype.sendToBack=function(t){return t.parent===this&&this.getIndex(t)>0&&(this.remove(t,!1,!0),this.addAt(t,0,!0)),t},n.Group.prototype.moveUp=function(t){if(t.parent===this&&this.getIndex(t)<this.children.length-1){var e=this.getIndex(t),i=this.getAt(e+1);i&&this.swap(t,i)}return t},n.Group.prototype.moveDown=function(t){if(t.parent===this&&this.getIndex(t)>0){var e=this.getIndex(t),i=this.getAt(e-1);i&&this.swap(t,i)}return t},n.Group.prototype.xy=function(t,e,i){if(t<0||t>this.children.length)return-1;this.getChildAt(t).x=e,this.getChildAt(t).y=i},n.Group.prototype.reverse=function(){this.children.reverse(),this.updateZ()},n.Group.prototype.getIndex=function(t){return this.children.indexOf(t)},n.Group.prototype.getByName=function(t){for(var e=0;e<this.children.length;e++)if(this.children[e].name===t)return this.children[e];return null},n.Group.prototype.replace=function(t,e){var i=this.getIndex(t);if(-1!==i)return e.parent&&(e.parent instanceof n.Group?e.parent.remove(e):e.parent.removeChild(e)),this.remove(t),this.addAt(e,i),t},n.Group.prototype.hasProperty=function(t,e){var i=e.length;return 1===i&&e[0]in t||(2===i&&e[0]in t&&e[1]in t[e[0]]||(3===i&&e[0]in t&&e[1]in t[e[0]]&&e[2]in t[e[0]][e[1]]||4===i&&e[0]in t&&e[1]in t[e[0]]&&e[2]in t[e[0]][e[1]]&&e[3]in t[e[0]][e[1]][e[2]]))},n.Group.prototype.setProperty=function(t,e,i,s,n){if(void 0===n&&(n=!1),s=s||0,!this.hasProperty(t,e)&&(!n||s>0))return!1;var r=e.length;return 1===r?0===s?t[e[0]]=i:1===s?t[e[0]]+=i:2===s?t[e[0]]-=i:3===s?t[e[0]]*=i:4===s&&(t[e[0]]/=i):2===r?0===s?t[e[0]][e[1]]=i:1===s?t[e[0]][e[1]]+=i:2===s?t[e[0]][e[1]]-=i:3===s?t[e[0]][e[1]]*=i:4===s&&(t[e[0]][e[1]]/=i):3===r?0===s?t[e[0]][e[1]][e[2]]=i:1===s?t[e[0]][e[1]][e[2]]+=i:2===s?t[e[0]][e[1]][e[2]]-=i:3===s?t[e[0]][e[1]][e[2]]*=i:4===s&&(t[e[0]][e[1]][e[2]]/=i):4===r&&(0===s?t[e[0]][e[1]][e[2]][e[3]]=i:1===s?t[e[0]][e[1]][e[2]][e[3]]+=i:2===s?t[e[0]][e[1]][e[2]][e[3]]-=i:3===s?t[e[0]][e[1]][e[2]][e[3]]*=i:4===s&&(t[e[0]][e[1]][e[2]][e[3]]/=i)),!0},n.Group.prototype.checkProperty=function(t,e,i,s){return void 0===s&&(s=!1),!(!n.Utils.getProperty(t,e)&&s)&&n.Utils.getProperty(t,e)===i},n.Group.prototype.set=function(t,e,i,s,n,r,o){if(void 0===o&&(o=!1),e=e.split("."),void 0===s&&(s=!1),void 0===n&&(n=!1),(!1===s||s&&t.alive)&&(!1===n||n&&t.visible))return this.setProperty(t,e,i,r,o)},n.Group.prototype.setAll=function(t,e,i,s,n,r){void 0===i&&(i=!1),void 0===s&&(s=!1),void 0===r&&(r=!1),t=t.split("."),n=n||0;for(var o=0;o<this.children.length;o++)(!i||i&&this.children[o].alive)&&(!s||s&&this.children[o].visible)&&this.setProperty(this.children[o],t,e,n,r)},n.Group.prototype.setAllChildren=function(t,e,i,s,r,o){void 0===i&&(i=!1),void 0===s&&(s=!1),void 0===o&&(o=!1),r=r||0;for(var a=0;a<this.children.length;a++)(!i||i&&this.children[a].alive)&&(!s||s&&this.children[a].visible)&&(this.children[a]instanceof n.Group?this.children[a].setAllChildren(t,e,i,s,r,o):this.setProperty(this.children[a],t.split("."),e,r,o))},n.Group.prototype.checkAll=function(t,e,i,s,n){void 0===i&&(i=!1),void 0===s&&(s=!1),void 0===n&&(n=!1);for(var r=0;r<this.children.length;r++)if((!i||i&&this.children[r].alive)&&(!s||s&&this.children[r].visible)&&!this.checkProperty(this.children[r],t,e,n))return!1;return!0},n.Group.prototype.addAll=function(t,e,i,s){this.setAll(t,e,i,s,1)},n.Group.prototype.subAll=function(t,e,i,s){this.setAll(t,e,i,s,2)},n.Group.prototype.multiplyAll=function(t,e,i,s){this.setAll(t,e,i,s,3)},n.Group.prototype.divideAll=function(t,e,i,s){this.setAll(t,e,i,s,4)},n.Group.prototype.callAllExists=function(t,e){var i;if(arguments.length>2){i=[];for(var s=2;s<arguments.length;s++)i.push(arguments[s])}for(var s=0;s<this.children.length;s++)this.children[s].exists===e&&this.children[s][t]&&this.children[s][t].apply(this.children[s],i)},n.Group.prototype.callbackFromArray=function(t,e,i){if(1===i){if(t[e[0]])return t[e[0]]}else if(2===i){if(t[e[0]][e[1]])return t[e[0]][e[1]]}else if(3===i){if(t[e[0]][e[1]][e[2]])return t[e[0]][e[1]][e[2]]}else if(4===i){if(t[e[0]][e[1]][e[2]][e[3]])return t[e[0]][e[1]][e[2]][e[3]]}else if(t[e])return t[e];return!1},n.Group.prototype.callAll=function(t,e){if(void 0!==t){t=t.split(".");var i=t.length;if(void 0===e||null===e||""===e)e=null;else if("string"==typeof e){e=e.split(".");var s=e.length}var n;if(arguments.length>2){n=[];for(var r=2;r<arguments.length;r++)n.push(arguments[r])}for(var o=null,a=null,r=0;r<this.children.length;r++)o=this.callbackFromArray(this.children[r],t,i),e&&o?(a=this.callbackFromArray(this.children[r],e,s),o&&o.apply(a,n)):o&&o.apply(this.children[r],n)}},n.Group.prototype.preUpdate=function(){if(this.pendingDestroy)return this.destroy(),!1;if(!this.exists||!this.parent.exists)return this.renderOrderID=-1,!1;for(var t=0;t<this.children.length;t++)this.children[t].preUpdate();return!0},n.Group.prototype.update=function(){for(var t=this.children.length;t--;)this.children[t].update()},n.Group.prototype.postUpdate=function(){this.fixedToCamera&&(this.x=this.game.camera.view.x+this.cameraOffset.x,this.y=this.game.camera.view.y+this.cameraOffset.y);for(var t=0;t<this.children.length;t++)this.children[t].postUpdate()},n.Group.prototype.filter=function(t,e){for(var i=-1,s=this.children.length,r=[];++i<s;){var o=this.children[i];(!e||e&&o.exists)&&t(o,i,this.children)&&r.push(o)}return new n.ArraySet(r)},n.Group.prototype.forEach=function(t,e,i){if(void 0===i&&(i=!1),arguments.length<=3)for(var s=0;s<this.children.length;s++)(!i||i&&this.children[s].exists)&&t.call(e,this.children[s]);else{for(var n=[null],s=3;s<arguments.length;s++)n.push(arguments[s]);for(var s=0;s<this.children.length;s++)(!i||i&&this.children[s].exists)&&(n[0]=this.children[s],t.apply(e,n))}},n.Group.prototype.forEachExists=function(t,e){var i;if(arguments.length>2){i=[null];for(var s=2;s<arguments.length;s++)i.push(arguments[s])}this.iterate("exists",!0,n.Group.RETURN_TOTAL,t,e,i)},n.Group.prototype.forEachAlive=function(t,e){var i;if(arguments.length>2){i=[null];for(var s=2;s<arguments.length;s++)i.push(arguments[s])}this.iterate("alive",!0,n.Group.RETURN_TOTAL,t,e,i)},n.Group.prototype.forEachDead=function(t,e){var i;if(arguments.length>2){i=[null];for(var s=2;s<arguments.length;s++)i.push(arguments[s])}this.iterate("alive",!1,n.Group.RETURN_TOTAL,t,e,i)},n.Group.prototype.sort=function(t,e){this.children.length<2||(void 0===t&&(t="z"),void 0===e&&(e=n.Group.SORT_ASCENDING),this._sortProperty=t,e===n.Group.SORT_ASCENDING?this.children.sort(this.ascendingSortHandler.bind(this)):this.children.sort(this.descendingSortHandler.bind(this)),this.updateZ())},n.Group.prototype.customSort=function(t,e){this.children.length<2||(this.children.sort(t.bind(e)),this.updateZ())},n.Group.prototype.ascendingSortHandler=function(t,e){return t[this._sortProperty]<e[this._sortProperty]?-1:t[this._sortProperty]>e[this._sortProperty]?1:t.z<e.z?-1:1},n.Group.prototype.descendingSortHandler=function(t,e){return t[this._sortProperty]<e[this._sortProperty]?1:t[this._sortProperty]>e[this._sortProperty]?-1:0},n.Group.prototype.iterate=function(t,e,i,s,r,o){if(0===this.children.length){if(i===n.Group.RETURN_TOTAL)return 0;if(i===n.Group.RETURN_ALL)return[]}var a=0;if(i===n.Group.RETURN_ALL)var h=[];for(var l=0;l<this.children.length;l++)if(this.children[l][t]===e){if(a++,s&&(o?(o[0]=this.children[l],s.apply(r,o)):s.call(r,this.children[l])),i===n.Group.RETURN_CHILD)return this.children[l];i===n.Group.RETURN_ALL&&h.push(this.children[l])}return i===n.Group.RETURN_TOTAL?a:i===n.Group.RETURN_ALL?h:null},n.Group.prototype.getFirstExists=function(t,e,i,s,r,o){void 0===e&&(e=!1),"boolean"!=typeof t&&(t=!0);var a=this.iterate("exists",t,n.Group.RETURN_CHILD);return null===a&&e?this.create(i,s,r,o):this.resetChild(a,i,s,r,o)},n.Group.prototype.getFirstAlive=function(t,e,i,s,r){void 0===t&&(t=!1);var o=this.iterate("alive",!0,n.Group.RETURN_CHILD);return null===o&&t?this.create(e,i,s,r):this.resetChild(o,e,i,s,r)},n.Group.prototype.getFirstDead=function(t,e,i,s,r){void 0===t&&(t=!1);var o=this.iterate("alive",!1,n.Group.RETURN_CHILD);return null===o&&t?this.create(e,i,s,r):this.resetChild(o,e,i,s,r)},n.Group.prototype.resetChild=function(t,e,i,s,n){return null===t?null:(void 0===e&&(e=null),void 0===i&&(i=null),null!==e&&null!==i&&t.reset(e,i),void 0!==s&&t.loadTexture(s,n),t)},n.Group.prototype.getTop=function(){if(this.children.length>0)return this.children[this.children.length-1]},n.Group.prototype.getBottom=function(){if(this.children.length>0)return this.children[0]},n.Group.prototype.getClosestTo=function(t,e,i){for(var s=Number.MAX_VALUE,r=0,o=null,a=0;a<this.children.length;a++){var h=this.children[a];h.exists&&(r=Math.abs(n.Point.distance(t,h)))<s&&(!e||e.call(i,h,r))&&(s=r,o=h)}return o},n.Group.prototype.getFurthestFrom=function(t,e,i){for(var s=0,r=0,o=null,a=0;a<this.children.length;a++){var h=this.children[a];h.exists&&(r=Math.abs(n.Point.distance(t,h)))>s&&(!e||e.call(i,h,r))&&(s=r,o=h)}return o},n.Group.prototype.countLiving=function(){return this.iterate("alive",!0,n.Group.RETURN_TOTAL)},n.Group.prototype.countDead=function(){return this.iterate("alive",!1,n.Group.RETURN_TOTAL)},n.Group.prototype.getRandom=function(t,e){return void 0===t&&(t=0),void 0===e&&(e=this.children.length),0===e?null:n.ArrayUtils.getRandomItem(this.children,t,e)},n.Group.prototype.getRandomExists=function(t,e){var i=this.getAll("exists",!0,t,e);return this.game.rnd.pick(i)},n.Group.prototype.getAll=function(t,e,i,s){void 0===i&&(i=0),void 0===s&&(s=this.children.length);for(var n=[],r=i;r<s;r++){var o=this.children[r];t&&o[t]===e&&n.push(o)}return n},n.Group.prototype.remove=function(t,e,i){if(void 0===e&&(e=!1),void 0===i&&(i=!1),0===this.children.length||-1===this.children.indexOf(t))return!1;i||!t.events||t.destroyPhase||t.events.onRemovedFromGroup$dispatch(t,this);var s=this.removeChild(t);return this.removeFromHash(t),this.updateZ(),this.cursor===t&&this.next(),e&&s&&s.destroy(!0),!0},n.Group.prototype.moveAll=function(t,e){if(void 0===e&&(e=!1),this.children.length>0&&t instanceof n.Group){do{t.add(this.children[0],e)}while(this.children.length>0);this.hash=[],this.cursor=null}return t},n.Group.prototype.removeAll=function(t,e,i){if(void 0===t&&(t=!1),void 0===e&&(e=!1),void 0===i&&(i=!1),0!==this.children.length){do{!e&&this.children[0].events&&this.children[0].events.onRemovedFromGroup$dispatch(this.children[0],this);var s=this.removeChild(this.children[0]);this.removeFromHash(s),t&&s&&s.destroy(!0,i)}while(this.children.length>0);this.hash=[],this.cursor=null}},n.Group.prototype.removeBetween=function(t,e,i,s){if(void 0===e&&(e=this.children.length-1),void 0===i&&(i=!1),void 0===s&&(s=!1),0!==this.children.length){if(t>e||t<0||e>this.children.length)return!1;for(var n=e;n>=t;){!s&&this.children[n].events&&this.children[n].events.onRemovedFromGroup$dispatch(this.children[n],this);var r=this.removeChild(this.children[n]);this.removeFromHash(r),i&&r&&r.destroy(!0),this.cursor===this.children[n]&&(this.cursor=null),n--}this.updateZ()}},n.Group.prototype.destroy=function(t,e){null===this.game||this.ignoreDestroy||(void 0===t&&(t=!0),void 0===e&&(e=!1),this.onDestroy.dispatch(this,t,e),this.removeAll(t),this.cursor=null,this.filters=null,this.pendingDestroy=!1,e||(this.parent&&this.parent.removeChild(this),this.game=null,this.exists=!1))},Object.defineProperty(n.Group.prototype,"total",{get:function(){return this.iterate("exists",!0,n.Group.RETURN_TOTAL)}}),Object.defineProperty(n.Group.prototype,"length",{get:function(){return this.children.length}}),Object.defineProperty(n.Group.prototype,"angle",{get:function(){return n.Math.radToDeg(this.rotation)},set:function(t){this.rotation=n.Math.degToRad(t)}}),Object.defineProperty(n.Group.prototype,"centerX",{get:function(){return this.getBounds(this.parent).centerX},set:function(t){var e=this.getBounds(this.parent),i=this.x-e.x;this.x=t+i-e.halfWidth}}),Object.defineProperty(n.Group.prototype,"centerY",{get:function(){return this.getBounds(this.parent).centerY},set:function(t){var e=this.getBounds(this.parent),i=this.y-e.y;this.y=t+i-e.halfHeight}}),Object.defineProperty(n.Group.prototype,"left",{get:function(){return this.getBounds(this.parent).left},set:function(t){var e=this.getBounds(this.parent),i=this.x-e.x;this.x=t+i}}),Object.defineProperty(n.Group.prototype,"right",{get:function(){return this.getBounds(this.parent).right},set:function(t){var e=this.getBounds(this.parent),i=this.x-e.x;this.x=t+i-e.width}}),Object.defineProperty(n.Group.prototype,"top",{get:function(){return this.getBounds(this.parent).top},set:function(t){var e=this.getBounds(this.parent),i=this.y-e.y;this.y=t+i}}),Object.defineProperty(n.Group.prototype,"bottom",{get:function(){return this.getBounds(this.parent).bottom},set:function(t){var e=this.getBounds(this.parent),i=this.y-e.y;this.y=t+i-e.height}}),/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.World=function(t){n.Group.call(this,t,null,"__world",!1),this.bounds=new n.Rectangle(0,0,t.width,t.height),this.camera=null,this._definedSize=!1,this._width=t.width,this._height=t.height,this.game.state.onStateChange.add(this.stateChange,this)},n.World.prototype=Object.create(n.Group.prototype),n.World.prototype.constructor=n.World,n.World.prototype.boot=function(){this.camera=new n.Camera(this.game,0,0,0,this.game.width,this.game.height),this.game.stage.addChild(this),this.camera.boot()},n.World.prototype.stateChange=function(){this.x=0,this.y=0,this.camera.reset()},n.World.prototype.setBounds=function(t,e,i,s){this._definedSize=!0,this._width=i,this._height=s,this.bounds.setTo(t,e,i,s),this.x=t,this.y=e,this.camera.bounds&&this.camera.bounds.setTo(t,e,Math.max(i,this.game.width),Math.max(s,this.game.height)),this.game.physics.setBoundsToWorld()},n.World.prototype.resize=function(t,e){this._definedSize&&(t<this._width&&(t=this._width),e<this._height&&(e=this._height)),this.bounds.width=t,this.bounds.height=e,this.game.camera.setBoundsToWorld(),this.game.physics.setBoundsToWorld()},n.World.prototype.shutdown=function(){this.destroy(!0,!0)},n.World.prototype.wrap=function(t,e,i,s,n){void 0===e&&(e=0),void 0===i&&(i=!1),void 0===s&&(s=!0),void 0===n&&(n=!0),i?(t.getBounds(),s&&(t.x+t._currentBounds.width<this.bounds.x?t.x=this.bounds.right:t.x>this.bounds.right&&(t.x=this.bounds.left)),n&&(t.y+t._currentBounds.height<this.bounds.top?t.y=this.bounds.bottom:t.y>this.bounds.bottom&&(t.y=this.bounds.top))):(s&&t.x+e<this.bounds.x?t.x=this.bounds.right+e:s&&t.x-e>this.bounds.right&&(t.x=this.bounds.left-e),n&&t.y+e<this.bounds.top?t.y=this.bounds.bottom+e:n&&t.y-e>this.bounds.bottom&&(t.y=this.bounds.top-e))},Object.defineProperty(n.World.prototype,"width",{get:function(){return this.bounds.width},set:function(t){t<this.game.width&&(t=this.game.width),this.bounds.width=t,this._width=t,this._definedSize=!0}}),Object.defineProperty(n.World.prototype,"height",{get:function(){return this.bounds.height},set:function(t){t<this.game.height&&(t=this.game.height),this.bounds.height=t,this._height=t,this._definedSize=!0}}),Object.defineProperty(n.World.prototype,"centerX",{get:function(){return this.bounds.halfWidth+this.bounds.x}}),Object.defineProperty(n.World.prototype,"centerY",{get:function(){return this.bounds.halfHeight+this.bounds.y}}),Object.defineProperty(n.World.prototype,"randomX",{get:function(){return this.bounds.x<0?this.game.rnd.between(this.bounds.x,this.bounds.width-Math.abs(this.bounds.x)):this.game.rnd.between(this.bounds.x,this.bounds.width)}}),Object.defineProperty(n.World.prototype,"randomY",{get:function(){return this.bounds.y<0?this.game.rnd.between(this.bounds.y,this.bounds.height-Math.abs(this.bounds.y)):this.game.rnd.between(this.bounds.y,this.bounds.height)}}),/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Game=function(t,e,i,s,r,o,a,h){return this.id=n.GAMES.push(this)-1,this.config=null,this.physicsConfig=h,this.parent="",this.width=800,this.height=600,this.resolution=1,this._width=800,this._height=600,this.transparent=!1,this.antialias=!0,this.preserveDrawingBuffer=!1,this.clearBeforeRender=!0,this.renderer=null,this.renderType=n.AUTO,this.state=null,this.isBooted=!1,this.isRunning=!1,this.raf=null,this.add=null,this.make=null,this.cache=null,this.input=null,this.load=null,this.math=null,this.net=null,this.scale=null,this.sound=null,this.stage=null,this.time=null,this.tweens=null,this.world=null,this.physics=null,this.plugins=null,this.rnd=null,this.device=n.Device,this.camera=null,this.canvas=null,this.context=null,this.debug=null,this.particles=null,this.create=null,this.lockRender=!1,this.stepping=!1,this.pendingStep=!1,this.stepCount=0,this.onPause=null,this.onResume=null,this.onBlur=null,this.onFocus=null,this._paused=!1,this._codePaused=!1,this.currentUpdateID=0,this.updatesThisFrame=1,this._deltaTime=0,this._lastCount=0,this._spiraling=0,this._kickstart=!0,this.fpsProblemNotifier=new n.Signal,this.forceSingleUpdate=!0,this._nextFpsNotification=0,1===arguments.length&&"object"==typeof arguments[0]?this.parseConfig(arguments[0]):(this.config={enableDebug:!0},void 0!==t&&(this._width=t),void 0!==e&&(this._height=e),void 0!==i&&(this.renderType=i),void 0!==s&&(this.parent=s),void 0!==o&&(this.transparent=o),void 0!==a&&(this.antialias=a),this.rnd=new n.RandomDataGenerator([(Date.now()*Math.random()).toString()]),this.state=new n.StateManager(this,r)),this.device.whenReady(this.boot,this),this},n.Game.prototype={parseConfig:function(t){this.config=t,void 0===t.enableDebug&&(this.config.enableDebug=!0),t.width&&(this._width=t.width),t.height&&(this._height=t.height),t.renderer&&(this.renderType=t.renderer),t.parent&&(this.parent=t.parent),void 0!==t.transparent&&(this.transparent=t.transparent),void 0!==t.antialias&&(this.antialias=t.antialias),t.resolution&&(this.resolution=t.resolution),void 0!==t.preserveDrawingBuffer&&(this.preserveDrawingBuffer=t.preserveDrawingBuffer),t.physicsConfig&&(this.physicsConfig=t.physicsConfig);var e=[(Date.now()*Math.random()).toString()];t.seed&&(e=t.seed),this.rnd=new n.RandomDataGenerator(e);var i=null;t.state&&(i=t.state),this.state=new n.StateManager(this,i)},boot:function(){this.isBooted||(this.onPause=new n.Signal,this.onResume=new n.Signal,this.onBlur=new n.Signal,this.onFocus=new n.Signal,this.isBooted=!0,PIXI.game=this,this.math=n.Math,this.scale=new n.ScaleManager(this,this._width,this._height),this.stage=new n.Stage(this),this.setUpRenderer(),this.world=new n.World(this),this.add=new n.GameObjectFactory(this),this.make=new n.GameObjectCreator(this),this.cache=new n.Cache(this),this.load=new n.Loader(this),this.time=new n.Time(this),this.tweens=new n.TweenManager(this),this.input=new n.Input(this),this.sound=new n.SoundManager(this),this.physics=new n.Physics(this,this.physicsConfig),this.particles=new n.Particles(this),this.create=new n.Create(this),this.plugins=new n.PluginManager(this),this.net=new n.Net(this),this.time.boot(),this.stage.boot(),this.world.boot(),this.scale.boot(),this.input.boot(),this.sound.boot(),this.state.boot(),this.config.enableDebug?(this.debug=new n.Utils.Debug(this),this.debug.boot()):this.debug={preUpdate:function(){},update:function(){},reset:function(){}},this.showDebugHeader(),this.isRunning=!0,this.config&&this.config.forceSetTimeOut?this.raf=new n.RequestAnimationFrame(this,this.config.forceSetTimeOut):this.raf=new n.RequestAnimationFrame(this,!1),this._kickstart=!0,window.focus&&(!window.PhaserGlobal||window.PhaserGlobal&&!window.PhaserGlobal.stopFocus)&&window.focus(),this.raf.start())},showDebugHeader:function(){if(!window.PhaserGlobal||!window.PhaserGlobal.hideBanner){var t=n.VERSION,e="Canvas",i="HTML Audio",s=1;if(this.renderType===n.WEBGL?(e="WebGL",s++):this.renderType===n.HEADLESS&&(e="Headless"),this.device.webAudio&&(i="WebAudio",s++),this.device.chrome){for(var r=["%c %c %c Phaser v"+t+" | Pixi.js | "+e+" | "+i+" %c %c %c http://phaser.io %c♥%c♥%c♥","background: #fb8cb3","background: #d44a52","color: #ffffff; background: #871905;","background: #d44a52","background: #fb8cb3","background: #ffffff"],o=0;o<3;o++)o<s?r.push("color: #ff2424; background: #fff"):r.push("color: #959595; background: #fff");console.log.apply(console,r)}else window.console&&console.log("Phaser v"+t+" | Pixi.js "+PIXI.VERSION+" | "+e+" | "+i+" | http://phaser.io")}},setUpRenderer:function(){if(this.config.canvas?this.canvas=this.config.canvas:this.canvas=n.Canvas.create(this,this.width,this.height,this.config.canvasID,!0),this.config.canvasStyle?this.canvas.style=this.config.canvasStyle:this.canvas.style["-webkit-full-screen"]="width: 100%; height: 100%",this.renderType===n.HEADLESS||this.renderType===n.CANVAS||this.renderType===n.AUTO&&!this.device.webGL){if(!this.device.canvas)throw new Error("Phaser.Game - Cannot create Canvas or WebGL context, aborting.");this.renderType=n.CANVAS,this.renderer=new PIXI.CanvasRenderer(this),this.context=this.renderer.context}else this.renderType=n.WEBGL,this.renderer=new PIXI.WebGLRenderer(this),this.context=null,this.canvas.addEventListener("webglcontextlost",this.contextLost.bind(this),!1),this.canvas.addEventListener("webglcontextrestored",this.contextRestored.bind(this),!1);this.device.cocoonJS&&(this.canvas.screencanvas=this.renderType===n.CANVAS),this.renderType!==n.HEADLESS&&(this.stage.smoothed=this.antialias,n.Canvas.addToDOM(this.canvas,this.parent,!1),n.Canvas.setTouchAction(this.canvas))},contextLost:function(t){t.preventDefault(),this.renderer.contextLost=!0},contextRestored:function(){this.renderer.initContext(),this.cache.clearGLTextures(),this.renderer.contextLost=!1},update:function(t){if(this.time.update(t),this._kickstart)return this.updateLogic(this.time.desiredFpsMult),this.updateRender(this.time.slowMotion*this.time.desiredFps),void(this._kickstart=!1);if(this._spiraling>1&&!this.forceSingleUpdate)this.time.time>this._nextFpsNotification&&(this._nextFpsNotification=this.time.time+1e4,this.fpsProblemNotifier.dispatch()),this._deltaTime=0,this._spiraling=0,this.updateRender(this.time.slowMotion*this.time.desiredFps);else{var e=1e3*this.time.slowMotion/this.time.desiredFps;this._deltaTime+=Math.max(Math.min(3*e,this.time.elapsed),0);var i=0;for(this.updatesThisFrame=Math.floor(this._deltaTime/e),this.forceSingleUpdate&&(this.updatesThisFrame=Math.min(1,this.updatesThisFrame));this._deltaTime>=e&&(this._deltaTime-=e,this.currentUpdateID=i,this.updateLogic(this.time.desiredFpsMult),i++,!this.forceSingleUpdate||1!==i);)this.time.refresh();i>this._lastCount?this._spiraling++:i<this._lastCount&&(this._spiraling=0),this._lastCount=i,this.updateRender(this._deltaTime/e)}},updateLogic:function(t){this._paused||this.pendingStep?(this.scale.pauseUpdate(),this.state.pauseUpdate(),this.debug.preUpdate()):(this.stepping&&(this.pendingStep=!0),this.scale.preUpdate(),this.debug.preUpdate(),this.camera.preUpdate(),this.physics.preUpdate(),this.state.preUpdate(t),this.plugins.preUpdate(t),this.stage.preUpdate(),this.state.update(),this.stage.update(),this.tweens.update(),this.sound.update(),this.input.update(),this.physics.update(),this.particles.update(),this.plugins.update(),this.stage.postUpdate(),this.plugins.postUpdate()),this.stage.updateTransform()},updateRender:function(t){this.lockRender||(this.state.preRender(t),this.renderType!==n.HEADLESS&&(this.renderer.render(this.stage),this.plugins.render(t),this.state.render(t)),this.plugins.postRender(t))},enableStep:function(){this.stepping=!0,this.pendingStep=!1,this.stepCount=0},disableStep:function(){this.stepping=!1,this.pendingStep=!1},step:function(){this.pendingStep=!1,this.stepCount++},destroy:function(){this.raf.stop(),this.state.destroy(),this.sound.destroy(),this.scale.destroy(),this.stage.destroy(),this.input.destroy(),this.physics.destroy(),this.plugins.destroy(),this.state=null,this.sound=null,this.scale=null,this.stage=null,this.input=null,this.physics=null,this.plugins=null,this.cache=null,this.load=null,this.time=null,this.world=null,this.isBooted=!1,this.renderer.destroy(!1),n.Canvas.removeFromDOM(this.canvas),PIXI.defaultRenderer=null,n.GAMES[this.id]=null},gamePaused:function(t){this._paused||(this._paused=!0,this.time.gamePaused(),this.sound.muteOnPause&&this.sound.setMute(),this.onPause.dispatch(t),this.device.cordova&&this.device.iOS&&(this.lockRender=!0))},gameResumed:function(t){this._paused&&!this._codePaused&&(this._paused=!1,this.time.gameResumed(),this.input.reset(),this.sound.muteOnPause&&this.sound.unsetMute(),this.onResume.dispatch(t),this.device.cordova&&this.device.iOS&&(this.lockRender=!1))},focusLoss:function(t){this.onBlur.dispatch(t),this.stage.disableVisibilityChange||this.gamePaused(t)},focusGain:function(t){this.onFocus.dispatch(t),this.stage.disableVisibilityChange||this.gameResumed(t)}},n.Game.prototype.constructor=n.Game,Object.defineProperty(n.Game.prototype,"paused",{get:function(){return this._paused},set:function(t){!0===t?(!1===this._paused&&(this._paused=!0,this.sound.setMute(),this.time.gamePaused(),this.onPause.dispatch(this)),this._codePaused=!0):(this._paused&&(this._paused=!1,this.input.reset(),this.sound.unsetMute(),this.time.gameResumed(),this.onResume.dispatch(this)),this._codePaused=!1)}}),/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Input=function(t){this.game=t,this.hitCanvas=null,this.hitContext=null,this.moveCallbacks=[],this.customCandidateHandler=null,this.customCandidateHandlerContext=null,this.pollRate=0,this.enabled=!0,this.multiInputOverride=n.Input.MOUSE_TOUCH_COMBINE,this.position=null,this.speed=null,this.circle=null,this.scale=null,this.maxPointers=-1,this.tapRate=200,this.doubleTapRate=300,this.holdRate=2e3,this.justPressedRate=200,this.justReleasedRate=200,this.recordPointerHistory=!1,this.recordRate=100,this.recordLimit=100,this.pointer1=null,this.pointer2=null,this.pointer3=null,this.pointer4=null,this.pointer5=null,this.pointer6=null,this.pointer7=null,this.pointer8=null,this.pointer9=null,this.pointer10=null,this.pointers=[],this.activePointer=null,this.mousePointer=null,this.mouse=null,this.keyboard=null,this.touch=null,this.mspointer=null,this.gamepad=null,this.resetLocked=!1,this.onDown=null,this.onUp=null,this.onTap=null,this.onHold=null,this.minPriorityID=0,this.interactiveItems=new n.ArraySet,this._localPoint=new n.Point,this._pollCounter=0,this._oldPosition=null,this._x=0,this._y=0},n.Input.MOUSE_OVERRIDES_TOUCH=0,n.Input.TOUCH_OVERRIDES_MOUSE=1,n.Input.MOUSE_TOUCH_COMBINE=2,n.Input.MAX_POINTERS=10,n.Input.prototype={boot:function(){this.mousePointer=new n.Pointer(this.game,0,n.PointerMode.CURSOR),this.addPointer(),this.addPointer(),this.mouse=new n.Mouse(this.game),this.touch=new n.Touch(this.game),this.mspointer=new n.MSPointer(this.game),n.Keyboard&&(this.keyboard=new n.Keyboard(this.game)),n.Gamepad&&(this.gamepad=new n.Gamepad(this.game)),this.onDown=new n.Signal,this.onUp=new n.Signal,this.onTap=new n.Signal,this.onHold=new n.Signal,this.scale=new n.Point(1,1),this.speed=new n.Point,this.position=new n.Point,this._oldPosition=new n.Point,this.circle=new n.Circle(0,0,44),this.activePointer=this.mousePointer,this.hitCanvas=PIXI.CanvasPool.create(this,1,1),this.hitContext=this.hitCanvas.getContext("2d"),this.mouse.start(),this.touch.start(),this.mspointer.start(),this.mousePointer.active=!0,this.keyboard&&this.keyboard.start();var t=this;this._onClickTrampoline=function(e){t.onClickTrampoline(e)},this.game.canvas.addEventListener("click",this._onClickTrampoline,!1)},destroy:function(){this.mouse.stop(),this.touch.stop(),this.mspointer.stop(),this.keyboard&&this.keyboard.stop(),this.gamepad&&this.gamepad.stop(),this.moveCallbacks=[],PIXI.CanvasPool.remove(this),this.game.canvas.removeEventListener("click",this._onClickTrampoline)},setInteractiveCandidateHandler:function(t,e){this.customCandidateHandler=t,this.customCandidateHandlerContext=e},addMoveCallback:function(t,e){this.moveCallbacks.push({callback:t,context:e})},deleteMoveCallback:function(t,e){for(var i=this.moveCallbacks.length;i--;)if(this.moveCallbacks[i].callback===t&&this.moveCallbacks[i].context===e)return void this.moveCallbacks.splice(i,1)},addPointer:function(){if(this.pointers.length>=n.Input.MAX_POINTERS)return console.warn("Phaser.Input.addPointer: Maximum limit of "+n.Input.MAX_POINTERS+" pointers reached."),null;var t=this.pointers.length+1,e=new n.Pointer(this.game,t,n.PointerMode.TOUCH);return this.pointers.push(e),this["pointer"+t]=e,e},update:function(){if(this.keyboard&&this.keyboard.update(),this.pollRate>0&&this._pollCounter<this.pollRate)return void this._pollCounter++;this.speed.x=this.position.x-this._oldPosition.x,this.speed.y=this.position.y-this._oldPosition.y,this._oldPosition.copyFrom(this.position),this.mousePointer.update(),this.gamepad&&this.gamepad.active&&this.gamepad.update();for(var t=0;t<this.pointers.length;t++)this.pointers[t].update();this._pollCounter=0},reset:function(t){if(this.game.isBooted&&!this.resetLocked){void 0===t&&(t=!1),this.mousePointer.reset(),this.keyboard&&this.keyboard.reset(t),this.gamepad&&this.gamepad.reset();for(var e=0;e<this.pointers.length;e++)this.pointers[e].reset();"none"!==this.game.canvas.style.cursor&&(this.game.canvas.style.cursor="inherit"),t&&(this.onDown.dispose(),this.onUp.dispose(),this.onTap.dispose(),this.onHold.dispose(),this.onDown=new n.Signal,this.onUp=new n.Signal,this.onTap=new n.Signal,this.onHold=new n.Signal,this.moveCallbacks=[]),this._pollCounter=0}},resetSpeed:function(t,e){this._oldPosition.setTo(t,e),this.speed.setTo(0,0)},startPointer:function(t){if(this.maxPointers>=0&&this.countActivePointers(this.maxPointers)>=this.maxPointers)return null;if(!this.pointer1.active)return this.pointer1.start(t);if(!this.pointer2.active)return this.pointer2.start(t);for(var e=2;e<this.pointers.length;e++){var i=this.pointers[e];if(!i.active)return i.start(t)}return null},updatePointer:function(t){if(this.pointer1.active&&this.pointer1.identifier===t.identifier)return this.pointer1.move(t);if(this.pointer2.active&&this.pointer2.identifier===t.identifier)return this.pointer2.move(t);for(var e=2;e<this.pointers.length;e++){var i=this.pointers[e];if(i.active&&i.identifier===t.identifier)return i.move(t)}return null},stopPointer:function(t){if(this.pointer1.active&&this.pointer1.identifier===t.identifier)return this.pointer1.stop(t);if(this.pointer2.active&&this.pointer2.identifier===t.identifier)return this.pointer2.stop(t);for(var e=2;e<this.pointers.length;e++){var i=this.pointers[e];if(i.active&&i.identifier===t.identifier)return i.stop(t)}return null},countActivePointers:function(t){void 0===t&&(t=this.pointers.length);for(var e=t,i=0;i<this.pointers.length&&e>0;i++){this.pointers[i].active&&e--}return t-e},getPointer:function(t){void 0===t&&(t=!1);for(var e=0;e<this.pointers.length;e++){var i=this.pointers[e];if(i.active===t)return i}return null},getPointerFromIdentifier:function(t){for(var e=0;e<this.pointers.length;e++){var i=this.pointers[e];if(i.identifier===t)return i}return null},getPointerFromId:function(t){for(var e=0;e<this.pointers.length;e++){var i=this.pointers[e];if(i.pointerId===t)return i}return null},getLocalPosition:function(t,e,i){void 0===i&&(i=new n.Point);var s=t.worldTransform,r=1/(s.a*s.d+s.c*-s.b);return i.setTo(s.d*r*e.x+-s.c*r*e.y+(s.ty*s.c-s.tx*s.d)*r,s.a*r*e.y+-s.b*r*e.x+(-s.ty*s.a+s.tx*s.b)*r)},hitTest:function(t,e,i){if(!t.worldVisible)return!1;if(this.getLocalPosition(t,e,this._localPoint),i.copyFrom(this._localPoint),t.hitArea&&t.hitArea.contains)return t.hitArea.contains(this._localPoint.x,this._localPoint.y);if(t instanceof n.TileSprite){var s=t.width,r=t.height,o=-s*t.anchor.x;if(this._localPoint.x>=o&&this._localPoint.x<o+s){var a=-r*t.anchor.y;if(this._localPoint.y>=a&&this._localPoint.y<a+r)return!0}}else if(t instanceof PIXI.Sprite){var s=t.texture.frame.width,r=t.texture.frame.height,o=-s*t.anchor.x;if(this._localPoint.x>=o&&this._localPoint.x<o+s){var a=-r*t.anchor.y;if(this._localPoint.y>=a&&this._localPoint.y<a+r)return!0}}else if(t instanceof n.Graphics)for(var h=0;h<t.graphicsData.length;h++){var l=t.graphicsData[h];if(l.fill&&(l.shape&&l.shape.contains(this._localPoint.x,this._localPoint.y)))return!0}for(var h=0;h<t.children.length;h++)if(this.hitTest(t.children[h],e,i))return!0;return!1},onClickTrampoline:function(){this.activePointer.processClickTrampolines()}},n.Input.prototype.constructor=n.Input,Object.defineProperty(n.Input.prototype,"x",{get:function(){return this._x},set:function(t){this._x=Math.floor(t)}}),Object.defineProperty(n.Input.prototype,"y",{get:function(){return this._y},set:function(t){this._y=Math.floor(t)}}),Object.defineProperty(n.Input.prototype,"pollLocked",{get:function(){return this.pollRate>0&&this._pollCounter<this.pollRate}}),Object.defineProperty(n.Input.prototype,"totalInactivePointers",{get:function(){return this.pointers.length-this.countActivePointers()}}),Object.defineProperty(n.Input.prototype,"totalActivePointers",{get:function(){return this.countActivePointers()}}),Object.defineProperty(n.Input.prototype,"worldX",{get:function(){return this.game.camera.view.x+this.x}}),Object.defineProperty(n.Input.prototype,"worldY",{get:function(){return this.game.camera.view.y+this.y}}),/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Mouse=function(t){this.game=t,this.input=t.input,this.callbackContext=this.game,this.mouseDownCallback=null,this.mouseUpCallback=null,this.mouseOutCallback=null,this.mouseOverCallback=null,this.mouseWheelCallback=null,this.capture=!1,this.button=-1,this.wheelDelta=0,this.enabled=!0,this.locked=!1,this.stopOnGameOut=!1,this.pointerLock=new n.Signal,this.event=null,this._onMouseDown=null,this._onMouseMove=null,this._onMouseUp=null,this._onMouseOut=null,this._onMouseOver=null,this._onMouseWheel=null,this._wheelEvent=null},n.Mouse.NO_BUTTON=-1,n.Mouse.LEFT_BUTTON=0,n.Mouse.MIDDLE_BUTTON=1,n.Mouse.RIGHT_BUTTON=2,n.Mouse.BACK_BUTTON=3,n.Mouse.FORWARD_BUTTON=4,n.Mouse.WHEEL_UP=1,n.Mouse.WHEEL_DOWN=-1,n.Mouse.prototype={start:function(){if((!this.game.device.android||!1!==this.game.device.chrome)&&null===this._onMouseDown){var t=this;this._onMouseDown=function(e){return t.onMouseDown(e)},this._onMouseMove=function(e){return t.onMouseMove(e)},this._onMouseUp=function(e){return t.onMouseUp(e)},this._onMouseUpGlobal=function(e){return t.onMouseUpGlobal(e)},this._onMouseOutGlobal=function(e){return t.onMouseOutGlobal(e)},this._onMouseOut=function(e){return t.onMouseOut(e)},this._onMouseOver=function(e){return t.onMouseOver(e)},this._onMouseWheel=function(e){return t.onMouseWheel(e)};var e=this.game.canvas;e.addEventListener("mousedown",this._onMouseDown,!0),e.addEventListener("mousemove",this._onMouseMove,!0),e.addEventListener("mouseup",this._onMouseUp,!0),this.game.device.cocoonJS||(window.addEventListener("mouseup",this._onMouseUpGlobal,!0),window.addEventListener("mouseout",this._onMouseOutGlobal,!0),e.addEventListener("mouseover",this._onMouseOver,!0),e.addEventListener("mouseout",this._onMouseOut,!0));var i=this.game.device.wheelEvent;i&&(e.addEventListener(i,this._onMouseWheel,!0),"mousewheel"===i?this._wheelEvent=new s(-.025,1):"DOMMouseScroll"===i&&(this._wheelEvent=new s(1,1)))}},onMouseDown:function(t){this.event=t,this.capture&&t.preventDefault(),this.mouseDownCallback&&this.mouseDownCallback.call(this.callbackContext,t),this.input.enabled&&this.enabled&&(t.identifier=0,this.input.mousePointer.start(t))},onMouseMove:function(t){this.event=t,this.capture&&t.preventDefault(),this.mouseMoveCallback&&this.mouseMoveCallback.call(this.callbackContext,t),this.input.enabled&&this.enabled&&(t.identifier=0,this.input.mousePointer.move(t))},onMouseUp:function(t){this.event=t,this.capture&&t.preventDefault(),this.mouseUpCallback&&this.mouseUpCallback.call(this.callbackContext,t),this.input.enabled&&this.enabled&&(t.identifier=0,this.input.mousePointer.stop(t))},onMouseUpGlobal:function(t){this.input.mousePointer.withinGame||(this.mouseUpCallback&&this.mouseUpCallback.call(this.callbackContext,t),t.identifier=0,this.input.mousePointer.stop(t))},onMouseOutGlobal:function(t){this.event=t,this.capture&&t.preventDefault(),this.input.mousePointer.withinGame=!1,this.input.enabled&&this.enabled&&(this.input.mousePointer.stop(t),this.input.mousePointer.leftButton.stop(t),this.input.mousePointer.rightButton.stop(t))},onMouseOut:function(t){this.event=t,this.capture&&t.preventDefault(),this.input.mousePointer.withinGame=!1,this.mouseOutCallback&&this.mouseOutCallback.call(this.callbackContext,t),this.input.enabled&&this.enabled&&this.stopOnGameOut&&(t.identifier=0,this.input.mousePointer.stop(t))},onMouseOver:function(t){this.event=t,this.capture&&t.preventDefault(),this.input.mousePointer.withinGame=!0,this.mouseOverCallback&&this.mouseOverCallback.call(this.callbackContext,t)},onMouseWheel:function(t){this._wheelEvent&&(t=this._wheelEvent.bindEvent(t)),this.event=t,this.capture&&t.preventDefault(),this.wheelDelta=n.Math.clamp(-t.deltaY,-1,1),this.mouseWheelCallback&&this.mouseWheelCallback.call(this.callbackContext,t)},requestPointerLock:function(){if(this.game.device.pointerLock){var t=this.game.canvas;t.requestPointerLock=t.requestPointerLock||t.mozRequestPointerLock||t.webkitRequestPointerLock,t.requestPointerLock();var e=this;this._pointerLockChange=function(t){return e.pointerLockChange(t)},document.addEventListener("pointerlockchange",this._pointerLockChange,!0),document.addEventListener("mozpointerlockchange",this._pointerLockChange,!0),document.addEventListener("webkitpointerlockchange",this._pointerLockChange,!0)}},pointerLockChange:function(t){var e=this.game.canvas;document.pointerLockElement===e||document.mozPointerLockElement===e||document.webkitPointerLockElement===e?(this.locked=!0,this.pointerLock.dispatch(!0,t)):(this.locked=!1,this.pointerLock.dispatch(!1,t))},releasePointerLock:function(){document.exitPointerLock=document.exitPointerLock||document.mozExitPointerLock||document.webkitExitPointerLock,document.exitPointerLock(),document.removeEventListener("pointerlockchange",this._pointerLockChange,!0),document.removeEventListener("mozpointerlockchange",this._pointerLockChange,!0),document.removeEventListener("webkitpointerlockchange",this._pointerLockChange,!0)},stop:function(){var t=this.game.canvas;t.removeEventListener("mousedown",this._onMouseDown,!0),t.removeEventListener("mousemove",this._onMouseMove,!0),t.removeEventListener("mouseup",this._onMouseUp,!0),t.removeEventListener("mouseover",this._onMouseOver,!0),t.removeEventListener("mouseout",this._onMouseOut,!0);var e=this.game.device.wheelEvent;e&&t.removeEventListener(e,this._onMouseWheel,!0),window.removeEventListener("mouseup",this._onMouseUpGlobal,!0),window.removeEventListener("mouseout",this._onMouseOutGlobal,!0),document.removeEventListener("pointerlockchange",this._pointerLockChange,!0),document.removeEventListener("mozpointerlockchange",this._pointerLockChange,!0),document.removeEventListener("webkitpointerlockchange",this._pointerLockChange,!0)}},n.Mouse.prototype.constructor=n.Mouse,s.prototype={},s.prototype.constructor=s,s.prototype.bindEvent=function(t){if(!s._stubsGenerated&&t){for(var e in t)e in s.prototype||Object.defineProperty(s.prototype,e,{get:function(t){return function(){var e=this.originalEvent[t];return"function"!=typeof e?e:e.bind(this.originalEvent)}}(e)});s._stubsGenerated=!0}return this.originalEvent=t,this},Object.defineProperties(s.prototype,{type:{value:"wheel"},deltaMode:{get:function(){return this._deltaMode}},deltaY:{get:function(){return this._scaleFactor*(this.originalEvent.wheelDelta||this.originalEvent.detail)||0}},deltaX:{get:function(){return this._scaleFactor*this.originalEvent.wheelDeltaX||0}},deltaZ:{value:0}}),/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.MSPointer=function(t){this.game=t,this.input=t.input,this.callbackContext=this.game,this.pointerDownCallback=null,this.pointerMoveCallback=null,this.pointerUpCallback=null,this.capture=!0,this.button=-1,this.event=null,this.enabled=!0,this._onMSPointerDown=null,this._onMSPointerMove=null,this._onMSPointerUp=null,this._onMSPointerUpGlobal=null,this._onMSPointerOut=null,this._onMSPointerOver=null},n.MSPointer.prototype={start:function(){if(null===this._onMSPointerDown){var t=this;if(this.game.device.mspointer){this._onMSPointerDown=function(e){return t.onPointerDown(e)},this._onMSPointerMove=function(e){return t.onPointerMove(e)},this._onMSPointerUp=function(e){return t.onPointerUp(e)},this._onMSPointerUpGlobal=function(e){return t.onPointerUpGlobal(e)},this._onMSPointerOut=function(e){return t.onPointerOut(e)},this._onMSPointerOver=function(e){return t.onPointerOver(e)};var e=this.game.canvas;e.addEventListener("MSPointerDown",this._onMSPointerDown,!1),e.addEventListener("MSPointerMove",this._onMSPointerMove,!1),e.addEventListener("MSPointerUp",this._onMSPointerUp,!1),e.addEventListener("pointerdown",this._onMSPointerDown,!1),e.addEventListener("pointermove",this._onMSPointerMove,!1),e.addEventListener("pointerup",this._onMSPointerUp,!1),e.style["-ms-content-zooming"]="none",e.style["-ms-touch-action"]="none",this.game.device.cocoonJS||(window.addEventListener("MSPointerUp",this._onMSPointerUpGlobal,!0),e.addEventListener("MSPointerOver",this._onMSPointerOver,!0),e.addEventListener("MSPointerOut",this._onMSPointerOut,!0),window.addEventListener("pointerup",this._onMSPointerUpGlobal,!0),e.addEventListener("pointerover",this._onMSPointerOver,!0),e.addEventListener("pointerout",this._onMSPointerOut,!0))}}},onPointerDown:function(t){this.event=t,this.capture&&t.preventDefault(),this.pointerDownCallback&&this.pointerDownCallback.call(this.callbackContext,t),this.input.enabled&&this.enabled&&(t.identifier=t.pointerId,"mouse"===t.pointerType||4===t.pointerType?this.input.mousePointer.start(t):this.input.startPointer(t))},onPointerMove:function(t){this.event=t,this.capture&&t.preventDefault(),this.pointerMoveCallback&&this.pointerMoveCallback.call(this.callbackContext,t),this.input.enabled&&this.enabled&&(t.identifier=t.pointerId,"mouse"===t.pointerType||4===t.pointerType?this.input.mousePointer.move(t):this.input.updatePointer(t))},onPointerUp:function(t){this.event=t,this.capture&&t.preventDefault(),this.pointerUpCallback&&this.pointerUpCallback.call(this.callbackContext,t),this.input.enabled&&this.enabled&&(t.identifier=t.pointerId,"mouse"===t.pointerType||4===t.pointerType?this.input.mousePointer.stop(t):this.input.stopPointer(t))},onPointerUpGlobal:function(t){if("mouse"!==t.pointerType&&4!==t.pointerType||this.input.mousePointer.withinGame){var e=this.input.getPointerFromIdentifier(t.identifier);e&&e.withinGame&&this.onPointerUp(t)}else this.onPointerUp(t)},onPointerOut:function(t){if(this.event=t,this.capture&&t.preventDefault(),"mouse"===t.pointerType||4===t.pointerType)this.input.mousePointer.withinGame=!1;else{var e=this.input.getPointerFromIdentifier(t.identifier);e&&(e.withinGame=!1)}this.input.mouse.mouseOutCallback&&this.input.mouse.mouseOutCallback.call(this.input.mouse.callbackContext,t),this.input.enabled&&this.enabled&&this.input.mouse.stopOnGameOut&&(t.identifier=0,e?e.stop(t):this.input.mousePointer.stop(t))},onPointerOver:function(t){if(this.event=t,this.capture&&t.preventDefault(),"mouse"===t.pointerType||4===t.pointerType)this.input.mousePointer.withinGame=!0;else{var e=this.input.getPointerFromIdentifier(t.identifier);e&&(e.withinGame=!0)}this.input.mouse.mouseOverCallback&&this.input.mouse.mouseOverCallback.call(this.input.mouse.callbackContext,t)},stop:function(){var t=this.game.canvas;t.removeEventListener("MSPointerDown",this._onMSPointerDown,!1),t.removeEventListener("MSPointerMove",this._onMSPointerMove,!1),t.removeEventListener("MSPointerUp",this._onMSPointerUp,!1),t.removeEventListener("pointerdown",this._onMSPointerDown,!1),t.removeEventListener("pointermove",this._onMSPointerMove,!1),t.removeEventListener("pointerup",this._onMSPointerUp,!1),window.removeEventListener("MSPointerUp",this._onMSPointerUpGlobal,!0),t.removeEventListener("MSPointerOver",this._onMSPointerOver,!0),t.removeEventListener("MSPointerOut",this._onMSPointerOut,!0),window.removeEventListener("pointerup",this._onMSPointerUpGlobal,!0),t.removeEventListener("pointerover",this._onMSPointerOver,!0),t.removeEventListener("pointerout",this._onMSPointerOut,!0)}},n.MSPointer.prototype.constructor=n.MSPointer,/**
* @author Richard Davey <[email protected]>
* @author @karlmacklin <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.DeviceButton=function(t,e){this.parent=t,this.game=t.game,this.event=null,this.isDown=!1,this.isUp=!0,this.timeDown=0,this.timeUp=0,this.repeats=0,this.altKey=!1,this.shiftKey=!1,this.ctrlKey=!1,this.value=0,this.buttonCode=e,this.onDown=new n.Signal,this.onUp=new n.Signal,this.onFloat=new n.Signal},n.DeviceButton.prototype={start:function(t,e){this.isDown||(this.isDown=!0,this.isUp=!1,this.timeDown=this.game.time.time,this.repeats=0,this.event=t,this.value=e,t&&(this.altKey=t.altKey,this.shiftKey=t.shiftKey,this.ctrlKey=t.ctrlKey),this.onDown.dispatch(this,e))},stop:function(t,e){this.isUp||(this.isDown=!1,this.isUp=!0,this.timeUp=this.game.time.time,this.event=t,this.value=e,t&&(this.altKey=t.altKey,this.shiftKey=t.shiftKey,this.ctrlKey=t.ctrlKey),this.onUp.dispatch(this,e))},padFloat:function(t){this.value=t,this.onFloat.dispatch(this,t)},justPressed:function(t){return t=t||250,this.isDown&&this.timeDown+t>this.game.time.time},justReleased:function(t){return t=t||250,this.isUp&&this.timeUp+t>this.game.time.time},reset:function(){this.isDown=!1,this.isUp=!0,this.timeDown=this.game.time.time,this.repeats=0,this.altKey=!1,this.shiftKey=!1,this.ctrlKey=!1},destroy:function(){this.onDown.dispose(),this.onUp.dispose(),this.onFloat.dispose(),this.parent=null,this.game=null}},n.DeviceButton.prototype.constructor=n.DeviceButton,Object.defineProperty(n.DeviceButton.prototype,"duration",{get:function(){return this.isUp?-1:this.game.time.time-this.timeDown}}),/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Pointer=function(t,e,i){this.game=t,this.id=e,this.type=n.POINTER,this.exists=!0,this.identifier=0,this.pointerId=null,this.pointerMode=i||n.PointerMode.CURSOR|n.PointerMode.CONTACT,this.target=null,this.button=null,this.leftButton=new n.DeviceButton(this,n.Pointer.LEFT_BUTTON),this.middleButton=new n.DeviceButton(this,n.Pointer.MIDDLE_BUTTON),this.rightButton=new n.DeviceButton(this,n.Pointer.RIGHT_BUTTON),this.backButton=new n.DeviceButton(this,n.Pointer.BACK_BUTTON),this.forwardButton=new n.DeviceButton(this,n.Pointer.FORWARD_BUTTON),this.eraserButton=new n.DeviceButton(this,n.Pointer.ERASER_BUTTON),this._holdSent=!1,this._history=[],this._nextDrop=0,this._stateReset=!1,this.withinGame=!1,this.clientX=-1,this.clientY=-1,this.pageX=-1,this.pageY=-1,this.screenX=-1,this.screenY=-1,this.rawMovementX=0,this.rawMovementY=0,this.movementX=0,this.movementY=0,this.x=-1,this.y=-1,this.isMouse=0===e,this.isDown=!1,this.isUp=!0,this.timeDown=0,this.timeUp=0,this.previousTapTime=0,this.totalTouches=0,this.msSinceLastClick=Number.MAX_VALUE,this.targetObject=null,this.interactiveCandidates=[],this.active=!1,this.dirty=!1,this.position=new n.Point,this.positionDown=new n.Point,this.positionUp=new n.Point,this.circle=new n.Circle(0,0,44),this._clickTrampolines=null,this._trampolineTargetObject=null},n.Pointer.NO_BUTTON=0,n.Pointer.LEFT_BUTTON=1,n.Pointer.RIGHT_BUTTON=2,n.Pointer.MIDDLE_BUTTON=4,n.Pointer.BACK_BUTTON=8,n.Pointer.FORWARD_BUTTON=16,n.Pointer.ERASER_BUTTON=32,n.Pointer.prototype={resetButtons:function(){this.isDown=!1,this.isUp=!0,this.isMouse&&(this.leftButton.reset(),this.middleButton.reset(),this.rightButton.reset(),this.backButton.reset(),this.forwardButton.reset(),this.eraserButton.reset())},processButtonsDown:function(t,e){n.Pointer.LEFT_BUTTON&t&&this.leftButton.start(e),n.Pointer.RIGHT_BUTTON&t&&this.rightButton.start(e),n.Pointer.MIDDLE_BUTTON&t&&this.middleButton.start(e),n.Pointer.BACK_BUTTON&t&&this.backButton.start(e),n.Pointer.FORWARD_BUTTON&t&&this.forwardButton.start(e),n.Pointer.ERASER_BUTTON&t&&this.eraserButton.start(e)},processButtonsUp:function(t,e){t===n.Mouse.LEFT_BUTTON&&this.leftButton.stop(e),t===n.Mouse.RIGHT_BUTTON&&this.rightButton.stop(e),t===n.Mouse.MIDDLE_BUTTON&&this.middleButton.stop(e),t===n.Mouse.BACK_BUTTON&&this.backButton.stop(e),t===n.Mouse.FORWARD_BUTTON&&this.forwardButton.stop(e),5===t&&this.eraserButton.stop(e)},updateButtons:function(t){this.button=t.button;var e="down"===t.type.toLowerCase().substr(-4);void 0!==t.buttons?e?this.processButtonsDown(t.buttons,t):this.processButtonsUp(t.button,t):e?this.leftButton.start(t):(this.leftButton.stop(t),this.rightButton.stop(t)),1===t.buttons&&t.ctrlKey&&this.leftButton.isDown&&(this.leftButton.stop(t),this.rightButton.start(t)),this.isUp=!0,this.isDown=!1,(this.leftButton.isDown||this.rightButton.isDown||this.middleButton.isDown||this.backButton.isDown||this.forwardButton.isDown||this.eraserButton.isDown)&&(this.isUp=!1,this.isDown=!0)},start:function(t){var e=this.game.input;return t.pointerId&&(this.pointerId=t.pointerId),this.identifier=t.identifier,this.target=t.target,this.isMouse?this.updateButtons(t):(this.isDown=!0,this.isUp=!1),this.active=!0,this.withinGame=!0,this.dirty=!1,this._history=[],this._clickTrampolines=null,this._trampolineTargetObject=null,this.msSinceLastClick=this.game.time.time-this.timeDown,this.timeDown=this.game.time.time,this._holdSent=!1,this.move(t,!0),this.positionDown.setTo(this.x,this.y),(e.multiInputOverride===n.Input.MOUSE_OVERRIDES_TOUCH||e.multiInputOverride===n.Input.MOUSE_TOUCH_COMBINE||e.multiInputOverride===n.Input.TOUCH_OVERRIDES_MOUSE&&0===e.totalActivePointers)&&(e.x=this.x,e.y=this.y,e.position.setTo(this.x,this.y),e.onDown.dispatch(this,t),e.resetSpeed(this.x,this.y)),this._stateReset=!1,this.totalTouches++,null!==this.targetObject&&this.targetObject._touchedHandler(this),this},update:function(){var t=this.game.input;this.active&&(this.dirty&&(t.interactiveItems.total>0&&this.processInteractiveObjects(!1),this.dirty=!1),!1===this._holdSent&&this.duration>=t.holdRate&&((t.multiInputOverride===n.Input.MOUSE_OVERRIDES_TOUCH||t.multiInputOverride===n.Input.MOUSE_TOUCH_COMBINE||t.multiInputOverride===n.Input.TOUCH_OVERRIDES_MOUSE&&0===t.totalActivePointers)&&t.onHold.dispatch(this),this._holdSent=!0),t.recordPointerHistory&&this.game.time.time>=this._nextDrop&&(this._nextDrop=this.game.time.time+t.recordRate,this._history.push({x:this.position.x,y:this.position.y}),this._history.length>t.recordLimit&&this._history.shift()))},move:function(t,e){var i=this.game.input;if(!i.pollLocked){if(void 0===e&&(e=!1),void 0!==t.button&&(this.button=t.button),e&&this.isMouse&&this.updateButtons(t),this.clientX=t.clientX,this.clientY=t.clientY,this.pageX=t.pageX,this.pageY=t.pageY,this.screenX=t.screenX,this.screenY=t.screenY,this.isMouse&&i.mouse.locked&&!e&&(this.rawMovementX=t.movementX||t.mozMovementX||t.webkitMovementX||0,this.rawMovementY=t.movementY||t.mozMovementY||t.webkitMovementY||0,this.movementX+=this.rawMovementX,this.movementY+=this.rawMovementY),this.x=(this.pageX-this.game.scale.offset.x)*i.scale.x,this.y=(this.pageY-this.game.scale.offset.y)*i.scale.y,this.position.setTo(this.x,this.y),this.circle.x=this.x,this.circle.y=this.y,(i.multiInputOverride===n.Input.MOUSE_OVERRIDES_TOUCH||i.multiInputOverride===n.Input.MOUSE_TOUCH_COMBINE||i.multiInputOverride===n.Input.TOUCH_OVERRIDES_MOUSE&&0===i.totalActivePointers)&&(i.activePointer=this,i.x=this.x,i.y=this.y,i.position.setTo(i.x,i.y),i.circle.x=i.x,i.circle.y=i.y),this.withinGame=this.game.scale.bounds.contains(this.pageX,this.pageY),this.game.paused)return this;for(var s=i.moveCallbacks.length;s--;)i.moveCallbacks[s].callback.call(i.moveCallbacks[s].context,this,this.x,this.y,e);return null!==this.targetObject&&!0===this.targetObject.isDragged?!1===this.targetObject.update(this)&&(this.targetObject=null):i.interactiveItems.total>0&&this.processInteractiveObjects(e),this}},processInteractiveObjects:function(t){var e=0,i=-1,s=null,n=this.game.input.interactiveItems.first;for(this.interactiveCandidates=[];n;)n.checked=!1,n.validForInput(i,e,!1)&&(n.checked=!0,(t&&n.checkPointerDown(this,!0)||!t&&n.checkPointerOver(this,!0))&&(e=n.sprite.renderOrderID,i=n.priorityID,s=n,this.interactiveCandidates.push(n))),n=this.game.input.interactiveItems.next;for(n=this.game.input.interactiveItems.first;n;)!n.checked&&n.validForInput(i,e,!0)&&(t&&n.checkPointerDown(this,!1)||!t&&n.checkPointerOver(this,!1))&&(e=n.sprite.renderOrderID,i=n.priorityID,s=n,this.interactiveCandidates.push(n)),n=this.game.input.interactiveItems.next;return this.game.input.customCandidateHandler&&(s=this.game.input.customCandidateHandler.call(this.game.input.customCandidateHandlerContext,this,this.interactiveCandidates,s)),this.swapTarget(s,!1),null!==this.targetObject},swapTarget:function(t,e){void 0===e&&(e=!1),null===t?this.targetObject&&(this.targetObject._pointerOutHandler(this,e),this.targetObject=null):null===this.targetObject?(this.targetObject=t,t._pointerOverHandler(this,e)):this.targetObject===t?!1===t.update(this)&&(this.targetObject=null):(this.targetObject._pointerOutHandler(this,e),this.targetObject=t,this.targetObject._pointerOverHandler(this,e))},leave:function(t){this.withinGame=!1,this.move(t,!1)},stop:function(t){var e=this.game.input;return this._stateReset&&this.withinGame?void t.preventDefault():(this.timeUp=this.game.time.time,(e.multiInputOverride===n.Input.MOUSE_OVERRIDES_TOUCH||e.multiInputOverride===n.Input.MOUSE_TOUCH_COMBINE||e.multiInputOverride===n.Input.TOUCH_OVERRIDES_MOUSE&&0===e.totalActivePointers)&&(e.onUp.dispatch(this,t),this.duration>=0&&this.duration<=e.tapRate&&(this.timeUp-this.previousTapTime<e.doubleTapRate?e.onTap.dispatch(this,!0):e.onTap.dispatch(this,!1),this.previousTapTime=this.timeUp)),this.isMouse?this.updateButtons(t):(this.isDown=!1,this.isUp=!0),this.id>0&&(this.active=!1),this.withinGame=this.game.scale.bounds.contains(t.pageX,t.pageY),this.pointerId=null,this.identifier=null,this.positionUp.setTo(this.x,this.y),!1===this.isMouse&&e.currentPointers--,e.interactiveItems.callAll("_releasedHandler",this),this._clickTrampolines&&(this._trampolineTargetObject=this.targetObject),this.targetObject=null,this)},justPressed:function(t){return t=t||this.game.input.justPressedRate,!0===this.isDown&&this.timeDown+t>this.game.time.time},justReleased:function(t){return t=t||this.game.input.justReleasedRate,this.isUp&&this.timeUp+t>this.game.time.time},addClickTrampoline:function(t,e,i,s){if(this.isDown){for(var n=this._clickTrampolines=this._clickTrampolines||[],r=0;r<n.length;r++)if(n[r].name===t){n.splice(r,1);break}n.push({name:t,targetObject:this.targetObject,callback:e,callbackContext:i,callbackArgs:s})}},processClickTrampolines:function(){var t=this._clickTrampolines;if(t){for(var e=0;e<t.length;e++){var i=t[e];i.targetObject===this._trampolineTargetObject&&i.callback.apply(i.callbackContext,i.callbackArgs)}this._clickTrampolines=null,this._trampolineTargetObject=null}},reset:function(){!1===this.isMouse&&(this.active=!1),this.pointerId=null,this.identifier=null,this.dirty=!1,this.totalTouches=0,this._holdSent=!1,this._history.length=0,this._stateReset=!0,this.resetButtons(),this.targetObject&&this.targetObject._releasedHandler(this),this.targetObject=null},resetMovement:function(){this.movementX=0,this.movementY=0}},n.Pointer.prototype.constructor=n.Pointer,Object.defineProperty(n.Pointer.prototype,"duration",{get:function(){return this.isUp?-1:this.game.time.time-this.timeDown}}),Object.defineProperty(n.Pointer.prototype,"worldX",{get:function(){return this.game.world.camera.x+this.x}}),Object.defineProperty(n.Pointer.prototype,"worldY",{get:function(){return this.game.world.camera.y+this.y}}),n.PointerMode={CURSOR:1,CONTACT:2},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Touch=function(t){this.game=t,this.enabled=!0,this.touchLockCallbacks=[],this.callbackContext=this.game,this.touchStartCallback=null,this.touchMoveCallback=null,this.touchEndCallback=null,this.touchEnterCallback=null,this.touchLeaveCallback=null,this.touchCancelCallback=null,this.preventDefault=!0,this.event=null,this._onTouchStart=null,this._onTouchMove=null,this._onTouchEnd=null,this._onTouchEnter=null,this._onTouchLeave=null,this._onTouchCancel=null,this._onTouchMove=null},n.Touch.prototype={start:function(){if(null===this._onTouchStart){var t=this;this.game.device.touch&&(this._onTouchStart=function(e){return t.onTouchStart(e)},this._onTouchMove=function(e){return t.onTouchMove(e)},this._onTouchEnd=function(e){return t.onTouchEnd(e)},this._onTouchEnter=function(e){return t.onTouchEnter(e)},this._onTouchLeave=function(e){return t.onTouchLeave(e)},this._onTouchCancel=function(e){return t.onTouchCancel(e)},this.game.canvas.addEventListener("touchstart",this._onTouchStart,!1),this.game.canvas.addEventListener("touchmove",this._onTouchMove,!1),this.game.canvas.addEventListener("touchend",this._onTouchEnd,!1),this.game.canvas.addEventListener("touchcancel",this._onTouchCancel,!1),this.game.device.cocoonJS||(this.game.canvas.addEventListener("touchenter",this._onTouchEnter,!1),this.game.canvas.addEventListener("touchleave",this._onTouchLeave,!1)))}},consumeDocumentTouches:function(){this._documentTouchMove=function(t){t.preventDefault()},document.addEventListener("touchmove",this._documentTouchMove,!1)},addTouchLockCallback:function(t,e,i){void 0===i&&(i=!1),this.touchLockCallbacks.push({callback:t,context:e,onEnd:i})},removeTouchLockCallback:function(t,e){for(var i=this.touchLockCallbacks.length;i--;)if(this.touchLockCallbacks[i].callback===t&&this.touchLockCallbacks[i].context===e)return this.touchLockCallbacks.splice(i,1),!0;return!1},onTouchStart:function(t){for(var e=this.touchLockCallbacks.length;e--;){var i=this.touchLockCallbacks[e];!i.onEnd&&i.callback.call(i.context,this,t)&&this.touchLockCallbacks.splice(e,1)}if(this.event=t,this.game.input.enabled&&this.enabled){this.touchStartCallback&&this.touchStartCallback.call(this.callbackContext,t),this.preventDefault&&t.preventDefault();for(var e=0;e<t.changedTouches.length;e++)this.game.input.startPointer(t.changedTouches[e])}},onTouchCancel:function(t){if(this.event=t,this.touchCancelCallback&&this.touchCancelCallback.call(this.callbackContext,t),this.game.input.enabled&&this.enabled){this.preventDefault&&t.preventDefault();for(var e=0;e<t.changedTouches.length;e++)this.game.input.stopPointer(t.changedTouches[e])}},onTouchEnter:function(t){this.event=t,this.touchEnterCallback&&this.touchEnterCallback.call(this.callbackContext,t),this.game.input.enabled&&this.enabled&&this.preventDefault&&t.preventDefault()},onTouchLeave:function(t){this.event=t,this.touchLeaveCallback&&this.touchLeaveCallback.call(this.callbackContext,t),this.preventDefault&&t.preventDefault()},onTouchMove:function(t){this.event=t,this.touchMoveCallback&&this.touchMoveCallback.call(this.callbackContext,t),this.preventDefault&&t.preventDefault();for(var e=0;e<t.changedTouches.length;e++)this.game.input.updatePointer(t.changedTouches[e])},onTouchEnd:function(t){for(var e=this.touchLockCallbacks.length;e--;){var i=this.touchLockCallbacks[e];i.onEnd&&i.callback.call(i.context,this,t)&&this.touchLockCallbacks.splice(e,1)}this.event=t,this.touchEndCallback&&this.touchEndCallback.call(this.callbackContext,t),this.preventDefault&&t.preventDefault();for(var e=0;e<t.changedTouches.length;e++)this.game.input.stopPointer(t.changedTouches[e])},stop:function(){this.game.device.touch&&(this.game.canvas.removeEventListener("touchstart",this._onTouchStart),this.game.canvas.removeEventListener("touchmove",this._onTouchMove),this.game.canvas.removeEventListener("touchend",this._onTouchEnd),this.game.canvas.removeEventListener("touchenter",this._onTouchEnter),this.game.canvas.removeEventListener("touchleave",this._onTouchLeave),this.game.canvas.removeEventListener("touchcancel",this._onTouchCancel))}},n.Touch.prototype.constructor=n.Touch,/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.InputHandler=function(t){this.sprite=t,this.game=t.game,this.enabled=!1,this.checked=!1,this.priorityID=0,this.useHandCursor=!1,this._setHandCursor=!1,this.isDragged=!1,this.allowHorizontalDrag=!0,this.allowVerticalDrag=!0,this.bringToTop=!1,this.snapOffset=null,this.snapOnDrag=!1,this.snapOnRelease=!1,this.snapX=0,this.snapY=0,this.snapOffsetX=0,this.snapOffsetY=0,this.pixelPerfectOver=!1,this.pixelPerfectClick=!1,this.pixelPerfectAlpha=255,this.draggable=!1,this.boundsRect=null,this.boundsSprite=null,this.scaleLayer=!1,this.dragOffset=new n.Point,this.dragFromCenter=!1,this.dragStopBlocksInputUp=!1,this.dragStartPoint=new n.Point,this.dragDistanceThreshold=0,this.dragTimeThreshold=0,this.downPoint=new n.Point,this.snapPoint=new n.Point,this._dragPoint=new n.Point,this._dragPhase=!1,this._pendingDrag=!1,this._dragTimePass=!1,this._dragDistancePass=!1,this._wasEnabled=!1,this._tempPoint=new n.Point,this._pointerData=[],this._pointerData.push({id:0,x:0,y:0,camX:0,camY:0,isDown:!1,isUp:!1,isOver:!1,isOut:!1,timeOver:0,timeOut:0,timeDown:0,timeUp:0,downDuration:0,isDragged:!1})},n.InputHandler.prototype={start:function(t,e){if(t=t||0,void 0===e&&(e=!1),!1===this.enabled){this.game.input.interactiveItems.add(this),this.useHandCursor=e,this.priorityID=t;for(var i=0;i<10;i++)this._pointerData[i]={id:i,x:0,y:0,isDown:!1,isUp:!1,isOver:!1,isOut:!1,timeOver:0,timeOut:0,timeDown:0,timeUp:0,downDuration:0,isDragged:!1};this.snapOffset=new n.Point,this.enabled=!0,this._wasEnabled=!0}return this.sprite.events.onAddedToGroup.add(this.addedToGroup,this),this.sprite.events.onRemovedFromGroup.add(this.removedFromGroup,this),this.sprite},addedToGroup:function(){this._dragPhase||this._wasEnabled&&!this.enabled&&this.start()},removedFromGroup:function(){this._dragPhase||(this.enabled?(this._wasEnabled=!0,this.stop()):this._wasEnabled=!1)},reset:function(){this.enabled=!1;for(var t=0;t<10;t++)this._pointerData[t]={id:t,x:0,y:0,isDown:!1,isUp:!1,isOver:!1,isOut:!1,timeOver:0,timeOut:0,timeDown:0,timeUp:0,downDuration:0,isDragged:!1}},stop:function(){!1!==this.enabled&&(this.enabled=!1,this.game.input.interactiveItems.remove(this))},destroy:function(){this.sprite&&(this._setHandCursor&&(this.game.canvas.style.cursor="default",this._setHandCursor=!1),this.enabled=!1,this.game.input.interactiveItems.remove(this),this._pointerData.length=0,this.boundsRect=null,this.boundsSprite=null,this.sprite=null)},validForInput:function(t,e,i){return void 0===i&&(i=!0),!(!this.enabled||0===this.sprite.scale.x||0===this.sprite.scale.y||this.priorityID<this.game.input.minPriorityID||this.sprite.parent&&this.sprite.parent.ignoreChildInput)&&(!(!i&&(this.pixelPerfectClick||this.pixelPerfectOver))&&(this.priorityID>t||this.priorityID===t&&this.sprite.renderOrderID>e))},isPixelPerfect:function(){return this.pixelPerfectClick||this.pixelPerfectOver},pointerX:function(t){return t=t||0,this._pointerData[t].x},pointerY:function(t){return t=t||0,this._pointerData[t].y},pointerDown:function(t){return t=t||0,this._pointerData[t].isDown},pointerUp:function(t){return t=t||0,this._pointerData[t].isUp},pointerTimeDown:function(t){return t=t||0,this._pointerData[t].timeDown},pointerTimeUp:function(t){return t=t||0,this._pointerData[t].timeUp},pointerOver:function(t){if(!this.enabled)return!1;if(void 0===t){for(var e=0;e<10;e++)if(this._pointerData[e].isOver)return!0;return!1}return this._pointerData[t].isOver},pointerOut:function(t){if(!this.enabled)return!1;if(void 0!==t)return this._pointerData[t].isOut;for(var e=0;e<10;e++)if(this._pointerData[e].isOut)return!0},pointerTimeOver:function(t){return t=t||0,this._pointerData[t].timeOver},pointerTimeOut:function(t){return t=t||0,this._pointerData[t].timeOut},pointerDragged:function(t){return t=t||0,this._pointerData[t].isDragged},checkPointerDown:function(t,e){return!!(t.isDown&&this.enabled&&this.sprite&&this.sprite.parent&&this.sprite.visible&&this.sprite.parent.visible&&0!==this.sprite.worldScale.x&&0!==this.sprite.worldScale.y)&&(!!this.game.input.hitTest(this.sprite,t,this._tempPoint)&&(void 0===e&&(e=!1),!(!e&&this.pixelPerfectClick)||this.checkPixel(this._tempPoint.x,this._tempPoint.y)))},checkPointerOver:function(t,e){return!!(this.enabled&&this.sprite&&this.sprite.parent&&this.sprite.visible&&this.sprite.parent.visible&&0!==this.sprite.worldScale.x&&0!==this.sprite.worldScale.y)&&(!!this.game.input.hitTest(this.sprite,t,this._tempPoint)&&(void 0===e&&(e=!1),!(!e&&this.pixelPerfectOver)||this.checkPixel(this._tempPoint.x,this._tempPoint.y)))},checkPixel:function(t,e,i){if(this.sprite.texture.baseTexture.source){if(null===t&&null===e){this.game.input.getLocalPosition(this.sprite,i,this._tempPoint);var t=this._tempPoint.x,e=this._tempPoint.y}if(0!==this.sprite.anchor.x&&(t-=-this.sprite.texture.frame.width*this.sprite.anchor.x),0!==this.sprite.anchor.y&&(e-=-this.sprite.texture.frame.height*this.sprite.anchor.y),t+=this.sprite.texture.frame.x,e+=this.sprite.texture.frame.y,this.sprite.texture.trim&&(t-=this.sprite.texture.trim.x,e-=this.sprite.texture.trim.y,t<this.sprite.texture.crop.x||t>this.sprite.texture.crop.right||e<this.sprite.texture.crop.y||e>this.sprite.texture.crop.bottom))return this._dx=t,this._dy=e,!1;this._dx=t,this._dy=e,this.game.input.hitContext.clearRect(0,0,1,1),this.game.input.hitContext.drawImage(this.sprite.texture.baseTexture.source,t,e,1,1,0,0,1,1);if(this.game.input.hitContext.getImageData(0,0,1,1).data[3]>=this.pixelPerfectAlpha)return!0}return!1},update:function(t){if(null!==this.sprite&&void 0!==this.sprite.parent)return this.enabled&&this.sprite.visible&&this.sprite.parent.visible?this._pendingDrag?(this._dragDistancePass||(this._dragDistancePass=n.Math.distance(t.x,t.y,this.downPoint.x,this.downPoint.y)>=this.dragDistanceThreshold),this._dragDistancePass&&this._dragTimePass&&this.startDrag(t),!0):this.draggable&&this._draggedPointerID===t.id?this.updateDrag(t,!1):this._pointerData[t.id].isOver?this.checkPointerOver(t)?(this._pointerData[t.id].x=t.x-this.sprite.x,this._pointerData[t.id].y=t.y-this.sprite.y,!0):(this._pointerOutHandler(t),!1):void 0:(this._pointerOutHandler(t),!1)},_pointerOverHandler:function(t,e){if(null!==this.sprite){var i=this._pointerData[t.id];if(!1===i.isOver||t.dirty){var s=!1===i.isOver;i.isOver=!0,i.isOut=!1,i.timeOver=this.game.time.time,i.x=t.x-this.sprite.x,i.y=t.y-this.sprite.y,this.useHandCursor&&!1===i.isDragged&&(this.game.canvas.style.cursor="pointer",this._setHandCursor=!0),!e&&s&&this.sprite&&this.sprite.events&&this.sprite.events.onInputOver$dispatch(this.sprite,t),this.sprite.parent&&this.sprite.parent.type===n.GROUP&&this.sprite.parent.onChildInputOver.dispatch(this.sprite,t)}}},_pointerOutHandler:function(t,e){if(null!==this.sprite){var i=this._pointerData[t.id];i.isOver=!1,i.isOut=!0,i.timeOut=this.game.time.time,this.useHandCursor&&!1===i.isDragged&&(this.game.canvas.style.cursor="default",this._setHandCursor=!1),!e&&this.sprite&&this.sprite.events&&(this.sprite.events.onInputOut$dispatch(this.sprite,t),this.sprite&&this.sprite.parent&&this.sprite.parent.type===n.GROUP&&this.sprite.parent.onChildInputOut.dispatch(this.sprite,t))}},_touchedHandler:function(t){if(null!==this.sprite){var e=this._pointerData[t.id];if(!e.isDown&&e.isOver){if(this.pixelPerfectClick&&!this.checkPixel(null,null,t))return;if(e.isDown=!0,e.isUp=!1,e.timeDown=this.game.time.time,this.downPoint.set(t.x,t.y),t.dirty=!0,this.sprite&&this.sprite.events&&(this.sprite.events.onInputDown$dispatch(this.sprite,t),this.sprite&&this.sprite.parent&&this.sprite.parent.type===n.GROUP&&this.sprite.parent.onChildInputDown.dispatch(this.sprite,t),null===this.sprite))return;this.draggable&&!1===this.isDragged&&(0===this.dragTimeThreshold&&0===this.dragDistanceThreshold?this.startDrag(t):(this._pendingDrag=!0,this._dragDistancePass=0===this.dragDistanceThreshold,this.dragTimeThreshold>0?(this._dragTimePass=!1,this.game.time.events.add(this.dragTimeThreshold,this.dragTimeElapsed,this,t)):this._dragTimePass=!0)),this.bringToTop&&this.sprite.bringToTop()}}},dragTimeElapsed:function(t){this._dragTimePass=!0,this._pendingDrag&&this.sprite&&this._dragDistancePass&&this.startDrag(t)},_releasedHandler:function(t){if(null!==this.sprite){var e=this._pointerData[t.id];if(e.isDown&&t.isUp){e.isDown=!1,e.isUp=!0,e.timeUp=this.game.time.time,e.downDuration=e.timeUp-e.timeDown;var i=this.checkPointerOver(t);this.sprite&&this.sprite.events&&(this.dragStopBlocksInputUp&&(!this.dragStopBlocksInputUp||this.draggable&&this.isDragged&&this._draggedPointerID===t.id)||this.sprite.events.onInputUp$dispatch(this.sprite,t,i),this.sprite&&this.sprite.parent&&this.sprite.parent.type===n.GROUP&&this.sprite.parent.onChildInputUp.dispatch(this.sprite,t,i),i&&(i=this.checkPointerOver(t))),e.isOver=i,!i&&this.useHandCursor&&(this.game.canvas.style.cursor="default",this._setHandCursor=!1),t.dirty=!0,this._pendingDrag=!1,this.draggable&&this.isDragged&&this._draggedPointerID===t.id&&this.stopDrag(t)}}},updateDrag:function(t,e){if(void 0===e&&(e=!1),t.isUp)return this.stopDrag(t),!1;var i=this.globalToLocalX(t.x)+this._dragPoint.x+this.dragOffset.x,s=this.globalToLocalY(t.y)+this._dragPoint.y+this.dragOffset.y;if(this.sprite.fixedToCamera)this.allowHorizontalDrag&&(this.sprite.cameraOffset.x=i),this.allowVerticalDrag&&(this.sprite.cameraOffset.y=s),this.boundsRect&&this.checkBoundsRect(),this.boundsSprite&&this.checkBoundsSprite(),this.snapOnDrag&&(this.sprite.cameraOffset.x=Math.round((this.sprite.cameraOffset.x-this.snapOffsetX%this.snapX)/this.snapX)*this.snapX+this.snapOffsetX%this.snapX,this.sprite.cameraOffset.y=Math.round((this.sprite.cameraOffset.y-this.snapOffsetY%this.snapY)/this.snapY)*this.snapY+this.snapOffsetY%this.snapY,this.snapPoint.set(this.sprite.cameraOffset.x,this.sprite.cameraOffset.y));else{var n=this.game.camera.x-this._pointerData[t.id].camX,r=this.game.camera.y-this._pointerData[t.id].camY;this.allowHorizontalDrag&&(this.sprite.x=i+n),this.allowVerticalDrag&&(this.sprite.y=s+r),this.boundsRect&&this.checkBoundsRect(),this.boundsSprite&&this.checkBoundsSprite(),this.snapOnDrag&&(this.sprite.x=Math.round((this.sprite.x-this.snapOffsetX%this.snapX)/this.snapX)*this.snapX+this.snapOffsetX%this.snapX,this.sprite.y=Math.round((this.sprite.y-this.snapOffsetY%this.snapY)/this.snapY)*this.snapY+this.snapOffsetY%this.snapY,this.snapPoint.set(this.sprite.x,this.sprite.y))}return this.sprite.events.onDragUpdate.dispatch(this.sprite,t,i,s,this.snapPoint,e),!0},justOver:function(t,e){return t=t||0,e=e||500,this._pointerData[t].isOver&&this.overDuration(t)<e},justOut:function(t,e){return t=t||0,e=e||500,this._pointerData[t].isOut&&this.game.time.time-this._pointerData[t].timeOut<e},justPressed:function(t,e){return t=t||0,e=e||500,this._pointerData[t].isDown&&this.downDuration(t)<e},justReleased:function(t,e){return t=t||0,e=e||500,this._pointerData[t].isUp&&this.game.time.time-this._pointerData[t].timeUp<e},overDuration:function(t){return t=t||0,this._pointerData[t].isOver?this.game.time.time-this._pointerData[t].timeOver:-1},downDuration:function(t){return t=t||0,this._pointerData[t].isDown?this.game.time.time-this._pointerData[t].timeDown:-1},enableDrag:function(t,e,i,s,r,o){void 0===t&&(t=!1),void 0===e&&(e=!1),void 0===i&&(i=!1),void 0===s&&(s=255),void 0===r&&(r=null),void 0===o&&(o=null),this._dragPoint=new n.Point,this.draggable=!0,this.bringToTop=e,this.dragOffset=new n.Point,this.dragFromCenter=t,this.pixelPerfectClick=i,this.pixelPerfectAlpha=s,r&&(this.boundsRect=r),o&&(this.boundsSprite=o)},disableDrag:function(){if(this._pointerData)for(var t=0;t<10;t++)this._pointerData[t].isDragged=!1;this.draggable=!1,this.isDragged=!1,this._draggedPointerID=-1,this._pendingDrag=!1},startDrag:function(t){var e=this.sprite.x,i=this.sprite.y;if(this.isDragged=!0,this._draggedPointerID=t.id,this._pointerData[t.id].camX=this.game.camera.x,this._pointerData[t.id].camY=this.game.camera.y,this._pointerData[t.id].isDragged=!0,this.sprite.fixedToCamera){if(this.dragFromCenter){var s=this.sprite.getBounds();this.sprite.cameraOffset.x=this.globalToLocalX(t.x)+(this.sprite.cameraOffset.x-s.centerX),this.sprite.cameraOffset.y=this.globalToLocalY(t.y)+(this.sprite.cameraOffset.y-s.centerY)}this._dragPoint.setTo(this.sprite.cameraOffset.x-t.x,this.sprite.cameraOffset.y-t.y)}else{if(this.dragFromCenter){var s=this.sprite.getBounds();this.sprite.x=this.globalToLocalX(t.x)+(this.sprite.x-s.centerX),this.sprite.y=this.globalToLocalY(t.y)+(this.sprite.y-s.centerY)}this._dragPoint.setTo(this.sprite.x-this.globalToLocalX(t.x),this.sprite.y-this.globalToLocalY(t.y))}this.updateDrag(t,!0),this.bringToTop&&(this._dragPhase=!0,this.sprite.bringToTop()),this.dragStartPoint.set(e,i),this.sprite.events.onDragStart$dispatch(this.sprite,t,e,i),this._pendingDrag=!1},globalToLocalX:function(t){return this.scaleLayer&&(t-=this.game.scale.grid.boundsFluid.x,t*=this.game.scale.grid.scaleFluidInversed.x),t},globalToLocalY:function(t){return this.scaleLayer&&(t-=this.game.scale.grid.boundsFluid.y,t*=this.game.scale.grid.scaleFluidInversed.y),t},stopDrag:function(t){this.isDragged=!1,this._draggedPointerID=-1,this._pointerData[t.id].isDragged=!1,this._dragPhase=!1,this._pendingDrag=!1,this.snapOnRelease&&(this.sprite.fixedToCamera?(this.sprite.cameraOffset.x=Math.round((this.sprite.cameraOffset.x-this.snapOffsetX%this.snapX)/this.snapX)*this.snapX+this.snapOffsetX%this.snapX,this.sprite.cameraOffset.y=Math.round((this.sprite.cameraOffset.y-this.snapOffsetY%this.snapY)/this.snapY)*this.snapY+this.snapOffsetY%this.snapY):(this.sprite.x=Math.round((this.sprite.x-this.snapOffsetX%this.snapX)/this.snapX)*this.snapX+this.snapOffsetX%this.snapX,this.sprite.y=Math.round((this.sprite.y-this.snapOffsetY%this.snapY)/this.snapY)*this.snapY+this.snapOffsetY%this.snapY)),this.sprite.events.onDragStop$dispatch(this.sprite,t),!1===this.checkPointerOver(t)&&this._pointerOutHandler(t)},setDragLock:function(t,e){void 0===t&&(t=!0),void 0===e&&(e=!0),this.allowHorizontalDrag=t,this.allowVerticalDrag=e},enableSnap:function(t,e,i,s,n,r){void 0===i&&(i=!0),void 0===s&&(s=!1),void 0===n&&(n=0),void 0===r&&(r=0),this.snapX=t,this.snapY=e,this.snapOffsetX=n,this.snapOffsetY=r,this.snapOnDrag=i,this.snapOnRelease=s},disableSnap:function(){this.snapOnDrag=!1,this.snapOnRelease=!1},checkBoundsRect:function(){this.sprite.fixedToCamera?(this.sprite.cameraOffset.x<this.boundsRect.left?this.sprite.cameraOffset.x=this.boundsRect.left:this.sprite.cameraOffset.x+this.sprite.width>this.boundsRect.right&&(this.sprite.cameraOffset.x=this.boundsRect.right-this.sprite.width),this.sprite.cameraOffset.y<this.boundsRect.top?this.sprite.cameraOffset.y=this.boundsRect.top:this.sprite.cameraOffset.y+this.sprite.height>this.boundsRect.bottom&&(this.sprite.cameraOffset.y=this.boundsRect.bottom-this.sprite.height)):(this.sprite.left<this.boundsRect.left?this.sprite.x=this.boundsRect.x+this.sprite.offsetX:this.sprite.right>this.boundsRect.right&&(this.sprite.x=this.boundsRect.right-(this.sprite.width-this.sprite.offsetX)),this.sprite.top<this.boundsRect.top?this.sprite.y=this.boundsRect.top+this.sprite.offsetY:this.sprite.bottom>this.boundsRect.bottom&&(this.sprite.y=this.boundsRect.bottom-(this.sprite.height-this.sprite.offsetY)))},checkBoundsSprite:function(){this.sprite.fixedToCamera&&this.boundsSprite.fixedToCamera?(this.sprite.cameraOffset.x<this.boundsSprite.cameraOffset.x?this.sprite.cameraOffset.x=this.boundsSprite.cameraOffset.x:this.sprite.cameraOffset.x+this.sprite.width>this.boundsSprite.cameraOffset.x+this.boundsSprite.width&&(this.sprite.cameraOffset.x=this.boundsSprite.cameraOffset.x+this.boundsSprite.width-this.sprite.width),this.sprite.cameraOffset.y<this.boundsSprite.cameraOffset.y?this.sprite.cameraOffset.y=this.boundsSprite.cameraOffset.y:this.sprite.cameraOffset.y+this.sprite.height>this.boundsSprite.cameraOffset.y+this.boundsSprite.height&&(this.sprite.cameraOffset.y=this.boundsSprite.cameraOffset.y+this.boundsSprite.height-this.sprite.height)):(this.sprite.left<this.boundsSprite.left?this.sprite.x=this.boundsSprite.left+this.sprite.offsetX:this.sprite.right>this.boundsSprite.right&&(this.sprite.x=this.boundsSprite.right-(this.sprite.width-this.sprite.offsetX)),this.sprite.top<this.boundsSprite.top?this.sprite.y=this.boundsSprite.top+this.sprite.offsetY:this.sprite.bottom>this.boundsSprite.bottom&&(this.sprite.y=this.boundsSprite.bottom-(this.sprite.height-this.sprite.offsetY)))}},n.InputHandler.prototype.constructor=n.InputHandler,/**
* @author @karlmacklin <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Gamepad=function(t){this.game=t,this._gamepadIndexMap={},this._rawPads=[],this._active=!1,this.enabled=!0,this._gamepadSupportAvailable=!!navigator.webkitGetGamepads||!!navigator.webkitGamepads||-1!==navigator.userAgent.indexOf("Firefox/")||!!navigator.getGamepads,this._prevRawGamepadTypes=[],this._prevTimestamps=[],this.callbackContext=this,this.onConnectCallback=null,this.onDisconnectCallback=null,this.onDownCallback=null,this.onUpCallback=null,this.onAxisCallback=null,this.onFloatCallback=null,this._ongamepadconnected=null,this._gamepaddisconnected=null,this._gamepads=[new n.SinglePad(t,this),new n.SinglePad(t,this),new n.SinglePad(t,this),new n.SinglePad(t,this)]},n.Gamepad.prototype={addCallbacks:function(t,e){void 0!==e&&(this.onConnectCallback="function"==typeof e.onConnect?e.onConnect:this.onConnectCallback,this.onDisconnectCallback="function"==typeof e.onDisconnect?e.onDisconnect:this.onDisconnectCallback,this.onDownCallback="function"==typeof e.onDown?e.onDown:this.onDownCallback,this.onUpCallback="function"==typeof e.onUp?e.onUp:this.onUpCallback,this.onAxisCallback="function"==typeof e.onAxis?e.onAxis:this.onAxisCallback,this.onFloatCallback="function"==typeof e.onFloat?e.onFloat:this.onFloatCallback,this.callbackContext=t)},start:function(){if(!this._active){this._active=!0;var t=this;this._onGamepadConnected=function(e){return t.onGamepadConnected(e)},this._onGamepadDisconnected=function(e){return t.onGamepadDisconnected(e)},window.addEventListener("gamepadconnected",this._onGamepadConnected,!1),window.addEventListener("gamepaddisconnected",this._onGamepadDisconnected,!1)}},onGamepadConnected:function(t){var e=t.gamepad;this._rawPads.push(e),this._gamepads[e.index].connect(e)},onGamepadDisconnected:function(t){var e=t.gamepad;for(var i in this._rawPads)this._rawPads[i].index===e.index&&this._rawPads.splice(i,1);this._gamepads[e.index].disconnect()},update:function(){this._pollGamepads(),this.pad1.pollStatus(),this.pad2.pollStatus(),this.pad3.pollStatus(),this.pad4.pollStatus()},_pollGamepads:function(){if(this._active){if(navigator.getGamepads)var t=navigator.getGamepads();else if(navigator.webkitGetGamepads)var t=navigator.webkitGetGamepads();else if(navigator.webkitGamepads)var t=navigator.webkitGamepads();if(t){this._rawPads=[];for(var e=!1,i=0;i<t.length&&(typeof t[i]!==this._prevRawGamepadTypes[i]&&(e=!0,this._prevRawGamepadTypes[i]=typeof t[i]),t[i]&&this._rawPads.push(t[i]),3!==i);i++);for(var s=0;s<this._gamepads.length;s++)this._gamepads[s]._rawPad=this._rawPads[s];if(e){for(var n,r={rawIndices:{},padIndices:{}},o=0;o<this._gamepads.length;o++)if(n=this._gamepads[o],n.connected)for(var a=0;a<this._rawPads.length;a++)this._rawPads[a].index===n.index&&(r.rawIndices[n.index]=!0,r.padIndices[o]=!0);for(var h=0;h<this._gamepads.length;h++)if(n=this._gamepads[h],!r.padIndices[h]){this._rawPads.length<1&&n.disconnect();for(var l=0;l<this._rawPads.length&&!r.padIndices[h];l++){var c=this._rawPads[l];if(c){if(r.rawIndices[c.index]){n.disconnect();continue}n.connect(c),r.rawIndices[c.index]=!0,r.padIndices[h]=!0}else n.disconnect()}}}}}},setDeadZones:function(t){for(var e=0;e<this._gamepads.length;e++)this._gamepads[e].deadZone=t},stop:function(){this._active=!1,window.removeEventListener("gamepadconnected",this._onGamepadConnected),window.removeEventListener("gamepaddisconnected",this._onGamepadDisconnected)},reset:function(){this.update();for(var t=0;t<this._gamepads.length;t++)this._gamepads[t].reset()},justPressed:function(t,e){for(var i=0;i<this._gamepads.length;i++)if(!0===this._gamepads[i].justPressed(t,e))return!0;return!1},justReleased:function(t,e){for(var i=0;i<this._gamepads.length;i++)if(!0===this._gamepads[i].justReleased(t,e))return!0;return!1},isDown:function(t){for(var e=0;e<this._gamepads.length;e++)if(!0===this._gamepads[e].isDown(t))return!0;return!1},destroy:function(){this.stop();for(var t=0;t<this._gamepads.length;t++)this._gamepads[t].destroy()}},n.Gamepad.prototype.constructor=n.Gamepad,Object.defineProperty(n.Gamepad.prototype,"active",{get:function(){return this._active}}),Object.defineProperty(n.Gamepad.prototype,"supported",{get:function(){return this._gamepadSupportAvailable}}),Object.defineProperty(n.Gamepad.prototype,"padsConnected",{get:function(){return this._rawPads.length}}),Object.defineProperty(n.Gamepad.prototype,"pad1",{get:function(){return this._gamepads[0]}}),Object.defineProperty(n.Gamepad.prototype,"pad2",{get:function(){return this._gamepads[1]}}),Object.defineProperty(n.Gamepad.prototype,"pad3",{get:function(){return this._gamepads[2]}}),Object.defineProperty(n.Gamepad.prototype,"pad4",{get:function(){return this._gamepads[3]}}),n.Gamepad.BUTTON_0=0,n.Gamepad.BUTTON_1=1,n.Gamepad.BUTTON_2=2,n.Gamepad.BUTTON_3=3,n.Gamepad.BUTTON_4=4,n.Gamepad.BUTTON_5=5,n.Gamepad.BUTTON_6=6,n.Gamepad.BUTTON_7=7,n.Gamepad.BUTTON_8=8,n.Gamepad.BUTTON_9=9,n.Gamepad.BUTTON_10=10,n.Gamepad.BUTTON_11=11,n.Gamepad.BUTTON_12=12,n.Gamepad.BUTTON_13=13,n.Gamepad.BUTTON_14=14,n.Gamepad.BUTTON_15=15,n.Gamepad.AXIS_0=0,n.Gamepad.AXIS_1=1,n.Gamepad.AXIS_2=2,n.Gamepad.AXIS_3=3,n.Gamepad.AXIS_4=4,n.Gamepad.AXIS_5=5,n.Gamepad.AXIS_6=6,n.Gamepad.AXIS_7=7,n.Gamepad.AXIS_8=8,n.Gamepad.AXIS_9=9,n.Gamepad.XBOX360_A=0,n.Gamepad.XBOX360_B=1,n.Gamepad.XBOX360_X=2,n.Gamepad.XBOX360_Y=3,n.Gamepad.XBOX360_LEFT_BUMPER=4,n.Gamepad.XBOX360_RIGHT_BUMPER=5,n.Gamepad.XBOX360_LEFT_TRIGGER=6,n.Gamepad.XBOX360_RIGHT_TRIGGER=7,n.Gamepad.XBOX360_BACK=8,n.Gamepad.XBOX360_START=9,n.Gamepad.XBOX360_STICK_LEFT_BUTTON=10,n.Gamepad.XBOX360_STICK_RIGHT_BUTTON=11,n.Gamepad.XBOX360_DPAD_LEFT=14,n.Gamepad.XBOX360_DPAD_RIGHT=15,n.Gamepad.XBOX360_DPAD_UP=12,n.Gamepad.XBOX360_DPAD_DOWN=13,n.Gamepad.XBOX360_STICK_LEFT_X=0,n.Gamepad.XBOX360_STICK_LEFT_Y=1,n.Gamepad.XBOX360_STICK_RIGHT_X=2,n.Gamepad.XBOX360_STICK_RIGHT_Y=3,n.Gamepad.PS3XC_X=0,n.Gamepad.PS3XC_CIRCLE=1;n.Gamepad.PS3XC_SQUARE=2,n.Gamepad.PS3XC_TRIANGLE=3,n.Gamepad.PS3XC_L1=4,n.Gamepad.PS3XC_R1=5,n.Gamepad.PS3XC_L2=6,n.Gamepad.PS3XC_R2=7,n.Gamepad.PS3XC_SELECT=8,n.Gamepad.PS3XC_START=9,n.Gamepad.PS3XC_STICK_LEFT_BUTTON=10,n.Gamepad.PS3XC_STICK_RIGHT_BUTTON=11,n.Gamepad.PS3XC_DPAD_UP=12,n.Gamepad.PS3XC_DPAD_DOWN=13,n.Gamepad.PS3XC_DPAD_LEFT=14,n.Gamepad.PS3XC_DPAD_RIGHT=15,n.Gamepad.PS3XC_STICK_LEFT_X=0,n.Gamepad.PS3XC_STICK_LEFT_Y=1,n.Gamepad.PS3XC_STICK_RIGHT_X=2,n.Gamepad.PS3XC_STICK_RIGHT_Y=3,/**
* @author @karlmacklin <[email protected]>
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.SinglePad=function(t,e){this.game=t,this.index=null,this.connected=!1,this.callbackContext=this,this.onConnectCallback=null,this.onDisconnectCallback=null,this.onDownCallback=null,this.onUpCallback=null,this.onAxisCallback=null,this.onFloatCallback=null,this.deadZone=.26,this._padParent=e,this._rawPad=null,this._prevTimestamp=null,this._buttons=[],this._buttonsLen=0,this._axes=[],this._axesLen=0},n.SinglePad.prototype={addCallbacks:function(t,e){void 0!==e&&(this.onConnectCallback="function"==typeof e.onConnect?e.onConnect:this.onConnectCallback,this.onDisconnectCallback="function"==typeof e.onDisconnect?e.onDisconnect:this.onDisconnectCallback,this.onDownCallback="function"==typeof e.onDown?e.onDown:this.onDownCallback,this.onUpCallback="function"==typeof e.onUp?e.onUp:this.onUpCallback,this.onAxisCallback="function"==typeof e.onAxis?e.onAxis:this.onAxisCallback,this.onFloatCallback="function"==typeof e.onFloat?e.onFloat:this.onFloatCallback,this.callbackContext=t)},getButton:function(t){return this._buttons[t]?this._buttons[t]:null},pollStatus:function(){if(this.connected&&this.game.input.enabled&&this.game.input.gamepad.enabled&&(!this._rawPad.timestamp||this._rawPad.timestamp!==this._prevTimestamp)){for(var t=0;t<this._buttonsLen;t++){var e=isNaN(this._rawPad.buttons[t])?this._rawPad.buttons[t].value:this._rawPad.buttons[t];e!==this._buttons[t].value&&(1===e?this.processButtonDown(t,e):0===e?this.processButtonUp(t,e):this.processButtonFloat(t,e))}for(var i=0;i<this._axesLen;i++){var s=this._rawPad.axes[i];s>0&&s>this.deadZone||s<0&&s<-this.deadZone?this.processAxisChange(i,s):this.processAxisChange(i,0)}this._prevTimestamp=this._rawPad.timestamp}},connect:function(t){var e=!this.connected;this.connected=!0,this.index=t.index,this._rawPad=t,this._buttons=[],this._buttonsLen=t.buttons.length,this._axes=[],this._axesLen=t.axes.length;for(var i=0;i<this._axesLen;i++)this._axes[i]=t.axes[i];for(var s in t.buttons)s=parseInt(s,10),this._buttons[s]=new n.DeviceButton(this,s);e&&this._padParent.onConnectCallback&&this._padParent.onConnectCallback.call(this._padParent.callbackContext,this.index),e&&this.onConnectCallback&&this.onConnectCallback.call(this.callbackContext)},disconnect:function(){var t=this.connected,e=this.index;this.connected=!1,this.index=null,this._rawPad=void 0;for(var i=0;i<this._buttonsLen;i++)this._buttons[i].destroy();this._buttons=[],this._buttonsLen=0,this._axes=[],this._axesLen=0,t&&this._padParent.onDisconnectCallback&&this._padParent.onDisconnectCallback.call(this._padParent.callbackContext,e),t&&this.onDisconnectCallback&&this.onDisconnectCallback.call(this.callbackContext)},destroy:function(){this._rawPad=void 0;for(var t=0;t<this._buttonsLen;t++)this._buttons[t].destroy();this._buttons=[],this._buttonsLen=0,this._axes=[],this._axesLen=0,this.onConnectCallback=null,this.onDisconnectCallback=null,this.onDownCallback=null,this.onUpCallback=null,this.onAxisCallback=null,this.onFloatCallback=null},processAxisChange:function(t,e){this._axes[t]!==e&&(this._axes[t]=e,this._padParent.onAxisCallback&&this._padParent.onAxisCallback.call(this._padParent.callbackContext,this,t,e),this.onAxisCallback&&this.onAxisCallback.call(this.callbackContext,this,t,e))},processButtonDown:function(t,e){this._buttons[t]&&this._buttons[t].start(null,e),this._padParent.onDownCallback&&this._padParent.onDownCallback.call(this._padParent.callbackContext,t,e,this.index),this.onDownCallback&&this.onDownCallback.call(this.callbackContext,t,e)},processButtonUp:function(t,e){this._padParent.onUpCallback&&this._padParent.onUpCallback.call(this._padParent.callbackContext,t,e,this.index),this.onUpCallback&&this.onUpCallback.call(this.callbackContext,t,e),this._buttons[t]&&this._buttons[t].stop(null,e)},processButtonFloat:function(t,e){this._padParent.onFloatCallback&&this._padParent.onFloatCallback.call(this._padParent.callbackContext,t,e,this.index),this.onFloatCallback&&this.onFloatCallback.call(this.callbackContext,t,e),this._buttons[t]&&this._buttons[t].padFloat(e)},axis:function(t){return!!this._axes[t]&&this._axes[t]},isDown:function(t){return!!this._buttons[t]&&this._buttons[t].isDown},isUp:function(t){return!!this._buttons[t]&&this._buttons[t].isUp},justReleased:function(t,e){if(this._buttons[t])return this._buttons[t].justReleased(e)},justPressed:function(t,e){if(this._buttons[t])return this._buttons[t].justPressed(e)},buttonValue:function(t){return this._buttons[t]?this._buttons[t].value:null},reset:function(){for(var t=0;t<this._axes.length;t++)this._axes[t]=0}},n.SinglePad.prototype.constructor=n.SinglePad,/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Key=function(t,e){this.game=t,this._enabled=!0,this.event=null,this.isDown=!1,this.isUp=!0,this.altKey=!1,this.ctrlKey=!1,this.shiftKey=!1,this.timeDown=0,this.duration=0,this.timeUp=-2500,this.repeats=0,this.keyCode=e,this.onDown=new n.Signal,this.onHoldCallback=null,this.onHoldContext=null,this.onUp=new n.Signal,this._justDown=!1,this._justUp=!1},n.Key.prototype={update:function(){this._enabled&&this.isDown&&(this.duration=this.game.time.time-this.timeDown,this.repeats++,this.onHoldCallback&&this.onHoldCallback.call(this.onHoldContext,this))},processKeyDown:function(t){this._enabled&&(this.event=t,this.isDown||(this.altKey=t.altKey,this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.isDown=!0,this.isUp=!1,this.timeDown=this.game.time.time,this.duration=0,this.repeats=0,this._justDown=!0,this.onDown.dispatch(this)))},processKeyUp:function(t){this._enabled&&(this.event=t,this.isUp||(this.isDown=!1,this.isUp=!0,this.timeUp=this.game.time.time,this.duration=this.game.time.time-this.timeDown,this._justUp=!0,this.onUp.dispatch(this)))},reset:function(t){void 0===t&&(t=!0),this.isDown=!1,this.isUp=!0,this.timeUp=this.game.time.time,this.duration=0,this._enabled=!0,this._justDown=!1,this._justUp=!1,t&&(this.onDown.removeAll(),this.onUp.removeAll(),this.onHoldCallback=null,this.onHoldContext=null)},downDuration:function(t){return void 0===t&&(t=50),this.isDown&&this.duration<t},upDuration:function(t){return void 0===t&&(t=50),!this.isDown&&this.game.time.time-this.timeUp<t}},Object.defineProperty(n.Key.prototype,"justDown",{get:function(){var t=this._justDown;return this._justDown=!1,t}}),Object.defineProperty(n.Key.prototype,"justUp",{get:function(){var t=this._justUp;return this._justUp=!1,t}}),Object.defineProperty(n.Key.prototype,"enabled",{get:function(){return this._enabled},set:function(t){(t=!!t)!==this._enabled&&(t||this.reset(!1),this._enabled=t)}}),n.Key.prototype.constructor=n.Key,/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Keyboard=function(t){this.game=t,this.enabled=!0,this.event=null,this.pressEvent=null,this.callbackContext=this,this.onDownCallback=null,this.onPressCallback=null,this.onUpCallback=null,this._keys=[],this._capture=[],this._onKeyDown=null,this._onKeyPress=null,this._onKeyUp=null,this._i=0,this._k=0},n.Keyboard.prototype={addCallbacks:function(t,e,i,s){this.callbackContext=t,void 0!==e&&null!==e&&(this.onDownCallback=e),void 0!==i&&null!==i&&(this.onUpCallback=i),void 0!==s&&null!==s&&(this.onPressCallback=s)},addKey:function(t){return this._keys[t]||(this._keys[t]=new n.Key(this.game,t),this.addKeyCapture(t)),this._keys[t]},addKeys:function(t){var e={};for(var i in t)e[i]=this.addKey(t[i]);return e},removeKey:function(t){this._keys[t]&&(this._keys[t]=null,this.removeKeyCapture(t))},createCursorKeys:function(){return this.addKeys({up:n.KeyCode.UP,down:n.KeyCode.DOWN,left:n.KeyCode.LEFT,right:n.KeyCode.RIGHT})},start:function(){if(!this.game.device.cocoonJS&&null===this._onKeyDown){var t=this;this._onKeyDown=function(e){return t.processKeyDown(e)},this._onKeyUp=function(e){return t.processKeyUp(e)},this._onKeyPress=function(e){return t.processKeyPress(e)},window.addEventListener("keydown",this._onKeyDown,!1),window.addEventListener("keyup",this._onKeyUp,!1),window.addEventListener("keypress",this._onKeyPress,!1)}},stop:function(){window.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("keyup",this._onKeyUp),window.removeEventListener("keypress",this._onKeyPress),this._onKeyDown=null,this._onKeyUp=null,this._onKeyPress=null},destroy:function(){this.stop(),this.clearCaptures(),this._keys.length=0,this._i=0},addKeyCapture:function(t){if("object"==typeof t)for(var e in t)this._capture[t[e]]=!0;else this._capture[t]=!0},removeKeyCapture:function(t){delete this._capture[t]},clearCaptures:function(){this._capture={}},update:function(){for(this._i=this._keys.length;this._i--;)this._keys[this._i]&&this._keys[this._i].update()},processKeyDown:function(t){if(this.event=t,this.game.input.enabled&&this.enabled){var e=t.keyCode;this._capture[e]&&t.preventDefault(),this._keys[e]||(this._keys[e]=new n.Key(this.game,e)),this._keys[e].processKeyDown(t),this._k=e,this.onDownCallback&&this.onDownCallback.call(this.callbackContext,t)}},processKeyPress:function(t){this.pressEvent=t,this.game.input.enabled&&this.enabled&&this.onPressCallback&&this.onPressCallback.call(this.callbackContext,String.fromCharCode(t.charCode),t)},processKeyUp:function(t){if(this.event=t,this.game.input.enabled&&this.enabled){var e=t.keyCode;this._capture[e]&&t.preventDefault(),this._keys[e]||(this._keys[e]=new n.Key(this.game,e)),this._keys[e].processKeyUp(t),this.onUpCallback&&this.onUpCallback.call(this.callbackContext,t)}},reset:function(t){void 0===t&&(t=!0),this.event=null;for(var e=this._keys.length;e--;)this._keys[e]&&this._keys[e].reset(t)},downDuration:function(t,e){return this._keys[t]?this._keys[t].downDuration(e):null},upDuration:function(t,e){return this._keys[t]?this._keys[t].upDuration(e):null},isDown:function(t){return this._keys[t]?this._keys[t].isDown:null}},Object.defineProperty(n.Keyboard.prototype,"lastChar",{get:function(){return 32===this.event.charCode?"":String.fromCharCode(this.pressEvent.charCode)}}),Object.defineProperty(n.Keyboard.prototype,"lastKey",{get:function(){return this._keys[this._k]}}),n.Keyboard.prototype.constructor=n.Keyboard,n.KeyCode={A:"A".charCodeAt(0),B:"B".charCodeAt(0),C:"C".charCodeAt(0),D:"D".charCodeAt(0),E:"E".charCodeAt(0),F:"F".charCodeAt(0),G:"G".charCodeAt(0),H:"H".charCodeAt(0),I:"I".charCodeAt(0),J:"J".charCodeAt(0),K:"K".charCodeAt(0),L:"L".charCodeAt(0),M:"M".charCodeAt(0),N:"N".charCodeAt(0),O:"O".charCodeAt(0),P:"P".charCodeAt(0),Q:"Q".charCodeAt(0),R:"R".charCodeAt(0),S:"S".charCodeAt(0),T:"T".charCodeAt(0),U:"U".charCodeAt(0),V:"V".charCodeAt(0),W:"W".charCodeAt(0),X:"X".charCodeAt(0),Y:"Y".charCodeAt(0),Z:"Z".charCodeAt(0),ZERO:"0".charCodeAt(0),ONE:"1".charCodeAt(0),TWO:"2".charCodeAt(0),THREE:"3".charCodeAt(0),FOUR:"4".charCodeAt(0),FIVE:"5".charCodeAt(0),SIX:"6".charCodeAt(0),SEVEN:"7".charCodeAt(0),EIGHT:"8".charCodeAt(0),NINE:"9".charCodeAt(0),NUMPAD_0:96,NUMPAD_1:97,NUMPAD_2:98,NUMPAD_3:99,NUMPAD_4:100,NUMPAD_5:101,NUMPAD_6:102,NUMPAD_7:103,NUMPAD_8:104,NUMPAD_9:105,NUMPAD_MULTIPLY:106,NUMPAD_ADD:107,NUMPAD_ENTER:108,NUMPAD_SUBTRACT:109,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,F1:112,F2:113,F3:114,F4:115,F5:116,F6:117,F7:118,F8:119,F9:120,F10:121,F11:122,F12:123,F13:124,F14:125,F15:126,COLON:186,EQUALS:187,COMMA:188,UNDERSCORE:189,PERIOD:190,QUESTION_MARK:191,TILDE:192,OPEN_BRACKET:219,BACKWARD_SLASH:220,CLOSED_BRACKET:221,QUOTES:222,BACKSPACE:8,TAB:9,CLEAR:12,ENTER:13,SHIFT:16,CONTROL:17,ALT:18,CAPS_LOCK:20,ESC:27,SPACEBAR:32,PAGE_UP:33,PAGE_DOWN:34,END:35,HOME:36,LEFT:37,UP:38,RIGHT:39,DOWN:40,PLUS:43,MINUS:44,INSERT:45,DELETE:46,HELP:47,NUM_LOCK:144};for(var o in n.KeyCode)n.KeyCode.hasOwnProperty(o)&&!o.match(/[a-z]/)&&(n.Keyboard[o]=n.KeyCode[o]);/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component=function(){},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.Angle=function(){},n.Component.Angle.prototype={angle:{get:function(){return n.Math.wrapAngle(n.Math.radToDeg(this.rotation))},set:function(t){this.rotation=n.Math.degToRad(n.Math.wrapAngle(t))}}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.Animation=function(){},n.Component.Animation.prototype={play:function(t,e,i,s){if(this.animations)return this.animations.play(t,e,i,s)}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.AutoCull=function(){},n.Component.AutoCull.prototype={autoCull:!1,inCamera:{get:function(){return this.autoCull||this.checkWorldBounds||(this._bounds.copyFrom(this.getBounds()),this._bounds.x+=this.game.camera.view.x,this._bounds.y+=this.game.camera.view.y),this.game.world.camera.view.intersects(this._bounds)}}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.Bounds=function(){},n.Component.Bounds.prototype={offsetX:{get:function(){return this.anchor.x*this.width}},offsetY:{get:function(){return this.anchor.y*this.height}},centerX:{get:function(){return this.x-this.offsetX+.5*this.width},set:function(t){this.x=t+this.offsetX-.5*this.width}},centerY:{get:function(){return this.y-this.offsetY+.5*this.height},set:function(t){this.y=t+this.offsetY-.5*this.height}},left:{get:function(){return this.x-this.offsetX},set:function(t){this.x=t+this.offsetX}},right:{get:function(){return this.x+this.width-this.offsetX},set:function(t){this.x=t-this.width+this.offsetX}},top:{get:function(){return this.y-this.offsetY},set:function(t){this.y=t+this.offsetY}},bottom:{get:function(){return this.y+this.height-this.offsetY},set:function(t){this.y=t-this.height+this.offsetY}},alignIn:function(t,e,i,s){switch(void 0===i&&(i=0),void 0===s&&(s=0),e){default:case n.TOP_LEFT:this.left=t.left-i,this.top=t.top-s;break;case n.TOP_CENTER:this.centerX=t.centerX+i,this.top=t.top-s;break;case n.TOP_RIGHT:this.right=t.right+i,this.top=t.top-s;break;case n.LEFT_CENTER:this.left=t.left-i,this.centerY=t.centerY+s;break;case n.CENTER:this.centerX=t.centerX+i,this.centerY=t.centerY+s;break;case n.RIGHT_CENTER:this.right=t.right+i,this.centerY=t.centerY+s;break;case n.BOTTOM_LEFT:this.left=t.left-i,this.bottom=t.bottom+s;break;case n.BOTTOM_CENTER:this.centerX=t.centerX+i,this.bottom=t.bottom+s;break;case n.BOTTOM_RIGHT:this.right=t.right+i,this.bottom=t.bottom+s}return this},alignTo:function(t,e,i,s){switch(void 0===i&&(i=0),void 0===s&&(s=0),e){default:case n.TOP_LEFT:this.left=t.left-i,this.bottom=t.top-s;break;case n.TOP_CENTER:this.centerX=t.centerX+i,this.bottom=t.top-s;break;case n.TOP_RIGHT:this.right=t.right+i,this.bottom=t.top-s;break;case n.LEFT_TOP:this.right=t.left-i,this.top=t.top-s;break;case n.LEFT_CENTER:this.right=t.left-i,this.centerY=t.centerY+s;break;case n.LEFT_BOTTOM:this.right=t.left-i,this.bottom=t.bottom+s;break;case n.RIGHT_TOP:this.left=t.right+i,this.top=t.top-s;break;case n.RIGHT_CENTER:this.left=t.right+i,this.centerY=t.centerY+s;break;case n.RIGHT_BOTTOM:this.left=t.right+i,this.bottom=t.bottom+s;break;case n.BOTTOM_LEFT:this.left=t.left-i,this.top=t.bottom+s;break;case n.BOTTOM_CENTER:this.centerX=t.centerX+i,this.top=t.bottom+s;break;case n.BOTTOM_RIGHT:this.right=t.right+i,this.top=t.bottom+s}return this}},n.Group.prototype.alignIn=n.Component.Bounds.prototype.alignIn,n.Group.prototype.alignTo=n.Component.Bounds.prototype.alignTo,/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.BringToTop=function(){},n.Component.BringToTop.prototype.bringToTop=function(){return this.parent&&this.parent.bringToTop(this),this},n.Component.BringToTop.prototype.sendToBack=function(){return this.parent&&this.parent.sendToBack(this),this},n.Component.BringToTop.prototype.moveUp=function(){return this.parent&&this.parent.moveUp(this),this},n.Component.BringToTop.prototype.moveDown=function(){return this.parent&&this.parent.moveDown(this),this},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.Core=function(){},n.Component.Core.install=function(t){n.Utils.mixinPrototype(this,n.Component.Core.prototype),this.components={};for(var e=0;e<t.length;e++){var i=t[e],s=!1;"Destroy"===i&&(s=!0),n.Utils.mixinPrototype(this,n.Component[i].prototype,s),this.components[i]=!0}},n.Component.Core.init=function(t,e,i,s,r){this.game=t,this.key=s,this.data={},this.position.set(e,i),this.world=new n.Point(e,i),this.previousPosition=new n.Point(e,i),this.events=new n.Events(this),this._bounds=new n.Rectangle,this.components.PhysicsBody&&(this.body=this.body),this.components.Animation&&(this.animations=new n.AnimationManager(this)),this.components.LoadTexture&&null!==s&&this.loadTexture(s,r),this.components.FixedToCamera&&(this.cameraOffset=new n.Point(e,i))},n.Component.Core.preUpdate=function(){if(this.pendingDestroy)return void this.destroy();if(this.previousPosition.set(this.world.x,this.world.y),this.previousRotation=this.rotation,!this.exists||!this.parent.exists)return this.renderOrderID=-1,!1;this.world.setTo(this.game.camera.x+this.worldTransform.tx,this.game.camera.y+this.worldTransform.ty),this.visible&&(this.renderOrderID=this.game.stage.currentRenderOrderID++),this.animations&&this.animations.update(),this.body&&this.body.preUpdate();for(var t=0;t<this.children.length;t++)this.children[t].preUpdate();return!0},n.Component.Core.prototype={game:null,name:"",data:{},components:{},z:0,events:void 0,animations:void 0,key:"",world:null,debug:!1,previousPosition:null,previousRotation:0,renderOrderID:0,fresh:!0,pendingDestroy:!1,_bounds:null,_exists:!0,exists:{get:function(){return this._exists},set:function(t){t?(this._exists=!0,this.body&&this.body.type===n.Physics.P2JS&&this.body.addToWorld(),this.visible=!0):(this._exists=!1,this.body&&this.body.type===n.Physics.P2JS&&this.body.removeFromWorld(),this.visible=!1)}},update:function(){},postUpdate:function(){this.customRender&&this.key.render(),this.components.PhysicsBody&&n.Component.PhysicsBody.postUpdate.call(this),this.components.FixedToCamera&&n.Component.FixedToCamera.postUpdate.call(this);for(var t=0;t<this.children.length;t++)this.children[t].postUpdate()}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.Crop=function(){},n.Component.Crop.prototype={cropRect:null,_crop:null,crop:function(t,e){void 0===e&&(e=!1),t?(e&&null!==this.cropRect?this.cropRect.setTo(t.x,t.y,t.width,t.height):e&&null===this.cropRect?this.cropRect=new n.Rectangle(t.x,t.y,t.width,t.height):this.cropRect=t,this.updateCrop()):(this._crop=null,this.cropRect=null,this.resetFrame())},updateCrop:function(){if(this.cropRect){var t=this.texture.crop.x,e=this.texture.crop.y,i=this.texture.crop.width,s=this.texture.crop.height;this._crop=n.Rectangle.clone(this.cropRect,this._crop),this._crop.x+=this._frame.x,this._crop.y+=this._frame.y;var r=Math.max(this._frame.x,this._crop.x),o=Math.max(this._frame.y,this._crop.y),a=Math.min(this._frame.right,this._crop.right)-r,h=Math.min(this._frame.bottom,this._crop.bottom)-o;this.texture.crop.x=r,this.texture.crop.y=o,this.texture.crop.width=a,this.texture.crop.height=h,this.texture.frame.width=Math.min(a,this.cropRect.width),this.texture.frame.height=Math.min(h,this.cropRect.height),this.texture.width=this.texture.frame.width,this.texture.height=this.texture.frame.height,this.texture._updateUvs(),16777215===this.tint||t===r&&e===o&&i===a&&s===h||(this.texture.requiresReTint=!0)}}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.Delta=function(){},n.Component.Delta.prototype={deltaX:{get:function(){return this.world.x-this.previousPosition.x}},deltaY:{get:function(){return this.world.y-this.previousPosition.y}},deltaZ:{get:function(){return this.rotation-this.previousRotation}}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.Destroy=function(){},n.Component.Destroy.prototype={destroyPhase:!1,destroy:function(t,e){if(null!==this.game&&!this.destroyPhase){void 0===t&&(t=!0),void 0===e&&(e=!1),this.destroyPhase=!0,this.events&&this.events.onDestroy$dispatch(this),this.parent&&(this.parent instanceof n.Group?this.parent.remove(this):this.parent.removeChild(this)),this.input&&this.input.destroy(),this.animations&&this.animations.destroy(),this.body&&this.body.destroy(),this.events&&this.events.destroy(),this.game.tweens.removeFrom(this);var i=this.children.length;if(t)for(;i--;)this.children[i].destroy(t);else for(;i--;)this.removeChild(this.children[i]);this._crop&&(this._crop=null,this.cropRect=null),this._frame&&(this._frame=null),n.Video&&this.key instanceof n.Video&&this.key.onChangeSource.remove(this.resizeFrame,this),n.BitmapText&&this._glyphs&&(this._glyphs=[]),this.alive=!1,this.exists=!1,this.visible=!1,this.filters=null,this.mask=null,this.game=null,this.data={},this.renderable=!1,this.transformCallback&&(this.transformCallback=null,this.transformCallbackContext=null),this.hitArea=null,this.parent=null,this.stage=null,this.worldTransform=null,this.filterArea=null,this._bounds=null,this._currentBounds=null,this._mask=null,this._destroyCachedSprite(),e&&this.texture.destroy(!0),this.destroyPhase=!1,this.pendingDestroy=!1}}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Events=function(t){this.parent=t},n.Events.prototype={destroy:function(){this._parent=null,this._onDestroy&&this._onDestroy.dispose(),this._onAddedToGroup&&this._onAddedToGroup.dispose(),this._onRemovedFromGroup&&this._onRemovedFromGroup.dispose(),this._onRemovedFromWorld&&this._onRemovedFromWorld.dispose(),this._onKilled&&this._onKilled.dispose(),this._onRevived&&this._onRevived.dispose(),this._onEnterBounds&&this._onEnterBounds.dispose(),this._onOutOfBounds&&this._onOutOfBounds.dispose(),this._onInputOver&&this._onInputOver.dispose(),this._onInputOut&&this._onInputOut.dispose(),this._onInputDown&&this._onInputDown.dispose(),this._onInputUp&&this._onInputUp.dispose(),this._onDragStart&&this._onDragStart.dispose(),this._onDragUpdate&&this._onDragUpdate.dispose(),this._onDragStop&&this._onDragStop.dispose(),this._onAnimationStart&&this._onAnimationStart.dispose(),this._onAnimationComplete&&this._onAnimationComplete.dispose(),this._onAnimationLoop&&this._onAnimationLoop.dispose()},onAddedToGroup:null,onRemovedFromGroup:null,onRemovedFromWorld:null,onDestroy:null,onKilled:null,onRevived:null,onOutOfBounds:null,onEnterBounds:null,onInputOver:null,onInputOut:null,onInputDown:null,onInputUp:null,onDragStart:null,onDragUpdate:null,onDragStop:null,onAnimationStart:null,onAnimationComplete:null,onAnimationLoop:null},n.Events.prototype.constructor=n.Events;for(var a in n.Events.prototype)n.Events.prototype.hasOwnProperty(a)&&0===a.indexOf("on")&&null===n.Events.prototype[a]&&function(t,e){"use strict";Object.defineProperty(n.Events.prototype,t,{get:function(){return this[e]||(this[e]=new n.Signal)}}),n.Events.prototype[t+"$dispatch"]=function(){return this[e]?this[e].dispatch.apply(this[e],arguments):null}}(a,"_"+a);/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.FixedToCamera=function(){},n.Component.FixedToCamera.postUpdate=function(){this.fixedToCamera&&(this.position.x=(this.game.camera.view.x+this.cameraOffset.x)/this.game.camera.scale.x,this.position.y=(this.game.camera.view.y+this.cameraOffset.y)/this.game.camera.scale.y)},n.Component.FixedToCamera.prototype={_fixedToCamera:!1,fixedToCamera:{get:function(){return this._fixedToCamera},set:function(t){t?(this._fixedToCamera=!0,this.cameraOffset.set(this.x,this.y)):this._fixedToCamera=!1}},cameraOffset:new n.Point},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.Health=function(){},n.Component.Health.prototype={health:1,maxHealth:100,damage:function(t){return this.alive&&(this.health-=t,this.health<=0&&this.kill()),this},setHealth:function(t){return this.health=t,this.health>this.maxHealth&&(this.health=this.maxHealth),this},heal:function(t){return this.alive&&(this.health+=t,this.health>this.maxHealth&&(this.health=this.maxHealth)),this}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.InCamera=function(){},n.Component.InCamera.prototype={inCamera:{get:function(){return this.game.world.camera.view.intersects(this._bounds)}}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.InputEnabled=function(){},n.Component.InputEnabled.prototype={input:null,inputEnabled:{get:function(){return this.input&&this.input.enabled},set:function(t){t?null===this.input?(this.input=new n.InputHandler(this),this.input.start()):this.input&&!this.input.enabled&&this.input.start():this.input&&this.input.enabled&&this.input.stop()}}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.InWorld=function(){},n.Component.InWorld.preUpdate=function(){if(this.autoCull||this.checkWorldBounds){if(this._bounds.copyFrom(this.getBounds()),this._bounds.x+=this.game.camera.view.x,this._bounds.y+=this.game.camera.view.y,this.autoCull)if(this.game.world.camera.view.intersects(this._bounds))this.renderable=!0,this.game.world.camera.totalInView++;else if(this.renderable=!1,this.outOfCameraBoundsKill)return this.kill(),!1;if(this.checkWorldBounds)if(this._outOfBoundsFired&&this.game.world.bounds.intersects(this._bounds))this._outOfBoundsFired=!1,this.events.onEnterBounds$dispatch(this);else if(!this._outOfBoundsFired&&!this.game.world.bounds.intersects(this._bounds)&&(this._outOfBoundsFired=!0,this.events.onOutOfBounds$dispatch(this),this.outOfBoundsKill))return this.kill(),!1}return!0},n.Component.InWorld.prototype={checkWorldBounds:!1,outOfBoundsKill:!1,outOfCameraBoundsKill:!1,_outOfBoundsFired:!1,inWorld:{get:function(){return this.game.world.bounds.intersects(this.getBounds())}}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.LifeSpan=function(){},n.Component.LifeSpan.preUpdate=function(){return!(this.lifespan>0&&(this.lifespan-=this.game.time.physicsElapsedMS,this.lifespan<=0))||(this.kill(),!1)},n.Component.LifeSpan.prototype={alive:!0,lifespan:0,revive:function(t){return void 0===t&&(t=100),this.alive=!0,this.exists=!0,this.visible=!0,"function"==typeof this.setHealth&&this.setHealth(t),this.events&&this.events.onRevived$dispatch(this),this},kill:function(){return this.alive=!1,this.exists=!1,this.visible=!1,this.events&&this.events.onKilled$dispatch(this),this}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.LoadTexture=function(){},n.Component.LoadTexture.prototype={customRender:!1,_frame:null,loadTexture:function(t,e,i){t===n.PENDING_ATLAS?(t=e,e=0):e=e||0,(i||void 0===i)&&this.animations&&this.animations.stop(),this.key=t,this.customRender=!1;var s=this.game.cache,r=!0,o=!this.texture.baseTexture.scaleMode;if(n.RenderTexture&&t instanceof n.RenderTexture)this.key=t.key,this.setTexture(t);else if(n.BitmapData&&t instanceof n.BitmapData)this.customRender=!0,this.setTexture(t.texture),r=s.hasFrameData(t.key,n.Cache.BITMAPDATA)?!this.animations.loadFrameData(s.getFrameData(t.key,n.Cache.BITMAPDATA),e):!this.animations.loadFrameData(t.frameData,0);else if(n.Video&&t instanceof n.Video){this.customRender=!0;var a=t.texture.valid;this.setTexture(t.texture),this.setFrame(t.texture.frame.clone()),t.onChangeSource.add(this.resizeFrame,this),this.texture.valid=a}else if(n.Tilemap&&t instanceof n.TilemapLayer)this.setTexture(PIXI.Texture.fromCanvas(t.canvas));else if(t instanceof PIXI.Texture)this.setTexture(t);else{var h=s.getImage(t,!0);this.key=h.key,this.setTexture(new PIXI.Texture(h.base)),this.texture.baseTexture.skipRender="__default"===t,r=!this.animations.loadFrameData(h.frameData,e)}r&&(this._frame=n.Rectangle.clone(this.texture.frame)),o||(this.texture.baseTexture.scaleMode=1)},setFrame:function(t){this._frame=t,this.texture.frame.x=t.x,this.texture.frame.y=t.y,this.texture.frame.width=t.width,this.texture.frame.height=t.height,this.texture.crop.x=t.x,this.texture.crop.y=t.y,this.texture.crop.width=t.width,this.texture.crop.height=t.height,t.trimmed?(this.texture.trim?(this.texture.trim.x=t.spriteSourceSizeX,this.texture.trim.y=t.spriteSourceSizeY,this.texture.trim.width=t.sourceSizeW,this.texture.trim.height=t.sourceSizeH):this.texture.trim={x:t.spriteSourceSizeX,y:t.spriteSourceSizeY,width:t.sourceSizeW,height:t.sourceSizeH},this.texture.width=t.sourceSizeW,this.texture.height=t.sourceSizeH,this.texture.frame.width=t.sourceSizeW,this.texture.frame.height=t.sourceSizeH):!t.trimmed&&this.texture.trim&&(this.texture.trim=null),this.cropRect&&this.updateCrop(),this.texture.requiresReTint=!0,this.texture._updateUvs(),this.tilingTexture&&(this.refreshTexture=!0)},resizeFrame:function(t,e,i){this.texture.frame.resize(e,i),this.texture.setFrame(this.texture.frame)},resetFrame:function(){this._frame&&this.setFrame(this._frame)},frame:{get:function(){return this.animations.frame},set:function(t){this.animations.frame=t}},frameName:{get:function(){return this.animations.frameName},set:function(t){this.animations.frameName=t}}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.Overlap=function(){},n.Component.Overlap.prototype={overlap:function(t){return n.Rectangle.intersects(this.getBounds(),t.getBounds())}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.PhysicsBody=function(){},n.Component.PhysicsBody.preUpdate=function(){return this.fresh&&this.exists?(this.world.setTo(this.parent.position.x+this.position.x,this.parent.position.y+this.position.y),this.worldTransform.tx=this.world.x,this.worldTransform.ty=this.world.y,this.previousPosition.set(this.world.x,this.world.y),this.previousRotation=this.rotation,this.body&&this.body.preUpdate(),this.fresh=!1,!1):(this.previousPosition.set(this.world.x,this.world.y),this.previousRotation=this.rotation,!(!this._exists||!this.parent.exists)||(this.renderOrderID=-1,!1))},n.Component.PhysicsBody.postUpdate=function(){this.exists&&this.body&&this.body.postUpdate()},n.Component.PhysicsBody.prototype={body:null,x:{get:function(){return this.position.x},set:function(t){this.position.x=t,this.body&&!this.body.dirty&&(this.body._reset=!0)}},y:{get:function(){return this.position.y},set:function(t){this.position.y=t,this.body&&!this.body.dirty&&(this.body._reset=!0)}}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.Reset=function(){},n.Component.Reset.prototype.reset=function(t,e,i){return void 0===i&&(i=1),this.world.set(t,e),this.position.set(t,e),this.fresh=!0,this.exists=!0,this.visible=!0,this.renderable=!0,this.components.InWorld&&(this._outOfBoundsFired=!1),this.components.LifeSpan&&(this.alive=!0,this.health=i),this.components.PhysicsBody&&this.body&&this.body.reset(t,e,!1,!1),this},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.ScaleMinMax=function(){},n.Component.ScaleMinMax.prototype={transformCallback:null,transformCallbackContext:this,scaleMin:null,scaleMax:null,checkTransform:function(t){this.scaleMin&&(t.a<this.scaleMin.x&&(t.a=this.scaleMin.x),t.d<this.scaleMin.y&&(t.d=this.scaleMin.y)),this.scaleMax&&(t.a>this.scaleMax.x&&(t.a=this.scaleMax.x),t.d>this.scaleMax.y&&(t.d=this.scaleMax.y))},setScaleMinMax:function(t,e,i,s){void 0===e?e=i=s=t:void 0===i&&(i=s=e,e=t),null===t?this.scaleMin=null:this.scaleMin?this.scaleMin.set(t,e):this.scaleMin=new n.Point(t,e),null===i?this.scaleMax=null:this.scaleMax?this.scaleMax.set(i,s):this.scaleMax=new n.Point(i,s),null===this.scaleMin?this.transformCallback=null:(this.transformCallback=this.checkTransform,this.transformCallbackContext=this)}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Component.Smoothed=function(){},n.Component.Smoothed.prototype={smoothed:{get:function(){return!this.texture.baseTexture.scaleMode},set:function(t){t?this.texture&&(this.texture.baseTexture.scaleMode=0):this.texture&&(this.texture.baseTexture.scaleMode=1)}}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.GameObjectFactory=function(t){this.game=t,this.world=this.game.world},n.GameObjectFactory.prototype={existing:function(t){return this.world.add(t)},weapon:function(t,e,i,s){var r=this.game.plugins.add(n.Weapon);return r.createBullets(t,e,i,s),r},image:function(t,e,i,s,r){return void 0===r&&(r=this.world),r.add(new n.Image(this.game,t,e,i,s))},sprite:function(t,e,i,s,n){return void 0===n&&(n=this.world),n.create(t,e,i,s)},creature:function(t,e,i,s,r){void 0===r&&(r=this.world);var o=new n.Creature(this.game,t,e,i,s);return r.add(o),o},tween:function(t){return this.game.tweens.create(t)},group:function(t,e,i,s,r){return new n.Group(this.game,t,e,i,s,r)},physicsGroup:function(t,e,i,s){return new n.Group(this.game,e,i,s,!0,t)},spriteBatch:function(t,e,i){return void 0===t&&(t=null),void 0===e&&(e="group"),void 0===i&&(i=!1),new n.SpriteBatch(this.game,t,e,i)},audio:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},sound:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},audioSprite:function(t){return this.game.sound.addSprite(t)},tileSprite:function(t,e,i,s,r,o,a){return void 0===a&&(a=this.world),a.add(new n.TileSprite(this.game,t,e,i,s,r,o))},rope:function(t,e,i,s,r,o){return void 0===o&&(o=this.world),o.add(new n.Rope(this.game,t,e,i,s,r))},text:function(t,e,i,s,r){return void 0===r&&(r=this.world),r.add(new n.Text(this.game,t,e,i,s))},button:function(t,e,i,s,r,o,a,h,l,c){return void 0===c&&(c=this.world),c.add(new n.Button(this.game,t,e,i,s,r,o,a,h,l))},graphics:function(t,e,i){return void 0===i&&(i=this.world),i.add(new n.Graphics(this.game,t,e))},emitter:function(t,e,i){return this.game.particles.add(new n.Particles.Arcade.Emitter(this.game,t,e,i))},retroFont:function(t,e,i,s,r,o,a,h,l){return new n.RetroFont(this.game,t,e,i,s,r,o,a,h,l)},bitmapText:function(t,e,i,s,r,o){return void 0===o&&(o=this.world),o.add(new n.BitmapText(this.game,t,e,i,s,r))},tilemap:function(t,e,i,s,r){return new n.Tilemap(this.game,t,e,i,s,r)},renderTexture:function(t,e,i,s){void 0!==i&&""!==i||(i=this.game.rnd.uuid()),void 0===s&&(s=!1);var r=new n.RenderTexture(this.game,t,e,i);return s&&this.game.cache.addRenderTexture(i,r),r},video:function(t,e){return new n.Video(this.game,t,e)},bitmapData:function(t,e,i,s){void 0===s&&(s=!1),void 0!==i&&""!==i||(i=this.game.rnd.uuid());var r=new n.BitmapData(this.game,i,t,e);return s&&this.game.cache.addBitmapData(i,r),r},filter:function(t){var e=Array.prototype.slice.call(arguments,1),t=new n.Filter[t](this.game);return t.init.apply(t,e),t},plugin:function(t){return this.game.plugins.add(t)}},n.GameObjectFactory.prototype.constructor=n.GameObjectFactory,/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.GameObjectCreator=function(t){this.game=t,this.world=this.game.world},n.GameObjectCreator.prototype={image:function(t,e,i,s){return new n.Image(this.game,t,e,i,s)},sprite:function(t,e,i,s){return new n.Sprite(this.game,t,e,i,s)},tween:function(t){return new n.Tween(t,this.game,this.game.tweens)},group:function(t,e,i,s,r){return new n.Group(this.game,t,e,i,s,r)},spriteBatch:function(t,e,i){return void 0===e&&(e="group"),void 0===i&&(i=!1),new n.SpriteBatch(this.game,t,e,i)},audio:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},audioSprite:function(t){return this.game.sound.addSprite(t)},sound:function(t,e,i,s){return this.game.sound.add(t,e,i,s)},tileSprite:function(t,e,i,s,r,o){return new n.TileSprite(this.game,t,e,i,s,r,o)},rope:function(t,e,i,s,r){return new n.Rope(this.game,t,e,i,s,r)},text:function(t,e,i,s){return new n.Text(this.game,t,e,i,s)},button:function(t,e,i,s,r,o,a,h,l){return new n.Button(this.game,t,e,i,s,r,o,a,h,l)},graphics:function(t,e){return new n.Graphics(this.game,t,e)},emitter:function(t,e,i){return new n.Particles.Arcade.Emitter(this.game,t,e,i)},retroFont:function(t,e,i,s,r,o,a,h,l){return new n.RetroFont(this.game,t,e,i,s,r,o,a,h,l)},bitmapText:function(t,e,i,s,r,o){return new n.BitmapText(this.game,t,e,i,s,r,o)},tilemap:function(t,e,i,s,r){return new n.Tilemap(this.game,t,e,i,s,r)},renderTexture:function(t,e,i,s){void 0!==i&&""!==i||(i=this.game.rnd.uuid()),void 0===s&&(s=!1);var r=new n.RenderTexture(this.game,t,e,i);return s&&this.game.cache.addRenderTexture(i,r),r},bitmapData:function(t,e,i,s){void 0===s&&(s=!1),void 0!==i&&""!==i||(i=this.game.rnd.uuid());var r=new n.BitmapData(this.game,i,t,e);return s&&this.game.cache.addBitmapData(i,r),r},filter:function(t){var e=Array.prototype.slice.call(arguments,1),t=new n.Filter[t](this.game);return t.init.apply(t,e),t}},n.GameObjectCreator.prototype.constructor=n.GameObjectCreator,/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Sprite=function(t,e,i,s,r){e=e||0,i=i||0,s=s||null,r=r||null,this.type=n.SPRITE,this.physicsType=n.SPRITE,PIXI.Sprite.call(this,n.Cache.DEFAULT),n.Component.Core.init.call(this,t,e,i,s,r)},n.Sprite.prototype=Object.create(PIXI.Sprite.prototype),n.Sprite.prototype.constructor=n.Sprite,n.Component.Core.install.call(n.Sprite.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Delta","Destroy","FixedToCamera","Health","InCamera","InputEnabled","InWorld","LifeSpan","LoadTexture","Overlap","PhysicsBody","Reset","ScaleMinMax","Smoothed"]),n.Sprite.prototype.preUpdatePhysics=n.Component.PhysicsBody.preUpdate,n.Sprite.prototype.preUpdateLifeSpan=n.Component.LifeSpan.preUpdate,n.Sprite.prototype.preUpdateInWorld=n.Component.InWorld.preUpdate,n.Sprite.prototype.preUpdateCore=n.Component.Core.preUpdate,n.Sprite.prototype.preUpdate=function(){return!!(this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld())&&this.preUpdateCore()},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Image=function(t,e,i,s,r){e=e||0,i=i||0,s=s||null,r=r||null,this.type=n.IMAGE,PIXI.Sprite.call(this,n.Cache.DEFAULT),n.Component.Core.init.call(this,t,e,i,s,r)},n.Image.prototype=Object.create(PIXI.Sprite.prototype),n.Image.prototype.constructor=n.Image,n.Component.Core.install.call(n.Image.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Destroy","FixedToCamera","InputEnabled","LifeSpan","LoadTexture","Overlap","Reset","ScaleMinMax","Smoothed"]),n.Image.prototype.preUpdateInWorld=n.Component.InWorld.preUpdate,n.Image.prototype.preUpdateCore=n.Component.Core.preUpdate,n.Image.prototype.preUpdate=function(){return!!this.preUpdateInWorld()&&this.preUpdateCore()},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Button=function(t,e,i,s,r,o,a,h,l,c){e=e||0,i=i||0,s=s||null,r=r||null,o=o||this,n.Image.call(this,t,e,i,s,h),this.type=n.BUTTON,this.physicsType=n.SPRITE,this._onOverFrame=null,this._onOutFrame=null,this._onDownFrame=null,this._onUpFrame=null,this.onOverSound=null,this.onOutSound=null,this.onDownSound=null,this.onUpSound=null,this.onOverSoundMarker="",this.onOutSoundMarker="",this.onDownSoundMarker="",this.onUpSoundMarker="",this.onInputOver=new n.Signal,this.onInputOut=new n.Signal,this.onInputDown=new n.Signal,this.onInputUp=new n.Signal,this.onOverMouseOnly=!0,this.justReleasedPreventsOver=n.PointerMode.TOUCH,this.freezeFrames=!1,this.forceOut=!1,this.inputEnabled=!0,this.input.start(0,!0),this.input.useHandCursor=!0,this.setFrames(a,h,l,c),null!==r&&this.onInputUp.add(r,o),this.events.onInputOver.add(this.onInputOverHandler,this),this.events.onInputOut.add(this.onInputOutHandler,this),this.events.onInputDown.add(this.onInputDownHandler,this),this.events.onInputUp.add(this.onInputUpHandler,this),this.events.onRemovedFromWorld.add(this.removedFromWorld,this)},n.Button.prototype=Object.create(n.Image.prototype),n.Button.prototype.constructor=n.Button;n.Button.prototype.clearFrames=function(){this.setFrames(null,null,null,null)},n.Button.prototype.removedFromWorld=function(){this.inputEnabled=!1},n.Button.prototype.setStateFrame=function(t,e,i){var s="_on"+t+"Frame";null!==e?(this[s]=e,i&&this.changeStateFrame(t)):this[s]=null},n.Button.prototype.changeStateFrame=function(t){if(this.freezeFrames)return!1;var e="_on"+t+"Frame",i=this[e];return"string"==typeof i?(this.frameName=i,!0):"number"==typeof i&&(this.frame=i,!0)},n.Button.prototype.setFrames=function(t,e,i,s){this.setStateFrame("Over",t,this.input.pointerOver()),this.setStateFrame("Out",e,!this.input.pointerOver()),this.setStateFrame("Down",i,this.input.pointerDown()),this.setStateFrame("Up",s,this.input.pointerUp())},n.Button.prototype.setStateSound=function(t,e,i){var s="on"+t+"Sound",r="on"+t+"SoundMarker";e instanceof n.Sound||e instanceof n.AudioSprite?(this[s]=e,this[r]="string"==typeof i?i:""):(this[s]=null,this[r]="")},n.Button.prototype.playStateSound=function(t){var e="on"+t+"Sound",i=this[e];if(i){var s="on"+t+"SoundMarker",n=this[s];return i.play(n),!0}return!1},n.Button.prototype.setSounds=function(t,e,i,s,n,r,o,a){this.setStateSound("Over",t,e),this.setStateSound("Out",n,r),this.setStateSound("Down",i,s),this.setStateSound("Up",o,a)},n.Button.prototype.setOverSound=function(t,e){this.setStateSound("Over",t,e)},n.Button.prototype.setOutSound=function(t,e){this.setStateSound("Out",t,e)},n.Button.prototype.setDownSound=function(t,e){this.setStateSound("Down",t,e)},n.Button.prototype.setUpSound=function(t,e){this.setStateSound("Up",t,e)},n.Button.prototype.onInputOverHandler=function(t,e){e.justReleased()&&(this.justReleasedPreventsOver&e.pointerMode)===e.pointerMode||(this.changeStateFrame("Over"),this.onOverMouseOnly&&!e.isMouse||(this.playStateSound("Over"),this.onInputOver&&this.onInputOver.dispatch(this,e)))},n.Button.prototype.onInputOutHandler=function(t,e){this.changeStateFrame("Out"),this.playStateSound("Out"),this.onInputOut&&this.onInputOut.dispatch(this,e)},n.Button.prototype.onInputDownHandler=function(t,e){this.changeStateFrame("Down"),this.playStateSound("Down"),this.onInputDown&&this.onInputDown.dispatch(this,e)},n.Button.prototype.onInputUpHandler=function(t,e,i){if(this.playStateSound("Up"),this.onInputUp&&this.onInputUp.dispatch(this,e,i),!this.freezeFrames)if(!0===this.forceOut||(this.forceOut&e.pointerMode)===e.pointerMode)this.changeStateFrame("Out");else{var s=this.changeStateFrame("Up");s||(i?this.changeStateFrame("Over"):this.changeStateFrame("Out"))}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.SpriteBatch=function(t,e,i,s){void 0!==e&&null!==e||(e=t.world),PIXI.SpriteBatch.call(this),n.Group.call(this,t,e,i,s),this.type=n.SPRITEBATCH},n.SpriteBatch.prototype=n.Utils.extend(!0,n.SpriteBatch.prototype,PIXI.SpriteBatch.prototype,n.Group.prototype),n.SpriteBatch.prototype.constructor=n.SpriteBatch,/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.BitmapData=function(t,e,i,s,r){void 0!==i&&0!==i||(i=256),void 0!==s&&0!==s||(s=256),void 0===r&&(r=!1),this.game=t,this.key=e,this.width=i,this.height=s,this.canvas=n.Canvas.create(this,i,s,null,r),this.context=this.canvas.getContext("2d",{alpha:!0}),this.ctx=this.context,this.smoothProperty=t.renderType===n.CANVAS?t.renderer.renderSession.smoothProperty:n.Canvas.getSmoothingPrefix(this.context),this.imageData=this.context.getImageData(0,0,i,s),this.data=null,this.imageData&&(this.data=this.imageData.data),this.pixels=null,this.data&&(this.imageData.data.buffer?(this.buffer=this.imageData.data.buffer,this.pixels=new Uint32Array(this.buffer)):window.ArrayBuffer?(this.buffer=new ArrayBuffer(this.imageData.data.length),this.pixels=new Uint32Array(this.buffer)):this.pixels=this.imageData.data),this.baseTexture=new PIXI.BaseTexture(this.canvas),this.texture=new PIXI.Texture(this.baseTexture),this.frameData=new n.FrameData,this.textureFrame=this.frameData.addFrame(new n.Frame(0,0,0,i,s,"bitmapData")),this.texture.frame=this.textureFrame,this.type=n.BITMAPDATA,this.disableTextureUpload=!1,this.dirty=!1,this.cls=this.clear,this._image=null,this._pos=new n.Point,this._size=new n.Point,this._scale=new n.Point,this._rotate=0,this._alpha={prev:1,current:1},this._anchor=new n.Point,this._tempR=0,this._tempG=0,this._tempB=0,this._circle=new n.Circle,this._swapCanvas=void 0},n.BitmapData.prototype={move:function(t,e,i){return 0!==t&&this.moveH(t,i),0!==e&&this.moveV(e,i),this},moveH:function(t,e){void 0===e&&(e=!0),void 0===this._swapCanvas&&(this._swapCanvas=PIXI.CanvasPool.create(this,this.width,this.height));var i=this._swapCanvas,s=i.getContext("2d"),n=this.height,r=this.canvas;if(s.clearRect(0,0,this.width,this.height),t<0){t=Math.abs(t);var o=this.width-t;e&&s.drawImage(r,0,0,t,n,o,0,t,n),s.drawImage(r,t,0,o,n,0,0,o,n)}else{var o=this.width-t;e&&s.drawImage(r,o,0,t,n,0,0,t,n),s.drawImage(r,0,0,o,n,t,0,o,n)}return this.clear(),this.copy(this._swapCanvas)},moveV:function(t,e){void 0===e&&(e=!0),void 0===this._swapCanvas&&(this._swapCanvas=PIXI.CanvasPool.create(this,this.width,this.height));var i=this._swapCanvas,s=i.getContext("2d"),n=this.width,r=this.canvas;if(s.clearRect(0,0,this.width,this.height),t<0){t=Math.abs(t);var o=this.height-t;e&&s.drawImage(r,0,0,n,t,0,o,n,t),s.drawImage(r,0,t,n,o,0,0,n,o)}else{var o=this.height-t;e&&s.drawImage(r,0,o,n,t,0,0,n,t),s.drawImage(r,0,0,n,o,0,t,n,o)}return this.clear(),this.copy(this._swapCanvas)},add:function(t){if(Array.isArray(t))for(var e=0;e<t.length;e++)t[e].loadTexture&&t[e].loadTexture(this);else t.loadTexture(this);return this},load:function(t){if("string"==typeof t&&(t=this.game.cache.getImage(t)),t)return this.resize(t.width,t.height),this.cls(),this.draw(t),this.update(),this},clear:function(t,e,i,s){return void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=this.width),void 0===s&&(s=this.height),this.context.clearRect(t,e,i,s),this.dirty=!0,this},fill:function(t,e,i,s){return void 0===s&&(s=1),this.context.fillStyle="rgba("+t+","+e+","+i+","+s+")",this.context.fillRect(0,0,this.width,this.height),this.dirty=!0,this},generateTexture:function(t){var e=new Image;e.src=this.canvas.toDataURL("image/png");var i=this.game.cache.addImage(t,"",e);return new PIXI.Texture(i.base)},resize:function(t,e){return t===this.width&&e===this.height||(this.width=t,this.height=e,this.canvas.width=t,this.canvas.height=e,void 0!==this._swapCanvas&&(this._swapCanvas.width=t,this._swapCanvas.height=e),this.baseTexture.width=t,this.baseTexture.height=e,this.textureFrame.width=t,this.textureFrame.height=e,this.texture.width=t,this.texture.height=e,this.texture.crop.width=t,this.texture.crop.height=e,this.update(),this.dirty=!0),this},update:function(t,e,i,s){return void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=Math.max(1,this.width)),void 0===s&&(s=Math.max(1,this.height)),this.imageData=this.context.getImageData(t,e,i,s),this.data=this.imageData.data,this.imageData.data.buffer?(this.buffer=this.imageData.data.buffer,this.pixels=new Uint32Array(this.buffer)):window.ArrayBuffer?(this.buffer=new ArrayBuffer(this.imageData.data.length),this.pixels=new Uint32Array(this.buffer)):this.pixels=this.imageData.data,this},processPixelRGB:function(t,e,i,s,r,o){void 0===i&&(i=0),void 0===s&&(s=0),void 0===r&&(r=this.width),void 0===o&&(o=this.height);for(var a=i+r,h=s+o,l=n.Color.createColor(),c={r:0,g:0,b:0,a:0},u=!1,d=s;d<h;d++)for(var p=i;p<a;p++)n.Color.unpackPixel(this.getPixel32(p,d),l),!1!==(c=t.call(e,l,p,d))&&null!==c&&void 0!==c&&(this.setPixel32(p,d,c.r,c.g,c.b,c.a,!1),u=!0);return u&&(this.context.putImageData(this.imageData,0,0),this.dirty=!0),this},processPixel:function(t,e,i,s,n,r){void 0===i&&(i=0),void 0===s&&(s=0),void 0===n&&(n=this.width),void 0===r&&(r=this.height);for(var o=i+n,a=s+r,h=0,l=0,c=!1,u=s;u<a;u++)for(var d=i;d<o;d++)h=this.getPixel32(d,u),(l=t.call(e,h,d,u))!==h&&(this.pixels[u*this.width+d]=l,c=!0);return c&&(this.context.putImageData(this.imageData,0,0),this.dirty=!0),this},replaceRGB:function(t,e,i,s,r,o,a,h,l){var c=0,u=0,d=this.width,p=this.height,f=n.Color.packPixel(t,e,i,s);void 0!==l&&l instanceof n.Rectangle&&(c=l.x,u=l.y,d=l.width,p=l.height);for(var g=0;g<p;g++)for(var m=0;m<d;m++)this.getPixel32(c+m,u+g)===f&&this.setPixel32(c+m,u+g,r,o,a,h,!1);return this.context.putImageData(this.imageData,0,0),this.dirty=!0,this},setHSL:function(t,e,i,s){var r=t||0===t,o=e||0===e,a=i||0===i;if(r||o||a){void 0===s&&(s=new n.Rectangle(0,0,this.width,this.height));for(var h=n.Color.createColor(),l=s.y;l<s.bottom;l++)for(var c=s.x;c<s.right;c++)n.Color.unpackPixel(this.getPixel32(c,l),h,!0),r&&(h.h=t),o&&(h.s=e),a&&(h.l=i),n.Color.HSLtoRGB(h.h,h.s,h.l,h),this.setPixel32(c,l,h.r,h.g,h.b,h.a,!1);return this.context.putImageData(this.imageData,0,0),this.dirty=!0,this}},shiftHSL:function(t,e,i,s){if(void 0!==t&&null!==t||(t=!1),void 0!==e&&null!==e||(e=!1),void 0!==i&&null!==i||(i=!1),t||e||i){void 0===s&&(s=new n.Rectangle(0,0,this.width,this.height));for(var r=n.Color.createColor(),o=s.y;o<s.bottom;o++)for(var a=s.x;a<s.right;a++)n.Color.unpackPixel(this.getPixel32(a,o),r,!0),t&&(r.h=this.game.math.wrap(r.h+t,0,1)),e&&(r.s=this.game.math.clamp(r.s+e,0,1)),i&&(r.l=this.game.math.clamp(r.l+i,0,1)),n.Color.HSLtoRGB(r.h,r.s,r.l,r),this.setPixel32(a,o,r.r,r.g,r.b,r.a,!1);return this.context.putImageData(this.imageData,0,0),this.dirty=!0,this}},setPixel32:function(t,e,i,s,r,o,a){return void 0===a&&(a=!0),t>=0&&t<=this.width&&e>=0&&e<=this.height&&(n.Device.LITTLE_ENDIAN?this.pixels[e*this.width+t]=o<<24|r<<16|s<<8|i:this.pixels[e*this.width+t]=i<<24|s<<16|r<<8|o,a&&(this.context.putImageData(this.imageData,0,0),this.dirty=!0)),this},setPixel:function(t,e,i,s,n,r){return this.setPixel32(t,e,i,s,n,255,r)},getPixel:function(t,e,i){i||(i=n.Color.createColor());var s=~~(t+e*this.width);return s*=4,i.r=this.data[s],i.g=this.data[++s],i.b=this.data[++s],i.a=this.data[++s],i},getPixel32:function(t,e){if(t>=0&&t<=this.width&&e>=0&&e<=this.height)return this.pixels[e*this.width+t]},getPixelRGB:function(t,e,i,s,r){return n.Color.unpackPixel(this.getPixel32(t,e),i,s,r)},getPixels:function(t){return this.context.getImageData(t.x,t.y,t.width,t.height)},getFirstPixel:function(t){void 0===t&&(t=0);var e=n.Color.createColor(),i=0,s=0,r=1,o=!1;1===t?(r=-1,s=this.height):3===t&&(r=-1,i=this.width);do{n.Color.unpackPixel(this.getPixel32(i,s),e),0===t||1===t?++i===this.width&&(i=0,((s+=r)>=this.height||s<=0)&&(o=!0)):2!==t&&3!==t||++s===this.height&&(s=0,((i+=r)>=this.width||i<=0)&&(o=!0))}while(0===e.a&&!o);return e.x=i,e.y=s,e},getBounds:function(t){return void 0===t&&(t=new n.Rectangle),t.x=this.getFirstPixel(2).x,t.x===this.width?t.setTo(0,0,0,0):(t.y=this.getFirstPixel(0).y,t.width=this.getFirstPixel(3).x-t.x+1,t.height=this.getFirstPixel(1).y-t.y+1,t)},addToWorld:function(t,e,i,s,n,r){n=n||1,r=r||1;var o=this.game.add.image(t,e,this);return o.anchor.set(i,s),o.scale.set(n,r),o},copy:function(t,e,i,s,r,o,a,h,l,c,u,d,p,f,g,m,y){if(void 0!==t&&null!==t||(t=this),(t instanceof n.RenderTexture||t instanceof PIXI.RenderTexture)&&(t=t.getCanvas()),this._image=t,t instanceof n.Sprite||t instanceof n.Image||t instanceof n.Text||t instanceof PIXI.Sprite)this._pos.set(t.texture.crop.x,t.texture.crop.y),this._size.set(t.texture.crop.width,t.texture.crop.height),this._scale.set(t.scale.x,t.scale.y),this._anchor.set(t.anchor.x,t.anchor.y),this._rotate=t.rotation,this._alpha.current=t.alpha,t.texture instanceof n.RenderTexture||t.texture instanceof PIXI.RenderTexture?this._image=t.texture.getCanvas():this._image=t.texture.baseTexture.source,void 0!==o&&null!==o||(o=t.x),void 0!==a&&null!==a||(a=t.y),t.texture.trim&&(o+=t.texture.trim.x-t.anchor.x*t.texture.trim.width,a+=t.texture.trim.y-t.anchor.y*t.texture.trim.height),16777215!==t.tint&&(t.cachedTint!==t.tint&&(t.cachedTint=t.tint,t.tintedTexture=PIXI.CanvasTinter.getTintedTexture(t,t.tint)),this._image=t.tintedTexture,this._pos.set(0));else{if(this._pos.set(0),this._scale.set(1),this._anchor.set(0),this._rotate=0,this._alpha.current=1,t instanceof n.BitmapData)this._image=t.canvas;else if("string"==typeof t){if(null===(t=this.game.cache.getImage(t)))return;this._image=t}this._size.set(this._image.width,this._image.height)}if(void 0!==e&&null!==e||(e=0),void 0!==i&&null!==i||(i=0),s&&(this._size.x=s),r&&(this._size.y=r),void 0!==o&&null!==o||(o=e),void 0!==a&&null!==a||(a=i),void 0!==h&&null!==h||(h=this._size.x),void 0!==l&&null!==l||(l=this._size.y),"number"==typeof c&&(this._rotate=c),"number"==typeof u&&(this._anchor.x=u),"number"==typeof d&&(this._anchor.y=d),"number"==typeof p&&(this._scale.x=p),"number"==typeof f&&(this._scale.y=f),"number"==typeof g&&(this._alpha.current=g),void 0===m&&(m=null),void 0===y&&(y=!1),!(this._alpha.current<=0||0===this._scale.x||0===this._scale.y||0===this._size.x||0===this._size.y)){var v=this.context;return this._alpha.prev=v.globalAlpha,v.save(),v.globalAlpha=this._alpha.current,m&&(this.op=m),y&&(o|=0,a|=0),v.translate(o,a),v.scale(this._scale.x,this._scale.y),v.rotate(this._rotate),v.drawImage(this._image,this._pos.x+e,this._pos.y+i,this._size.x,this._size.y,-h*this._anchor.x,-l*this._anchor.y,h,l),v.restore(),v.globalAlpha=this._alpha.prev,this.dirty=!0,this}},copyTransform:function(t,e,i){if(void 0===e&&(e=null),void 0===i&&(i=!1),!t.hasOwnProperty("worldTransform")||!t.worldVisible||0===t.worldAlpha)return this;var s=t.worldTransform;if(this._pos.set(t.texture.crop.x,t.texture.crop.y),this._size.set(t.texture.crop.width,t.texture.crop.height),0===s.a||0===s.d||0===this._size.x||0===this._size.y)return this;t.texture instanceof n.RenderTexture||t.texture instanceof PIXI.RenderTexture?this._image=t.texture.getCanvas():this._image=t.texture.baseTexture.source;var r=s.tx,o=s.ty;t.texture.trim&&(r+=t.texture.trim.x-t.anchor.x*t.texture.trim.width,o+=t.texture.trim.y-t.anchor.y*t.texture.trim.height),16777215!==t.tint&&(t.cachedTint!==t.tint&&(t.cachedTint=t.tint,t.tintedTexture=PIXI.CanvasTinter.getTintedTexture(t,t.tint)),this._image=t.tintedTexture,this._pos.set(0)),i&&(r|=0,o|=0);var a=this.context;return this._alpha.prev=a.globalAlpha,a.save(),a.globalAlpha=this._alpha.current,e&&(this.op=e),a[this.smoothProperty]=t.texture.baseTexture.scaleMode===PIXI.scaleModes.LINEAR,a.setTransform(s.a,s.b,s.c,s.d,r,o),a.drawImage(this._image,this._pos.x,this._pos.y,this._size.x,this._size.y,-this._size.x*t.anchor.x,-this._size.y*t.anchor.y,this._size.x,this._size.y),a.restore(),a.globalAlpha=this._alpha.prev,this.dirty=!0,this},copyRect:function(t,e,i,s,n,r,o){return this.copy(t,e.x,e.y,e.width,e.height,i,s,e.width,e.height,0,0,0,1,1,n,r,o)},draw:function(t,e,i,s,n,r,o){return this.copy(t,null,null,null,null,e,i,s,n,null,null,null,null,null,null,r,o)},drawGroup:function(t,e,i){return t.total>0&&t.forEachExists(this.drawGroupProxy,this,e,i),this},drawGroupProxy:function(t,e,i){if(t.hasOwnProperty("texture")&&this.copyTransform(t,e,i),t.type===n.GROUP&&t.exists)this.drawGroup(t,e,i);else if(t.hasOwnProperty("children")&&t.children.length>0)for(var s=0;s<t.children.length;s++)t.children[s].exists&&this.copyTransform(t.children[s],e,i)},drawFull:function(t,e,i){if(!1===t.worldVisible||0===t.worldAlpha||t.hasOwnProperty("exists")&&!1===t.exists)return this;if(t.type!==n.GROUP&&t.type!==n.EMITTER&&t.type!==n.BITMAPTEXT)if(t.type===n.GRAPHICS){var s=t.getBounds();this.ctx.save(),this.ctx.translate(s.x,s.y),PIXI.CanvasGraphics.renderGraphics(t,this.ctx),this.ctx.restore()}else this.copy(t,null,null,null,null,t.worldPosition.x,t.worldPosition.y,null,null,t.worldRotation,null,null,t.worldScale.x,t.worldScale.y,t.worldAlpha,e,i);if(t.children)for(var r=0;r<t.children.length;r++)this.drawFull(t.children[r],e,i);return this},shadow:function(t,e,i,s){var n=this.context;return void 0===t||null===t?n.shadowColor="rgba(0,0,0,0)":(n.shadowColor=t,n.shadowBlur=e||5,n.shadowOffsetX=i||10,n.shadowOffsetY=s||10),this},alphaMask:function(t,e,i,s){return void 0===s||null===s?this.draw(e).blendSourceAtop():this.draw(e,s.x,s.y,s.width,s.height).blendSourceAtop(),void 0===i||null===i?this.draw(t).blendReset():this.draw(t,i.x,i.y,i.width,i.height).blendReset(),this},extract:function(t,e,i,s,n,r,o,a,h){return void 0===n&&(n=255),void 0===r&&(r=!1),void 0===o&&(o=e),void 0===a&&(a=i),void 0===h&&(h=s),r&&t.resize(this.width,this.height),this.processPixelRGB(function(r,l,c){return r.r===e&&r.g===i&&r.b===s&&t.setPixel32(l,c,o,a,h,n,!1),!1},this),t.context.putImageData(t.imageData,0,0),t.dirty=!0,t},rect:function(t,e,i,s,n){return void 0!==n&&(this.context.fillStyle=n),this.context.fillRect(t,e,i,s),this},text:function(t,e,i,s,n,r){void 0===e&&(e=0),void 0===i&&(i=0),void 0===s&&(s="14px Courier"),void 0===n&&(n="rgb(255,255,255)"),void 0===r&&(r=!0);var o=this.context,a=o.font;return o.font=s,r&&(o.fillStyle="rgb(0,0,0)",o.fillText(t,e+1,i+1)),o.fillStyle=n,o.fillText(t,e,i),o.font=a,this},circle:function(t,e,i,s){var n=this.context;return void 0!==s&&(n.fillStyle=s),n.beginPath(),n.arc(t,e,i,0,2*Math.PI,!1),n.closePath(),n.fill(),this},line:function(t,e,i,s,n,r){void 0===n&&(n="#fff"),void 0===r&&(r=1);var o=this.context;return o.beginPath(),o.moveTo(t,e),o.lineTo(i,s),o.lineWidth=r,o.strokeStyle=n,o.stroke(),o.closePath(),this},textureLine:function(t,e,i){if(void 0===i&&(i="repeat-x"),"string"!=typeof e||(e=this.game.cache.getImage(e))){var s=t.length;"no-repeat"===i&&s>e.width&&(s=e.width);var r=this.context;return r.fillStyle=r.createPattern(e,i),this._circle=new n.Circle(t.start.x,t.start.y,e.height),this._circle.circumferencePoint(t.angle-1.5707963267948966,!1,this._pos),r.save(),r.translate(this._pos.x,this._pos.y),r.rotate(t.angle),r.fillRect(0,0,s,e.height),r.restore(),this.dirty=!0,this}},render:function(){return!this.disableTextureUpload&&this.dirty&&(this.baseTexture.dirty(),this.dirty=!1),this},destroy:function(){this.frameData.destroy(),this.texture.destroy(!0),PIXI.CanvasPool.remove(this)},blendReset:function(){return this.op="source-over",this},blendSourceOver:function(){return this.op="source-over",this},blendSourceIn:function(){return this.op="source-in",this},blendSourceOut:function(){return this.op="source-out",this},blendSourceAtop:function(){return this.op="source-atop",this},blendDestinationOver:function(){return this.op="destination-over",this},blendDestinationIn:function(){return this.op="destination-in",this},blendDestinationOut:function(){return this.op="destination-out",this},blendDestinationAtop:function(){return this.op="destination-atop",this},blendXor:function(){return this.op="xor",this},blendAdd:function(){return this.op="lighter",this},blendMultiply:function(){return this.op="multiply",this},blendScreen:function(){return this.op="screen",this},blendOverlay:function(){return this.op="overlay",this},blendDarken:function(){return this.op="darken",this},blendLighten:function(){return this.op="lighten",this},blendColorDodge:function(){return this.op="color-dodge",this},blendColorBurn:function(){return this.op="color-burn",this},blendHardLight:function(){return this.op="hard-light",this},blendSoftLight:function(){return this.op="soft-light",this},blendDifference:function(){return this.op="difference",this},blendExclusion:function(){return this.op="exclusion",this},blendHue:function(){return this.op="hue",this},blendSaturation:function(){return this.op="saturation",this},blendColor:function(){return this.op="color",this},blendLuminosity:function(){return this.op="luminosity",this}},Object.defineProperty(n.BitmapData.prototype,"smoothed",{get:function(){n.Canvas.getSmoothingEnabled(this.context)},set:function(t){n.Canvas.setSmoothingEnabled(this.context,t)}}),Object.defineProperty(n.BitmapData.prototype,"op",{get:function(){return this.context.globalCompositeOperation},set:function(t){this.context.globalCompositeOperation=t}}),n.BitmapData.getTransform=function(t,e,i,s,n,r){return"number"!=typeof t&&(t=0),"number"!=typeof e&&(e=0),"number"!=typeof i&&(i=1),"number"!=typeof s&&(s=1),"number"!=typeof n&&(n=0),"number"!=typeof r&&(r=0),{sx:i,sy:s,scaleX:i,scaleY:s,skewX:n,skewY:r,translateX:t,translateY:e,tx:t,ty:e}},n.BitmapData.prototype.constructor=n.BitmapData,PIXI.Graphics=function(){PIXI.DisplayObjectContainer.call(this),this.renderable=!0,this.fillAlpha=1,this.lineWidth=0,this.lineColor=0,this.graphicsData=[],this.tint=16777215,this.blendMode=PIXI.blendModes.NORMAL,this.currentPath=null,this._webGL=[],this.isMask=!1,this.boundsPadding=0,this._localBounds=new PIXI.Rectangle(0,0,1,1),this.dirty=!0,this._boundsDirty=!1,this.webGLDirty=!1,this.cachedSpriteDirty=!1},PIXI.Graphics.prototype=Object.create(PIXI.DisplayObjectContainer.prototype),PIXI.Graphics.prototype.constructor=PIXI.Graphics,PIXI.Graphics.prototype.lineStyle=function(t,e,i){return this.lineWidth=t||0,this.lineColor=e||0,this.lineAlpha=void 0===i?1:i,this.currentPath&&(this.currentPath.shape.points.length?this.drawShape(new PIXI.Polygon(this.currentPath.shape.points.slice(-2))):(this.currentPath.lineWidth=this.lineWidth,this.currentPath.lineColor=this.lineColor,this.currentPath.lineAlpha=this.lineAlpha)),this},PIXI.Graphics.prototype.moveTo=function(t,e){return this.drawShape(new PIXI.Polygon([t,e])),this},PIXI.Graphics.prototype.lineTo=function(t,e){return this.currentPath||this.moveTo(0,0),this.currentPath.shape.points.push(t,e),this.dirty=!0,this._boundsDirty=!0,this},PIXI.Graphics.prototype.quadraticCurveTo=function(t,e,i,s){this.currentPath?0===this.currentPath.shape.points.length&&(this.currentPath.shape.points=[0,0]):this.moveTo(0,0);var n,r,o=this.currentPath.shape.points;0===o.length&&this.moveTo(0,0);for(var a=o[o.length-2],h=o[o.length-1],l=0,c=1;c<=20;++c)l=c/20,n=a+(t-a)*l,r=h+(e-h)*l,o.push(n+(t+(i-t)*l-n)*l,r+(e+(s-e)*l-r)*l);return this.dirty=!0,this._boundsDirty=!0,this},PIXI.Graphics.prototype.bezierCurveTo=function(t,e,i,s,n,r){this.currentPath?0===this.currentPath.shape.points.length&&(this.currentPath.shape.points=[0,0]):this.moveTo(0,0);for(var o,a,h,l,c,u=this.currentPath.shape.points,d=u[u.length-2],p=u[u.length-1],f=0,g=1;g<=20;++g)f=g/20,o=1-f,a=o*o,h=a*o,l=f*f,c=l*f,u.push(h*d+3*a*f*t+3*o*l*i+c*n,h*p+3*a*f*e+3*o*l*s+c*r);return this.dirty=!0,this._boundsDirty=!0,this},PIXI.Graphics.prototype.arcTo=function(t,e,i,s,n){this.currentPath?0===this.currentPath.shape.points.length&&this.currentPath.shape.points.push(t,e):this.moveTo(t,e);var r=this.currentPath.shape.points,o=r[r.length-2],a=r[r.length-1],h=a-e,l=o-t,c=s-e,u=i-t,d=Math.abs(h*u-l*c);if(d<1e-8||0===n)r[r.length-2]===t&&r[r.length-1]===e||r.push(t,e);else{var p=h*h+l*l,f=c*c+u*u,g=h*c+l*u,m=n*Math.sqrt(p)/d,y=n*Math.sqrt(f)/d,v=m*g/p,b=y*g/f,x=m*u+y*l,w=m*c+y*h,_=l*(y+v),P=h*(y+v),T=u*(m+b),C=c*(m+b),S=Math.atan2(P-w,_-x),A=Math.atan2(C-w,T-x);this.arc(x+t,w+e,n,S,A,l*c>u*h)}return this.dirty=!0,this._boundsDirty=!0,this},PIXI.Graphics.prototype.arc=function(t,e,i,s,n,r,o){if(s===n)return this;void 0===r&&(r=!1),void 0===o&&(o=40),!r&&n<=s?n+=2*Math.PI:r&&s<=n&&(s+=2*Math.PI);var a=r?-1*(s-n):n-s,h=Math.ceil(Math.abs(a)/(2*Math.PI))*o;if(0===a)return this;var l=t+Math.cos(s)*i,c=e+Math.sin(s)*i;r&&this.filling?this.moveTo(t,e):this.moveTo(l,c);for(var u=this.currentPath.shape.points,d=a/(2*h),p=2*d,f=Math.cos(d),g=Math.sin(d),m=h-1,y=m%1/m,v=0;v<=m;v++){var b=v+y*v,x=d+s+p*b,w=Math.cos(x),_=-Math.sin(x);u.push((f*w+g*_)*i+t,(f*-_+g*w)*i+e)}return this.dirty=!0,this._boundsDirty=!0,this},PIXI.Graphics.prototype.beginFill=function(t,e){return this.filling=!0,this.fillColor=t||0,this.fillAlpha=void 0===e?1:e,this.currentPath&&this.currentPath.shape.points.length<=2&&(this.currentPath.fill=this.filling,this.currentPath.fillColor=this.fillColor,this.currentPath.fillAlpha=this.fillAlpha),this},PIXI.Graphics.prototype.endFill=function(){return this.filling=!1,this.fillColor=null,this.fillAlpha=1,this},PIXI.Graphics.prototype.drawRect=function(t,e,i,s){return this.drawShape(new PIXI.Rectangle(t,e,i,s)),this},PIXI.Graphics.prototype.drawRoundedRect=function(t,e,i,s,n){return this.drawShape(new PIXI.RoundedRectangle(t,e,i,s,n)),this},PIXI.Graphics.prototype.drawCircle=function(t,e,i){return this.drawShape(new PIXI.Circle(t,e,i)),this},PIXI.Graphics.prototype.drawEllipse=function(t,e,i,s){return this.drawShape(new PIXI.Ellipse(t,e,i,s)),this},PIXI.Graphics.prototype.drawPolygon=function(t){(t instanceof n.Polygon||t instanceof PIXI.Polygon)&&(t=t.points);var e=t;if(!Array.isArray(e)){e=new Array(arguments.length);for(var i=0;i<e.length;++i)e[i]=arguments[i]}return this.drawShape(new n.Polygon(e)),this},PIXI.Graphics.prototype.clear=function(){return this.lineWidth=0,this.filling=!1,this.dirty=!0,this._boundsDirty=!0,this.clearDirty=!0,this.graphicsData=[],this.updateLocalBounds(),this},PIXI.Graphics.prototype.generateTexture=function(t,e,i){void 0===t&&(t=1),void 0===e&&(e=PIXI.scaleModes.DEFAULT),void 0===i&&(i=0);var s=this.getBounds();s.width+=i,s.height+=i;var n=new PIXI.CanvasBuffer(s.width*t,s.height*t),r=PIXI.Texture.fromCanvas(n.canvas,e);return r.baseTexture.resolution=t,n.context.scale(t,t),n.context.translate(-s.x,-s.y),PIXI.CanvasGraphics.renderGraphics(this,n.context),r},PIXI.Graphics.prototype._renderWebGL=function(t){if(!1!==this.visible&&0!==this.alpha&&!0!==this.isMask){if(this._cacheAsBitmap)return(this.dirty||this.cachedSpriteDirty)&&(this._generateCachedSprite(),this.updateCachedSpriteTexture(),this.cachedSpriteDirty=!1,this.dirty=!1),this._cachedSprite.worldAlpha=this.worldAlpha,void PIXI.Sprite.prototype._renderWebGL.call(this._cachedSprite,t);if(t.spriteBatch.stop(),t.blendModeManager.setBlendMode(this.blendMode),this._mask&&t.maskManager.pushMask(this._mask,t),this._filters&&t.filterManager.pushFilter(this._filterBlock),this.blendMode!==t.spriteBatch.currentBlendMode){t.spriteBatch.currentBlendMode=this.blendMode;var e=PIXI.blendModesWebGL[t.spriteBatch.currentBlendMode];t.spriteBatch.gl.blendFunc(e[0],e[1])}if(this.webGLDirty&&(this.dirty=!0,this.webGLDirty=!1),PIXI.WebGLGraphics.renderGraphics(this,t),this.children.length){t.spriteBatch.start();for(var i=0;i<this.children.length;i++)this.children[i]._renderWebGL(t);t.spriteBatch.stop()}this._filters&&t.filterManager.popFilter(),this._mask&&t.maskManager.popMask(this.mask,t),t.drawCount++,t.spriteBatch.start()}},PIXI.Graphics.prototype._renderCanvas=function(t){if(!1!==this.visible&&0!==this.alpha&&!0!==this.isMask){if(this._prevTint!==this.tint&&(this.dirty=!0,this._prevTint=this.tint),this._cacheAsBitmap)return(this.dirty||this.cachedSpriteDirty)&&(this._generateCachedSprite(),this.updateCachedSpriteTexture(),this.cachedSpriteDirty=!1,this.dirty=!1),this._cachedSprite.alpha=this.alpha,void PIXI.Sprite.prototype._renderCanvas.call(this._cachedSprite,t);var e=t.context,i=this.worldTransform;this.blendMode!==t.currentBlendMode&&(t.currentBlendMode=this.blendMode,e.globalCompositeOperation=PIXI.blendModesCanvas[t.currentBlendMode]),this._mask&&t.maskManager.pushMask(this._mask,t);var s=t.resolution,n=i.tx*t.resolution+t.shakeX,r=i.ty*t.resolution+t.shakeY;e.setTransform(i.a*s,i.b*s,i.c*s,i.d*s,n,r),PIXI.CanvasGraphics.renderGraphics(this,e);for(var o=0;o<this.children.length;o++)this.children[o]._renderCanvas(t);this._mask&&t.maskManager.popMask(t)}},PIXI.Graphics.prototype.getBounds=function(t){if(!this._currentBounds){if(!this.renderable)return PIXI.EmptyRectangle;this.dirty&&(this.updateLocalBounds(),this.webGLDirty=!0,this.cachedSpriteDirty=!0,this.dirty=!1);var e=this._localBounds,i=e.x,s=e.width+e.x,n=e.y,r=e.height+e.y,o=t||this.worldTransform,a=o.a,h=o.b,l=o.c,c=o.d,u=o.tx,d=o.ty,p=a*s+l*r+u,f=c*r+h*s+d,g=a*i+l*r+u,m=c*r+h*i+d,y=a*i+l*n+u,v=c*n+h*i+d,b=a*s+l*n+u,x=c*n+h*s+d,w=p,_=f,P=p,T=f;P=g<P?g:P,P=y<P?y:P,P=b<P?b:P,T=m<T?m:T,T=v<T?v:T,T=x<T?x:T,w=g>w?g:w,w=y>w?y:w,w=b>w?b:w,_=m>_?m:_,_=v>_?v:_,_=x>_?x:_,this._bounds.x=P,this._bounds.width=w-P,this._bounds.y=T,this._bounds.height=_-T,this._currentBounds=this._bounds}return this._currentBounds},PIXI.Graphics.prototype.getLocalBounds=function(){var t=this.worldTransform;this.worldTransform=PIXI.identityMatrix;for(var e=0;e<this.children.length;e++)this.children[e].updateTransform();var i=this.getBounds();for(this.worldTransform=t,e=0;e<this.children.length;e++)this.children[e].updateTransform();return i},PIXI.Graphics.prototype.containsPoint=function(t){this.worldTransform.applyInverse(t,tempPoint);for(var e=this.graphicsData,i=0;i<e.length;i++){var s=e[i];if(s.fill&&(s.shape&&s.shape.contains(tempPoint.x,tempPoint.y)))return!0}return!1},PIXI.Graphics.prototype.updateLocalBounds=function(){var t=1/0,e=-1/0,i=1/0,s=-1/0;if(this.graphicsData.length)for(var r,o,a,h,l,c,u=0;u<this.graphicsData.length;u++){var d=this.graphicsData[u],p=d.type,f=d.lineWidth;if(r=d.shape,p===PIXI.Graphics.RECT||p===PIXI.Graphics.RREC)a=r.x-f/2,h=r.y-f/2,l=r.width+f,c=r.height+f,t=a<t?a:t,e=a+l>e?a+l:e,i=h<i?h:i,s=h+c>s?h+c:s;else if(p===PIXI.Graphics.CIRC)a=r.x,h=r.y,l=r.radius+f/2,c=r.radius+f/2,t=a-l<t?a-l:t,e=a+l>e?a+l:e,i=h-c<i?h-c:i,s=h+c>s?h+c:s;else if(p===PIXI.Graphics.ELIP)a=r.x,h=r.y,l=r.width+f/2,c=r.height+f/2,t=a-l<t?a-l:t,e=a+l>e?a+l:e,i=h-c<i?h-c:i,s=h+c>s?h+c:s;else{o=r.points;for(var g=0;g<o.length;g++)o[g]instanceof n.Point?(a=o[g].x,h=o[g].y):(a=o[g],h=o[g+1],g<o.length-1&&g++),t=a-f<t?a-f:t,e=a+f>e?a+f:e,i=h-f<i?h-f:i,s=h+f>s?h+f:s}}else t=0,e=0,i=0,s=0;var m=this.boundsPadding;this._localBounds.x=t-m,this._localBounds.width=e-t+2*m,this._localBounds.y=i-m,this._localBounds.height=s-i+2*m},PIXI.Graphics.prototype._generateCachedSprite=function(){var t=this.getLocalBounds();if(this._cachedSprite)this._cachedSprite.buffer.resize(t.width,t.height);else{var e=new PIXI.CanvasBuffer(t.width,t.height),i=PIXI.Texture.fromCanvas(e.canvas);this._cachedSprite=new PIXI.Sprite(i),this._cachedSprite.buffer=e,this._cachedSprite.worldTransform=this.worldTransform}this._cachedSprite.anchor.x=-t.x/t.width,this._cachedSprite.anchor.y=-t.y/t.height,this._cachedSprite.buffer.context.translate(-t.x,-t.y),this.worldAlpha=1,PIXI.CanvasGraphics.renderGraphics(this,this._cachedSprite.buffer.context),this._cachedSprite.alpha=this.alpha},PIXI.Graphics.prototype.updateCachedSpriteTexture=function(){var t=this._cachedSprite,e=t.texture,i=t.buffer.canvas;e.baseTexture.width=i.width,e.baseTexture.height=i.height,e.crop.width=e.frame.width=i.width,e.crop.height=e.frame.height=i.height,t._width=i.width,t._height=i.height,e.baseTexture.dirty()},PIXI.Graphics.prototype.destroyCachedSprite=function(){this._cachedSprite.texture.destroy(!0),this._cachedSprite=null},PIXI.Graphics.prototype.drawShape=function(t){this.currentPath&&this.currentPath.shape.points.length<=2&&this.graphicsData.pop(),this.currentPath=null,t instanceof n.Polygon&&(t=t.clone(),t.flatten());var e=new PIXI.GraphicsData(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.filling,t);return this.graphicsData.push(e),e.type===PIXI.Graphics.POLY&&(e.shape.closed=this.filling,this.currentPath=e),this.dirty=!0,this._boundsDirty=!0,e},Object.defineProperty(PIXI.Graphics.prototype,"cacheAsBitmap",{get:function(){return this._cacheAsBitmap},set:function(t){this._cacheAsBitmap=t,this._cacheAsBitmap?this._generateCachedSprite():this.destroyCachedSprite(),this.dirty=!0,this.webGLDirty=!0}}),PIXI.GraphicsData=function(t,e,i,s,n,r,o){this.lineWidth=t,this.lineColor=e,this.lineAlpha=i,this._lineTint=e,this.fillColor=s,this.fillAlpha=n,this._fillTint=s,this.fill=r,this.shape=o,this.type=o.type},PIXI.GraphicsData.prototype.constructor=PIXI.GraphicsData,PIXI.GraphicsData.prototype.clone=function(){return new GraphicsData(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.fill,this.shape)},PIXI.EarCut={},PIXI.EarCut.Triangulate=function(t,e,i){i=i||2;var s=e&&e.length,n=s?e[0]*i:t.length,r=PIXI.EarCut.linkedList(t,0,n,i,!0),o=[];if(!r)return o;var a,h,l,c,u,d,p;if(s&&(r=PIXI.EarCut.eliminateHoles(t,e,r,i)),t.length>80*i){a=l=t[0],h=c=t[1];for(var f=i;f<n;f+=i)u=t[f],d=t[f+1],u<a&&(a=u),d<h&&(h=d),u>l&&(l=u),d>c&&(c=d);p=Math.max(l-a,c-h)}return PIXI.EarCut.earcutLinked(r,o,i,a,h,p),o},PIXI.EarCut.linkedList=function(t,e,i,s,n){var r,o,a,h=0;for(r=e,o=i-s;r<i;r+=s)h+=(t[o]-t[r])*(t[r+1]+t[o+1]),o=r;if(n===h>0)for(r=e;r<i;r+=s)a=PIXI.EarCut.insertNode(r,t[r],t[r+1],a);else for(r=i-s;r>=e;r-=s)a=PIXI.EarCut.insertNode(r,t[r],t[r+1],a);return a},PIXI.EarCut.filterPoints=function(t,e){if(!t)return t;e||(e=t);var i,s=t;do{if(i=!1,s.steiner||!PIXI.EarCut.equals(s,s.next)&&0!==PIXI.EarCut.area(s.prev,s,s.next))s=s.next;else{if(PIXI.EarCut.removeNode(s),(s=e=s.prev)===s.next)return null;i=!0}}while(i||s!==e);return e},PIXI.EarCut.earcutLinked=function(t,e,i,s,n,r,o){if(t){!o&&r&&PIXI.EarCut.indexCurve(t,s,n,r);for(var a,h,l=t;t.prev!==t.next;)if(a=t.prev,h=t.next,r?PIXI.EarCut.isEarHashed(t,s,n,r):PIXI.EarCut.isEar(t))e.push(a.i/i),e.push(t.i/i),e.push(h.i/i),PIXI.EarCut.removeNode(t),t=h.next,l=h.next;else if((t=h)===l){o?1===o?(t=PIXI.EarCut.cureLocalIntersections(t,e,i),PIXI.EarCut.earcutLinked(t,e,i,s,n,r,2)):2===o&&PIXI.EarCut.splitEarcut(t,e,i,s,n,r):PIXI.EarCut.earcutLinked(PIXI.EarCut.filterPoints(t),e,i,s,n,r,1);break}}},PIXI.EarCut.isEar=function(t){var e=t.prev,i=t,s=t.next;if(PIXI.EarCut.area(e,i,s)>=0)return!1;for(var n=t.next.next;n!==t.prev;){if(PIXI.EarCut.pointInTriangle(e.x,e.y,i.x,i.y,s.x,s.y,n.x,n.y)&&PIXI.EarCut.area(n.prev,n,n.next)>=0)return!1;n=n.next}return!0},PIXI.EarCut.isEarHashed=function(t,e,i,s){var n=t.prev,r=t,o=t.next;if(PIXI.EarCut.area(n,r,o)>=0)return!1;for(var a=n.x<r.x?n.x<o.x?n.x:o.x:r.x<o.x?r.x:o.x,h=n.y<r.y?n.y<o.y?n.y:o.y:r.y<o.y?r.y:o.y,l=n.x>r.x?n.x>o.x?n.x:o.x:r.x>o.x?r.x:o.x,c=n.y>r.y?n.y>o.y?n.y:o.y:r.y>o.y?r.y:o.y,u=PIXI.EarCut.zOrder(a,h,e,i,s),d=PIXI.EarCut.zOrder(l,c,e,i,s),p=t.nextZ;p&&p.z<=d;){if(p!==t.prev&&p!==t.next&&PIXI.EarCut.pointInTriangle(n.x,n.y,r.x,r.y,o.x,o.y,p.x,p.y)&&PIXI.EarCut.area(p.prev,p,p.next)>=0)return!1;p=p.nextZ}for(p=t.prevZ;p&&p.z>=u;){if(p!==t.prev&&p!==t.next&&PIXI.EarCut.pointInTriangle(n.x,n.y,r.x,r.y,o.x,o.y,p.x,p.y)&&PIXI.EarCut.area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}return!0},PIXI.EarCut.cureLocalIntersections=function(t,e,i){var s=t;do{var n=s.prev,r=s.next.next;PIXI.EarCut.intersects(n,s,s.next,r)&&PIXI.EarCut.locallyInside(n,r)&&PIXI.EarCut.locallyInside(r,n)&&(e.push(n.i/i),e.push(s.i/i),e.push(r.i/i),PIXI.EarCut.removeNode(s),PIXI.EarCut.removeNode(s.next),s=t=r),s=s.next}while(s!==t);return s},PIXI.EarCut.splitEarcut=function(t,e,i,s,n,r){var o=t;do{for(var a=o.next.next;a!==o.prev;){if(o.i!==a.i&&PIXI.EarCut.isValidDiagonal(o,a)){var h=PIXI.EarCut.splitPolygon(o,a);return o=PIXI.EarCut.filterPoints(o,o.next),h=PIXI.EarCut.filterPoints(h,h.next),PIXI.EarCut.earcutLinked(o,e,i,s,n,r),void PIXI.EarCut.earcutLinked(h,e,i,s,n,r)}a=a.next}o=o.next}while(o!==t)},PIXI.EarCut.eliminateHoles=function(t,e,i,s){var n,r,o,a,h,l=[];for(n=0,r=e.length;n<r;n++)o=e[n]*s,a=n<r-1?e[n+1]*s:t.length,h=PIXI.EarCut.linkedList(t,o,a,s,!1),h===h.next&&(h.steiner=!0),l.push(PIXI.EarCut.getLeftmost(h));for(l.sort(compareX),n=0;n<l.length;n++)PIXI.EarCut.eliminateHole(l[n],i),i=PIXI.EarCut.filterPoints(i,i.next);return i},PIXI.EarCut.compareX=function(t,e){return t.x-e.x},PIXI.EarCut.eliminateHole=function(t,e){if(e=PIXI.EarCut.findHoleBridge(t,e)){var i=PIXI.EarCut.splitPolygon(e,t);PIXI.EarCut.filterPoints(i,i.next)}},PIXI.EarCut.findHoleBridge=function(t,e){var i,s=e,n=t.x,r=t.y,o=-1/0;do{if(r<=s.y&&r>=s.next.y){var a=s.x+(r-s.y)*(s.next.x-s.x)/(s.next.y-s.y);a<=n&&a>o&&(o=a,i=s.x<s.next.x?s:s.next)}s=s.next}while(s!==e);if(!i)return null;if(t.x===i.x)return i.prev;var h,l=i,c=1/0;for(s=i.next;s!==l;)n>=s.x&&s.x>=i.x&&PIXI.EarCut.pointInTriangle(r<i.y?n:o,r,i.x,i.y,r<i.y?o:n,r,s.x,s.y)&&((h=Math.abs(r-s.y)/(n-s.x))<c||h===c&&s.x>i.x)&&PIXI.EarCut.locallyInside(s,t)&&(i=s,c=h),s=s.next;return i},PIXI.EarCut.indexCurve=function(t,e,i,s){var n=t;do{null===n.z&&(n.z=PIXI.EarCut.zOrder(n.x,n.y,e,i,s)),n.prevZ=n.prev,n.nextZ=n.next,n=n.next}while(n!==t);n.prevZ.nextZ=null,n.prevZ=null,PIXI.EarCut.sortLinked(n)},PIXI.EarCut.sortLinked=function(t){var e,i,s,n,r,o,a,h,l=1;do{for(i=t,t=null,r=null,o=0;i;){for(o++,s=i,a=0,e=0;e<l&&(a++,s=s.nextZ);e++);for(h=l;a>0||h>0&&s;)0===a?(n=s,s=s.nextZ,h--):0!==h&&s?i.z<=s.z?(n=i,i=i.nextZ,a--):(n=s,s=s.nextZ,h--):(n=i,i=i.nextZ,a--),r?r.nextZ=n:t=n,n.prevZ=r,r=n;i=s}r.nextZ=null,l*=2}while(o>1);return t},PIXI.EarCut.zOrder=function(t,e,i,s,n){return t=32767*(t-i)/n,e=32767*(e-s)/n,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1},PIXI.EarCut.getLeftmost=function(t){var e=t,i=t;do{e.x<i.x&&(i=e),e=e.next}while(e!==t);return i},PIXI.EarCut.pointInTriangle=function(t,e,i,s,n,r,o,a){return(n-o)*(e-a)-(t-o)*(r-a)>=0&&(t-o)*(s-a)-(i-o)*(e-a)>=0&&(i-o)*(r-a)-(n-o)*(s-a)>=0},PIXI.EarCut.isValidDiagonal=function(t,e){return PIXI.EarCut.equals(t,e)||t.next.i!==e.i&&t.prev.i!==e.i&&!PIXI.EarCut.intersectsPolygon(t,e)&&PIXI.EarCut.locallyInside(t,e)&&PIXI.EarCut.locallyInside(e,t)&&PIXI.EarCut.middleInside(t,e)},PIXI.EarCut.area=function(t,e,i){return(e.y-t.y)*(i.x-e.x)-(e.x-t.x)*(i.y-e.y)},PIXI.EarCut.equals=function(t,e){return t.x===e.x&&t.y===e.y},PIXI.EarCut.intersects=function(t,e,i,s){return PIXI.EarCut.area(t,e,i)>0!=PIXI.EarCut.area(t,e,s)>0&&PIXI.EarCut.area(i,s,t)>0!=PIXI.EarCut.area(i,s,e)>0},PIXI.EarCut.intersectsPolygon=function(t,e){var i=t;do{if(i.i!==t.i&&i.next.i!==t.i&&i.i!==e.i&&i.next.i!==e.i&&PIXI.EarCut.intersects(i,i.next,t,e))return!0;i=i.next}while(i!==t);return!1},PIXI.EarCut.locallyInside=function(t,e){return PIXI.EarCut.area(t.prev,t,t.next)<0?PIXI.EarCut.area(t,e,t.next)>=0&&PIXI.EarCut.area(t,t.prev,e)>=0:PIXI.EarCut.area(t,e,t.prev)<0||PIXI.EarCut.area(t,t.next,e)<0},PIXI.EarCut.middleInside=function(t,e){var i=t,s=!1,n=(t.x+e.x)/2,r=(t.y+e.y)/2;do{i.y>r!=i.next.y>r&&n<(i.next.x-i.x)*(r-i.y)/(i.next.y-i.y)+i.x&&(s=!s),i=i.next}while(i!==t);return s},PIXI.EarCut.splitPolygon=function(t,e){var i=new PIXI.EarCut.Node(t.i,t.x,t.y),s=new PIXI.EarCut.Node(e.i,e.x,e.y),n=t.next,r=e.prev;return t.next=e,e.prev=t,i.next=n,n.prev=i,s.next=i,i.prev=s,r.next=s,s.prev=r,s},PIXI.EarCut.insertNode=function(t,e,i,s){var n=new PIXI.EarCut.Node(t,e,i);return s?(n.next=s.next,n.prev=s,s.next.prev=n,s.next=n):(n.prev=n,n.next=n),n},PIXI.EarCut.removeNode=function(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)},PIXI.EarCut.Node=function(t,e,i){this.i=t,this.x=e,this.y=i,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1},PIXI.WebGLGraphics=function(){},PIXI.WebGLGraphics.stencilBufferLimit=6,PIXI.WebGLGraphics.renderGraphics=function(t,e){var i,s=e.gl,n=e.projection,r=e.offset,o=e.shaderManager.primitiveShader;t.dirty&&PIXI.WebGLGraphics.updateGraphics(t,s);for(var a=t._webGL[s.id],h=0;h<a.data.length;h++)1===a.data[h].mode?(i=a.data[h],e.stencilManager.pushStencil(t,i,e),s.drawElements(s.TRIANGLE_FAN,4,s.UNSIGNED_SHORT,2*(i.indices.length-4)),e.stencilManager.popStencil(t,i,e)):(i=a.data[h],e.shaderManager.setShader(o),o=e.shaderManager.primitiveShader,s.uniformMatrix3fv(o.translationMatrix,!1,t.worldTransform.toArray(!0)),s.uniform1f(o.flipY,1),s.uniform2f(o.projectionVector,n.x,-n.y),s.uniform2f(o.offsetVector,-r.x,-r.y),s.uniform3fv(o.tintColor,PIXI.hex2rgb(t.tint)),s.uniform1f(o.alpha,t.worldAlpha),s.bindBuffer(s.ARRAY_BUFFER,i.buffer),s.vertexAttribPointer(o.aVertexPosition,2,s.FLOAT,!1,24,0),s.vertexAttribPointer(o.colorAttribute,4,s.FLOAT,!1,24,8),s.bindBuffer(s.ELEMENT_ARRAY_BUFFER,i.indexBuffer),s.drawElements(s.TRIANGLE_STRIP,i.indices.length,s.UNSIGNED_SHORT,0))},PIXI.WebGLGraphics.updateGraphics=function(t,e){var i=t._webGL[e.id];i||(i=t._webGL[e.id]={lastIndex:0,data:[],gl:e}),t.dirty=!1;var s;if(t.clearDirty){for(t.clearDirty=!1,s=0;s<i.data.length;s++){var n=i.data[s];n.reset(),PIXI.WebGLGraphics.graphicsDataPool.push(n)}i.data=[],i.lastIndex=0}var r;for(s=i.lastIndex;s<t.graphicsData.length;s++){var o=t.graphicsData[s];if(o.type===PIXI.Graphics.POLY){if(o.points=o.shape.points.slice(),o.shape.closed&&(o.points[0]===o.points[o.points.length-2]&&o.points[1]===o.points[o.points.length-1]||o.points.push(o.points[0],o.points[1])),o.fill&&o.points.length>=PIXI.WebGLGraphics.stencilBufferLimit)if(o.points.length<2*PIXI.WebGLGraphics.stencilBufferLimit){r=PIXI.WebGLGraphics.switchMode(i,0);var a=PIXI.WebGLGraphics.buildPoly(o,r);a||(r=PIXI.WebGLGraphics.switchMode(i,1),PIXI.WebGLGraphics.buildComplexPoly(o,r))}else r=PIXI.WebGLGraphics.switchMode(i,1),PIXI.WebGLGraphics.buildComplexPoly(o,r);o.lineWidth>0&&(r=PIXI.WebGLGraphics.switchMode(i,0),PIXI.WebGLGraphics.buildLine(o,r))}else r=PIXI.WebGLGraphics.switchMode(i,0),o.type===PIXI.Graphics.RECT?PIXI.WebGLGraphics.buildRectangle(o,r):o.type===PIXI.Graphics.CIRC||o.type===PIXI.Graphics.ELIP?PIXI.WebGLGraphics.buildCircle(o,r):o.type===PIXI.Graphics.RREC&&PIXI.WebGLGraphics.buildRoundedRectangle(o,r);i.lastIndex++}for(s=0;s<i.data.length;s++)r=i.data[s],r.dirty&&r.upload()},PIXI.WebGLGraphics.switchMode=function(t,e){var i;return t.data.length?(i=t.data[t.data.length-1],i.mode===e&&1!==e||(i=PIXI.WebGLGraphics.graphicsDataPool.pop()||new PIXI.WebGLGraphicsData(t.gl),i.mode=e,t.data.push(i))):(i=PIXI.WebGLGraphics.graphicsDataPool.pop()||new PIXI.WebGLGraphicsData(t.gl),i.mode=e,t.data.push(i)),i.dirty=!0,i},PIXI.WebGLGraphics.buildRectangle=function(t,e){var i=t.shape,s=i.x,n=i.y,r=i.width,o=i.height;if(t.fill){var a=PIXI.hex2rgb(t.fillColor),h=t.fillAlpha,l=a[0]*h,c=a[1]*h,u=a[2]*h,d=e.points,p=e.indices,f=d.length/6;d.push(s,n),d.push(l,c,u,h),d.push(s+r,n),d.push(l,c,u,h),d.push(s,n+o),d.push(l,c,u,h),d.push(s+r,n+o),d.push(l,c,u,h),p.push(f,f,f+1,f+2,f+3,f+3)}if(t.lineWidth){var g=t.points;t.points=[s,n,s+r,n,s+r,n+o,s,n+o,s,n],PIXI.WebGLGraphics.buildLine(t,e),t.points=g}},PIXI.WebGLGraphics.buildRoundedRectangle=function(t,e){var i=t.shape,s=i.x,n=i.y,r=i.width,o=i.height,a=i.radius,h=[];if(h.push(s,n+a),h=h.concat(PIXI.WebGLGraphics.quadraticBezierCurve(s,n+o-a,s,n+o,s+a,n+o)),h=h.concat(PIXI.WebGLGraphics.quadraticBezierCurve(s+r-a,n+o,s+r,n+o,s+r,n+o-a)),h=h.concat(PIXI.WebGLGraphics.quadraticBezierCurve(s+r,n+a,s+r,n,s+r-a,n)),h=h.concat(PIXI.WebGLGraphics.quadraticBezierCurve(s+a,n,s,n,s,n+a)),t.fill){var l=PIXI.hex2rgb(t.fillColor),c=t.fillAlpha,u=l[0]*c,d=l[1]*c,p=l[2]*c,f=e.points,g=e.indices,m=f.length/6,y=PIXI.EarCut.Triangulate(h,null,2),v=0;for(v=0;v<y.length;v+=3)g.push(y[v]+m),g.push(y[v]+m),g.push(y[v+1]+m),g.push(y[v+2]+m),g.push(y[v+2]+m);for(v=0;v<h.length;v++)f.push(h[v],h[++v],u,d,p,c)}if(t.lineWidth){var b=t.points;t.points=h,PIXI.WebGLGraphics.buildLine(t,e),t.points=b}},PIXI.WebGLGraphics.quadraticBezierCurve=function(t,e,i,s,n,r){function o(t,e,i){return t+(e-t)*i}for(var a,h,l,c,u,d,p=[],f=0,g=0;g<=20;g++)f=g/20,a=o(t,i,f),h=o(e,s,f),l=o(i,n,f),c=o(s,r,f),u=o(a,l,f),d=o(h,c,f),p.push(u,d);return p},PIXI.WebGLGraphics.buildCircle=function(t,e){var i,s,n=t.shape,r=n.x,o=n.y;t.type===PIXI.Graphics.CIRC?(i=n.radius,s=n.radius):(i=n.width,s=n.height);var a=2*Math.PI/40,h=0;if(t.fill){var l=PIXI.hex2rgb(t.fillColor),c=t.fillAlpha,u=l[0]*c,d=l[1]*c,p=l[2]*c,f=e.points,g=e.indices,m=f.length/6;for(g.push(m),h=0;h<41;h++)f.push(r,o,u,d,p,c),f.push(r+Math.sin(a*h)*i,o+Math.cos(a*h)*s,u,d,p,c),g.push(m++,m++);g.push(m-1)}if(t.lineWidth){var y=t.points;for(t.points=[],h=0;h<41;h++)t.points.push(r+Math.sin(a*h)*i,o+Math.cos(a*h)*s);PIXI.WebGLGraphics.buildLine(t,e),t.points=y}},PIXI.WebGLGraphics.buildLine=function(t,e){var i=0,s=t.points;if(0!==s.length){if(t.lineWidth%2)for(i=0;i<s.length;i++)s[i]+=.5;var n=new PIXI.Point(s[0],s[1]),r=new PIXI.Point(s[s.length-2],s[s.length-1]);if(n.x===r.x&&n.y===r.y){s=s.slice(),s.pop(),s.pop(),r=new PIXI.Point(s[s.length-2],s[s.length-1]);var o=r.x+.5*(n.x-r.x),a=r.y+.5*(n.y-r.y);s.unshift(o,a),s.push(o,a)}var h,l,c,u,d,p,f,g,m,y,v,b,x,w,_,P,T,C,S,A,E,I,M,R=e.points,B=e.indices,L=s.length/2,O=s.length,k=R.length/6,F=t.lineWidth/2,D=PIXI.hex2rgb(t.lineColor),U=t.lineAlpha,G=D[0]*U,N=D[1]*U,X=D[2]*U;for(c=s[0],u=s[1],d=s[2],p=s[3],m=-(u-p),y=c-d,M=Math.sqrt(m*m+y*y),m/=M,y/=M,m*=F,y*=F,R.push(c-m,u-y,G,N,X,U),R.push(c+m,u+y,G,N,X,U),i=1;i<L-1;i++)c=s[2*(i-1)],u=s[2*(i-1)+1],d=s[2*i],p=s[2*i+1],f=s[2*(i+1)],g=s[2*(i+1)+1],m=-(u-p),y=c-d,M=Math.sqrt(m*m+y*y),m/=M,y/=M,m*=F,y*=F,v=-(p-g),b=d-f,M=Math.sqrt(v*v+b*b),v/=M,b/=M,v*=F,b*=F,_=-y+u-(-y+p),P=-m+d-(-m+c),T=(-m+c)*(-y+p)-(-m+d)*(-y+u),C=-b+g-(-b+p),S=-v+d-(-v+f),A=(-v+f)*(-b+p)-(-v+d)*(-b+g),E=_*S-C*P,Math.abs(E)<.1?(E+=10.1,R.push(d-m,p-y,G,N,X,U),R.push(d+m,p+y,G,N,X,U)):(h=(P*A-S*T)/E,l=(C*T-_*A)/E,I=(h-d)*(h-d)+(l-p)+(l-p),I>19600?(x=m-v,w=y-b,M=Math.sqrt(x*x+w*w),x/=M,w/=M,x*=F,w*=F,R.push(d-x,p-w),R.push(G,N,X,U),R.push(d+x,p+w),R.push(G,N,X,U),R.push(d-x,p-w),R.push(G,N,X,U),O++):(R.push(h,l),R.push(G,N,X,U),R.push(d-(h-d),p-(l-p)),R.push(G,N,X,U)));for(c=s[2*(L-2)],u=s[2*(L-2)+1],d=s[2*(L-1)],p=s[2*(L-1)+1],m=-(u-p),y=c-d,M=Math.sqrt(m*m+y*y),m/=M,y/=M,m*=F,y*=F,R.push(d-m,p-y),R.push(G,N,X,U),R.push(d+m,p+y),R.push(G,N,X,U),B.push(k),i=0;i<O;i++)B.push(k++);B.push(k-1)}},PIXI.WebGLGraphics.buildComplexPoly=function(t,e){var i=t.points.slice();if(!(i.length<6)){var s=e.indices;e.points=i,e.alpha=t.fillAlpha,e.color=PIXI.hex2rgb(t.fillColor);for(var n,r,o=1/0,a=-1/0,h=1/0,l=-1/0,c=0;c<i.length;c+=2)n=i[c],r=i[c+1],o=n<o?n:o,a=n>a?n:a,h=r<h?r:h,l=r>l?r:l;i.push(o,h,a,h,a,l,o,l);var u=i.length/2;for(c=0;c<u;c++)s.push(c)}},PIXI.WebGLGraphics.buildPoly=function(t,e){var i=t.points;if(!(i.length<6)){var s=e.points,n=e.indices,r=i.length/2,o=PIXI.hex2rgb(t.fillColor),a=t.fillAlpha,h=o[0]*a,l=o[1]*a,c=o[2]*a,u=PIXI.EarCut.Triangulate(i,null,2);if(!u)return!1;var d=s.length/6,p=0;for(p=0;p<u.length;p+=3)n.push(u[p]+d),n.push(u[p]+d),n.push(u[p+1]+d),n.push(u[p+2]+d),n.push(u[p+2]+d);for(p=0;p<r;p++)s.push(i[2*p],i[2*p+1],h,l,c,a);return!0}},PIXI.WebGLGraphics.graphicsDataPool=[],PIXI.WebGLGraphicsData=function(t){this.gl=t,this.color=[0,0,0],this.points=[],this.indices=[],this.buffer=t.createBuffer(),this.indexBuffer=t.createBuffer(),this.mode=1,this.alpha=1,this.dirty=!0},PIXI.WebGLGraphicsData.prototype.reset=function(){this.points=[],this.indices=[]},PIXI.WebGLGraphicsData.prototype.upload=function(){var t=this.gl;this.glPoints=new PIXI.Float32Array(this.points),t.bindBuffer(t.ARRAY_BUFFER,this.buffer),t.bufferData(t.ARRAY_BUFFER,this.glPoints,t.STATIC_DRAW),this.glIndicies=new PIXI.Uint16Array(this.indices),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,this.glIndicies,t.STATIC_DRAW),this.dirty=!1},PIXI.CanvasGraphics=function(){},PIXI.CanvasGraphics.renderGraphics=function(t,e){var i=t.worldAlpha;t.dirty&&(this.updateGraphicsTint(t),t.dirty=!1);for(var s=0;s<t.graphicsData.length;s++){var n=t.graphicsData[s],r=n.shape,o=n._fillTint,a=n._lineTint;if(e.lineWidth=n.lineWidth,n.type===PIXI.Graphics.POLY){e.beginPath();var h=r.points;e.moveTo(h[0],h[1]);for(var l=1;l<h.length/2;l++)e.lineTo(h[2*l],h[2*l+1]);r.closed&&e.lineTo(h[0],h[1]),h[0]===h[h.length-2]&&h[1]===h[h.length-1]&&e.closePath(),n.fill&&(e.globalAlpha=n.fillAlpha*i,e.fillStyle="#"+("00000"+(0|o).toString(16)).substr(-6),e.fill()),n.lineWidth&&(e.globalAlpha=n.lineAlpha*i,e.strokeStyle="#"+("00000"+(0|a).toString(16)).substr(-6),e.stroke())}else if(n.type===PIXI.Graphics.RECT)(n.fillColor||0===n.fillColor)&&(e.globalAlpha=n.fillAlpha*i,e.fillStyle="#"+("00000"+(0|o).toString(16)).substr(-6),e.fillRect(r.x,r.y,r.width,r.height)),n.lineWidth&&(e.globalAlpha=n.lineAlpha*i,e.strokeStyle="#"+("00000"+(0|a).toString(16)).substr(-6),e.strokeRect(r.x,r.y,r.width,r.height));else if(n.type===PIXI.Graphics.CIRC)e.beginPath(),e.arc(r.x,r.y,r.radius,0,2*Math.PI),e.closePath(),n.fill&&(e.globalAlpha=n.fillAlpha*i,e.fillStyle="#"+("00000"+(0|o).toString(16)).substr(-6),e.fill()),n.lineWidth&&(e.globalAlpha=n.lineAlpha*i,e.strokeStyle="#"+("00000"+(0|a).toString(16)).substr(-6),e.stroke());else if(n.type===PIXI.Graphics.ELIP){var c=2*r.width,u=2*r.height,d=r.x-c/2,p=r.y-u/2;e.beginPath();var f=c/2*.5522848,g=u/2*.5522848,m=d+c,y=p+u,v=d+c/2,b=p+u/2;e.moveTo(d,b),e.bezierCurveTo(d,b-g,v-f,p,v,p),e.bezierCurveTo(v+f,p,m,b-g,m,b),e.bezierCurveTo(m,b+g,v+f,y,v,y),e.bezierCurveTo(v-f,y,d,b+g,d,b),e.closePath(),n.fill&&(e.globalAlpha=n.fillAlpha*i,e.fillStyle="#"+("00000"+(0|o).toString(16)).substr(-6),e.fill()),n.lineWidth&&(e.globalAlpha=n.lineAlpha*i,e.strokeStyle="#"+("00000"+(0|a).toString(16)).substr(-6),e.stroke())}else if(n.type===PIXI.Graphics.RREC){var x=r.x,w=r.y,_=r.width,P=r.height,T=r.radius,C=Math.min(_,P)/2|0;T=T>C?C:T,e.beginPath(),e.moveTo(x,w+T),e.lineTo(x,w+P-T),e.quadraticCurveTo(x,w+P,x+T,w+P),e.lineTo(x+_-T,w+P),e.quadraticCurveTo(x+_,w+P,x+_,w+P-T),e.lineTo(x+_,w+T),e.quadraticCurveTo(x+_,w,x+_-T,w),e.lineTo(x+T,w),e.quadraticCurveTo(x,w,x,w+T),e.closePath(),(n.fillColor||0===n.fillColor)&&(e.globalAlpha=n.fillAlpha*i,e.fillStyle="#"+("00000"+(0|o).toString(16)).substr(-6),e.fill()),n.lineWidth&&(e.globalAlpha=n.lineAlpha*i,e.strokeStyle="#"+("00000"+(0|a).toString(16)).substr(-6),e.stroke())}}},PIXI.CanvasGraphics.renderGraphicsMask=function(t,e){var i=t.graphicsData.length;if(0!==i){e.beginPath();for(var s=0;s<i;s++){var n=t.graphicsData[s],r=n.shape;if(n.type===PIXI.Graphics.POLY){var o=r.points;e.moveTo(o[0],o[1]);for(var a=1;a<o.length/2;a++)e.lineTo(o[2*a],o[2*a+1]);o[0]===o[o.length-2]&&o[1]===o[o.length-1]&&e.closePath()}else if(n.type===PIXI.Graphics.RECT)e.rect(r.x,r.y,r.width,r.height),e.closePath();else if(n.type===PIXI.Graphics.CIRC)e.arc(r.x,r.y,r.radius,0,2*Math.PI),e.closePath();else if(n.type===PIXI.Graphics.ELIP){var h=2*r.width,l=2*r.height,c=r.x-h/2,u=r.y-l/2,d=h/2*.5522848,p=l/2*.5522848,f=c+h,g=u+l,m=c+h/2,y=u+l/2;e.moveTo(c,y),e.bezierCurveTo(c,y-p,m-d,u,m,u),e.bezierCurveTo(m+d,u,f,y-p,f,y),e.bezierCurveTo(f,y+p,m+d,g,m,g),e.bezierCurveTo(m-d,g,c,y+p,c,y),e.closePath()}else if(n.type===PIXI.Graphics.RREC){var v=r.x,b=r.y,x=r.width,w=r.height,_=r.radius,P=Math.min(x,w)/2|0;_=_>P?P:_,e.moveTo(v,b+_),e.lineTo(v,b+w-_),e.quadraticCurveTo(v,b+w,v+_,b+w),e.lineTo(v+x-_,b+w),e.quadraticCurveTo(v+x,b+w,v+x,b+w-_),e.lineTo(v+x,b+_),e.quadraticCurveTo(v+x,b,v+x-_,b),e.lineTo(v+_,b),e.quadraticCurveTo(v,b,v,b+_),e.closePath()}}}},PIXI.CanvasGraphics.updateGraphicsTint=function(t){if(16777215!==t.tint)for(var e=(t.tint>>16&255)/255,i=(t.tint>>8&255)/255,s=(255&t.tint)/255,n=0;n<t.graphicsData.length;n++){var r=t.graphicsData[n],o=0|r.fillColor,a=0|r.lineColor;r._fillTint=((o>>16&255)/255*e*255<<16)+((o>>8&255)/255*i*255<<8)+(255&o)/255*s*255,r._lineTint=((a>>16&255)/255*e*255<<16)+((a>>8&255)/255*i*255<<8)+(255&a)/255*s*255}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Graphics=function(t,e,i){void 0===e&&(e=0),void 0===i&&(i=0),this.type=n.GRAPHICS,this.physicsType=n.SPRITE,this.anchor=new n.Point,PIXI.Graphics.call(this),n.Component.Core.init.call(this,t,e,i,"",null)},n.Graphics.prototype=Object.create(PIXI.Graphics.prototype),n.Graphics.prototype.constructor=n.Graphics,n.Component.Core.install.call(n.Graphics.prototype,["Angle","AutoCull","Bounds","Destroy","FixedToCamera","InputEnabled","InWorld","LifeSpan","PhysicsBody","Reset"]),n.Graphics.prototype.preUpdatePhysics=n.Component.PhysicsBody.preUpdate,n.Graphics.prototype.preUpdateLifeSpan=n.Component.LifeSpan.preUpdate,n.Graphics.prototype.preUpdateInWorld=n.Component.InWorld.preUpdate,n.Graphics.prototype.preUpdateCore=n.Component.Core.preUpdate,n.Graphics.prototype.preUpdate=function(){return!!(this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld())&&this.preUpdateCore()},n.Graphics.prototype.postUpdate=function(){n.Component.PhysicsBody.postUpdate.call(this),n.Component.FixedToCamera.postUpdate.call(this),this._boundsDirty&&(this.updateLocalBounds(),this._boundsDirty=!1);for(var t=0;t<this.children.length;t++)this.children[t].postUpdate()},n.Graphics.prototype.destroy=function(t){this.clear(),n.Component.Destroy.prototype.destroy.call(this,t)},n.Graphics.prototype.drawTriangle=function(t,e){void 0===e&&(e=!1);var i=new n.Polygon(t);if(e){var s=new n.Point(this.game.camera.x-t[0].x,this.game.camera.y-t[0].y),r=new n.Point(t[1].x-t[0].x,t[1].y-t[0].y),o=new n.Point(t[1].x-t[2].x,t[1].y-t[2].y),a=o.cross(r);s.dot(a)>0&&this.drawPolygon(i)}else this.drawPolygon(i)},n.Graphics.prototype.drawTriangles=function(t,e,i){void 0===i&&(i=!1);var s,r=new n.Point,o=new n.Point,a=new n.Point,h=[];if(e)if(t[0]instanceof n.Point)for(s=0;s<e.length/3;s++)h.push(t[e[3*s]]),h.push(t[e[3*s+1]]),h.push(t[e[3*s+2]]),3===h.length&&(this.drawTriangle(h,i),h=[]);else for(s=0;s<e.length;s++)r.x=t[2*e[s]],r.y=t[2*e[s]+1],h.push(r.copyTo({})),3===h.length&&(this.drawTriangle(h,i),h=[]);else if(t[0]instanceof n.Point)for(s=0;s<t.length/3;s++)this.drawTriangle([t[3*s],t[3*s+1],t[3*s+2]],i);else for(s=0;s<t.length/6;s++)r.x=t[6*s+0],r.y=t[6*s+1],o.x=t[6*s+2],o.y=t[6*s+3],a.x=t[6*s+4],a.y=t[6*s+5],this.drawTriangle([r,o,a],i)},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.RenderTexture=function(t,e,i,s,r,o){void 0===s&&(s=""),void 0===r&&(r=n.scaleModes.DEFAULT),void 0===o&&(o=1),this.game=t,this.key=s,this.type=n.RENDERTEXTURE,this._tempMatrix=new PIXI.Matrix,PIXI.RenderTexture.call(this,e,i,this.game.renderer,r,o),this.render=n.RenderTexture.prototype.render},n.RenderTexture.prototype=Object.create(PIXI.RenderTexture.prototype),n.RenderTexture.prototype.constructor=n.RenderTexture,n.RenderTexture.prototype.renderXY=function(t,e,i,s){t.updateTransform(),this._tempMatrix.copyFrom(t.worldTransform),this._tempMatrix.tx=e,this._tempMatrix.ty=i,this.renderer.type===PIXI.WEBGL_RENDERER?this.renderWebGL(t,this._tempMatrix,s):this.renderCanvas(t,this._tempMatrix,s)},n.RenderTexture.prototype.renderRawXY=function(t,e,i,s){this._tempMatrix.identity().translate(e,i),this.renderer.type===PIXI.WEBGL_RENDERER?this.renderWebGL(t,this._tempMatrix,s):this.renderCanvas(t,this._tempMatrix,s)},n.RenderTexture.prototype.render=function(t,e,i){void 0===e||null===e?this._tempMatrix.copyFrom(t.worldTransform):this._tempMatrix.copyFrom(e),this.renderer.type===PIXI.WEBGL_RENDERER?this.renderWebGL(t,this._tempMatrix,i):this.renderCanvas(t,this._tempMatrix,i)},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Text=function(t,e,i,s,r){e=e||0,i=i||0,s=void 0===s||null===s?"":s.toString(),r=n.Utils.extend({},r),this.type=n.TEXT,this.physicsType=n.SPRITE,this.padding=new n.Point,this.textBounds=null,this.canvas=PIXI.CanvasPool.create(this),this.context=this.canvas.getContext("2d"),this.colors=[],this.strokeColors=[],this.fontStyles=[],this.fontWeights=[],this.autoRound=!1,this.useAdvancedWrap=!1,this._res=t.renderer.resolution,this._text=s,this._fontComponents=null,this._lineSpacing=0,this._charCount=0,this._width=0,this._height=0,n.Sprite.call(this,t,e,i,PIXI.Texture.fromCanvas(this.canvas)),this.setStyle(r),""!==s&&this.updateText()},n.Text.prototype=Object.create(n.Sprite.prototype),n.Text.prototype.constructor=n.Text,n.Text.prototype.preUpdate=function(){return!!(this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld())&&this.preUpdateCore()},n.Text.prototype.update=function(){},n.Text.prototype.destroy=function(t){this.texture.destroy(!0),n.Component.Destroy.prototype.destroy.call(this,t)},n.Text.prototype.setShadow=function(t,e,i,s,n,r){return void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i="rgba(0, 0, 0, 1)"),void 0===s&&(s=0),void 0===n&&(n=!0),void 0===r&&(r=!0),this.style.shadowOffsetX=t,this.style.shadowOffsetY=e,this.style.shadowColor=i,this.style.shadowBlur=s,this.style.shadowStroke=n,this.style.shadowFill=r,this.dirty=!0,this},n.Text.prototype.setStyle=function(t,e){void 0===e&&(e=!1),t=t||{},t.font=t.font||"bold 20pt Arial",t.backgroundColor=t.backgroundColor||null,t.fill=t.fill||"black",t.align=t.align||"left",t.boundsAlignH=t.boundsAlignH||"left",t.boundsAlignV=t.boundsAlignV||"top",t.stroke=t.stroke||"black",t.strokeThickness=t.strokeThickness||0,t.wordWrap=t.wordWrap||!1,t.wordWrapWidth=t.wordWrapWidth||100,t.maxLines=t.maxLines||0,t.shadowOffsetX=t.shadowOffsetX||0,t.shadowOffsetY=t.shadowOffsetY||0,t.shadowColor=t.shadowColor||"rgba(0,0,0,0)",t.shadowBlur=t.shadowBlur||0,t.tabs=t.tabs||0;var i=this.fontToComponents(t.font);return t.fontStyle&&(i.fontStyle=t.fontStyle),t.fontVariant&&(i.fontVariant=t.fontVariant),t.fontWeight&&(i.fontWeight=t.fontWeight),t.fontSize&&("number"==typeof t.fontSize&&(t.fontSize=t.fontSize+"px"),i.fontSize=t.fontSize),this._fontComponents=i,t.font=this.componentsToFont(this._fontComponents),this.style=t,this.dirty=!0,e&&this.updateText(),this},n.Text.prototype.updateText=function(){this.texture.baseTexture.resolution=this._res,this.context.font=this.style.font;var t=this.text;this.style.wordWrap&&(t=this.runWordWrap(this.text));var e=t.split(/(?:\r\n|\r|\n)/),i=this.style.tabs,s=[],n=0,r=this.determineFontProperties(this.style.font),o=e.length;this.style.maxLines>0&&this.style.maxLines<e.length&&(o=this.style.maxLines),this._charCount=0;for(var a=0;a<o;a++){if(0===i){var h=this.style.strokeThickness+this.padding.x;this.colors.length>0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?h+=this.measureLine(e[a]):h+=this.context.measureText(e[a]).width,this.style.wordWrap&&(h-=this.context.measureText(" ").width)}else{var l=e[a].split(/(?:\t)/),h=this.padding.x+this.style.strokeThickness;if(Array.isArray(i))for(var c=0,u=0;u<l.length;u++){var d=0;d=this.colors.length>0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?this.measureLine(l[u]):Math.ceil(this.context.measureText(l[u]).width),u>0&&(c+=i[u-1]),h=c+d}else for(var u=0;u<l.length;u++){this.colors.length>0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?h+=this.measureLine(l[u]):h+=Math.ceil(this.context.measureText(l[u]).width);var p=this.game.math.snapToCeil(h,i)-h;h+=p}}s[a]=Math.ceil(h),n=Math.max(n,s[a])}this.canvas.width=n*this._res;var f=r.fontSize+this.style.strokeThickness+this.padding.y,g=f*o,m=this._lineSpacing;m<0&&Math.abs(m)>f&&(m=-f),0!==m&&(g+=m>0?m*e.length:m*(e.length-1)),this.canvas.height=g*this._res,this.context.scale(this._res,this._res),navigator.isCocoonJS&&this.context.clearRect(0,0,this.canvas.width,this.canvas.height),this.style.backgroundColor&&(this.context.fillStyle=this.style.backgroundColor,this.context.fillRect(0,0,this.canvas.width,this.canvas.height)),this.context.fillStyle=this.style.fill,this.context.font=this.style.font,this.context.strokeStyle=this.style.stroke,this.context.textBaseline="alphabetic",this.context.lineWidth=this.style.strokeThickness,this.context.lineCap="round",this.context.lineJoin="round";var y,v;for(this._charCount=0,a=0;a<o;a++)y=this.style.strokeThickness/2,v=this.style.strokeThickness/2+a*f+r.ascent,a>0&&(v+=m*a),"right"===this.style.align?y+=n-s[a]:"center"===this.style.align&&(y+=(n-s[a])/2),this.autoRound&&(y=Math.round(y),v=Math.round(v)),this.colors.length>0||this.strokeColors.length>0||this.fontWeights.length>0||this.fontStyles.length>0?this.updateLine(e[a],y,v):(this.style.stroke&&this.style.strokeThickness&&(this.updateShadow(this.style.shadowStroke),0===i?this.context.strokeText(e[a],y,v):this.renderTabLine(e[a],y,v,!1)),this.style.fill&&(this.updateShadow(this.style.shadowFill),0===i?this.context.fillText(e[a],y,v):this.renderTabLine(e[a],y,v,!0)));this.updateTexture(),this.dirty=!1},n.Text.prototype.renderTabLine=function(t,e,i,s){var n=t.split(/(?:\t)/),r=this.style.tabs,o=0;if(Array.isArray(r))for(var a=0,h=0;h<n.length;h++)h>0&&(a+=r[h-1]),o=e+a,s?this.context.fillText(n[h],o,i):this.context.strokeText(n[h],o,i);else for(var h=0;h<n.length;h++){var l=Math.ceil(this.context.measureText(n[h]).width);o=this.game.math.snapToCeil(e,r),s?this.context.fillText(n[h],o,i):this.context.strokeText(n[h],o,i),e=o+l}},n.Text.prototype.updateShadow=function(t){t?(this.context.shadowOffsetX=this.style.shadowOffsetX,this.context.shadowOffsetY=this.style.shadowOffsetY,this.context.shadowColor=this.style.shadowColor,this.context.shadowBlur=this.style.shadowBlur):(this.context.shadowOffsetX=0,this.context.shadowOffsetY=0,this.context.shadowColor=0,this.context.shadowBlur=0)},n.Text.prototype.measureLine=function(t){for(var e=0,i=0;i<t.length;i++){var s=t[i];if(this.fontWeights.length>0||this.fontStyles.length>0){var n=this.fontToComponents(this.context.font);this.fontStyles[this._charCount]&&(n.fontStyle=this.fontStyles[this._charCount]),this.fontWeights[this._charCount]&&(n.fontWeight=this.fontWeights[this._charCount]),this.context.font=this.componentsToFont(n)}this.style.stroke&&this.style.strokeThickness&&(this.strokeColors[this._charCount]&&(this.context.strokeStyle=this.strokeColors[this._charCount]),this.updateShadow(this.style.shadowStroke)),this.style.fill&&(this.colors[this._charCount]&&(this.context.fillStyle=this.colors[this._charCount]),this.updateShadow(this.style.shadowFill)),e+=this.context.measureText(s).width,this._charCount++}return Math.ceil(e)},n.Text.prototype.updateLine=function(t,e,i){for(var s=0;s<t.length;s++){var n=t[s];if(this.fontWeights.length>0||this.fontStyles.length>0){var r=this.fontToComponents(this.context.font);this.fontStyles[this._charCount]&&(r.fontStyle=this.fontStyles[this._charCount]),this.fontWeights[this._charCount]&&(r.fontWeight=this.fontWeights[this._charCount]),this.context.font=this.componentsToFont(r)}this.style.stroke&&this.style.strokeThickness&&(this.strokeColors[this._charCount]&&(this.context.strokeStyle=this.strokeColors[this._charCount]),this.updateShadow(this.style.shadowStroke),this.context.strokeText(n,e,i)),this.style.fill&&(this.colors[this._charCount]&&(this.context.fillStyle=this.colors[this._charCount]),this.updateShadow(this.style.shadowFill),this.context.fillText(n,e,i)),e+=this.context.measureText(n).width,this._charCount++}},n.Text.prototype.clearColors=function(){return this.colors=[],this.strokeColors=[],this.dirty=!0,this},n.Text.prototype.clearFontValues=function(){return this.fontStyles=[],this.fontWeights=[],this.dirty=!0,this},n.Text.prototype.addColor=function(t,e){return this.colors[e]=t,this.dirty=!0,this},n.Text.prototype.addStrokeColor=function(t,e){return this.strokeColors[e]=t,this.dirty=!0,this},n.Text.prototype.addFontStyle=function(t,e){return this.fontStyles[e]=t,this.dirty=!0,this},n.Text.prototype.addFontWeight=function(t,e){return this.fontWeights[e]=t,this.dirty=!0,this},n.Text.prototype.precalculateWordWrap=function(t){return this.texture.baseTexture.resolution=this._res,this.context.font=this.style.font,this.runWordWrap(t).split(/(?:\r\n|\r|\n)/)},n.Text.prototype.runWordWrap=function(t){return this.useAdvancedWrap?this.advancedWordWrap(t):this.basicWordWrap(t)},n.Text.prototype.advancedWordWrap=function(t){for(var e=this.context,i=this.style.wordWrapWidth,s="",n=t.replace(/ +/gi," ").split(/\r?\n/gi),r=n.length,o=0;o<r;o++){var a=n[o],h="";a=a.replace(/^ *|\s*$/gi,"");if(e.measureText(a).width<i)s+=a+"\n";else{for(var l=i,c=a.split(" "),u=0;u<c.length;u++){var d=c[u],p=d+" ",f=e.measureText(p).width;if(f>l){if(0===u){for(var g=p;g.length&&(g=g.slice(0,-1),!((f=e.measureText(g).width)<=l)););if(!g.length)throw new Error("This text's wordWrapWidth setting is less than a single character!");var m=d.substr(g.length);c[u]=m,h+=g}var y=c[u].length?u:u+1,v=c.slice(y).join(" ").replace(/[ \n]*$/gi,"");n[o+1]=v+" "+(n[o+1]||""),r=n.length;break}h+=p,l-=f}s+=h.replace(/[ \n]*$/gi,"")+"\n"}}return s=s.replace(/[\s|\n]*$/gi,"")},n.Text.prototype.basicWordWrap=function(t){for(var e="",i=t.split("\n"),s=0;s<i.length;s++){for(var n=this.style.wordWrapWidth,r=i[s].split(" "),o=0;o<r.length;o++){var a=this.context.measureText(r[o]).width,h=a+this.context.measureText(" ").width;h>n?(o>0&&(e+="\n"),e+=r[o]+" ",n=this.style.wordWrapWidth-a):(n-=h,e+=r[o]+" ")}s<i.length-1&&(e+="\n")}return e},n.Text.prototype.updateFont=function(t){var e=this.componentsToFont(t);this.style.font!==e&&(this.style.font=e,this.dirty=!0,this.parent&&this.updateTransform())},n.Text.prototype.fontToComponents=function(t){var e=t.match(/^\s*(?:\b(normal|italic|oblique|inherit)?\b)\s*(?:\b(normal|small-caps|inherit)?\b)\s*(?:\b(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900|inherit)?\b)\s*(?:\b(xx-small|x-small|small|medium|large|x-large|xx-large|larger|smaller|0|\d*(?:[.]\d*)?(?:%|[a-z]{2,5}))?\b)\s*(.*)\s*$/);if(e){var i=e[5].trim();return/^(?:inherit|serif|sans-serif|cursive|fantasy|monospace)$/.exec(i)||/['",]/.exec(i)||(i="'"+i+"'"),{font:t,fontStyle:e[1]||"normal",fontVariant:e[2]||"normal",fontWeight:e[3]||"normal",fontSize:e[4]||"medium",fontFamily:i}}return console.warn("Phaser.Text - unparsable CSS font: "+t),{font:t}},n.Text.prototype.componentsToFont=function(t){var e,i=[];return e=t.fontStyle,e&&"normal"!==e&&i.push(e),e=t.fontVariant,e&&"normal"!==e&&i.push(e),e=t.fontWeight,e&&"normal"!==e&&i.push(e),e=t.fontSize,e&&"medium"!==e&&i.push(e),e=t.fontFamily,e&&i.push(e),i.length||i.push(t.font),i.join(" ")},n.Text.prototype.setText=function(t,e){return void 0===e&&(e=!1),this.text=t.toString()||"",e?this.updateText():this.dirty=!0,this},n.Text.prototype.parseList=function(t){if(!Array.isArray(t))return this;for(var e="",i=0;i<t.length;i++)Array.isArray(t[i])?(e+=t[i].join("\t"),i<t.length-1&&(e+="\n")):(e+=t[i],i<t.length-1&&(e+="\t"));return this.text=e,this.dirty=!0,this},n.Text.prototype.setTextBounds=function(t,e,i,s){return void 0===t?this.textBounds=null:(this.textBounds?this.textBounds.setTo(t,e,i,s):this.textBounds=new n.Rectangle(t,e,i,s),this.style.wordWrapWidth>i&&(this.style.wordWrapWidth=i)),this.updateTexture(),this},n.Text.prototype.updateTexture=function(){var t=this.texture.baseTexture,e=this.texture.crop,i=this.texture.frame,s=this.canvas.width,n=this.canvas.height;if(t.width=s,t.height=n,e.width=s,e.height=n,i.width=s,i.height=n,this.texture.width=s,this.texture.height=n,this._width=s,this._height=n,this.textBounds){var r=this.textBounds.x,o=this.textBounds.y;"right"===this.style.boundsAlignH?r+=this.textBounds.width-this.canvas.width/this.resolution:"center"===this.style.boundsAlignH&&(r+=this.textBounds.halfWidth-this.canvas.width/this.resolution/2),"bottom"===this.style.boundsAlignV?o+=this.textBounds.height-this.canvas.height/this.resolution:"middle"===this.style.boundsAlignV&&(o+=this.textBounds.halfHeight-this.canvas.height/this.resolution/2),this.pivot.x=-r,this.pivot.y=-o}this.renderable=0!==s&&0!==n,this.texture.requiresReTint=!0,this.texture.baseTexture.dirty()},n.Text.prototype._renderWebGL=function(t){this.dirty&&(this.updateText(),this.dirty=!1),PIXI.Sprite.prototype._renderWebGL.call(this,t)},n.Text.prototype._renderCanvas=function(t){this.dirty&&(this.updateText(),this.dirty=!1),PIXI.Sprite.prototype._renderCanvas.call(this,t)},n.Text.prototype.determineFontProperties=function(t){var e=n.Text.fontPropertiesCache[t];if(!e){e={};var i=n.Text.fontPropertiesCanvas,s=n.Text.fontPropertiesContext;s.font=t;var r=Math.ceil(s.measureText("|MÉq").width),o=Math.ceil(s.measureText("|MÉq").width),a=2*o;if(o=1.4*o|0,i.width=r,i.height=a,s.fillStyle="#f00",s.fillRect(0,0,r,a),s.font=t,s.textBaseline="alphabetic",s.fillStyle="#000",s.fillText("|MÉq",0,o),!s.getImageData(0,0,r,a))return e.ascent=o,e.descent=o+6,e.fontSize=e.ascent+e.descent,n.Text.fontPropertiesCache[t]=e,e;var h,l,c=s.getImageData(0,0,r,a).data,u=c.length,d=4*r,p=0,f=!1;for(h=0;h<o;h++){for(l=0;l<d;l+=4)if(255!==c[p+l]){f=!0;break}if(f)break;p+=d}for(e.ascent=o-h,p=u-d,f=!1,h=a;h>o;h--){for(l=0;l<d;l+=4)if(255!==c[p+l]){f=!0;break}if(f)break;p-=d}e.descent=h-o,e.descent+=6,e.fontSize=e.ascent+e.descent,n.Text.fontPropertiesCache[t]=e}return e},n.Text.prototype.getBounds=function(t){return this.dirty&&(this.updateText(),this.dirty=!1),PIXI.Sprite.prototype.getBounds.call(this,t)},Object.defineProperty(n.Text.prototype,"text",{get:function(){return this._text},set:function(t){t!==this._text&&(this._text=t.toString()||"",this.dirty=!0,this.parent&&this.updateTransform())}}),Object.defineProperty(n.Text.prototype,"cssFont",{get:function(){return this.componentsToFont(this._fontComponents)},set:function(t){t=t||"bold 20pt Arial",this._fontComponents=this.fontToComponents(t),this.updateFont(this._fontComponents)}}),Object.defineProperty(n.Text.prototype,"font",{get:function(){return this._fontComponents.fontFamily},set:function(t){t=t||"Arial",t=t.trim(),/^(?:inherit|serif|sans-serif|cursive|fantasy|monospace)$/.exec(t)||/['",]/.exec(t)||(t="'"+t+"'"),this._fontComponents.fontFamily=t,this.updateFont(this._fontComponents)}}),Object.defineProperty(n.Text.prototype,"fontSize",{get:function(){var t=this._fontComponents.fontSize;return t&&/(?:^0$|px$)/.exec(t)?parseInt(t,10):t},set:function(t){t=t||"0","number"==typeof t&&(t+="px"),this._fontComponents.fontSize=t,this.updateFont(this._fontComponents)}}),Object.defineProperty(n.Text.prototype,"fontWeight",{get:function(){return this._fontComponents.fontWeight||"normal"},set:function(t){t=t||"normal",this._fontComponents.fontWeight=t,this.updateFont(this._fontComponents)}}),Object.defineProperty(n.Text.prototype,"fontStyle",{get:function(){return this._fontComponents.fontStyle||"normal"},set:function(t){t=t||"normal",this._fontComponents.fontStyle=t,this.updateFont(this._fontComponents)}}),Object.defineProperty(n.Text.prototype,"fontVariant",{get:function(){return this._fontComponents.fontVariant||"normal"},set:function(t){t=t||"normal",this._fontComponents.fontVariant=t,this.updateFont(this._fontComponents)}}),Object.defineProperty(n.Text.prototype,"fill",{get:function(){return this.style.fill},set:function(t){t!==this.style.fill&&(this.style.fill=t,this.dirty=!0)}}),Object.defineProperty(n.Text.prototype,"align",{get:function(){return this.style.align},set:function(t){t!==this.style.align&&(this.style.align=t,this.dirty=!0)}}),Object.defineProperty(n.Text.prototype,"resolution",{get:function(){return this._res},set:function(t){t!==this._res&&(this._res=t,this.dirty=!0)}}),Object.defineProperty(n.Text.prototype,"tabs",{get:function(){return this.style.tabs},set:function(t){t!==this.style.tabs&&(this.style.tabs=t,this.dirty=!0)}}),Object.defineProperty(n.Text.prototype,"boundsAlignH",{get:function(){return this.style.boundsAlignH},set:function(t){t!==this.style.boundsAlignH&&(this.style.boundsAlignH=t,this.dirty=!0)}}),Object.defineProperty(n.Text.prototype,"boundsAlignV",{get:function(){return this.style.boundsAlignV},set:function(t){t!==this.style.boundsAlignV&&(this.style.boundsAlignV=t,this.dirty=!0)}}),Object.defineProperty(n.Text.prototype,"stroke",{get:function(){return this.style.stroke},set:function(t){t!==this.style.stroke&&(this.style.stroke=t,this.dirty=!0)}}),Object.defineProperty(n.Text.prototype,"strokeThickness",{get:function(){return this.style.strokeThickness},set:function(t){t!==this.style.strokeThickness&&(this.style.strokeThickness=t,this.dirty=!0)}}),Object.defineProperty(n.Text.prototype,"wordWrap",{get:function(){return this.style.wordWrap},set:function(t){t!==this.style.wordWrap&&(this.style.wordWrap=t,this.dirty=!0)}}),Object.defineProperty(n.Text.prototype,"wordWrapWidth",{get:function(){return this.style.wordWrapWidth},set:function(t){t!==this.style.wordWrapWidth&&(this.style.wordWrapWidth=t,this.dirty=!0)}}),Object.defineProperty(n.Text.prototype,"lineSpacing",{get:function(){return this._lineSpacing},set:function(t){t!==this._lineSpacing&&(this._lineSpacing=parseFloat(t),this.dirty=!0,this.parent&&this.updateTransform())}}),Object.defineProperty(n.Text.prototype,"shadowOffsetX",{get:function(){return this.style.shadowOffsetX},set:function(t){t!==this.style.shadowOffsetX&&(this.style.shadowOffsetX=t,this.dirty=!0)}}),Object.defineProperty(n.Text.prototype,"shadowOffsetY",{get:function(){return this.style.shadowOffsetY},set:function(t){t!==this.style.shadowOffsetY&&(this.style.shadowOffsetY=t,this.dirty=!0)}}),Object.defineProperty(n.Text.prototype,"shadowColor",{get:function(){return this.style.shadowColor},set:function(t){t!==this.style.shadowColor&&(this.style.shadowColor=t,this.dirty=!0)}}),Object.defineProperty(n.Text.prototype,"shadowBlur",{get:function(){return this.style.shadowBlur},set:function(t){t!==this.style.shadowBlur&&(this.style.shadowBlur=t,this.dirty=!0)}}),Object.defineProperty(n.Text.prototype,"shadowStroke",{get:function(){return this.style.shadowStroke},set:function(t){t!==this.style.shadowStroke&&(this.style.shadowStroke=t,this.dirty=!0)}}),Object.defineProperty(n.Text.prototype,"shadowFill",{get:function(){return this.style.shadowFill},set:function(t){t!==this.style.shadowFill&&(this.style.shadowFill=t,this.dirty=!0)}}),Object.defineProperty(n.Text.prototype,"width",{get:function(){return this.dirty&&(this.updateText(),this.dirty=!1),this.scale.x*this.texture.frame.width},set:function(t){this.scale.x=t/this.texture.frame.width,this._width=t}}),Object.defineProperty(n.Text.prototype,"height",{get:function(){return this.dirty&&(this.updateText(),this.dirty=!1),this.scale.y*this.texture.frame.height},set:function(t){this.scale.y=t/this.texture.frame.height,this._height=t}}),n.Text.fontPropertiesCache={},n.Text.fontPropertiesCanvas=document.createElement("canvas"),n.Text.fontPropertiesContext=n.Text.fontPropertiesCanvas.getContext("2d"),/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.BitmapText=function(t,e,i,s,r,o,a){e=e||0,i=i||0,s=s||"",r=r||"",o=o||32,a=a||"left",PIXI.DisplayObjectContainer.call(this),this.type=n.BITMAPTEXT,this.physicsType=n.SPRITE,this.textWidth=0,this.textHeight=0,this.anchor=new n.Point,this._prevAnchor=new n.Point,this._glyphs=[],this._maxWidth=0,this._text=r.toString()||"",this._data=t.cache.getBitmapFont(s),this._font=s,this._fontSize=o,this._align=a,this._tint=16777215,this.updateText(),this.dirty=!1,n.Component.Core.init.call(this,t,e,i,"",null)},n.BitmapText.prototype=Object.create(PIXI.DisplayObjectContainer.prototype),n.BitmapText.prototype.constructor=n.BitmapText,n.Component.Core.install.call(n.BitmapText.prototype,["Angle","AutoCull","Bounds","Destroy","FixedToCamera","InputEnabled","InWorld","LifeSpan","PhysicsBody","Reset"]),n.BitmapText.prototype.preUpdatePhysics=n.Component.PhysicsBody.preUpdate,n.BitmapText.prototype.preUpdateLifeSpan=n.Component.LifeSpan.preUpdate,n.BitmapText.prototype.preUpdateInWorld=n.Component.InWorld.preUpdate,n.BitmapText.prototype.preUpdateCore=n.Component.Core.preUpdate,n.BitmapText.prototype.preUpdate=function(){return!!(this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld())&&this.preUpdateCore()},n.BitmapText.prototype.postUpdate=function(){n.Component.PhysicsBody.postUpdate.call(this),n.Component.FixedToCamera.postUpdate.call(this),this.body&&this.body.type===n.Physics.ARCADE&&(this.textWidth===this.body.sourceWidth&&this.textHeight===this.body.sourceHeight||this.body.setSize(this.textWidth,this.textHeight))},n.BitmapText.prototype.setText=function(t){this.text=t};n.BitmapText.prototype.scanLine=function(t,e,i){for(var s=0,n=0,r=-1,o=0,a=null,h=this._maxWidth>0?this._maxWidth:null,l=[],c=0;c<i.length;c++){var u=c===i.length-1;if(/(?:\r\n|\r|\n)/.test(i.charAt(c)))return{width:n,text:i.substr(0,c),end:u,chars:l};var d=i.charCodeAt(c),p=t.chars[d],f=0;void 0===p&&(d=32,p=t.chars[d]);var g=a&&p.kerning[a]?p.kerning[a]:0;if(/(\s)/.test(i.charAt(c))&&(r=c,o=n),f=(g+p.texture.width+p.xOffset)*e,h&&n+f>=h&&r>-1)return{width:o||n,text:i.substr(0,c-(c-r)),end:u,chars:l};n+=(p.xAdvance+g)*e,l.push(s+(p.xOffset+g)*e),s+=(p.xAdvance+g)*e,a=d}return{width:n,text:i,end:u,chars:l}},n.BitmapText.prototype.cleanText=function(t,e){void 0===e&&(e="");var i=this._data.font;if(!i)return"";for(var s=t.replace(/\r\n|\n\r|\n|\r/g,"\n").split("\n"),n=0;n<s.length;n++){for(var r="",o=s[n],a=0;a<o.length;a++)r=i.chars[o.charCodeAt(a)]?r.concat(o[a]):r.concat(e);s[n]=r}return s.join("\n")},n.BitmapText.prototype.updateText=function(){var t=this._data.font;if(t){var e=this.text,i=this._fontSize/t.size,s=[],n=0;this.textWidth=0;do{var r=this.scanLine(t,i,e);r.y=n,s.push(r),r.width>this.textWidth&&(this.textWidth=r.width),n+=t.lineHeight*i,e=e.substr(r.text.length+1)}while(!1===r.end);this.textHeight=n;for(var o=0,a=0,h=this.textWidth*this.anchor.x,l=this.textHeight*this.anchor.y,c=0;c<s.length;c++){var r=s[c];"right"===this._align?a=this.textWidth-r.width:"center"===this._align&&(a=(this.textWidth-r.width)/2);for(var u=0;u<r.text.length;u++){var d=r.text.charCodeAt(u),p=t.chars[d];void 0===p&&(d=32,p=t.chars[d]);var f=this._glyphs[o];f?f.texture=p.texture:(f=new PIXI.Sprite(p.texture),f.name=r.text[u],this._glyphs.push(f)),f.position.x=r.chars[u]+a-h,f.position.y=r.y+p.yOffset*i-l,f.scale.set(i),f.tint=this.tint,f.texture.requiresReTint=!0,f.parent||this.addChild(f),o++}}for(c=o;c<this._glyphs.length;c++)this.removeChild(this._glyphs[c])}},n.BitmapText.prototype.purgeGlyphs=function(){for(var t=this._glyphs.length,e=[],i=0;i<this._glyphs.length;i++)this._glyphs[i].parent!==this?this._glyphs[i].destroy():e.push(this._glyphs[i]);return this._glyphs=[],this._glyphs=e,this.updateText(),t-e.length},n.BitmapText.prototype.updateTransform=function(){!this.dirty&&this.anchor.equals(this._prevAnchor)||(this.updateText(),this.dirty=!1,this._prevAnchor.copyFrom(this.anchor)),PIXI.DisplayObjectContainer.prototype.updateTransform.call(this)},Object.defineProperty(n.BitmapText.prototype,"align",{get:function(){return this._align},set:function(t){t===this._align||"left"!==t&&"center"!==t&&"right"!==t||(this._align=t,this.updateText())}}),Object.defineProperty(n.BitmapText.prototype,"tint",{get:function(){return this._tint},set:function(t){t!==this._tint&&(this._tint=t,this.updateText())}}),Object.defineProperty(n.BitmapText.prototype,"font",{get:function(){return this._font},set:function(t){t!==this._font&&(this._font=t.trim(),this._data=this.game.cache.getBitmapFont(this._font),this.updateText())}}),Object.defineProperty(n.BitmapText.prototype,"fontSize",{get:function(){return this._fontSize},set:function(t){(t=parseInt(t,10))!==this._fontSize&&t>0&&(this._fontSize=t,this.updateText())}}),Object.defineProperty(n.BitmapText.prototype,"text",{get:function(){return this._text},set:function(t){t!==this._text&&(this._text=t.toString()||"",this.updateText())}}),Object.defineProperty(n.BitmapText.prototype,"maxWidth",{get:function(){return this._maxWidth},set:function(t){t!==this._maxWidth&&(this._maxWidth=t,this.updateText())}}),Object.defineProperty(n.BitmapText.prototype,"smoothed",{get:function(){return!this._data.base.scaleMode},set:function(t){this._data.base.scaleMode=t?0:1}}),/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.RetroFont=function(t,e,i,s,r,o,a,h,l,c){if(!t.cache.checkImageKey(e))return!1;void 0!==o&&null!==o||(o=t.cache.getImage(e).width/i),this.characterWidth=i,this.characterHeight=s,this.characterSpacingX=a||0,this.characterSpacingY=h||0,this.characterPerRow=o,this.offsetX=l||0,this.offsetY=c||0,this.align="left",this.multiLine=!1,this.autoUpperCase=!0,this.customSpacingX=0,this.customSpacingY=0,this.fixedWidth=0,this.fontSet=t.cache.getImage(e),this._text="",this.grabData=[],this.frameData=new n.FrameData;for(var u=this.offsetX,d=this.offsetY,p=0,f=0;f<r.length;f++){var g=this.frameData.addFrame(new n.Frame(f,u,d,this.characterWidth,this.characterHeight));this.grabData[r.charCodeAt(f)]=g.index,p++,p===this.characterPerRow?(p=0,u=this.offsetX,d+=this.characterHeight+this.characterSpacingY):u+=this.characterWidth+this.characterSpacingX}t.cache.updateFrameData(e,this.frameData),this.stamp=new n.Image(t,0,0,e,0),n.RenderTexture.call(this,t,100,100,"",n.scaleModes.NEAREST),this.type=n.RETROFONT},n.RetroFont.prototype=Object.create(n.RenderTexture.prototype),n.RetroFont.prototype.constructor=n.RetroFont,n.RetroFont.ALIGN_LEFT="left",n.RetroFont.ALIGN_RIGHT="right",n.RetroFont.ALIGN_CENTER="center",n.RetroFont.TEXT_SET1=" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~",n.RetroFont.TEXT_SET2=" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ",n.RetroFont.TEXT_SET3="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ",n.RetroFont.TEXT_SET4="ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789",n.RetroFont.TEXT_SET5="ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789",n.RetroFont.TEXT_SET6="ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.' ",n.RetroFont.TEXT_SET7="AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-'39",n.RetroFont.TEXT_SET8="0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ",n.RetroFont.TEXT_SET9="ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'\"?!",n.RetroFont.TEXT_SET10="ABCDEFGHIJKLMNOPQRSTUVWXYZ",n.RetroFont.TEXT_SET11="ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()':;0123456789",n.RetroFont.prototype.setFixedWidth=function(t,e){void 0===e&&(e="left"),this.fixedWidth=t,this.align=e},n.RetroFont.prototype.setText=function(t,e,i,s,n,r){this.multiLine=e||!1,this.customSpacingX=i||0,this.customSpacingY=s||0,this.align=n||"left",this.autoUpperCase=!r,t.length>0&&(this.text=t)},n.RetroFont.prototype.buildRetroFontText=function(){var t=0,e=0;if(this.clear(),this.multiLine){var i=this._text.split("\n");this.fixedWidth>0?this.resize(this.fixedWidth,i.length*(this.characterHeight+this.customSpacingY)-this.customSpacingY,!0):this.resize(this.getLongestLine()*(this.characterWidth+this.customSpacingX),i.length*(this.characterHeight+this.customSpacingY)-this.customSpacingY,!0);for(var s=0;s<i.length;s++)t=0,this.align===n.RetroFont.ALIGN_RIGHT?t=this.width-i[s].length*(this.characterWidth+this.customSpacingX):this.align===n.RetroFont.ALIGN_CENTER&&(t=this.width/2-i[s].length*(this.characterWidth+this.customSpacingX)/2,t+=this.customSpacingX/2),t<0&&(t=0),this.pasteLine(i[s],t,e,this.customSpacingX),e+=this.characterHeight+this.customSpacingY}else this.fixedWidth>0?this.resize(this.fixedWidth,this.characterHeight,!0):this.resize(this._text.length*(this.characterWidth+this.customSpacingX),this.characterHeight,!0),t=0,this.align===n.RetroFont.ALIGN_RIGHT?t=this.width-this._text.length*(this.characterWidth+this.customSpacingX):this.align===n.RetroFont.ALIGN_CENTER&&(t=this.width/2-this._text.length*(this.characterWidth+this.customSpacingX)/2,t+=this.customSpacingX/2),t<0&&(t=0),this.pasteLine(this._text,t,0,this.customSpacingX);this.requiresReTint=!0},n.RetroFont.prototype.pasteLine=function(t,e,i,s){for(var n=0;n<t.length;n++)if(" "===t.charAt(n))e+=this.characterWidth+s;else if(this.grabData[t.charCodeAt(n)]>=0&&(this.stamp.frame=this.grabData[t.charCodeAt(n)],this.renderXY(this.stamp,e,i,!1),(e+=this.characterWidth+s)>this.width))break},n.RetroFont.prototype.getLongestLine=function(){var t=0;if(this._text.length>0)for(var e=this._text.split("\n"),i=0;i<e.length;i++)e[i].length>t&&(t=e[i].length);return t},n.RetroFont.prototype.removeUnsupportedCharacters=function(t){for(var e="",i=0;i<this._text.length;i++){var s=this._text[i],n=s.charCodeAt(0);(this.grabData[n]>=0||!t&&"\n"===s)&&(e=e.concat(s))}return e},n.RetroFont.prototype.updateOffset=function(t,e){if(this.offsetX!==t||this.offsetY!==e){for(var i=t-this.offsetX,s=e-this.offsetY,n=this.game.cache.getFrameData(this.stamp.key).getFrames(),r=n.length;r--;)n[r].x+=i,n[r].y+=s;this.buildRetroFontText()}},Object.defineProperty(n.RetroFont.prototype,"text",{get:function(){return this._text},set:function(t){var e;(e=this.autoUpperCase?t.toUpperCase():t)!==this._text&&(this._text=e,this.removeUnsupportedCharacters(this.multiLine),this.buildRetroFontText())}}),Object.defineProperty(n.RetroFont.prototype,"smoothed",{get:function(){return this.stamp.smoothed},set:function(t){this.stamp.smoothed=t,this.buildRetroFontText()}}),/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd, Richard Davey
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Rope=function(t,e,i,s,r,o){this.points=[],this.points=o,this._hasUpdateAnimation=!1,this._updateAnimationCallback=null,e=e||0,i=i||0,s=s||null,r=r||null,this.type=n.ROPE,PIXI.Rope.call(this,n.Cache.DEFAULT,this.points),n.Component.Core.init.call(this,t,e,i,s,r)},n.Rope.prototype=Object.create(PIXI.Rope.prototype),n.Rope.prototype.constructor=n.Rope,n.Component.Core.install.call(n.Rope.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Crop","Delta","Destroy","FixedToCamera","InWorld","LifeSpan","LoadTexture","Overlap","PhysicsBody","Reset","ScaleMinMax","Smoothed"]),n.Rope.prototype.preUpdatePhysics=n.Component.PhysicsBody.preUpdate,n.Rope.prototype.preUpdateLifeSpan=n.Component.LifeSpan.preUpdate,n.Rope.prototype.preUpdateInWorld=n.Component.InWorld.preUpdate,n.Rope.prototype.preUpdateCore=n.Component.Core.preUpdate,n.Rope.prototype.preUpdate=function(){return!!(this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld())&&this.preUpdateCore()},n.Rope.prototype.update=function(){this._hasUpdateAnimation&&this.updateAnimation.call(this)},n.Rope.prototype.reset=function(t,e){return n.Component.Reset.prototype.reset.call(this,t,e),this},Object.defineProperty(n.Rope.prototype,"updateAnimation",{get:function(){return this._updateAnimation},set:function(t){t&&"function"==typeof t?(this._hasUpdateAnimation=!0,this._updateAnimation=t):(this._hasUpdateAnimation=!1,this._updateAnimation=null)}}),Object.defineProperty(n.Rope.prototype,"segments",{get:function(){for(var t,e,i,s,r,o,a,h,l=[],c=0;c<this.points.length;c++)t=4*c,e=this.vertices[t]*this.scale.x,i=this.vertices[t+1]*this.scale.y,s=this.vertices[t+4]*this.scale.x,r=this.vertices[t+3]*this.scale.y,o=n.Math.difference(e,s),a=n.Math.difference(i,r),e+=this.world.x,i+=this.world.y,h=new n.Rectangle(e,i,o,a),l.push(h);return l}}),/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.TileSprite=function(t,e,i,s,r,o,a){e=e||0,i=i||0,s=s||256,r=r||256,o=o||null,a=a||null,this.type=n.TILESPRITE,this.physicsType=n.SPRITE,this._scroll=new n.Point;var h=t.cache.getImage("__default",!0);PIXI.TilingSprite.call(this,new PIXI.Texture(h.base),s,r),n.Component.Core.init.call(this,t,e,i,o,a)},n.TileSprite.prototype=Object.create(PIXI.TilingSprite.prototype),n.TileSprite.prototype.constructor=n.TileSprite,n.Component.Core.install.call(n.TileSprite.prototype,["Angle","Animation","AutoCull","Bounds","BringToTop","Destroy","FixedToCamera","Health","InCamera","InputEnabled","InWorld","LifeSpan","LoadTexture","Overlap","PhysicsBody","Reset","Smoothed"]),n.TileSprite.prototype.preUpdatePhysics=n.Component.PhysicsBody.preUpdate,n.TileSprite.prototype.preUpdateLifeSpan=n.Component.LifeSpan.preUpdate,n.TileSprite.prototype.preUpdateInWorld=n.Component.InWorld.preUpdate,n.TileSprite.prototype.preUpdateCore=n.Component.Core.preUpdate,n.TileSprite.prototype.preUpdate=function(){return 0!==this._scroll.x&&(this.tilePosition.x+=this._scroll.x*this.game.time.physicsElapsed),0!==this._scroll.y&&(this.tilePosition.y+=this._scroll.y*this.game.time.physicsElapsed),!!(this.preUpdatePhysics()&&this.preUpdateLifeSpan()&&this.preUpdateInWorld())&&this.preUpdateCore()},n.TileSprite.prototype.autoScroll=function(t,e){this._scroll.set(t,e)},n.TileSprite.prototype.stopScroll=function(){this._scroll.set(0,0)},n.TileSprite.prototype.destroy=function(t){n.Component.Destroy.prototype.destroy.call(this,t),PIXI.TilingSprite.prototype.destroy.call(this)},n.TileSprite.prototype.reset=function(t,e){return n.Component.Reset.prototype.reset.call(this,t,e),this.tilePosition.x=0,this.tilePosition.y=0,this},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Device=function(){this.deviceReadyAt=0,this.initialized=!1,this.desktop=!1,this.iOS=!1,this.iOSVersion=0,this.cocoonJS=!1,this.cocoonJSApp=!1,this.cordova=!1,this.node=!1,this.nodeWebkit=!1,this.electron=!1,this.ejecta=!1,this.crosswalk=!1,this.android=!1,this.chromeOS=!1,this.linux=!1,this.macOS=!1,this.windows=!1,this.windowsPhone=!1,this.canvas=!1,this.canvasBitBltShift=null,this.webGL=!1,this.file=!1,this.fileSystem=!1,this.localStorage=!1,this.worker=!1,this.css3D=!1,this.pointerLock=!1,this.typedArray=!1,this.vibration=!1,this.getUserMedia=!0,this.quirksMode=!1,this.touch=!1,this.mspointer=!1,this.wheelEvent=null,this.arora=!1,this.chrome=!1,this.chromeVersion=0,this.epiphany=!1,this.firefox=!1,this.firefoxVersion=0,this.ie=!1,this.ieVersion=0,this.trident=!1,this.tridentVersion=0,this.edge=!1,this.mobileSafari=!1,this.midori=!1,this.opera=!1,this.safari=!1,this.safariVersion=0,this.webApp=!1,this.silk=!1,this.audioData=!1,this.webAudio=!1,this.ogg=!1,this.opus=!1,this.mp3=!1,this.wav=!1,this.m4a=!1,this.webm=!1,this.dolby=!1,this.oggVideo=!1,this.h264Video=!1,this.mp4Video=!1,this.webmVideo=!1,this.vp9Video=!1,this.hlsVideo=!1,this.iPhone=!1,this.iPhone4=!1,this.iPad=!1,this.pixelRatio=0,this.littleEndian=!1,this.LITTLE_ENDIAN=!1,this.support32bit=!1,this.fullscreen=!1,this.requestFullscreen="",this.cancelFullscreen="",this.fullscreenKeyboard=!1},n.Device=new n.Device,n.Device.onInitialized=new n.Signal,n.Device.whenReady=function(t,e,i){var s=this._readyCheck;if(this.deviceReadyAt||!s)t.call(e,this);else if(s._monitor||i)s._queue=s._queue||[],s._queue.push([t,e]);else{s._monitor=s.bind(this),s._queue=s._queue||[],s._queue.push([t,e]);var n=void 0!==window.cordova,r=navigator.isCocoonJS;"complete"===document.readyState||"interactive"===document.readyState?window.setTimeout(s._monitor,0):n&&!r?document.addEventListener("deviceready",s._monitor,!1):(document.addEventListener("DOMContentLoaded",s._monitor,!1),window.addEventListener("load",s._monitor,!1))}},n.Device._readyCheck=function(){var t=this._readyCheck;if(document.body){if(!this.deviceReadyAt){this.deviceReadyAt=Date.now(),document.removeEventListener("deviceready",t._monitor),document.removeEventListener("DOMContentLoaded",t._monitor),window.removeEventListener("load",t._monitor),this._initialize(),this.initialized=!0,this.onInitialized.dispatch(this);for(var e;e=t._queue.shift();){var i=e[0],s=e[1];i.call(s,this)}this._readyCheck=null,this._initialize=null,this.onInitialized=null}}else window.setTimeout(t._monitor,20)},n.Device._initialize=function(){function t(){var t=new ArrayBuffer(4),e=new Uint8Array(t),i=new Uint32Array(t);return e[0]=161,e[1]=178,e[2]=195,e[3]=212,3569595041===i[0]||2712847316!==i[0]&&null}function e(){if(void 0===Uint8ClampedArray)return!1;var t=PIXI.CanvasPool.create(this,1,1),e=t.getContext("2d");if(!e)return!1;var i=e.createImageData(1,1);return PIXI.CanvasPool.remove(this),i.data instanceof Uint8ClampedArray}var s=this;!function(){var t=navigator.userAgent;/Playstation Vita/.test(t)?s.vita=!0:/Kindle/.test(t)||/\bKF[A-Z][A-Z]+/.test(t)||/Silk.*Mobile Safari/.test(t)?s.kindle=!0:/Android/.test(t)?s.android=!0:/CrOS/.test(t)?s.chromeOS=!0:/iP[ao]d|iPhone/i.test(t)?(s.iOS=!0,navigator.appVersion.match(/OS (\d+)/),s.iOSVersion=parseInt(RegExp.$1,10)):/Linux/.test(t)?s.linux=!0:/Mac OS/.test(t)?s.macOS=!0:/Windows/.test(t)&&(s.windows=!0),(/Windows Phone/i.test(t)||/IEMobile/i.test(t))&&(s.android=!1,s.iOS=!1,s.macOS=!1,s.windows=!0,s.windowsPhone=!0);var e=/Silk/.test(t);(s.windows||s.macOS||s.linux&&!e||s.chromeOS)&&(s.desktop=!0),(s.windowsPhone||/Windows NT/i.test(t)&&/Touch/i.test(t))&&(s.desktop=!1)}(),function(){var t=navigator.userAgent;if(/Arora/.test(t)?s.arora=!0:/Edge\/\d+/.test(t)?s.edge=!0:/Chrome\/(\d+)/.test(t)&&!s.windowsPhone?(s.chrome=!0,s.chromeVersion=parseInt(RegExp.$1,10)):/Epiphany/.test(t)?s.epiphany=!0:/Firefox\D+(\d+)/.test(t)?(s.firefox=!0,s.firefoxVersion=parseInt(RegExp.$1,10)):/AppleWebKit/.test(t)&&s.iOS?s.mobileSafari=!0:/MSIE (\d+\.\d+);/.test(t)?(s.ie=!0,s.ieVersion=parseInt(RegExp.$1,10)):/Midori/.test(t)?s.midori=!0:/Opera/.test(t)?s.opera=!0:/Safari\/(\d+)/.test(t)&&!s.windowsPhone?(s.safari=!0,/Version\/(\d+)\./.test(t)&&(s.safariVersion=parseInt(RegExp.$1,10))):/Trident\/(\d+\.\d+)(.*)rv:(\d+\.\d+)/.test(t)&&(s.ie=!0,s.trident=!0,s.tridentVersion=parseInt(RegExp.$1,10),s.ieVersion=parseInt(RegExp.$3,10)),/Silk/.test(t)&&(s.silk=!0),navigator.standalone&&(s.webApp=!0),void 0!==window.cordova&&(s.cordova=!0),void 0!==i&&(s.node=!0),s.node&&"object"==typeof i.versions&&(s.nodeWebkit=!!i.versions["node-webkit"],s.electron=!!i.versions.electron),navigator.isCocoonJS&&(s.cocoonJS=!0),s.cocoonJS)try{s.cocoonJSApp="undefined"!=typeof CocoonJS}catch(t){s.cocoonJSApp=!1}void 0!==window.ejecta&&(s.ejecta=!0),/Crosswalk/.test(t)&&(s.crosswalk=!0)}(),function(){s.audioData=!!window.Audio,s.webAudio=!(!window.AudioContext&&!window.webkitAudioContext);var t=document.createElement("audio");try{if(t.canPlayType&&(t.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,"")&&(s.ogg=!0),(t.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/,"")||t.canPlayType("audio/opus;").replace(/^no$/,""))&&(s.opus=!0),t.canPlayType("audio/mpeg;").replace(/^no$/,"")&&(s.mp3=!0),t.canPlayType('audio/wav; codecs="1"').replace(/^no$/,"")&&(s.wav=!0),(t.canPlayType("audio/x-m4a;")||t.canPlayType("audio/aac;").replace(/^no$/,""))&&(s.m4a=!0),t.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/,"")&&(s.webm=!0),""!==t.canPlayType('audio/mp4;codecs="ec-3"')))if(s.edge)s.dolby=!0;else if(s.safari&&s.safariVersion>=9&&/Mac OS X (\d+)_(\d+)/.test(navigator.userAgent)){var e=parseInt(RegExp.$1,10),i=parseInt(RegExp.$2,10);(10===e&&i>=11||e>10)&&(s.dolby=!0)}}catch(t){}}(),function(){var t=document.createElement("video");try{!!t.canPlayType&&(t.canPlayType('video/ogg; codecs="theora"').replace(/^no$/,"")&&(s.oggVideo=!0),t.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/,"")&&(s.h264Video=!0,s.mp4Video=!0),t.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/,"")&&(s.webmVideo=!0),t.canPlayType('video/webm; codecs="vp9"').replace(/^no$/,"")&&(s.vp9Video=!0),t.canPlayType('application/x-mpegURL; codecs="avc1.42E01E"').replace(/^no$/,"")&&(s.hlsVideo=!0))}catch(t){}}(),function(){var t,e=document.createElement("p"),i={webkitTransform:"-webkit-transform",OTransform:"-o-transform",msTransform:"-ms-transform",MozTransform:"-moz-transform",transform:"transform"};document.body.insertBefore(e,null);for(var n in i)void 0!==e.style[n]&&(e.style[n]="translate3d(1px,1px,1px)",t=window.getComputedStyle(e).getPropertyValue(i[n]));document.body.removeChild(e),s.css3D=void 0!==t&&t.length>0&&"none"!==t}(),function(){s.pixelRatio=window.devicePixelRatio||1,s.iPhone=-1!==navigator.userAgent.toLowerCase().indexOf("iphone"),s.iPhone4=2===s.pixelRatio&&s.iPhone,s.iPad=-1!==navigator.userAgent.toLowerCase().indexOf("ipad"),"undefined"!=typeof Int8Array?s.typedArray=!0:s.typedArray=!1,"undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint32Array&&(s.littleEndian=t(),s.LITTLE_ENDIAN=s.littleEndian),s.support32bit="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof Int32Array&&null!==s.littleEndian&&e(),navigator.vibrate=navigator.vibrate||navigator.webkitVibrate||navigator.mozVibrate||navigator.msVibrate,navigator.vibrate&&(s.vibration=!0)}(),function(){s.canvas=!!window.CanvasRenderingContext2D||s.cocoonJS;try{s.localStorage=!!localStorage.getItem}catch(t){s.localStorage=!1}s.file=!!(window.File&&window.FileReader&&window.FileList&&window.Blob),s.fileSystem=!!window.requestFileSystem,s.webGL=function(){try{var t=document.createElement("canvas");return t.screencanvas=!1,!!window.WebGLRenderingContext&&(t.getContext("webgl")||t.getContext("experimental-webgl"))}catch(t){return!1}}(),s.webGL=!!s.webGL,s.worker=!!window.Worker,s.pointerLock="pointerLockElement"in document||"mozPointerLockElement"in document||"webkitPointerLockElement"in document,s.quirksMode="CSS1Compat"!==document.compatMode,navigator.getUserMedia=navigator.getUserMedia||navigator.webkitGetUserMedia||navigator.mozGetUserMedia||navigator.msGetUserMedia||navigator.oGetUserMedia,window.URL=window.URL||window.webkitURL||window.mozURL||window.msURL,s.getUserMedia=s.getUserMedia&&!!navigator.getUserMedia&&!!window.URL,s.firefox&&s.firefoxVersion<21&&(s.getUserMedia=!1),!s.iOS&&(s.ie||s.firefox||s.chrome)&&(s.canvasBitBltShift=!0),(s.safari||s.mobileSafari)&&(s.canvasBitBltShift=!1)}(),function(){for(var t=["requestFullscreen","requestFullScreen","webkitRequestFullscreen","webkitRequestFullScreen","msRequestFullscreen","msRequestFullScreen","mozRequestFullScreen","mozRequestFullscreen"],e=document.createElement("div"),i=0;i<t.length;i++)if(e[t[i]]){s.fullscreen=!0,s.requestFullscreen=t[i];break}var n=["cancelFullScreen","exitFullscreen","webkitCancelFullScreen","webkitExitFullscreen","msCancelFullScreen","msExitFullscreen","mozCancelFullScreen","mozExitFullscreen"];if(s.fullscreen)for(var i=0;i<n.length;i++)if(document[n[i]]){s.cancelFullscreen=n[i];break}window.Element&&Element.ALLOW_KEYBOARD_INPUT&&(s.fullscreenKeyboard=!0)}(),function(){("ontouchstart"in document.documentElement||window.navigator.maxTouchPoints&&window.navigator.maxTouchPoints>=1)&&(s.touch=!0),(window.navigator.msPointerEnabled||window.navigator.pointerEnabled)&&(s.mspointer=!0),s.cocoonJS||("onwheel"in window||s.ie&&"WheelEvent"in window?s.wheelEvent="wheel":"onmousewheel"in window?s.wheelEvent="mousewheel":s.firefox&&"MouseScrollEvent"in window&&(s.wheelEvent="DOMMouseScroll"))}()},n.Device.canPlayAudio=function(t){return!("mp3"!==t||!this.mp3)||(!("ogg"!==t||!this.ogg&&!this.opus)||(!("m4a"!==t||!this.m4a)||(!("opus"!==t||!this.opus)||(!("wav"!==t||!this.wav)||(!("webm"!==t||!this.webm)||!("mp4"!==t||!this.dolby))))))},n.Device.canPlayVideo=function(t){return!("webm"!==t||!this.webmVideo&&!this.vp9Video)||(!("mp4"!==t||!this.mp4Video&&!this.h264Video)||(!("ogg"!==t&&"ogv"!==t||!this.oggVideo)||!("mpeg"!==t||!this.hlsVideo)))},n.Device.isConsoleOpen=function(){return!(!window.console||!window.console.firebug)||!(!window.console||(console.profile(),console.profileEnd(),console.clear&&console.clear(),!console.profiles))&&console.profiles.length>0},n.Device.isAndroidStockBrowser=function(){var t=window.navigator.userAgent.match(/Android.*AppleWebKit\/([\d.]+)/);return t&&t[1]<537},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Canvas={create:function(t,e,i,s,n){e=e||256,i=i||256;var r=n?document.createElement("canvas"):PIXI.CanvasPool.create(t,e,i);return"string"==typeof s&&""!==s&&(r.id=s),r.width=e,r.height=i,r.style.display="block",r},setBackgroundColor:function(t,e){return e=e||"rgb(0,0,0)",t.style.backgroundColor=e,t},setTouchAction:function(t,e){return e=e||"none",t.style.msTouchAction=e,t.style["ms-touch-action"]=e,t.style["touch-action"]=e,t},setUserSelect:function(t,e){return e=e||"none",t.style["-webkit-touch-callout"]=e,t.style["-webkit-user-select"]=e,t.style["-khtml-user-select"]=e,t.style["-moz-user-select"]=e,t.style["-ms-user-select"]=e,t.style["user-select"]=e,t.style["-webkit-tap-highlight-color"]="rgba(0, 0, 0, 0)",t},addToDOM:function(t,e,i){var s;return void 0===i&&(i=!0),e&&("string"==typeof e?s=document.getElementById(e):"object"==typeof e&&1===e.nodeType&&(s=e)),s||(s=document.body),i&&s.style&&(s.style.overflow="hidden"),s.appendChild(t),t},removeFromDOM:function(t){t.parentNode&&t.parentNode.removeChild(t)},setTransform:function(t,e,i,s,n,r,o){return t.setTransform(s,r,o,n,e,i),t},setSmoothingEnabled:function(t,e){var i=n.Canvas.getSmoothingPrefix(t);return i&&(t[i]=e),t},getSmoothingPrefix:function(t){var e=["i","webkitI","msI","mozI","oI"];for(var i in e){var s=e[i]+"mageSmoothingEnabled";if(s in t)return s}return null},getSmoothingEnabled:function(t){var e=n.Canvas.getSmoothingPrefix(t);if(e)return t[e]},setImageRenderingCrisp:function(t){for(var e=["optimizeSpeed","crisp-edges","-moz-crisp-edges","-webkit-optimize-contrast","optimize-contrast","pixelated"],i=0;i<e.length;i++)t.style["image-rendering"]=e[i];return t.style.msInterpolationMode="nearest-neighbor",t},setImageRenderingBicubic:function(t){return t.style["image-rendering"]="auto",t.style.msInterpolationMode="bicubic",t}},/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.RequestAnimationFrame=function(t,e){void 0===e&&(e=!1),this.game=t,this.isRunning=!1,this.forceSetTimeOut=e;for(var i=["ms","moz","webkit","o"],s=0;s<i.length&&!window.requestAnimationFrame;s++)window.requestAnimationFrame=window[i[s]+"RequestAnimationFrame"],window.cancelAnimationFrame=window[i[s]+"CancelAnimationFrame"];this._isSetTimeOut=!1,this._onLoop=null,this._timeOutID=null},n.RequestAnimationFrame.prototype={start:function(){this.isRunning=!0;var t=this;!window.requestAnimationFrame||this.forceSetTimeOut?(this._isSetTimeOut=!0,this._onLoop=function(){return t.updateSetTimeout()},this._timeOutID=window.setTimeout(this._onLoop,0)):(this._isSetTimeOut=!1,this._onLoop=function(e){return t.updateRAF(e)},this._timeOutID=window.requestAnimationFrame(this._onLoop))},updateRAF:function(t){this.isRunning&&(this.game.update(Math.floor(t)),this._timeOutID=window.requestAnimationFrame(this._onLoop))},updateSetTimeout:function(){this.isRunning&&(this.game.update(Date.now()),this._timeOutID=window.setTimeout(this._onLoop,this.game.time.timeToCall))},stop:function(){this._isSetTimeOut?clearTimeout(this._timeOutID):window.cancelAnimationFrame(this._timeOutID),this.isRunning=!1},isSetTimeOut:function(){return this._isSetTimeOut},isRAF:function(){return!1===this._isSetTimeOut}},n.RequestAnimationFrame.prototype.constructor=n.RequestAnimationFrame,/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
n.Math={PI2:2*Math.PI,between:function(t,e){return Math.floor(Math.random()*(e-t+1)+t)},fuzzyEqual:function(t,e,i){return void 0===i&&(i=1e-4),Math.abs(t-e)<i},fuzzyLessThan:function(t,e,i){return void 0===i&&(i=1e-4),t<e+i},fuzzyGreaterThan:function(t,e,i){return void 0===i&&(i=1e-4),t>e-i},fuzzyCeil:function(t,e){return void 0===e&&(e=1e-4),Math.ceil(t-e)},fuzzyFloor:function(t,e){return void 0===e&&(e=1e-4),Math.floor(t+e)},average:function(){for(var t=0,e=arguments.length,i=0;i<e;i++)t+=+arguments[i];return t/e},shear:function(t){return t%1},snapTo:function(t,e,i){return void 0===i&&(i=0),0===e?t:(t-=i,t=e*Math.round(t/e),i+t)},snapToFloor:function(t,e,i){return void 0===i&&(i=0),0===e?t:(t-=i,t=e*Math.floor(t/e),i+t)},snapToCeil:function(t,e,i){return void 0===i&&(i=0),0===e?t:(t-=i,t=e*Math.ceil(t/e),i+t)},roundTo:function(t,e,i){void 0===e&&(e=0),void 0===i&&(i=10);var s=Math.pow(i,-e);return Math.round(t*s)/s},floorTo:function(t,e,i){void 0===e&&(e=0),void 0===i&&(i=10);var s=Math.pow(i,-e);return Math.floor(t*s)/s},ceilTo:function(t,e,i){void 0===e&&(e=0),void 0===i&&(i=10);var s=Math.pow(i,-e);return Math.ceil(t*s)/s},rotateToAngle:function(t,e,i){return void 0===i&&(i=.05),t===e?t:(Math.abs(e-t)<=i||Math.abs(e-t)>=n.Math.PI2-i?t=e:(Math.abs(e-t)>Math.PI&&(e<t?e+=n.Math.PI2:e-=n.Math.PI2),e>t?t+=i:e<t&&(t-=i)),t)},getShortestAngle:function(t,e){var i=e-t;return 0===i?0:i-360*Math.floor((i- -180)/360)},angleBetween:function(t,e,i,s){return Math.atan2(s-e,i-t)},angleBetweenY:function(t,e,i,s){return Math.atan2(i-t,s-e)},angleBetweenPoints:function(t,e){return Math.atan2(e.y-t.y,e.x-t.x)},angleBetweenPointsY:function(t,e){return Math.atan2(e.x-t.x,e.y-t.y)},reverseAngle:function(t){return this.normalizeAngle(t+Math.PI,!0)},normalizeAngle:function(t){return t%=2*Math.PI,t>=0?t:t+2*Math.PI},maxAdd:function(t,e,i){return Math.min(t+e,i)},minSub:function(t,e,i){return Math.max(t-e,i)},wrap:function(t,e,i){var s=i-e;if(s<=0)return 0;var n=(t-e)%s;return n<0&&(n+=s),n+e},wrapValue:function(t,e,i){return t=Math.abs(t),e=Math.abs(e),i=Math.abs(i),(t+e)%i},isOdd:function(t){return!!(1&t)},isEven:function(t){return!(1&t)},min:function(){if(1===arguments.length&&"object"==typeof arguments[0])var t=arguments[0];else var t=arguments;for(var e=1,i=0,s=t.length;e<s;e++)t[e]<t[i]&&(i=e);return t[i]},max:function(){if(1===arguments.length&&"object"==typeof arguments[0])var t=arguments[0];else var t=arguments;for(var e=1,i=0,s=t.length;e<s;e++)t[e]>t[i]&&(i=e);return t[i]},minProperty:function(t){if(2===arguments.length&&"object"==typeof arguments[1])var e=arguments[1];else var e=arguments.slice(1);for(var i=1,s=0,n=e.length;i<n;i++)e[i][t]<e[s][t]&&(s=i);return e[s][t]},maxProperty:function(t){if(2===arguments.length&&"object"==typeof arguments[1])var e=arguments[1];else var e=arguments.slice(1);for(var i=1,s=0,n=e.length;i<n;i++)e[i][t]>e[s][t]&&(s=i);return e[s][t]},wrapAngle:function(t,e){return e?this.wrap(t,-Math.PI,Math.PI):this.wrap(t,-180,180)},linearInterpolation:function(t,e){var i=t.length-1,s=i*e,n=Math.floor(s);return e<0?this.linear(t[0],t[1],s):e>1?this.linear(t[i],t[i-1],i-s):this.linear(t[n],t[n+1>i?i:n+1],s-n)},bezierInterpolation:function(t,e){for(var i=0,s=t.length-1,n=0;n<=s;n++)i+=Math.pow(1-e,s-n)*Math.pow(e,n)*t[n]*this.bernstein(s,n);return i},catmullRomInterpolation:function(t,e){var i=t.length-1,s=i*e,n=Math.floor(s);return t[0]===t[i]?(e<0&&(n=Math.floor(s=i*(1+e))),this.catmullRom(t[(n-1+i)%i],t[n],t[(n+1)%i],t[(n+2)%i],s-n)):e<0?t[0]-(this.catmullRom(t[0],t[0],t[1],t[1],-s)-t[0]):e>1?t[i]-(this.catmullRom(t[i],t[i],t[i-1],t[i-1],s-i)-t[i]):this.catmullRom(t[n?n-1:0],t[n],t[i<n+1?i:n+1],t[i<n+2?i:n+2],s-n)},linear:function(t,e,i){return(e-t)*i+t},bernstein:function(t,e){return this.factorial(t)/this.factorial(e)/this.factorial(t-e)},factorial:function(t){if(0===t)return 1;for(var e=t;--t;)e*=t;return e},catmullRom:function(t,e,i,s,n){var r=.5*(i-t),o=.5*(s-e),a=n*n;return(2*e-2*i+r+o)*(n*a)+(-3*e+3*i-2*r-o)*a+r*n+e},difference:function(t,e){return Math.abs(t-e)},roundAwayFromZero:function(t){return t>0?Math.ceil(t):Math.floor(t)},sinCosGenerator:function(t,e,i,s){void 0===e&&(e=1),void 0===i&&(i=1),void 0===s&&(s=1);for(var n=e,r=i,o=s*Math.PI/t,a=[],h=[],l=0;l<t;l++)r-=n*o,n+=r*o,a[l]=r,h[l]=n;return{sin:h,cos:a,length:t}},distance:function(t,e,i,s){var n=t-i,r=e-s;return Math.sqrt(n*n+r*r)},distanceSq:function(t,e,i,s){var n=t-i,r=e-s;return n*n+r*r},distancePow:function(t,e,i,s,n){return void 0===n&&(n=2),Math.sqrt(Math.pow(i-t,n)+Math.pow(s-e,n))},clamp:function(t,e,i){return t<e?e:i<t?i:t},clampBottom:function(t,e){return t<e?e:t},within:function(t,e,i){return Math.abs(t-e)<=i},mapLinear:function(t,e,i,s,n){return s+(t-e)*(n-s)/(i-e)},smoothstep:function(t,e,i){return(t=Math.max(0,Math.min(1,(t-e)/(i-e))))*t*(3-2*t)},smootherstep:function(t,e,i){return(t=Math.max(0,Math.min(1,(t-e)/(i-e))))*t*t*(t*(6*t-15)+10)},sign:function(t){return t<0?-1:t>0?1:0},percent:function(t,e,i){return void 0===i&&(i=0),t>e||i>e?1:t<i||i>t?0:(t-i)/e}};var h=Math.PI/180,l=180/Math.PI;/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Timo Hausmann
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Jeremy Dowell <[email protected]>
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Georgios Kaleadis https://github.com/georgiee
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author George https://github.com/georgiee
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
return n.Math.degToRad=function(t){return t*h},n.Math.radToDeg=function(t){return t*l},n.RandomDataGenerator=function(t){void 0===t&&(t=[]),this.c=1,this.s0=0,this.s1=0,this.s2=0,"string"==typeof t?this.state(t):this.sow(t)},n.RandomDataGenerator.prototype={rnd:function(){var t=2091639*this.s0+2.3283064365386963e-10*this.c;return this.c=0|t,this.s0=this.s1,this.s1=this.s2,this.s2=t-this.c,this.s2},sow:function(t){if(this.s0=this.hash(" "),this.s1=this.hash(this.s0),this.s2=this.hash(this.s1),this.c=1,t)for(var e=0;e<t.length&&null!=t[e];e++){var i=t[e];this.s0-=this.hash(i),this.s0+=~~(this.s0<0),this.s1-=this.hash(i),this.s1+=~~(this.s1<0),this.s2-=this.hash(i),this.s2+=~~(this.s2<0)}},hash:function(t){var e,i,s;for(s=4022871197,t=t.toString(),i=0;i<t.length;i++)s+=t.charCodeAt(i),e=.02519603282416938*s,s=e>>>0,e-=s,e*=s,s=e>>>0,e-=s,s+=4294967296*e;return 2.3283064365386963e-10*(s>>>0)},integer:function(){return 4294967296*this.rnd.apply(this)},frac:function(){return this.rnd.apply(this)+1.1102230246251565e-16*(2097152*this.rnd.apply(this)|0)},real:function(){return this.integer()+this.frac()},integerInRange:function(t,e){return Math.floor(this.realInRange(0,e-t+1)+t)},between:function(t,e){return this.integerInRange(t,e)},realInRange:function(t,e){return this.frac()*(e-t)+t},normal:function(){return 1-2*this.frac()},uuid:function(){var t="",e="";for(e=t="";t++<36;e+=~t%5|3*t&4?(15^t?8^this.frac()*(20^t?16:4):4).toString(16):"-");return e},pick:function(t){return t[this.integerInRange(0,t.length-1)]},sign:function(){return this.pick([-1,1])},weightedPick:function(t){return t[~~(Math.pow(this.frac(),2)*(t.length-1)+.5)]},timestamp:function(t,e){return this.realInRange(t||9466848e5,e||1577862e6)},angle:function(){return this.integerInRange(-180,180)},state:function(t){return"string"==typeof t&&t.match(/^!rnd/)&&(t=t.split(","),this.c=parseFloat(t[1]),this.s0=parseFloat(t[2]),this.s1=parseFloat(t[3]),this.s2=parseFloat(t[4])),["!rnd",this.c,this.s0,this.s1,this.s2].join(",")}},n.RandomDataGenerator.prototype.constructor=n.RandomDataGenerator,n.QuadTree=function(t,e,i,s,n,r,o){this.maxObjects=10,this.maxLevels=4,this.level=0,this.bounds={},this.objects=[],this.nodes=[],this._empty=[],this.reset(t,e,i,s,n,r,o)},n.QuadTree.prototype={reset:function(t,e,i,s,n,r,o){this.maxObjects=n||10,this.maxLevels=r||4,this.level=o||0,this.bounds={x:Math.round(t),y:Math.round(e),width:i,height:s,subWidth:Math.floor(i/2),subHeight:Math.floor(s/2),right:Math.round(t)+Math.floor(i/2),bottom:Math.round(e)+Math.floor(s/2)},this.objects.length=0,this.nodes.length=0},populate:function(t){t.forEach(this.populateHandler,this,!0)},populateHandler:function(t){t.body&&t.exists&&this.insert(t.body)},split:function(){this.nodes[0]=new n.QuadTree(this.bounds.right,this.bounds.y,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[1]=new n.QuadTree(this.bounds.x,this.bounds.y,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[2]=new n.QuadTree(this.bounds.x,this.bounds.bottom,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[3]=new n.QuadTree(this.bounds.right,this.bounds.bottom,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1)},insert:function(t){var e,i=0;if(null!=this.nodes[0]&&-1!==(e=this.getIndex(t)))return void this.nodes[e].insert(t);if(this.objects.push(t),this.objects.length>this.maxObjects&&this.level<this.maxLevels)for(null==this.nodes[0]&&this.split();i<this.objects.length;)e=this.getIndex(this.objects[i]),-1!==e?this.nodes[e].insert(this.objects.splice(i,1)[0]):i++},getIndex:function(t){var e=-1;return t.x<this.bounds.right&&t.right<this.bounds.right?t.y<this.bounds.bottom&&t.bottom<this.bounds.bottom?e=1:t.y>this.bounds.bottom&&(e=2):t.x>this.bounds.right&&(t.y<this.bounds.bottom&&t.bottom<this.bounds.bottom?e=0:t.y>this.bounds.bottom&&(e=3)),e},retrieve:function(t){if(t instanceof n.Rectangle)var e=this.objects,i=this.getIndex(t);else{if(!t.body)return this._empty;var e=this.objects,i=this.getIndex(t.body)}return this.nodes[0]&&(-1!==i?e=e.concat(this.nodes[i].retrieve(t)):(e=e.concat(this.nodes[0].retrieve(t)),e=e.concat(this.nodes[1].retrieve(t)),e=e.concat(this.nodes[2].retrieve(t)),e=e.concat(this.nodes[3].retrieve(t)))),e},clear:function(){this.objects.length=0;for(var t=this.nodes.length;t--;)this.nodes[t].clear(),this.nodes.splice(t,1);this.nodes.length=0}},n.QuadTree.prototype.constructor=n.QuadTree,n.Net=function(t){this.game=t},n.Net.prototype={getHostName:function(){return window.location&&window.location.hostname?window.location.hostname:null},checkDomainName:function(t){return-1!==window.location.hostname.indexOf(t)},updateQueryString:function(t,e,i,s){void 0===i&&(i=!1),void 0!==s&&""!==s||(s=window.location.href);var n="",r=new RegExp("([?|&])"+t+"=.*?(&|#|$)(.*)","gi");if(r.test(s))n=void 0!==e&&null!==e?s.replace(r,"$1"+t+"="+e+"$2$3"):s.replace(r,"$1$3").replace(/(&|\?)$/,"");else if(void 0!==e&&null!==e){var o=-1!==s.indexOf("?")?"&":"?",a=s.split("#");s=a[0]+o+t+"="+e,a[1]&&(s+="#"+a[1]),n=s}else n=s;if(!i)return n;window.location.href=n},getQueryString:function(t){void 0===t&&(t="");var e={},i=location.search.substring(1).split("&");for(var s in i){var n=i[s].split("=");if(n.length>1){if(t&&t===this.decodeURI(n[0]))return this.decodeURI(n[1]);e[this.decodeURI(n[0])]=this.decodeURI(n[1])}}return e},decodeURI:function(t){return decodeURIComponent(t.replace(/\+/g," "))}},n.Net.prototype.constructor=n.Net,n.TweenManager=function(t){this.game=t,this.frameBased=!1,this._tweens=[],this._add=[],this.easeMap={Power0:n.Easing.Power0,Power1:n.Easing.Power1,Power2:n.Easing.Power2,Power3:n.Easing.Power3,Power4:n.Easing.Power4,Linear:n.Easing.Linear.None,Quad:n.Easing.Quadratic.Out,Cubic:n.Easing.Cubic.Out,Quart:n.Easing.Quartic.Out,Quint:n.Easing.Quintic.Out,Sine:n.Easing.Sinusoidal.Out,Expo:n.Easing.Exponential.Out,Circ:n.Easing.Circular.Out,Elastic:n.Easing.Elastic.Out,Back:n.Easing.Back.Out,Bounce:n.Easing.Bounce.Out,"Quad.easeIn":n.Easing.Quadratic.In,"Cubic.easeIn":n.Easing.Cubic.In,"Quart.easeIn":n.Easing.Quartic.In,"Quint.easeIn":n.Easing.Quintic.In,"Sine.easeIn":n.Easing.Sinusoidal.In,"Expo.easeIn":n.Easing.Exponential.In,"Circ.easeIn":n.Easing.Circular.In,"Elastic.easeIn":n.Easing.Elastic.In,"Back.easeIn":n.Easing.Back.In,"Bounce.easeIn":n.Easing.Bounce.In,"Quad.easeOut":n.Easing.Quadratic.Out,"Cubic.easeOut":n.Easing.Cubic.Out,"Quart.easeOut":n.Easing.Quartic.Out,"Quint.easeOut":n.Easing.Quintic.Out,"Sine.easeOut":n.Easing.Sinusoidal.Out,"Expo.easeOut":n.Easing.Exponential.Out,"Circ.easeOut":n.Easing.Circular.Out,"Elastic.easeOut":n.Easing.Elastic.Out,"Back.easeOut":n.Easing.Back.Out,"Bounce.easeOut":n.Easing.Bounce.Out,"Quad.easeInOut":n.Easing.Quadratic.InOut,"Cubic.easeInOut":n.Easing.Cubic.InOut,"Quart.easeInOut":n.Easing.Quartic.InOut,"Quint.easeInOut":n.Easing.Quintic.InOut,"Sine.easeInOut":n.Easing.Sinusoidal.InOut,"Expo.easeInOut":n.Easing.Exponential.InOut,"Circ.easeInOut":n.Easing.Circular.InOut,"Elastic.easeInOut":n.Easing.Elastic.InOut,"Back.easeInOut":n.Easing.Back.InOut,"Bounce.easeInOut":n.Easing.Bounce.InOut},this.game.onPause.add(this._pauseAll,this),this.game.onResume.add(this._resumeAll,this)},n.TweenManager.prototype={getAll:function(){return this._tweens},removeAll:function(){for(var t=0;t<this._tweens.length;t++)this._tweens[t].pendingDelete=!0;this._add=[]},removeFrom:function(t,e){void 0===e&&(e=!0);var i,s;if(Array.isArray(t))for(i=0,s=t.length;i<s;i++)this.removeFrom(t[i]);else if(t.type===n.GROUP&&e)for(var i=0,s=t.children.length;i<s;i++)this.removeFrom(t.children[i]);else{for(i=0,s=this._tweens.length;i<s;i++)t===this._tweens[i].target&&this.remove(this._tweens[i]);for(i=0,s=this._add.length;i<s;i++)t===this._add[i].target&&this.remove(this._add[i])}},add:function(t){t._manager=this,this._add.push(t)},create:function(t){return new n.Tween(t,this.game,this)},remove:function(t){var e=this._tweens.indexOf(t);-1!==e?this._tweens[e].pendingDelete=!0:-1!==(e=this._add.indexOf(t))&&(this._add[e].pendingDelete=!0)},update:function(){var t=this._add.length,e=this._tweens.length;if(0===e&&0===t)return!1;for(var i=0;i<e;)this._tweens[i].update(this.game.time.time)?i++:(this._tweens.splice(i,1),e--);return t>0&&(this._tweens=this._tweens.concat(this._add),this._add.length=0),!0},isTweening:function(t){return this._tweens.some(function(e){return e.target===t})},_pauseAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t]._pause()},_resumeAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t]._resume()},pauseAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t].pause()},resumeAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t].resume(!0)}},n.TweenManager.prototype.constructor=n.TweenManager,n.Tween=function(t,e,i){this.game=e,this.target=t,this.manager=i,this.timeline=[],this.reverse=!1,this.timeScale=1,this.repeatCounter=0,this.pendingDelete=!1,this.onStart=new n.Signal,this.onLoop=new n.Signal,this.onRepeat=new n.Signal,this.onChildComplete=new n.Signal,this.onComplete=new n.Signal,this.isRunning=!1,this.current=0,this.properties={},this.chainedTween=null,this.isPaused=!1,this.frameBased=i.frameBased,this._onUpdateCallback=null,this._onUpdateCallbackContext=null,this._pausedTime=0,this._codePaused=!1,this._hasStarted=!1},n.Tween.prototype={to:function(t,e,i,s,r,o,a){return(void 0===e||e<=0)&&(e=1e3),void 0!==i&&null!==i||(i=n.Easing.Default),void 0===s&&(s=!1),void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=!1),"string"==typeof i&&this.manager.easeMap[i]&&(i=this.manager.easeMap[i]),this.isRunning?(console.warn("Phaser.Tween.to cannot be called after Tween.start"),this):(this.timeline.push(new n.TweenData(this).to(t,e,i,r,o,a)),s&&this.start(),this)},from:function(t,e,i,s,r,o,a){return void 0===e&&(e=1e3),void 0!==i&&null!==i||(i=n.Easing.Default),void 0===s&&(s=!1),void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=!1),"string"==typeof i&&this.manager.easeMap[i]&&(i=this.manager.easeMap[i]),this.isRunning?(console.warn("Phaser.Tween.from cannot be called after Tween.start"),this):(this.timeline.push(new n.TweenData(this).from(t,e,i,r,o,a)),s&&this.start(),this)},start:function(t){if(void 0===t&&(t=0),null===this.game||null===this.target||0===this.timeline.length||this.isRunning)return this;for(var e=0;e<this.timeline.length;e++)for(var i in this.timeline[e].vEnd)this.properties[i]=this.target[i]||0,Array.isArray(this.properties[i])||(this.properties[i]*=1);for(var e=0;e<this.timeline.length;e++)this.timeline[e].loadValues();return this.manager.add(this),this.isRunning=!0,(t<0||t>this.timeline.length-1)&&(t=0),this.current=t,this.timeline[this.current].start(),this},stop:function(t){return void 0===t&&(t=!1),this.isRunning=!1,this._onUpdateCallback=null,this._onUpdateCallbackContext=null,t&&(this.onComplete.dispatch(this.target,this),this._hasStarted=!1,this.chainedTween&&this.chainedTween.start()),this.manager.remove(this),this},updateTweenData:function(t,e,i){if(0===this.timeline.length)return this;if(void 0===i&&(i=0),-1===i)for(var s=0;s<this.timeline.length;s++)this.timeline[s][t]=e;else this.timeline[i][t]=e;return this},delay:function(t,e){return this.updateTweenData("delay",t,e)},repeat:function(t,e,i){return void 0===e&&(e=0),this.updateTweenData("repeatCounter",t,i),this.updateTweenData("repeatDelay",e,i)},repeatDelay:function(t,e){return this.updateTweenData("repeatDelay",t,e)},yoyo:function(t,e,i){return void 0===e&&(e=0),this.updateTweenData("yoyo",t,i),this.updateTweenData("yoyoDelay",e,i)},yoyoDelay:function(t,e){return this.updateTweenData("yoyoDelay",t,e)},easing:function(t,e){return"string"==typeof t&&this.manager.easeMap[t]&&(t=this.manager.easeMap[t]),this.updateTweenData("easingFunction",t,e)},interpolation:function(t,e,i){return void 0===e&&(e=n.Math),this.updateTweenData("interpolationFunction",t,i),this.updateTweenData("interpolationContext",e,i)},repeatAll:function(t){return void 0===t&&(t=0),this.repeatCounter=t,this},chain:function(){for(var t=arguments.length;t--;)t>0?arguments[t-1].chainedTween=arguments[t]:this.chainedTween=arguments[t];return this},loop:function(t){return void 0===t&&(t=!0),this.repeatCounter=t?-1:0,this},onUpdateCallback:function(t,e){return this._onUpdateCallback=t,this._onUpdateCallbackContext=e,this},pause:function(){this.isPaused=!0,this._codePaused=!0,this._pausedTime=this.game.time.time},_pause:function(){this._codePaused||(this.isPaused=!0,this._pausedTime=this.game.time.time)},resume:function(){if(this.isPaused){this.isPaused=!1,this._codePaused=!1;for(var t=0;t<this.timeline.length;t++)this.timeline[t].isRunning||(this.timeline[t].startTime+=this.game.time.time-this._pausedTime)}},_resume:function(){this._codePaused||this.resume()},update:function(t){if(this.pendingDelete||!this.target)return!1;if(this.isPaused)return!0;var e=this.timeline[this.current].update(t);if(e===n.TweenData.PENDING)return!0;if(e===n.TweenData.RUNNING)return this._hasStarted||(this.onStart.dispatch(this.target,this),this._hasStarted=!0),null!==this._onUpdateCallback&&this._onUpdateCallback.call(this._onUpdateCallbackContext,this,this.timeline[this.current].value,this.timeline[this.current]),this.isRunning;if(e===n.TweenData.LOOPED)return-1===this.timeline[this.current].repeatCounter?this.onLoop.dispatch(this.target,this):this.onRepeat.dispatch(this.target,this),!0;if(e===n.TweenData.COMPLETE){var i=!1;return this.reverse?--this.current<0&&(this.current=this.timeline.length-1,i=!0):++this.current===this.timeline.length&&(this.current=0,i=!0),i?-1===this.repeatCounter?(this.timeline[this.current].start(),this.onLoop.dispatch(this.target,this),!0):this.repeatCounter>0?(this.repeatCounter--,this.timeline[this.current].start(),this.onRepeat.dispatch(this.target,this),!0):(this.isRunning=!1,this.onComplete.dispatch(this.target,this),this._hasStarted=!1,this.chainedTween&&this.chainedTween.start(),!1):(this.onChildComplete.dispatch(this.target,this),this.timeline[this.current].start(),!0)}},generateData:function(t,e){if(null===this.game||null===this.target)return null;void 0===t&&(t=60),void 0===e&&(e=[]);for(var i=0;i<this.timeline.length;i++)for(var s in this.timeline[i].vEnd)this.properties[s]=this.target[s]||0,Array.isArray(this.properties[s])||(this.properties[s]*=1);for(var i=0;i<this.timeline.length;i++)this.timeline[i].loadValues();for(var i=0;i<this.timeline.length;i++)e=e.concat(this.timeline[i].generateData(t));return e}},Object.defineProperty(n.Tween.prototype,"totalDuration",{get:function(){for(var t=0,e=0;e<this.timeline.length;e++)t+=this.timeline[e].duration;return t}}),n.Tween.prototype.constructor=n.Tween,n.TweenData=function(t){this.parent=t,this.game=t.game,this.vStart={},this.vStartCache={},this.vEnd={},this.vEndCache={},this.duration=1e3,this.percent=0,this.value=0,this.repeatCounter=0,this.repeatDelay=0,this.repeatTotal=0,this.interpolate=!1,this.yoyo=!1,this.yoyoDelay=0,this.inReverse=!1,this.delay=0,this.dt=0,this.startTime=null,this.easingFunction=n.Easing.Default,this.interpolationFunction=n.Math.linearInterpolation,this.interpolationContext=n.Math,this.isRunning=!1,this.isFrom=!1},n.TweenData.PENDING=0,n.TweenData.RUNNING=1,n.TweenData.LOOPED=2,n.TweenData.COMPLETE=3,n.TweenData.prototype={to:function(t,e,i,s,n,r){return this.vEnd=t,this.duration=e,this.easingFunction=i,this.delay=s,this.repeatTotal=n,this.yoyo=r,this.isFrom=!1,this},from:function(t,e,i,s,n,r){return this.vEnd=t,this.duration=e,this.easingFunction=i,this.delay=s,this.repeatTotal=n,this.yoyo=r,this.isFrom=!0,this},start:function(){if(this.startTime=this.game.time.time+this.delay,this.parent.reverse?this.dt=this.duration:this.dt=0,this.delay>0?this.isRunning=!1:this.isRunning=!0,this.isFrom)for(var t in this.vStartCache)this.vStart[t]=this.vEndCache[t],this.vEnd[t]=this.vStartCache[t],this.parent.target[t]=this.vStart[t];return this.value=0,this.yoyoCounter=0,this.repeatCounter=this.repeatTotal,this},loadValues:function(){for(var t in this.parent.properties){if(this.vStart[t]=this.parent.properties[t],Array.isArray(this.vEnd[t])){if(0===this.vEnd[t].length)continue;0===this.percent&&(this.vEnd[t]=[this.vStart[t]].concat(this.vEnd[t]))}void 0!==this.vEnd[t]?("string"==typeof this.vEnd[t]&&(this.vEnd[t]=this.vStart[t]+parseFloat(this.vEnd[t],10)),this.parent.properties[t]=this.vEnd[t]):this.vEnd[t]=this.vStart[t],this.vStartCache[t]=this.vStart[t],this.vEndCache[t]=this.vEnd[t]}return this},update:function(t){if(this.isRunning){if(t<this.startTime)return n.TweenData.RUNNING}else{if(!(t>=this.startTime))return n.TweenData.PENDING;this.isRunning=!0}var e=this.parent.frameBased?this.game.time.physicsElapsedMS:this.game.time.elapsedMS;this.parent.reverse?(this.dt-=e*this.parent.timeScale,this.dt=Math.max(this.dt,0)):(this.dt+=e*this.parent.timeScale,this.dt=Math.min(this.dt,this.duration)),this.percent=this.dt/this.duration,this.value=this.easingFunction(this.percent);for(var i in this.vEnd){var s=this.vStart[i],r=this.vEnd[i];Array.isArray(r)?this.parent.target[i]=this.interpolationFunction.call(this.interpolationContext,r,this.value):this.parent.target[i]=s+(r-s)*this.value}return!this.parent.reverse&&1===this.percent||this.parent.reverse&&0===this.percent?this.repeat():n.TweenData.RUNNING},generateData:function(t){this.parent.reverse?this.dt=this.duration:this.dt=0;var e=[],i=!1,s=1/t*1e3;do{this.parent.reverse?(this.dt-=s,this.dt=Math.max(this.dt,0)):(this.dt+=s,this.dt=Math.min(this.dt,this.duration)),this.percent=this.dt/this.duration,this.value=this.easingFunction(this.percent);var n={};for(var r in this.vEnd){var o=this.vStart[r],a=this.vEnd[r];Array.isArray(a)?n[r]=this.interpolationFunction(a,this.value):n[r]=o+(a-o)*this.value}e.push(n),(!this.parent.reverse&&1===this.percent||this.parent.reverse&&0===this.percent)&&(i=!0)}while(!i);if(this.yoyo){var h=e.slice();h.reverse(),e=e.concat(h)}return e},repeat:function(){if(this.yoyo){if(this.inReverse&&0===this.repeatCounter){for(var t in this.vStartCache)this.vStart[t]=this.vStartCache[t],this.vEnd[t]=this.vEndCache[t];return this.inReverse=!1,n.TweenData.COMPLETE}this.inReverse=!this.inReverse}else if(0===this.repeatCounter)return n.TweenData.COMPLETE;if(this.inReverse)for(var t in this.vStartCache)this.vStart[t]=this.vEndCache[t],this.vEnd[t]=this.vStartCache[t];else{for(var t in this.vStartCache)this.vStart[t]=this.vStartCache[t],this.vEnd[t]=this.vEndCache[t];this.repeatCounter>0&&this.repeatCounter--}return this.startTime=this.game.time.time,this.yoyo&&this.inReverse?this.startTime+=this.yoyoDelay:this.inReverse||(this.startTime+=this.repeatDelay),this.parent.reverse?this.dt=this.duration:this.dt=0,n.TweenData.LOOPED}},n.TweenData.prototype.constructor=n.TweenData,n.Easing={Linear:{None:function(t){return t}},Quadratic:{In:function(t){return t*t},Out:function(t){return t*(2-t)},InOut:function(t){return(t*=2)<1?.5*t*t:-.5*(--t*(t-2)-1)}},Cubic:{In:function(t){return t*t*t},Out:function(t){return--t*t*t+1},InOut:function(t){return(t*=2)<1?.5*t*t*t:.5*((t-=2)*t*t+2)}},Quartic:{In:function(t){return t*t*t*t},Out:function(t){return 1- --t*t*t*t},InOut:function(t){return(t*=2)<1?.5*t*t*t*t:-.5*((t-=2)*t*t*t-2)}},Quintic:{In:function(t){return t*t*t*t*t},Out:function(t){return--t*t*t*t*t+1},InOut:function(t){return(t*=2)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2)}},Sinusoidal:{In:function(t){return 0===t?0:1===t?1:1-Math.cos(t*Math.PI/2)},Out:function(t){return 0===t?0:1===t?1:Math.sin(t*Math.PI/2)},InOut:function(t){return 0===t?0:1===t?1:.5*(1-Math.cos(Math.PI*t))}},Exponential:{In:function(t){return 0===t?0:Math.pow(1024,t-1)},Out:function(t){return 1===t?1:1-Math.pow(2,-10*t)},InOut:function(t){return 0===t?0:1===t?1:(t*=2)<1?.5*Math.pow(1024,t-1):.5*(2-Math.pow(2,-10*(t-1)))}},Circular:{In:function(t){return 1-Math.sqrt(1-t*t)},Out:function(t){return Math.sqrt(1- --t*t)},InOut:function(t){return(t*=2)<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1)}},Elastic:{In:function(t){var e,i=.1;return 0===t?0:1===t?1:(!i||i<1?(i=1,e=.1):e=.4*Math.asin(1/i)/(2*Math.PI),-i*Math.pow(2,10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4))},Out:function(t){var e,i=.1;return 0===t?0:1===t?1:(!i||i<1?(i=1,e=.1):e=.4*Math.asin(1/i)/(2*Math.PI),i*Math.pow(2,-10*t)*Math.sin((t-e)*(2*Math.PI)/.4)+1)},InOut:function(t){var e,i=.1;return 0===t?0:1===t?1:(!i||i<1?(i=1,e=.1):e=.4*Math.asin(1/i)/(2*Math.PI),(t*=2)<1?i*Math.pow(2,10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4)*-.5:i*Math.pow(2,-10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4)*.5+1)}},Back:{In:function(t){var e=1.70158;return t*t*((e+1)*t-e)},Out:function(t){var e=1.70158;return--t*t*((e+1)*t+e)+1},InOut:function(t){var e=2.5949095;return(t*=2)<1?t*t*((e+1)*t-e)*.5:.5*((t-=2)*t*((e+1)*t+e)+2)}},Bounce:{In:function(t){return 1-n.Easing.Bounce.Out(1-t)},Out:function(t){return t<1/2.75?7.5625*t*t:t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375},InOut:function(t){return t<.5?.5*n.Easing.Bounce.In(2*t):.5*n.Easing.Bounce.Out(2*t-1)+.5}}},n.Easing.Default=n.Easing.Linear.None,n.Easing.Power0=n.Easing.Linear.None,n.Easing.Power1=n.Easing.Quadratic.Out,n.Easing.Power2=n.Easing.Cubic.Out,n.Easing.Power3=n.Easing.Quartic.Out,n.Easing.Power4=n.Easing.Quintic.Out,n.Time=function(t){this.game=t,this.time=0,this.prevTime=0,this.now=0,this.elapsed=0,this.elapsedMS=0,this.physicsElapsed=1/60,this.physicsElapsedMS=1/60*1e3,this.desiredFpsMult=1/60,this._desiredFps=60,this.suggestedFps=this.desiredFps,this.slowMotion=1,this.advancedTiming=!1,this.frames=0,this.fps=0,this.fpsMin=1e3,this.fpsMax=0,this.msMin=1e3,this.msMax=0,this.pauseDuration=0,this.timeToCall=0,this.timeExpected=0,this.events=new n.Timer(this.game,!1),this._frameCount=0,this._elapsedAccumulator=0,this._started=0,this._timeLastSecond=0,this._pauseStarted=0,this._justResumed=!1,this._timers=[]},n.Time.prototype={boot:function(){this._started=Date.now(),this.time=Date.now(),this.events.start(),this.timeExpected=this.time},add:function(t){return this._timers.push(t),t},create:function(t){void 0===t&&(t=!0);var e=new n.Timer(this.game,t);return this._timers.push(e),e},removeAll:function(){for(var t=0;t<this._timers.length;t++)this._timers[t].destroy();this._timers=[],this.events.removeAll()},refresh:function(){var t=this.time;this.time=Date.now(),this.elapsedMS=this.time-t},update:function(t){var e=this.time;this.time=Date.now(),this.elapsedMS=this.time-e,this.prevTime=this.now,this.now=t,this.elapsed=this.now-this.prevTime,this.game.raf._isSetTimeOut&&(this.timeToCall=Math.floor(Math.max(0,1e3/this._desiredFps-(this.timeExpected-t))),this.timeExpected=t+this.timeToCall),this.advancedTiming&&this.updateAdvancedTiming(),this.game.paused||(this.events.update(this.time),this._timers.length&&this.updateTimers())},updateTimers:function(){for(var t=0,e=this._timers.length;t<e;)this._timers[t].update(this.time)?t++:(this._timers.splice(t,1),e--)},updateAdvancedTiming:function(){this._frameCount++,this._elapsedAccumulator+=this.elapsed,this._frameCount>=2*this._desiredFps&&(this.suggestedFps=5*Math.floor(200/(this._elapsedAccumulator/this._frameCount)),this._frameCount=0,this._elapsedAccumulator=0),this.msMin=Math.min(this.msMin,this.elapsed),this.msMax=Math.max(this.msMax,this.elapsed),this.frames++,this.now>this._timeLastSecond+1e3&&(this.fps=Math.round(1e3*this.frames/(this.now-this._timeLastSecond)),this.fpsMin=Math.min(this.fpsMin,this.fps),this.fpsMax=Math.max(this.fpsMax,this.fps),this._timeLastSecond=this.now,this.frames=0)},gamePaused:function(){this._pauseStarted=Date.now(),this.events.pause();for(var t=this._timers.length;t--;)this._timers[t]._pause()},gameResumed:function(){this.time=Date.now(),this.pauseDuration=this.time-this._pauseStarted,this.events.resume();for(var t=this._timers.length;t--;)this._timers[t]._resume()},totalElapsedSeconds:function(){return.001*(this.time-this._started)},elapsedSince:function(t){return this.time-t},elapsedSecondsSince:function(t){return.001*(this.time-t)},reset:function(){this._started=this.time,this.removeAll()}},Object.defineProperty(n.Time.prototype,"desiredFps",{get:function(){return this._desiredFps},set:function(t){this._desiredFps=t,this.physicsElapsed=1/t,this.physicsElapsedMS=1e3*this.physicsElapsed,this.desiredFpsMult=1/t}}),n.Time.prototype.constructor=n.Time,n.Timer=function(t,e){void 0===e&&(e=!0),this.game=t,this.running=!1,this.autoDestroy=e,this.expired=!1,this.elapsed=0,this.events=[],this.onComplete=new n.Signal,this.nextTick=0,this.timeCap=1e3,this.paused=!1,this._codePaused=!1,this._started=0,this._pauseStarted=0,this._pauseTotal=0,this._now=Date.now(),this._len=0,this._marked=0,this._i=0,this._diff=0,this._newTick=0},n.Timer.MINUTE=6e4,n.Timer.SECOND=1e3,n.Timer.HALF=500,n.Timer.QUARTER=250,n.Timer.prototype={create:function(t,e,i,s,r,o){t=Math.round(t);var a=t;0===this._now?a+=this.game.time.time:a+=this._now;var h=new n.TimerEvent(this,t,a,i,e,s,r,o);return this.events.push(h),this.order(),this.expired=!1,h},add:function(t,e,i){return this.create(t,!1,0,e,i,Array.prototype.slice.call(arguments,3))},repeat:function(t,e,i,s){return this.create(t,!1,e,i,s,Array.prototype.slice.call(arguments,4))},loop:function(t,e,i){return this.create(t,!0,0,e,i,Array.prototype.slice.call(arguments,3))},start:function(t){if(!this.running){this._started=this.game.time.time+(t||0),this.running=!0;for(var e=0;e<this.events.length;e++)this.events[e].tick=this.events[e].delay+this._started}},stop:function(t){this.running=!1,void 0===t&&(t=!0),t&&(this.events.length=0)},remove:function(t){for(var e=0;e<this.events.length;e++)if(this.events[e]===t)return this.events[e].pendingDelete=!0,!0;return!1},order:function(){this.events.length>0&&(this.events.sort(this.sortHandler),this.nextTick=this.events[0].tick)},sortHandler:function(t,e){return t.tick<e.tick?-1:t.tick>e.tick?1:0},clearPendingEvents:function(){for(this._i=this.events.length;this._i--;)this.events[this._i].pendingDelete&&this.events.splice(this._i,1);this._len=this.events.length,this._i=0},update:function(t){if(this.paused)return!0;if(this.elapsed=t-this._now,this._now=t,this.elapsed>this.timeCap&&this.adjustEvents(t-this.elapsed),this._marked=0,this.clearPendingEvents(),this.running&&this._now>=this.nextTick&&this._len>0){for(;this._i<this._len&&this.running&&this._now>=this.events[this._i].tick&&!this.events[this._i].pendingDelete;)this._newTick=this._now+this.events[this._i].delay-(this._now-this.events[this._i].tick),this._newTick<0&&(this._newTick=this._now+this.events[this._i].delay),!0===this.events[this._i].loop?(this.events[this._i].tick=this._newTick,this.events[this._i].callback.apply(this.events[this._i].callbackContext,this.events[this._i].args)):this.events[this._i].repeatCount>0?(this.events[this._i].repeatCount--,this.events[this._i].tick=this._newTick,this.events[this._i].callback.apply(this.events[this._i].callbackContext,this.events[this._i].args)):(this._marked++,this.events[this._i].pendingDelete=!0,this.events[this._i].callback.apply(this.events[this._i].callbackContext,this.events[this._i].args)),this._i++;this.events.length>this._marked?this.order():(this.expired=!0,this.onComplete.dispatch(this))}return!this.expired||!this.autoDestroy},pause:function(){this.running&&(this._codePaused=!0,this.paused||(this._pauseStarted=this.game.time.time,this.paused=!0))},_pause:function(){!this.paused&&this.running&&(this._pauseStarted=this.game.time.time,this.paused=!0)},adjustEvents:function(t){for(var e=0;e<this.events.length;e++)if(!this.events[e].pendingDelete){var i=this.events[e].tick-t;i<0&&(i=0),this.events[e].tick=this._now+i}var s=this.nextTick-t;this.nextTick=s<0?this._now:this._now+s},resume:function(){if(this.paused){var t=this.game.time.time;this._pauseTotal+=t-this._now,this._now=t,this.adjustEvents(this._pauseStarted),this.paused=!1,this._codePaused=!1}},_resume:function(){this._codePaused||this.resume()},removeAll:function(){this.onComplete.removeAll(),this.events.length=0,this._len=0,this._i=0},destroy:function(){this.onComplete.removeAll(),this.running=!1,this.events=[],this._len=0,this._i=0}},Object.defineProperty(n.Timer.prototype,"next",{get:function(){return this.nextTick}}),Object.defineProperty(n.Timer.prototype,"duration",{get:function(){return this.running&&this.nextTick>this._now?this.nextTick-this._now:0}}),Object.defineProperty(n.Timer.prototype,"length",{get:function(){return this.events.length}}),Object.defineProperty(n.Timer.prototype,"ms",{get:function(){return this.running?this._now-this._started-this._pauseTotal:0}}),Object.defineProperty(n.Timer.prototype,"seconds",{get:function(){return this.running?.001*this.ms:0}}),n.Timer.prototype.constructor=n.Timer,n.TimerEvent=function(t,e,i,s,n,r,o,a){this.timer=t,this.delay=e,this.tick=i,this.repeatCount=s-1,this.loop=n,this.callback=r,this.callbackContext=o,this.args=a,this.pendingDelete=!1},n.TimerEvent.prototype.constructor=n.TimerEvent,n.AnimationManager=function(t){this.sprite=t,this.game=t.game,this.currentFrame=null,this.currentAnim=null,this.updateIfVisible=!0,this.isLoaded=!1,this._frameData=null,this._anims={},this._outputFrames=[]},n.AnimationManager.prototype={loadFrameData:function(t,e){if(void 0===t)return!1;if(this.isLoaded)for(var i in this._anims)this._anims[i].updateFrameData(t);return this._frameData=t,void 0===e||null===e?this.frame=0:"string"==typeof e?this.frameName=e:this.frame=e,this.isLoaded=!0,!0},copyFrameData:function(t,e){if(this._frameData=t.clone(),this.isLoaded)for(var i in this._anims)this._anims[i].updateFrameData(this._frameData);return void 0===e||null===e?this.frame=0:"string"==typeof e?this.frameName=e:this.frame=e,this.isLoaded=!0,!0},add:function(t,e,i,s,r){return e=e||[],i=i||60,void 0===s&&(s=!1),void 0===r&&(r=!(!e||"number"!=typeof e[0])),this._outputFrames=[],this._frameData.getFrameIndexes(e,r,this._outputFrames),this._anims[t]=new n.Animation(this.game,this.sprite,t,this._frameData,this._outputFrames,i,s),this.currentAnim=this._anims[t],this.sprite.tilingTexture&&(this.sprite.refreshTexture=!0),this._anims[t]},validateFrames:function(t,e){void 0===e&&(e=!0);for(var i=0;i<t.length;i++)if(!0===e){if(t[i]>this._frameData.total)return!1}else if(!1===this._frameData.checkFrameName(t[i]))return!1;return!0},play:function(t,e,i,s){if(this._anims[t])return this.currentAnim===this._anims[t]?!1===this.currentAnim.isPlaying?(this.currentAnim.paused=!1,this.currentAnim.play(e,i,s)):this.currentAnim:(this.currentAnim&&this.currentAnim.isPlaying&&this.currentAnim.stop(),this.currentAnim=this._anims[t],this.currentAnim.paused=!1,this.currentFrame=this.currentAnim.currentFrame,this.currentAnim.play(e,i,s))},stop:function(t,e){void 0===e&&(e=!1),!this.currentAnim||"string"==typeof t&&t!==this.currentAnim.name||this.currentAnim.stop(e)},update:function(){return!(this.updateIfVisible&&!this.sprite.visible)&&(!(!this.currentAnim||!this.currentAnim.update())&&(this.currentFrame=this.currentAnim.currentFrame,!0))},next:function(t){this.currentAnim&&(this.currentAnim.next(t),this.currentFrame=this.currentAnim.currentFrame)},previous:function(t){this.currentAnim&&(this.currentAnim.previous(t),this.currentFrame=this.currentAnim.currentFrame)},getAnimation:function(t){return"string"==typeof t&&this._anims[t]?this._anims[t]:null},refreshFrame:function(){},destroy:function(){var t=null;for(var t in this._anims)this._anims.hasOwnProperty(t)&&this._anims[t].destroy();this._anims={},this._outputFrames=[],this._frameData=null,this.currentAnim=null,this.currentFrame=null,this.sprite=null,this.game=null}},n.AnimationManager.prototype.constructor=n.AnimationManager,Object.defineProperty(n.AnimationManager.prototype,"frameData",{get:function(){return this._frameData}}),Object.defineProperty(n.AnimationManager.prototype,"frameTotal",{get:function(){return this._frameData.total}}),Object.defineProperty(n.AnimationManager.prototype,"paused",{get:function(){return this.currentAnim.isPaused},set:function(t){this.currentAnim.paused=t}}),Object.defineProperty(n.AnimationManager.prototype,"name",{get:function(){if(this.currentAnim)return this.currentAnim.name}}),Object.defineProperty(n.AnimationManager.prototype,"frame",{get:function(){if(this.currentFrame)return this.currentFrame.index},set:function(t){"number"==typeof t&&this._frameData&&null!==this._frameData.getFrame(t)&&(this.currentFrame=this._frameData.getFrame(t),this.currentFrame&&this.sprite.setFrame(this.currentFrame))}}),Object.defineProperty(n.AnimationManager.prototype,"frameName",{get:function(){if(this.currentFrame)return this.currentFrame.name},set:function(t){"string"==typeof t&&this._frameData&&null!==this._frameData.getFrameByName(t)?(this.currentFrame=this._frameData.getFrameByName(t),this.currentFrame&&(this._frameIndex=this.currentFrame.index,this.sprite.setFrame(this.currentFrame))):console.warn("Cannot set frameName: "+t)}}),n.Animation=function(t,e,i,s,r,o,a){void 0===a&&(a=!1),this.game=t,this._parent=e,this._frameData=s,this.name=i,this._frames=[],this._frames=this._frames.concat(r),this.delay=1e3/o,this.loop=a,this.loopCount=0,this.killOnComplete=!1,this.isFinished=!1,this.isPlaying=!1,this.isPaused=!1,this._pauseStartTime=0,this._frameIndex=0,this._frameDiff=0,this._frameSkip=1,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.onStart=new n.Signal,this.onUpdate=null,this.onComplete=new n.Signal,this.onLoop=new n.Signal,this.isReversed=!1,this.game.onPause.add(this.onPause,this),this.game.onResume.add(this.onResume,this)},n.Animation.prototype={play:function(t,e,i){return"number"==typeof t&&(this.delay=1e3/t),"boolean"==typeof e&&(this.loop=e),void 0!==i&&(this.killOnComplete=i),this.isPlaying=!0,this.isFinished=!1,this.paused=!1,this.loopCount=0,this._timeLastFrame=this.game.time.time,this._timeNextFrame=this.game.time.time+this.delay,this._frameIndex=this.isReversed?this._frames.length-1:0,this.updateCurrentFrame(!1,!0),this._parent.events.onAnimationStart$dispatch(this._parent,this),this.onStart.dispatch(this._parent,this),this._parent.animations.currentAnim=this,this._parent.animations.currentFrame=this.currentFrame,this},restart:function(){this.isPlaying=!0,this.isFinished=!1,this.paused=!1,this.loopCount=0,this._timeLastFrame=this.game.time.time,this._timeNextFrame=this.game.time.time+this.delay,this._frameIndex=0,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this._parent.setFrame(this.currentFrame),this._parent.animations.currentAnim=this,this._parent.animations.currentFrame=this.currentFrame,this.onStart.dispatch(this._parent,this)},reverse:function(){return this.reversed=!this.reversed,this},reverseOnce:function(){return this.onComplete.addOnce(this.reverse,this),this.reverse()},setFrame:function(t,e){var i;if(void 0===e&&(e=!1),"string"==typeof t)for(var s=0;s<this._frames.length;s++)this._frameData.getFrame(this._frames[s]).name===t&&(i=s);else if("number"==typeof t)if(e)i=t;else for(var s=0;s<this._frames.length;s++)this._frames[s]===t&&(i=s);i&&(this._frameIndex=i-1,this._timeNextFrame=this.game.time.time,this.update())},stop:function(t,e){void 0===t&&(t=!1),void 0===e&&(e=!1),this.isPlaying=!1,this.isFinished=!0,this.paused=!1,t&&(this.currentFrame=this._frameData.getFrame(this._frames[0]),this._parent.setFrame(this.currentFrame)),e&&(this._parent.events.onAnimationComplete$dispatch(this._parent,this),this.onComplete.dispatch(this._parent,this))},onPause:function(){this.isPlaying&&(this._frameDiff=this._timeNextFrame-this.game.time.time)},onResume:function(){this.isPlaying&&(this._timeNextFrame=this.game.time.time+this._frameDiff)},update:function(){return!this.isPaused&&(!!(this.isPlaying&&this.game.time.time>=this._timeNextFrame)&&(this._frameSkip=1,this._frameDiff=this.game.time.time-this._timeNextFrame,this._timeLastFrame=this.game.time.time,this._frameDiff>this.delay&&(this._frameSkip=Math.floor(this._frameDiff/this.delay),this._frameDiff-=this._frameSkip*this.delay),this._timeNextFrame=this.game.time.time+(this.delay-this._frameDiff),this.isReversed?this._frameIndex-=this._frameSkip:this._frameIndex+=this._frameSkip,!this.isReversed&&this._frameIndex>=this._frames.length||this.isReversed&&this._frameIndex<=-1?this.loop?(this._frameIndex=Math.abs(this._frameIndex)%this._frames.length,this.isReversed&&(this._frameIndex=this._frames.length-1-this._frameIndex),this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.currentFrame&&this._parent.setFrame(this.currentFrame),this.loopCount++,this._parent.events.onAnimationLoop$dispatch(this._parent,this),this.onLoop.dispatch(this._parent,this),!this.onUpdate||(this.onUpdate.dispatch(this,this.currentFrame),!!this._frameData)):(this.complete(),!1):this.updateCurrentFrame(!0)))},updateCurrentFrame:function(t,e){if(void 0===e&&(e=!1),!this._frameData)return!1;var i=this.currentFrame.index;return this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.currentFrame&&(e||!e&&i!==this.currentFrame.index)&&this._parent.setFrame(this.currentFrame),!this.onUpdate||!t||(this.onUpdate.dispatch(this,this.currentFrame),!!this._frameData)},next:function(t){void 0===t&&(t=1);var e=this._frameIndex+t;e>=this._frames.length&&(this.loop?e%=this._frames.length:e=this._frames.length-1),e!==this._frameIndex&&(this._frameIndex=e,this.updateCurrentFrame(!0))},previous:function(t){void 0===t&&(t=1);var e=this._frameIndex-t;e<0&&(this.loop?e=this._frames.length+e:e++),e!==this._frameIndex&&(this._frameIndex=e,this.updateCurrentFrame(!0))},updateFrameData:function(t){this._frameData=t,this.currentFrame=this._frameData?this._frameData.getFrame(this._frames[this._frameIndex%this._frames.length]):null},destroy:function(){this._frameData&&(this.game.onPause.remove(this.onPause,this),this.game.onResume.remove(this.onResume,this),this.game=null,this._parent=null,this._frames=null,this._frameData=null,this.currentFrame=null,this.isPlaying=!1,this.onStart.dispose(),this.onLoop.dispose(),this.onComplete.dispose(),this.onUpdate&&this.onUpdate.dispose())},complete:function(){this._frameIndex=this._frames.length-1,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.isPlaying=!1,this.isFinished=!0,this.paused=!1,this._parent.events.onAnimationComplete$dispatch(this._parent,this),this.onComplete.dispatch(this._parent,this),this.killOnComplete&&this._parent.kill()}},n.Animation.prototype.constructor=n.Animation,Object.defineProperty(n.Animation.prototype,"paused",{get:function(){return this.isPaused},set:function(t){this.isPaused=t,t?this._pauseStartTime=this.game.time.time:this.isPlaying&&(this._timeNextFrame=this.game.time.time+this.delay)}}),Object.defineProperty(n.Animation.prototype,"reversed",{get:function(){return this.isReversed},set:function(t){this.isReversed=t}}),Object.defineProperty(n.Animation.prototype,"frameTotal",{get:function(){return this._frames.length}}),Object.defineProperty(n.Animation.prototype,"frame",{get:function(){return null!==this.currentFrame?this.currentFrame.index:this._frameIndex},set:function(t){this.currentFrame=this._frameData.getFrame(this._frames[t]),null!==this.currentFrame&&(this._frameIndex=t,this._parent.setFrame(this.currentFrame),this.onUpdate&&this.onUpdate.dispatch(this,this.currentFrame))}}),Object.defineProperty(n.Animation.prototype,"speed",{get:function(){return 1e3/this.delay},set:function(t){t>0&&(this.delay=1e3/t)}}),Object.defineProperty(n.Animation.prototype,"enableUpdate",{get:function(){return null!==this.onUpdate},set:function(t){t&&null===this.onUpdate?this.onUpdate=new n.Signal:t||null===this.onUpdate||(this.onUpdate.dispose(),this.onUpdate=null)}}),n.Animation.generateFrameNames=function(t,e,i,s,r){void 0===s&&(s="");var o=[],a="";if(e<i)for(var h=e;h<=i;h++)a="number"==typeof r?n.Utils.pad(h.toString(),r,"0",1):h.toString(),a=t+a+s,o.push(a);else for(var h=e;h>=i;h--)a="number"==typeof r?n.Utils.pad(h.toString(),r,"0",1):h.toString(),a=t+a+s,o.push(a);return o},n.Frame=function(t,e,i,s,r,o){this.index=t,this.x=e,this.y=i,this.width=s,this.height=r,this.name=o,this.centerX=Math.floor(s/2),this.centerY=Math.floor(r/2),this.distance=n.Math.distance(0,0,s,r),this.rotated=!1,this.rotationDirection="cw",this.trimmed=!1,this.sourceSizeW=s,this.sourceSizeH=r,this.spriteSourceSizeX=0,this.spriteSourceSizeY=0,this.spriteSourceSizeW=0,this.spriteSourceSizeH=0,this.right=this.x+this.width,this.bottom=this.y+this.height},n.Frame.prototype={resize:function(t,e){this.width=t,this.height=e,this.centerX=Math.floor(t/2),this.centerY=Math.floor(e/2),this.distance=n.Math.distance(0,0,t,e),this.sourceSizeW=t,this.sourceSizeH=e,this.right=this.x+t,this.bottom=this.y+e},setTrim:function(t,e,i,s,n,r,o){this.trimmed=t,t&&(this.sourceSizeW=e,this.sourceSizeH=i,this.centerX=Math.floor(e/2),this.centerY=Math.floor(i/2),this.spriteSourceSizeX=s,this.spriteSourceSizeY=n,this.spriteSourceSizeW=r,this.spriteSourceSizeH=o)},clone:function(){var t=new n.Frame(this.index,this.x,this.y,this.width,this.height,this.name);for(var e in this)this.hasOwnProperty(e)&&(t[e]=this[e]);return t},getRect:function(t){return void 0===t?t=new n.Rectangle(this.x,this.y,this.width,this.height):t.setTo(this.x,this.y,this.width,this.height),t}},n.Frame.prototype.constructor=n.Frame,n.FrameData=function(){this._frames=[],this._frameNames=[]},n.FrameData.prototype={addFrame:function(t){return t.index=this._frames.length,this._frames.push(t),""!==t.name&&(this._frameNames[t.name]=t.index),t},getFrame:function(t){return t>=this._frames.length&&(t=0),this._frames[t]},getFrameByName:function(t){return"number"==typeof this._frameNames[t]?this._frames[this._frameNames[t]]:null},checkFrameName:function(t){return null!=this._frameNames[t]},clone:function(){for(var t=new n.FrameData,e=0;e<this._frames.length;e++)t._frames.push(this._frames[e].clone());for(var i in this._frameNames)this._frameNames.hasOwnProperty(i)&&t._frameNames.push(this._frameNames[i]);return t},getFrameRange:function(t,e,i){void 0===i&&(i=[]);for(var s=t;s<=e;s++)i.push(this._frames[s]);return i},getFrames:function(t,e,i){if(void 0===e&&(e=!0),void 0===i&&(i=[]),void 0===t||0===t.length)for(var s=0;s<this._frames.length;s++)i.push(this._frames[s]);else for(var s=0;s<t.length;s++)e?i.push(this.getFrame(t[s])):i.push(this.getFrameByName(t[s]));return i},getFrameIndexes:function(t,e,i){if(void 0===e&&(e=!0),void 0===i&&(i=[]),void 0===t||0===t.length)for(var s=0;s<this._frames.length;s++)i.push(this._frames[s].index);else for(var s=0;s<t.length;s++)e&&this._frames[t[s]]?i.push(this._frames[t[s]].index):this.getFrameByName(t[s])&&i.push(this.getFrameByName(t[s]).index);return i},destroy:function(){this._frames=null,this._frameNames=null}},n.FrameData.prototype.constructor=n.FrameData,Object.defineProperty(n.FrameData.prototype,"total",{get:function(){return this._frames.length}}),n.AnimationParser={spriteSheet:function(t,e,i,s,r,o,a){var h=e;if("string"==typeof e&&(h=t.cache.getImage(e)),null===h)return null;var l=h.width,c=h.height;i<=0&&(i=Math.floor(-l/Math.min(-1,i))),s<=0&&(s=Math.floor(-c/Math.min(-1,s)));var u=Math.floor((l-o)/(i+a)),d=Math.floor((c-o)/(s+a)),p=u*d;if(-1!==r&&(p=r),0===l||0===c||l<i||c<s||0===p)return console.warn("Phaser.AnimationParser.spriteSheet: '"+e+"'s width/height zero or width/height < given frameWidth/frameHeight"),null;for(var f=new n.FrameData,g=o,m=o,y=0;y<p;y++)f.addFrame(new n.Frame(y,g,m,i,s,"")),(g+=i+a)+i>l&&(g=o,m+=s+a);return f},JSONData:function(t,e){if(!e.frames)return console.warn("Phaser.AnimationParser.JSONData: Invalid Texture Atlas JSON given, missing 'frames' array"),void console.log(e);for(var i,s=new n.FrameData,r=e.frames,o=0;o<r.length;o++)i=s.addFrame(new n.Frame(o,r[o].frame.x,r[o].frame.y,r[o].frame.w,r[o].frame.h,r[o].filename)),r[o].trimmed&&i.setTrim(r[o].trimmed,r[o].sourceSize.w,r[o].sourceSize.h,r[o].spriteSourceSize.x,r[o].spriteSourceSize.y,r[o].spriteSourceSize.w,r[o].spriteSourceSize.h);return s},JSONDataPyxel:function(t,e){if(["layers","tilewidth","tileheight","tileswide","tileshigh"].forEach(function(t){if(!e[t])return console.warn('Phaser.AnimationParser.JSONDataPyxel: Invalid Pyxel Tilemap JSON given, missing "'+t+'" key.'),void console.log(e)}),1!==e.layers.length)return console.warn("Phaser.AnimationParser.JSONDataPyxel: Too many layers, this parser only supports flat Tilemaps."),void console.log(e);for(var i,s=new n.FrameData,r=e.tileheight,o=e.tilewidth,a=e.layers[0].tiles,h=0;h<a.length;h++)i=s.addFrame(new n.Frame(h,a[h].x,a[h].y,o,r,"frame_"+h)),i.setTrim(!1);return s},JSONDataHash:function(t,e){if(!e.frames)return console.warn("Phaser.AnimationParser.JSONDataHash: Invalid Texture Atlas JSON given, missing 'frames' object"),void console.log(e);var i,s=new n.FrameData,r=e.frames,o=0;for(var a in r)i=s.addFrame(new n.Frame(o,r[a].frame.x,r[a].frame.y,r[a].frame.w,r[a].frame.h,a)),r[a].trimmed&&i.setTrim(r[a].trimmed,r[a].sourceSize.w,r[a].sourceSize.h,r[a].spriteSourceSize.x,r[a].spriteSourceSize.y,r[a].spriteSourceSize.w,r[a].spriteSourceSize.h),o++;return s},XMLData:function(t,e){if(!e.getElementsByTagName("TextureAtlas"))return void console.warn("Phaser.AnimationParser.XMLData: Invalid Texture Atlas XML given, missing <TextureAtlas> tag");for(var i,s,r,o,a,h,l,c,u,d,p,f=new n.FrameData,g=e.getElementsByTagName("SubTexture"),m=0;m<g.length;m++)r=g[m].attributes,s=r.name.value,o=parseInt(r.x.value,10),a=parseInt(r.y.value,10),h=parseInt(r.width.value,10),l=parseInt(r.height.value,10),c=null,u=null,r.frameX&&(c=Math.abs(parseInt(r.frameX.value,10)),u=Math.abs(parseInt(r.frameY.value,10)),d=parseInt(r.frameWidth.value,10),p=parseInt(r.frameHeight.value,10)),i=f.addFrame(new n.Frame(m,o,a,h,l,s)),null===c&&null===u||i.setTrim(!0,h,l,c,u,d,p);return f}},n.Cache=function(t){this.game=t,this.autoResolveURL=!1,this._cache={canvas:{},image:{},texture:{},sound:{},video:{},text:{},json:{},xml:{},physics:{},tilemap:{},binary:{},bitmapData:{},bitmapFont:{},shader:{},renderTexture:{}},this._urlMap={},this._urlResolver=new Image,this._urlTemp=null,this.onSoundUnlock=new n.Signal,this._cacheMap=[],this._cacheMap[n.Cache.CANVAS]=this._cache.canvas,this._cacheMap[n.Cache.IMAGE]=this._cache.image,this._cacheMap[n.Cache.TEXTURE]=this._cache.texture,this._cacheMap[n.Cache.SOUND]=this._cache.sound,this._cacheMap[n.Cache.TEXT]=this._cache.text,this._cacheMap[n.Cache.PHYSICS]=this._cache.physics,this._cacheMap[n.Cache.TILEMAP]=this._cache.tilemap,this._cacheMap[n.Cache.BINARY]=this._cache.binary,this._cacheMap[n.Cache.BITMAPDATA]=this._cache.bitmapData,this._cacheMap[n.Cache.BITMAPFONT]=this._cache.bitmapFont,this._cacheMap[n.Cache.JSON]=this._cache.json,this._cacheMap[n.Cache.XML]=this._cache.xml,this._cacheMap[n.Cache.VIDEO]=this._cache.video,this._cacheMap[n.Cache.SHADER]=this._cache.shader,this._cacheMap[n.Cache.RENDER_TEXTURE]=this._cache.renderTexture,this.addDefaultImage(),this.addMissingImage()},n.Cache.CANVAS=1,n.Cache.IMAGE=2,n.Cache.TEXTURE=3,n.Cache.SOUND=4,n.Cache.TEXT=5,n.Cache.PHYSICS=6,n.Cache.TILEMAP=7,n.Cache.BINARY=8,n.Cache.BITMAPDATA=9,n.Cache.BITMAPFONT=10,n.Cache.JSON=11,n.Cache.XML=12,n.Cache.VIDEO=13,n.Cache.SHADER=14,n.Cache.RENDER_TEXTURE=15,n.Cache.DEFAULT=null,n.Cache.MISSING=null,n.Cache.prototype={addCanvas:function(t,e,i){void 0===i&&(i=e.getContext("2d")),this._cache.canvas[t]={canvas:e,context:i}},addImage:function(t,e,i){this.checkImageKey(t)&&this.removeImage(t);var s={key:t,url:e,data:i,base:new PIXI.BaseTexture(i),frame:new n.Frame(0,0,0,i.width,i.height,t),frameData:new n.FrameData};return s.frameData.addFrame(new n.Frame(0,0,0,i.width,i.height,e)),this._cache.image[t]=s,this._resolveURL(e,s),"__default"===t?n.Cache.DEFAULT=new PIXI.Texture(s.base):"__missing"===t&&(n.Cache.MISSING=new PIXI.Texture(s.base)),s},addDefaultImage:function(){var t=new Image;t.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgAQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg==";var e=this.addImage("__default",null,t);e.base.skipRender=!0,n.Cache.DEFAULT=new PIXI.Texture(e.base)},addMissingImage:function(){var t=new Image;t.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg==";var e=this.addImage("__missing",null,t);n.Cache.MISSING=new PIXI.Texture(e.base)},addSound:function(t,e,i,s,n){void 0===s&&(s=!0,n=!1),void 0===n&&(s=!1,n=!0);var r=!1;n&&(r=!0),this._cache.sound[t]={url:e,data:i,isDecoding:!1,decoded:r,webAudio:s,audioTag:n,locked:this.game.sound.touchLocked},this._resolveURL(e,this._cache.sound[t])},addText:function(t,e,i){this._cache.text[t]={url:e,data:i},this._resolveURL(e,this._cache.text[t])},addPhysicsData:function(t,e,i,s){this._cache.physics[t]={url:e,data:i,format:s},this._resolveURL(e,this._cache.physics[t])},addTilemap:function(t,e,i,s){this._cache.tilemap[t]={url:e,data:i,format:s},this._resolveURL(e,this._cache.tilemap[t])},addBinary:function(t,e){this._cache.binary[t]=e},addBitmapData:function(t,e,i){return e.key=t,void 0===i&&(i=new n.FrameData,i.addFrame(e.textureFrame)),this._cache.bitmapData[t]={data:e,frameData:i},e},addBitmapFont:function(t,e,i,s,r,o,a){var h={url:e,data:i,font:null,base:new PIXI.BaseTexture(i)};void 0===o&&(o=0),void 0===a&&(a=0),h.font="json"===r?n.LoaderParser.jsonBitmapFont(s,h.base,o,a):n.LoaderParser.xmlBitmapFont(s,h.base,o,a),this._cache.bitmapFont[t]=h,this._resolveURL(e,h)},addJSON:function(t,e,i){this._cache.json[t]={url:e,data:i},this._resolveURL(e,this._cache.json[t])},addXML:function(t,e,i){this._cache.xml[t]={url:e,data:i},this._resolveURL(e,this._cache.xml[t])},addVideo:function(t,e,i,s){this._cache.video[t]={url:e,data:i,isBlob:s,locked:!0},this._resolveURL(e,this._cache.video[t])},addShader:function(t,e,i){this._cache.shader[t]={url:e,data:i},this._resolveURL(e,this._cache.shader[t])},addRenderTexture:function(t,e){this._cache.renderTexture[t]={texture:e,frame:new n.Frame(0,0,0,e.width,e.height,"","")}},addSpriteSheet:function(t,e,i,s,r,o,a,h){void 0===o&&(o=-1),void 0===a&&(a=0),void 0===h&&(h=0);var l={key:t,url:e,data:i,frameWidth:s,frameHeight:r,margin:a,spacing:h,base:new PIXI.BaseTexture(i),frameData:n.AnimationParser.spriteSheet(this.game,i,s,r,o,a,h)};this._cache.image[t]=l,this._resolveURL(e,l)},addTextureAtlas:function(t,e,i,s,r){var o={key:t,url:e,data:i,base:new PIXI.BaseTexture(i)};r===n.Loader.TEXTURE_ATLAS_XML_STARLING?o.frameData=n.AnimationParser.XMLData(this.game,s,t):r===n.Loader.TEXTURE_ATLAS_JSON_PYXEL?o.frameData=n.AnimationParser.JSONDataPyxel(this.game,s,t):Array.isArray(s.frames)?o.frameData=n.AnimationParser.JSONData(this.game,s,t):o.frameData=n.AnimationParser.JSONDataHash(this.game,s,t),this._cache.image[t]=o,this._resolveURL(e,o)},reloadSound:function(t){var e=this,i=this.getSound(t);i&&(i.data.src=i.url,i.data.addEventListener("canplaythrough",function(){return e.reloadSoundComplete(t)},!1),i.data.load())},reloadSoundComplete:function(t){var e=this.getSound(t);e&&(e.locked=!1,this.onSoundUnlock.dispatch(t))},updateSound:function(t,e,i){var s=this.getSound(t);s&&(s[e]=i)},decodedSound:function(t,e){var i=this.getSound(t);i.data=e,i.decoded=!0,i.isDecoding=!1},isSoundDecoded:function(t){var e=this.getItem(t,n.Cache.SOUND,"isSoundDecoded");if(e)return e.decoded},isSoundReady:function(t){var e=this.getItem(t,n.Cache.SOUND,"isSoundDecoded");if(e)return e.decoded&&!this.game.sound.touchLocked},checkKey:function(t,e){return!!this._cacheMap[t][e]},checkURL:function(t){return!!this._urlMap[this._resolveURL(t)]},checkCanvasKey:function(t){return this.checkKey(n.Cache.CANVAS,t)},checkImageKey:function(t){return this.checkKey(n.Cache.IMAGE,t)},checkTextureKey:function(t){return this.checkKey(n.Cache.TEXTURE,t)},checkSoundKey:function(t){return this.checkKey(n.Cache.SOUND,t)},checkTextKey:function(t){return this.checkKey(n.Cache.TEXT,t)},checkPhysicsKey:function(t){return this.checkKey(n.Cache.PHYSICS,t)},checkTilemapKey:function(t){return this.checkKey(n.Cache.TILEMAP,t)},checkBinaryKey:function(t){return this.checkKey(n.Cache.BINARY,t)},checkBitmapDataKey:function(t){return this.checkKey(n.Cache.BITMAPDATA,t)},checkBitmapFontKey:function(t){return this.checkKey(n.Cache.BITMAPFONT,t)},checkJSONKey:function(t){return this.checkKey(n.Cache.JSON,t)},checkXMLKey:function(t){return this.checkKey(n.Cache.XML,t)},checkVideoKey:function(t){return this.checkKey(n.Cache.VIDEO,t)},checkShaderKey:function(t){return this.checkKey(n.Cache.SHADER,t)},checkRenderTextureKey:function(t){return this.checkKey(n.Cache.RENDER_TEXTURE,t)},getItem:function(t,e,i,s){return this.checkKey(e,t)?void 0===s?this._cacheMap[e][t]:this._cacheMap[e][t][s]:(i&&console.warn("Phaser.Cache."+i+': Key "'+t+'" not found in Cache.'),null)},getCanvas:function(t){return this.getItem(t,n.Cache.CANVAS,"getCanvas","canvas")},getImage:function(t,e){void 0!==t&&null!==t||(t="__default"),void 0===e&&(e=!1);var i=this.getItem(t,n.Cache.IMAGE,"getImage");return null===i&&(i=this.getItem("__missing",n.Cache.IMAGE,"getImage")),e?i:i.data},getTextureFrame:function(t){return this.getItem(t,n.Cache.TEXTURE,"getTextureFrame","frame")},getSound:function(t){return this.getItem(t,n.Cache.SOUND,"getSound")},getSoundData:function(t){return this.getItem(t,n.Cache.SOUND,"getSoundData","data")},getText:function(t){return this.getItem(t,n.Cache.TEXT,"getText","data")},getPhysicsData:function(t,e,i){var s=this.getItem(t,n.Cache.PHYSICS,"getPhysicsData","data");if(null===s||void 0===e||null===e)return s;if(s[e]){var r=s[e];if(!r||!i)return r;for(var o in r)if(o=r[o],o.fixtureKey===i)return o;console.warn('Phaser.Cache.getPhysicsData: Could not find given fixtureKey: "'+i+" in "+t+'"')}else console.warn('Phaser.Cache.getPhysicsData: Invalid key/object: "'+t+" / "+e+'"');return null},getTilemapData:function(t){return this.getItem(t,n.Cache.TILEMAP,"getTilemapData")},getBinary:function(t){return this.getItem(t,n.Cache.BINARY,"getBinary")},getBitmapData:function(t){return this.getItem(t,n.Cache.BITMAPDATA,"getBitmapData","data")},getBitmapFont:function(t){return this.getItem(t,n.Cache.BITMAPFONT,"getBitmapFont")},getJSON:function(t,e){var i=this.getItem(t,n.Cache.JSON,"getJSON","data");return i?e?n.Utils.extend(!0,Array.isArray(i)?[]:{},i):i:null},getXML:function(t){return this.getItem(t,n.Cache.XML,"getXML","data")},getVideo:function(t){return this.getItem(t,n.Cache.VIDEO,"getVideo")},getShader:function(t){return this.getItem(t,n.Cache.SHADER,"getShader","data")},getRenderTexture:function(t){return this.getItem(t,n.Cache.RENDER_TEXTURE,"getRenderTexture")},getBaseTexture:function(t,e){return void 0===e&&(e=n.Cache.IMAGE),this.getItem(t,e,"getBaseTexture","base")},getFrame:function(t,e){return void 0===e&&(e=n.Cache.IMAGE),this.getItem(t,e,"getFrame","frame")},getFrameCount:function(t,e){var i=this.getFrameData(t,e);return i?i.total:0},getFrameData:function(t,e){return void 0===e&&(e=n.Cache.IMAGE),this.getItem(t,e,"getFrameData","frameData")},hasFrameData:function(t,e){return void 0===e&&(e=n.Cache.IMAGE),null!==this.getItem(t,e,"","frameData")},updateFrameData:function(t,e,i){void 0===i&&(i=n.Cache.IMAGE),this._cacheMap[i][t]&&(this._cacheMap[i][t].frameData=e)},getFrameByIndex:function(t,e,i){var s=this.getFrameData(t,i);return s?s.getFrame(e):null},getFrameByName:function(t,e,i){var s=this.getFrameData(t,i);return s?s.getFrameByName(e):null},getURL:function(t){var t=this._resolveURL(t);return t?this._urlMap[t]:(console.warn('Phaser.Cache.getUrl: Invalid url: "'+t+'" or Cache.autoResolveURL was false'),null)},getKeys:function(t){void 0===t&&(t=n.Cache.IMAGE);var e=[];if(this._cacheMap[t])for(var i in this._cacheMap[t])"__default"!==i&&"__missing"!==i&&e.push(i);return e},removeCanvas:function(t){delete this._cache.canvas[t]},removeImage:function(t,e){void 0===e&&(e=!0);var i=this.getImage(t,!0);e&&i.base&&i.base.destroy(),delete this._cache.image[t]},removeSound:function(t){delete this._cache.sound[t]},removeText:function(t){delete this._cache.text[t]},removePhysics:function(t){delete this._cache.physics[t]},removeTilemap:function(t){delete this._cache.tilemap[t]},removeBinary:function(t){delete this._cache.binary[t]},removeBitmapData:function(t){delete this._cache.bitmapData[t]},removeBitmapFont:function(t){delete this._cache.bitmapFont[t]},removeJSON:function(t){delete this._cache.json[t]},removeXML:function(t){delete this._cache.xml[t]},removeVideo:function(t){delete this._cache.video[t]},removeShader:function(t){delete this._cache.shader[t]},removeRenderTexture:function(t){delete this._cache.renderTexture[t]},removeSpriteSheet:function(t){delete this._cache.spriteSheet[t]},removeTextureAtlas:function(t){delete this._cache.atlas[t]},clearGLTextures:function(){for(var t in this._cache.image)this._cache.image[t].base._glTextures=[]},_resolveURL:function(t,e){return this.autoResolveURL?(this._urlResolver.src=this.game.load.baseURL+t,this._urlTemp=this._urlResolver.src,this._urlResolver.src="",e&&(this._urlMap[this._urlTemp]=e),this._urlTemp):null},destroy:function(){for(var t=0;t<this._cacheMap.length;t++){var e=this._cacheMap[t];for(var i in e)"__default"!==i&&"__missing"!==i&&(e[i].destroy&&e[i].destroy(),delete e[i])}this._urlMap=null,this._urlResolver=null,this._urlTemp=null}},n.Cache.prototype.constructor=n.Cache,n.Loader=function(t){this.game=t,this.cache=t.cache,this.resetLocked=!1,this.isLoading=!1,this.hasLoaded=!1,this.preloadSprite=null,this.crossOrigin=!1,this.baseURL="",this.path="",this.headers={requestedWith:!1,json:"application/json",xml:"application/xml"},this.onLoadStart=new n.Signal,this.onLoadComplete=new n.Signal,this.onPackComplete=new n.Signal,this.onFileStart=new n.Signal,this.onFileComplete=new n.Signal,this.onFileError=new n.Signal,this.useXDomainRequest=!1,this._warnedAboutXDomainRequest=!1,this.enableParallel=!0,this.maxParallelDownloads=4,this._withSyncPointDepth=0,this._fileList=[],this._flightQueue=[],this._processingHead=0,this._fileLoadStarted=!1,this._totalPackCount=0,this._totalFileCount=0,this._loadedPackCount=0,this._loadedFileCount=0},n.Loader.TEXTURE_ATLAS_JSON_ARRAY=0,n.Loader.TEXTURE_ATLAS_JSON_HASH=1,n.Loader.TEXTURE_ATLAS_XML_STARLING=2,n.Loader.PHYSICS_LIME_CORONA_JSON=3,n.Loader.PHYSICS_PHASER_JSON=4,n.Loader.TEXTURE_ATLAS_JSON_PYXEL=5,n.Loader.prototype={setPreloadSprite:function(t,e){e=e||0,this.preloadSprite={sprite:t,direction:e,width:t.width,height:t.height,rect:null},this.preloadSprite.rect=0===e?new n.Rectangle(0,0,1,t.height):new n.Rectangle(0,0,t.width,1),t.crop(this.preloadSprite.rect),t.visible=!0},resize:function(){this.preloadSprite&&this.preloadSprite.height!==this.preloadSprite.sprite.height&&(this.preloadSprite.rect.height=this.preloadSprite.sprite.height)},checkKeyExists:function(t,e){return this.getAssetIndex(t,e)>-1},getAssetIndex:function(t,e){for(var i=-1,s=0;s<this._fileList.length;s++){var n=this._fileList[s];if(n.type===t&&n.key===e&&(i=s,!n.loaded&&!n.loading))break}return i},getAsset:function(t,e){var i=this.getAssetIndex(t,e);return i>-1&&{index:i,file:this._fileList[i]}},reset:function(t,e){void 0===e&&(e=!1),this.resetLocked||(t&&(this.preloadSprite=null),this.isLoading=!1,this._processingHead=0,this._fileList.length=0,this._flightQueue.length=0,this._fileLoadStarted=!1,this._totalFileCount=0,this._totalPackCount=0,this._loadedPackCount=0,this._loadedFileCount=0,e&&(this.onLoadStart.removeAll(),this.onLoadComplete.removeAll(),this.onPackComplete.removeAll(),this.onFileStart.removeAll(),this.onFileComplete.removeAll(),this.onFileError.removeAll()))},addToFileList:function(t,e,i,s,n,r){if(void 0===n&&(n=!1),void 0===e||""===e)return console.warn("Phaser.Loader: Invalid or no key given of type "+t),this;if(void 0===i||null===i){if(!r)return console.warn("Phaser.Loader: No URL given for file type: "+t+" key: "+e),this;i=e+r}var o={type:t,key:e,path:this.path,url:i,syncPoint:this._withSyncPointDepth>0,data:null,loading:!1,loaded:!1,error:!1};if(s)for(var a in s)o[a]=s[a];var h=this.getAssetIndex(t,e);if(n&&h>-1){var l=this._fileList[h];l.loading||l.loaded?(this._fileList.push(o),this._totalFileCount++):this._fileList[h]=o}else-1===h&&(this._fileList.push(o),this._totalFileCount++);return this},replaceInFileList:function(t,e,i,s){return this.addToFileList(t,e,i,s,!0)},pack:function(t,e,i,s){if(void 0===e&&(e=null),void 0===i&&(i=null),void 0===s&&(s=null),!e&&!i)return console.warn("Phaser.Loader.pack - Both url and data are null. One must be set."),this;var n={type:"packfile",key:t,url:e,path:this.path,syncPoint:!0,data:null,loading:!1,loaded:!1,error:!1,callbackContext:s};i&&("string"==typeof i&&(i=JSON.parse(i)),n.data=i||{},n.loaded=!0);for(var r=0;r<this._fileList.length+1;r++){var o=this._fileList[r];if(!o||!o.loaded&&!o.loading&&"packfile"!==o.type){this._fileList.splice(r,0,n),this._totalPackCount++;break}}return this},image:function(t,e,i){return this.addToFileList("image",t,e,void 0,i,".png")},images:function(t,e){if(Array.isArray(e))for(var i=0;i<t.length;i++)this.image(t[i],e[i]);else for(var i=0;i<t.length;i++)this.image(t[i]);return this},text:function(t,e,i){return this.addToFileList("text",t,e,void 0,i,".txt")},json:function(t,e,i){return this.addToFileList("json",t,e,void 0,i,".json")},shader:function(t,e,i){return this.addToFileList("shader",t,e,void 0,i,".frag")},xml:function(t,e,i){return this.addToFileList("xml",t,e,void 0,i,".xml")},script:function(t,e,i,s){return void 0===i&&(i=!1),!1!==i&&void 0===s&&(s=this),this.addToFileList("script",t,e,{syncPoint:!0,callback:i,callbackContext:s},!1,".js")},binary:function(t,e,i,s){return void 0===i&&(i=!1),!1!==i&&void 0===s&&(s=i),this.addToFileList("binary",t,e,{callback:i,callbackContext:s},!1,".bin")},spritesheet:function(t,e,i,s,n,r,o){return void 0===n&&(n=-1),void 0===r&&(r=0),void 0===o&&(o=0),this.addToFileList("spritesheet",t,e,{frameWidth:i,frameHeight:s,frameMax:n,margin:r,spacing:o},!1,".png")},audio:function(t,e,i){return this.game.sound.noAudio?this:(void 0===i&&(i=!0),"string"==typeof e&&(e=[e]),this.addToFileList("audio",t,e,{buffer:null,autoDecode:i}))},audioSprite:function(t,e,i,s,n){return this.game.sound.noAudio?this:(void 0===i&&(i=null),void 0===s&&(s=null),void 0===n&&(n=!0),this.audio(t,e,n),i?this.json(t+"-audioatlas",i):s?("string"==typeof s&&(s=JSON.parse(s)),this.cache.addJSON(t+"-audioatlas","",s)):console.warn("Phaser.Loader.audiosprite - You must specify either a jsonURL or provide a jsonData object"),this)},audiosprite:function(t,e,i,s,n){return this.audioSprite(t,e,i,s,n)},video:function(t,e,i,s){return void 0===i&&(i=this.game.device.firefox?"loadeddata":"canplaythrough"),void 0===s&&(s=!1),"string"==typeof e&&(e=[e]),this.addToFileList("video",t,e,{buffer:null,asBlob:s,loadEvent:i})},tilemap:function(t,e,i,s){if(void 0===e&&(e=null),void 0===i&&(i=null),void 0===s&&(s=n.Tilemap.CSV),e||i||(e=s===n.Tilemap.CSV?t+".csv":t+".json"),i){switch(s){case n.Tilemap.CSV:break;case n.Tilemap.TILED_JSON:"string"==typeof i&&(i=JSON.parse(i))}this.cache.addTilemap(t,null,i,s)}else this.addToFileList("tilemap",t,e,{format:s});return this},physics:function(t,e,i,s){return void 0===e&&(e=null),void 0===i&&(i=null),void 0===s&&(s=n.Physics.LIME_CORONA_JSON),e||i||(e=t+".json"),i?("string"==typeof i&&(i=JSON.parse(i)),this.cache.addPhysicsData(t,null,i,s)):this.addToFileList("physics",t,e,{format:s}),this},bitmapFont:function(t,e,i,s,n,r){if(void 0!==e&&null!==e||(e=t+".png"),void 0===i&&(i=null),void 0===s&&(s=null),null===i&&null===s&&(i=t+".xml"),void 0===n&&(n=0),void 0===r&&(r=0),i)this.addToFileList("bitmapfont",t,e,{atlasURL:i,xSpacing:n,ySpacing:r});else if("string"==typeof s){var o,a;try{o=JSON.parse(s)}catch(t){a=this.parseXml(s)}if(!a&&!o)throw new Error("Phaser.Loader. Invalid Bitmap Font atlas given");this.addToFileList("bitmapfont",t,e,{atlasURL:null,atlasData:o||a,atlasType:o?"json":"xml",xSpacing:n,ySpacing:r})}return this},atlasJSONArray:function(t,e,i,s){return this.atlas(t,e,i,s,n.Loader.TEXTURE_ATLAS_JSON_ARRAY)},atlasJSONHash:function(t,e,i,s){return this.atlas(t,e,i,s,n.Loader.TEXTURE_ATLAS_JSON_HASH)},atlasXML:function(t,e,i,s){return void 0===i&&(i=null),void 0===s&&(s=null),i||s||(i=t+".xml"),this.atlas(t,e,i,s,n.Loader.TEXTURE_ATLAS_XML_STARLING)},atlas:function(t,e,i,s,r){if(void 0!==e&&null!==e||(e=t+".png"),void 0===i&&(i=null),void 0===s&&(s=null),void 0===r&&(r=n.Loader.TEXTURE_ATLAS_JSON_ARRAY),i||s||(i=r===n.Loader.TEXTURE_ATLAS_XML_STARLING?t+".xml":t+".json"),i)this.addToFileList("textureatlas",t,e,{atlasURL:i,format:r});else{switch(r){case n.Loader.TEXTURE_ATLAS_JSON_ARRAY:"string"==typeof s&&(s=JSON.parse(s));break;case n.Loader.TEXTURE_ATLAS_XML_STARLING:if("string"==typeof s){var o=this.parseXml(s);if(!o)throw new Error("Phaser.Loader. Invalid Texture Atlas XML given");s=o}}this.addToFileList("textureatlas",t,e,{atlasURL:null,atlasData:s,format:r})}return this},withSyncPoint:function(t,e){this._withSyncPointDepth++;try{t.call(e||this,this)}finally{this._withSyncPointDepth--}return this},addSyncPoint:function(t,e){var i=this.getAsset(t,e);return i&&(i.file.syncPoint=!0),this},removeFile:function(t,e){var i=this.getAsset(t,e);i&&(i.loaded||i.loading||this._fileList.splice(i.index,1))},removeAll:function(){this._fileList.length=0,this._flightQueue.length=0},start:function(){this.isLoading||(this.hasLoaded=!1,this.isLoading=!0,this.updateProgress(),this.processLoadQueue())},processLoadQueue:function(){if(!this.isLoading)return console.warn("Phaser.Loader - active loading canceled / reset"),void this.finishedLoading(!0);for(var t=0;t<this._flightQueue.length;t++){var e=this._flightQueue[t];(e.loaded||e.error)&&(this._flightQueue.splice(t,1),t--,e.loading=!1,e.requestUrl=null,e.requestObject=null,e.error&&this.onFileError.dispatch(e.key,e),"packfile"!==e.type?(this._loadedFileCount++,this.onFileComplete.dispatch(this.progress,e.key,!e.error,this._loadedFileCount,this._totalFileCount)):"packfile"===e.type&&e.error&&(this._loadedPackCount++,this.onPackComplete.dispatch(e.key,!e.error,this._loadedPackCount,this._totalPackCount)))}for(var i=!1,s=this.enableParallel?n.Math.clamp(this.maxParallelDownloads,1,12):1,t=this._processingHead;t<this._fileList.length;t++){var e=this._fileList[t];if("packfile"===e.type&&!e.error&&e.loaded&&t===this._processingHead&&(this.processPack(e),this._loadedPackCount++,this.onPackComplete.dispatch(e.key,!e.error,this._loadedPackCount,this._totalPackCount)),e.loaded||e.error?t===this._processingHead&&(this._processingHead=t+1):!e.loading&&this._flightQueue.length<s&&("packfile"!==e.type||e.data?i||(this._fileLoadStarted||(this._fileLoadStarted=!0,this.onLoadStart.dispatch()),this._flightQueue.push(e),e.loading=!0,this.onFileStart.dispatch(this.progress,e.key,e.url),this.loadFile(e)):(this._flightQueue.push(e),e.loading=!0,this.loadFile(e))),!e.loaded&&e.syncPoint&&(i=!0),this._flightQueue.length>=s||i&&this._loadedPackCount===this._totalPackCount)break}if(this.updateProgress(),this._processingHead>=this._fileList.length)this.finishedLoading();else if(!this._flightQueue.length){console.warn("Phaser.Loader - aborting: processing queue empty, loading may have stalled");var r=this;setTimeout(function(){r.finishedLoading(!0)},2e3)}},finishedLoading:function(t){this.hasLoaded||(this.hasLoaded=!0,this.isLoading=!1,t||this._fileLoadStarted||(this._fileLoadStarted=!0,this.onLoadStart.dispatch()),this.onLoadComplete.dispatch(),this.game.state.loadComplete(),this.reset())},asyncComplete:function(t,e){void 0===e&&(e=""),t.loaded=!0,t.error=!!e,e&&(t.errorMessage=e,console.warn("Phaser.Loader - "+t.type+"["+t.key+"]: "+e)),this.processLoadQueue()},processPack:function(t){var e=t.data[t.key];if(!e)return void console.warn("Phaser.Loader - "+t.key+": pack has data, but not for pack key");for(var i=0;i<e.length;i++){var s=e[i];switch(s.type){case"image":this.image(s.key,s.url,s.overwrite);break;case"text":this.text(s.key,s.url,s.overwrite);break;case"json":this.json(s.key,s.url,s.overwrite);break;case"xml":this.xml(s.key,s.url,s.overwrite);break;case"script":this.script(s.key,s.url,s.callback,t.callbackContext||this);break;case"binary":this.binary(s.key,s.url,s.callback,t.callbackContext||this);break;case"spritesheet":this.spritesheet(s.key,s.url,s.frameWidth,s.frameHeight,s.frameMax,s.margin,s.spacing);break;case"video":this.video(s.key,s.urls);break;case"audio":this.audio(s.key,s.urls,s.autoDecode);break;case"audiosprite":this.audiosprite(s.key,s.urls,s.jsonURL,s.jsonData,s.autoDecode);break;case"tilemap":this.tilemap(s.key,s.url,s.data,n.Tilemap[s.format]);break;case"physics":this.physics(s.key,s.url,s.data,n.Loader[s.format]);break;case"bitmapFont":this.bitmapFont(s.key,s.textureURL,s.atlasURL,s.atlasData,s.xSpacing,s.ySpacing);break;case"atlasJSONArray":this.atlasJSONArray(s.key,s.textureURL,s.atlasURL,s.atlasData);break;case"atlasJSONHash":this.atlasJSONHash(s.key,s.textureURL,s.atlasURL,s.atlasData);break;case"atlasXML":this.atlasXML(s.key,s.textureURL,s.atlasURL,s.atlasData);break;case"atlas":this.atlas(s.key,s.textureURL,s.atlasURL,s.atlasData,n.Loader[s.format]);break;case"shader":this.shader(s.key,s.url,s.overwrite)}}},transformUrl:function(t,e){return!!t&&(t.match(/^(?:blob:|data:|http:\/\/|https:\/\/|\/\/)/)?t:this.baseURL+e.path+t)},loadFile:function(t){switch(t.type){case"packfile":this.xhrLoad(t,this.transformUrl(t.url,t),"text",this.fileComplete);break;case"image":case"spritesheet":case"textureatlas":case"bitmapfont":this.loadImageTag(t);break;case"audio":t.url=this.getAudioURL(t.url),t.url?this.game.sound.usingWebAudio?this.xhrLoad(t,this.transformUrl(t.url,t),"arraybuffer",this.fileComplete):this.game.sound.usingAudioTag&&this.loadAudioTag(t):this.fileError(t,null,"No supported audio URL specified or device does not have audio playback support");break;case"video":t.url=this.getVideoURL(t.url),t.url?t.asBlob?this.xhrLoad(t,this.transformUrl(t.url,t),"blob",this.fileComplete):this.loadVideoTag(t):this.fileError(t,null,"No supported video URL specified or device does not have video playback support");break;case"json":this.xhrLoad(t,this.transformUrl(t.url,t),"text",this.jsonLoadComplete);break;case"xml":this.xhrLoad(t,this.transformUrl(t.url,t),"text",this.xmlLoadComplete);break;case"tilemap":t.format===n.Tilemap.TILED_JSON?this.xhrLoad(t,this.transformUrl(t.url,t),"text",this.jsonLoadComplete):t.format===n.Tilemap.CSV?this.xhrLoad(t,this.transformUrl(t.url,t),"text",this.csvLoadComplete):this.asyncComplete(t,"invalid Tilemap format: "+t.format);break;case"text":case"script":case"shader":case"physics":this.xhrLoad(t,this.transformUrl(t.url,t),"text",this.fileComplete);break;case"binary":this.xhrLoad(t,this.transformUrl(t.url,t),"arraybuffer",this.fileComplete)}},loadImageTag:function(t){var e=this;t.data=new Image,t.data.name=t.key,this.crossOrigin&&(t.data.crossOrigin=this.crossOrigin),t.data.onload=function(){t.data.onload&&(t.data.onload=null,t.data.onerror=null,e.fileComplete(t))},t.data.onerror=function(){t.data.onload&&(t.data.onload=null,t.data.onerror=null,e.fileError(t))},t.data.src=this.transformUrl(t.url,t),t.data.complete&&t.data.width&&t.data.height&&(t.data.onload=null,t.data.onerror=null,this.fileComplete(t))},loadVideoTag:function(t){var e=this;t.data=document.createElement("video"),t.data.name=t.key,t.data.controls=!1,t.data.autoplay=!1;var i=function(){t.data.removeEventListener(t.loadEvent,i,!1),t.data.onerror=null,t.data.canplay=!0,n.GAMES[e.game.id].load.fileComplete(t)};t.data.onerror=function(){t.data.removeEventListener(t.loadEvent,i,!1),t.data.onerror=null,t.data.canplay=!1,e.fileError(t)},t.data.addEventListener(t.loadEvent,i,!1),t.data.src=this.transformUrl(t.url,t),t.data.load()},loadAudioTag:function(t){var e=this;if(this.game.sound.touchLocked)t.data=new Audio,t.data.name=t.key,t.data.preload="auto",t.data.src=this.transformUrl(t.url,t),this.fileComplete(t);else{t.data=new Audio,t.data.name=t.key;var i=function(){t.data.removeEventListener("canplaythrough",i,!1),t.data.onerror=null,e.fileComplete(t)};t.data.onerror=function(){t.data.removeEventListener("canplaythrough",i,!1),t.data.onerror=null,e.fileError(t)},t.data.preload="auto",t.data.src=this.transformUrl(t.url,t),t.data.addEventListener("canplaythrough",i,!1),t.data.load()}},xhrLoad:function(t,e,i,s,n){if(this.useXDomainRequest&&window.XDomainRequest)return void this.xhrLoadWithXDR(t,e,i,s,n);var r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType=i,!1!==this.headers.requestedWith&&r.setRequestHeader("X-Requested-With",this.headers.requestedWith),this.headers[t.type]&&r.setRequestHeader("Accept",this.headers[t.type]),n=n||this.fileError;var o=this;r.onload=function(){try{return 4===r.readyState&&r.status>=400&&r.status<=599?n.call(o,t,r):s.call(o,t,r)}catch(e){o.hasLoaded?window.console&&console.error(e):o.asyncComplete(t,e.message||"Exception")}},r.onerror=function(){try{return n.call(o,t,r)}catch(e){o.hasLoaded?window.console&&console.error(e):o.asyncComplete(t,e.message||"Exception")}},t.requestObject=r,t.requestUrl=e,r.send()},xhrLoadWithXDR:function(t,e,i,s,n){this._warnedAboutXDomainRequest||this.game.device.ie&&!(this.game.device.ieVersion>=10)||(this._warnedAboutXDomainRequest=!0,console.warn("Phaser.Loader - using XDomainRequest outside of IE 9"));var r=new window.XDomainRequest;r.open("GET",e,!0),r.responseType=i,r.timeout=3e3,n=n||this.fileError;var o=this;r.onerror=function(){try{return n.call(o,t,r)}catch(e){o.asyncComplete(t,e.message||"Exception")}},r.ontimeout=function(){try{return n.call(o,t,r)}catch(e){o.asyncComplete(t,e.message||"Exception")}},r.onprogress=function(){},r.onload=function(){try{return 4===r.readyState&&r.status>=400&&r.status<=599?n.call(o,t,r):s.call(o,t,r)}catch(e){o.asyncComplete(t,e.message||"Exception")}},t.requestObject=r,t.requestUrl=e,setTimeout(function(){r.send()},0)},getVideoURL:function(t){for(var e=0;e<t.length;e++){var i,s=t[e];if(s.uri){if(i=s.type,s=s.uri,this.game.device.canPlayVideo(i))return s}else{if(0===s.indexOf("blob:")||0===s.indexOf("data:"))return s;s.indexOf("?")>=0&&(s=s.substr(0,s.indexOf("?")));if(i=s.substr((Math.max(0,s.lastIndexOf("."))||1/0)+1).toLowerCase(),this.game.device.canPlayVideo(i))return t[e]}}return null},getAudioURL:function(t){if(this.game.sound.noAudio)return null;for(var e=0;e<t.length;e++){var i,s=t[e];if(s.uri){if(i=s.type,s=s.uri,this.game.device.canPlayAudio(i))return s}else{if(0===s.indexOf("blob:")||0===s.indexOf("data:"))return s;s.indexOf("?")>=0&&(s=s.substr(0,s.indexOf("?")));if(i=s.substr((Math.max(0,s.lastIndexOf("."))||1/0)+1).toLowerCase(),this.game.device.canPlayAudio(i))return t[e]}}return null},fileError:function(t,e,i){var s=t.requestUrl||this.transformUrl(t.url,t),n="error loading asset from URL "+s;!i&&e&&(i=e.status),i&&(n=n+" ("+i+")"),this.asyncComplete(t,n)},fileComplete:function(t,e){var i=!0;switch(t.type){case"packfile":var s=JSON.parse(e.responseText);t.data=s||{};break;case"image":this.cache.addImage(t.key,t.url,t.data);break;case"spritesheet":this.cache.addSpriteSheet(t.key,t.url,t.data,t.frameWidth,t.frameHeight,t.frameMax,t.margin,t.spacing);break;case"textureatlas":if(null==t.atlasURL)this.cache.addTextureAtlas(t.key,t.url,t.data,t.atlasData,t.format);else if(i=!1,t.format===n.Loader.TEXTURE_ATLAS_JSON_ARRAY||t.format===n.Loader.TEXTURE_ATLAS_JSON_HASH||t.format===n.Loader.TEXTURE_ATLAS_JSON_PYXEL)this.xhrLoad(t,this.transformUrl(t.atlasURL,t),"text",this.jsonLoadComplete);else{if(t.format!==n.Loader.TEXTURE_ATLAS_XML_STARLING)throw new Error("Phaser.Loader. Invalid Texture Atlas format: "+t.format);this.xhrLoad(t,this.transformUrl(t.atlasURL,t),"text",this.xmlLoadComplete)}break;case"bitmapfont":t.atlasURL?(i=!1,this.xhrLoad(t,this.transformUrl(t.atlasURL,t),"text",function(t,e){var i;try{i=JSON.parse(e.responseText)}catch(t){}i?(t.atlasType="json",this.jsonLoadComplete(t,e)):(t.atlasType="xml",this.xmlLoadComplete(t,e))})):this.cache.addBitmapFont(t.key,t.url,t.data,t.atlasData,t.atlasType,t.xSpacing,t.ySpacing);break;case"video":if(t.asBlob)try{t.data=e.response}catch(e){throw new Error("Phaser.Loader. Unable to parse video file as Blob: "+t.key)}this.cache.addVideo(t.key,t.url,t.data,t.asBlob);break;case"audio":this.game.sound.usingWebAudio?(t.data=e.response,this.cache.addSound(t.key,t.url,t.data,!0,!1),t.autoDecode&&this.game.sound.decode(t.key)):this.cache.addSound(t.key,t.url,t.data,!1,!0);break;case"text":t.data=e.responseText,this.cache.addText(t.key,t.url,t.data);break;case"shader":t.data=e.responseText,this.cache.addShader(t.key,t.url,t.data);break;case"physics":var s=JSON.parse(e.responseText);this.cache.addPhysicsData(t.key,t.url,s,t.format);break;case"script":t.data=document.createElement("script"),t.data.language="javascript",t.data.type="text/javascript",t.data.defer=!1,t.data.text=e.responseText,document.head.appendChild(t.data),t.callback&&(t.data=t.callback.call(t.callbackContext,t.key,e.responseText));break;case"binary":t.callback?t.data=t.callback.call(t.callbackContext,t.key,e.response):t.data=e.response,this.cache.addBinary(t.key,t.data)}i&&this.asyncComplete(t)},jsonLoadComplete:function(t,e){var i=JSON.parse(e.responseText);"tilemap"===t.type?this.cache.addTilemap(t.key,t.url,i,t.format):"bitmapfont"===t.type?this.cache.addBitmapFont(t.key,t.url,t.data,i,t.atlasType,t.xSpacing,t.ySpacing):"json"===t.type?this.cache.addJSON(t.key,t.url,i):this.cache.addTextureAtlas(t.key,t.url,t.data,i,t.format),this.asyncComplete(t)},csvLoadComplete:function(t,e){var i=e.responseText;this.cache.addTilemap(t.key,t.url,i,t.format),this.asyncComplete(t)},xmlLoadComplete:function(t,e){var i=e.responseText,s=this.parseXml(i);if(!s){var n=e.responseType||e.contentType;return console.warn("Phaser.Loader - "+t.key+": invalid XML ("+n+")"),void this.asyncComplete(t,"invalid XML")}"bitmapfont"===t.type?this.cache.addBitmapFont(t.key,t.url,t.data,s,t.atlasType,t.xSpacing,t.ySpacing):"textureatlas"===t.type?this.cache.addTextureAtlas(t.key,t.url,t.data,s,t.format):"xml"===t.type&&this.cache.addXML(t.key,t.url,s),this.asyncComplete(t)},parseXml:function(t){var e;try{if(window.DOMParser){var i=new DOMParser;e=i.parseFromString(t,"text/xml")}else e=new ActiveXObject("Microsoft.XMLDOM"),e.async="false",e.loadXML(t)}catch(t){e=null}return e&&e.documentElement&&!e.getElementsByTagName("parsererror").length?e:null},updateProgress:function(){this.preloadSprite&&(0===this.preloadSprite.direction?this.preloadSprite.rect.width=Math.floor(this.preloadSprite.width/100*this.progress):this.preloadSprite.rect.height=Math.floor(this.preloadSprite.height/100*this.progress),this.preloadSprite.sprite?this.preloadSprite.sprite.updateCrop():this.preloadSprite=null)},totalLoadedFiles:function(){return this._loadedFileCount},totalQueuedFiles:function(){return this._totalFileCount-this._loadedFileCount},totalLoadedPacks:function(){return this._totalPackCount},totalQueuedPacks:function(){return this._totalPackCount-this._loadedPackCount}},Object.defineProperty(n.Loader.prototype,"progressFloat",{get:function(){var t=this._loadedFileCount/this._totalFileCount*100;return n.Math.clamp(t||0,0,100)}}),Object.defineProperty(n.Loader.prototype,"progress",{get:function(){return Math.round(this.progressFloat)}}),n.Loader.prototype.constructor=n.Loader,n.LoaderParser={bitmapFont:function(t,e,i,s){return this.xmlBitmapFont(t,e,i,s)},xmlBitmapFont:function(t,e,i,s){var n={},r=t.getElementsByTagName("info")[0],o=t.getElementsByTagName("common")[0];n.font=r.getAttribute("face"),n.size=parseInt(r.getAttribute("size"),10),n.lineHeight=parseInt(o.getAttribute("lineHeight"),10)+s,n.chars={};for(var a=t.getElementsByTagName("char"),h=0;h<a.length;h++){var l=parseInt(a[h].getAttribute("id"),10);n.chars[l]={x:parseInt(a[h].getAttribute("x"),10),y:parseInt(a[h].getAttribute("y"),10),width:parseInt(a[h].getAttribute("width"),10),height:parseInt(a[h].getAttribute("height"),10),xOffset:parseInt(a[h].getAttribute("xoffset"),10),yOffset:parseInt(a[h].getAttribute("yoffset"),10),xAdvance:parseInt(a[h].getAttribute("xadvance"),10)+i,kerning:{}}}var c=t.getElementsByTagName("kerning");for(h=0;h<c.length;h++){var u=parseInt(c[h].getAttribute("first"),10),d=parseInt(c[h].getAttribute("second"),10),p=parseInt(c[h].getAttribute("amount"),10);n.chars[d].kerning[u]=p}return this.finalizeBitmapFont(e,n)},jsonBitmapFont:function(t,e,i,s){var n={font:t.font.info._face,size:parseInt(t.font.info._size,10),lineHeight:parseInt(t.font.common._lineHeight,10)+s,chars:{}};return t.font.chars.char.forEach(function(t){var e=parseInt(t._id,10);n.chars[e]={x:parseInt(t._x,10),y:parseInt(t._y,10),width:parseInt(t._width,10),height:parseInt(t._height,10),xOffset:parseInt(t._xoffset,10),yOffset:parseInt(t._yoffset,10),xAdvance:parseInt(t._xadvance,10)+i,kerning:{}}}),t.font.kernings&&t.font.kernings.kerning&&t.font.kernings.kerning.forEach(function(t){n.chars[t._second].kerning[t._first]=parseInt(t._amount,10)}),this.finalizeBitmapFont(e,n)},finalizeBitmapFont:function(t,e){return Object.keys(e.chars).forEach(function(i){var s=e.chars[i];s.texture=new PIXI.Texture(t,new n.Rectangle(s.x,s.y,s.width,s.height))}),e}},n.AudioSprite=function(t,e){this.game=t,this.key=e,this.config=this.game.cache.getJSON(e+"-audioatlas"),this.autoplayKey=null,this.autoplay=!1,this.sounds={};for(var i in this.config.spritemap){var s=this.config.spritemap[i],n=this.game.add.sound(this.key);n.addMarker(i,s.start,s.end-s.start,null,s.loop),this.sounds[i]=n}this.config.autoplay&&(this.autoplayKey=this.config.autoplay,this.play(this.autoplayKey),this.autoplay=this.sounds[this.autoplayKey])},n.AudioSprite.prototype={play:function(t,e){return void 0===e&&(e=1),this.sounds[t].play(t,null,e)},stop:function(t){if(t)this.sounds[t].stop();else for(var e in this.sounds)this.sounds[e].stop()},get:function(t){return this.sounds[t]}},n.AudioSprite.prototype.constructor=n.AudioSprite,n.Sound=function(t,e,i,s,r){void 0===i&&(i=1),void 0===s&&(s=!1),void 0===r&&(r=t.sound.connectToMaster),this.game=t,this.name=e,this.key=e,this.loop=s,this.markers={},this.context=null,this.autoplay=!1,this.totalDuration=0,this.startTime=0,this.currentTime=0,this.duration=0,this.durationMS=0,this.position=0,this.stopTime=0,this.paused=!1,this.pausedPosition=0,this.pausedTime=0,this.isPlaying=!1,this.currentMarker="",this.fadeTween=null,this.pendingPlayback=!1,this.override=!1,this.allowMultiple=!1,this.usingWebAudio=this.game.sound.usingWebAudio,this.usingAudioTag=this.game.sound.usingAudioTag,this.externalNode=null,this.masterGainNode=null,this.gainNode=null,this._sound=null,this.usingWebAudio?(this.context=this.game.sound.context,this.masterGainNode=this.game.sound.masterGain,void 0===this.context.createGain?this.gainNode=this.context.createGainNode():this.gainNode=this.context.createGain(),this.gainNode.gain.value=i*this.game.sound.volume,r&&this.gainNode.connect(this.masterGainNode)):this.usingAudioTag&&(this.game.cache.getSound(e)&&this.game.cache.isSoundReady(e)?(this._sound=this.game.cache.getSoundData(e),this.totalDuration=0,this._sound.duration&&(this.totalDuration=this._sound.duration)):this.game.cache.onSoundUnlock.add(this.soundHasUnlocked,this)),this.onDecoded=new n.Signal,this.onPlay=new n.Signal,this.onPause=new n.Signal,this.onResume=new n.Signal,this.onLoop=new n.Signal,this.onStop=new n.Signal,this.onMute=new n.Signal,this.onMarkerComplete=new n.Signal,this.onFadeComplete=new n.Signal,this._volume=i,this._buffer=null,this._muted=!1,this._tempMarker=0,this._tempPosition=0,this._tempVolume=0,this._tempPause=0,this._muteVolume=0,this._tempLoop=0,this._paused=!1,this._onDecodedEventDispatched=!1},n.Sound.prototype={soundHasUnlocked:function(t){t===this.key&&(this._sound=this.game.cache.getSoundData(this.key),this.totalDuration=this._sound.duration)},addMarker:function(t,e,i,s,n){void 0!==i&&null!==i||(i=1),void 0!==s&&null!==s||(s=1),void 0===n&&(n=!1),this.markers[t]={name:t,start:e,stop:e+i,volume:s,duration:i,durationMS:1e3*i,loop:n}},removeMarker:function(t){delete this.markers[t]},onEndedHandler:function(){this._sound.onended=null,this.isPlaying=!1,this.currentTime=this.durationMS,this.stop()},update:function(){if(!this.game.cache.checkSoundKey(this.key))return void this.destroy();this.isDecoded&&!this._onDecodedEventDispatched&&(this.onDecoded.dispatch(this),this._onDecodedEventDispatched=!0),this.pendingPlayback&&this.game.cache.isSoundReady(this.key)&&(this.pendingPlayback=!1,this.play(this._tempMarker,this._tempPosition,this._tempVolume,this._tempLoop)),this.isPlaying&&(this.currentTime=this.game.time.time-this.startTime,this.currentTime>=this.durationMS&&(this.usingWebAudio?this.loop?(this.onLoop.dispatch(this),this.isPlaying=!1,""===this.currentMarker?(this.currentTime=0,this.startTime=this.game.time.time,this.isPlaying=!0):(this.onMarkerComplete.dispatch(this.currentMarker,this),this.play(this.currentMarker,0,this.volume,!0,!0))):""!==this.currentMarker&&this.stop():this.loop?(this.onLoop.dispatch(this),""===this.currentMarker&&(this.currentTime=0,this.startTime=this.game.time.time),this.isPlaying=!1,this.play(this.currentMarker,0,this.volume,!0,!0)):this.stop()))},loopFull:function(t){return this.play(null,0,t,!0)},play:function(t,e,i,s,n){if(void 0!==t&&!1!==t&&null!==t||(t=""),void 0===n&&(n=!0),this.isPlaying&&!this.allowMultiple&&!n&&!this.override)return this;if(this._sound&&this.isPlaying&&!this.allowMultiple&&(this.override||n)){if(this.usingWebAudio){if(void 0===this._sound.stop)this._sound.noteOff(0);else try{this._sound.stop(0)}catch(t){}this.externalNode?this._sound.disconnect(this.externalNode):this.gainNode&&this._sound.disconnect(this.gainNode)}else this.usingAudioTag&&(this._sound.pause(),this._sound.currentTime=0);this.isPlaying=!1}if(""===t&&Object.keys(this.markers).length>0)return this;if(""!==t){if(!this.markers[t])return console.warn("Phaser.Sound.play: audio marker "+t+" doesn't exist"),this;this.currentMarker=t,this.position=this.markers[t].start,this.volume=this.markers[t].volume,this.loop=this.markers[t].loop,this.duration=this.markers[t].duration,this.durationMS=this.markers[t].durationMS,void 0!==i&&(this.volume=i),void 0!==s&&(this.loop=s),this._tempMarker=t,this._tempPosition=this.position,this._tempVolume=this.volume,this._tempLoop=this.loop}else e=e||0,void 0===i&&(i=this._volume),void 0===s&&(s=this.loop),this.position=Math.max(0,e),this.volume=i,this.loop=s,this.duration=0,this.durationMS=0,this._tempMarker=t,this._tempPosition=e,this._tempVolume=i,this._tempLoop=s;return this.usingWebAudio?this.game.cache.isSoundDecoded(this.key)?(this._sound=this.context.createBufferSource(),this.externalNode?this._sound.connect(this.externalNode):this._sound.connect(this.gainNode),this._buffer=this.game.cache.getSoundData(this.key),this._sound.buffer=this._buffer,this.loop&&""===t&&(this._sound.loop=!0),this.loop||""!==t||(this._sound.onended=this.onEndedHandler.bind(this)),this.totalDuration=this._sound.buffer.duration,0===this.duration&&(this.duration=this.totalDuration,this.durationMS=Math.ceil(1e3*this.totalDuration)),void 0===this._sound.start?this._sound.noteGrainOn(0,this.position,this.duration):this.loop&&""===t?this._sound.start(0,0):this._sound.start(0,this.position,this.duration),this.isPlaying=!0,this.startTime=this.game.time.time,this.currentTime=0,this.stopTime=this.startTime+this.durationMS,this.onPlay.dispatch(this)):(this.pendingPlayback=!0,this.game.cache.getSound(this.key)&&!1===this.game.cache.getSound(this.key).isDecoding&&this.game.sound.decode(this.key,this)):this.game.cache.getSound(this.key)&&this.game.cache.getSound(this.key).locked?(this.game.cache.reloadSound(this.key),this.pendingPlayback=!0):this._sound&&(this.game.device.cocoonJS||4===this._sound.readyState)?(this._sound.play(),this.totalDuration=this._sound.duration,0===this.duration&&(this.duration=this.totalDuration,this.durationMS=1e3*this.totalDuration),this._sound.currentTime=this.position,this._sound.muted=this._muted,this._muted||this.game.sound.mute?this._sound.volume=0:this._sound.volume=this._volume,this.isPlaying=!0,this.startTime=this.game.time.time,this.currentTime=0,this.stopTime=this.startTime+this.durationMS,this.onPlay.dispatch(this)):this.pendingPlayback=!0,this},restart:function(t,e,i,s){t=t||"",e=e||0,i=i||1,void 0===s&&(s=!1),this.play(t,e,i,s,!0)},pause:function(){this.isPlaying&&this._sound&&(this.paused=!0,this.pausedPosition=this.currentTime,this.pausedTime=this.game.time.time,this._tempPause=this._sound.currentTime,this.onPause.dispatch(this),this.stop())},resume:function(){if(this.paused&&this._sound){if(this.usingWebAudio){var t=Math.max(0,this.position+this.pausedPosition/1e3);this._sound=this.context.createBufferSource(),this._sound.buffer=this._buffer,this.externalNode?this._sound.connect(this.externalNode):this._sound.connect(this.gainNode),this.loop&&(this._sound.loop=!0),this.loop||""!==this.currentMarker||(this._sound.onended=this.onEndedHandler.bind(this));var e=this.duration-this.pausedPosition/1e3;void 0===this._sound.start?this._sound.noteGrainOn(0,t,e):this.loop&&this.game.device.chrome?42===this.game.device.chromeVersion?this._sound.start(0):this._sound.start(0,t):this._sound.start(0,t,e)}else this._sound.currentTime=this._tempPause,this._sound.play();this.isPlaying=!0,this.paused=!1,this.startTime+=this.game.time.time-this.pausedTime,this.onResume.dispatch(this)}},stop:function(){if(this.isPlaying&&this._sound)if(this.usingWebAudio){if(void 0===this._sound.stop)this._sound.noteOff(0);else try{this._sound.stop(0)}catch(t){}this.externalNode?this._sound.disconnect(this.externalNode):this.gainNode&&this._sound.disconnect(this.gainNode)}else this.usingAudioTag&&(this._sound.pause(),this._sound.currentTime=0);if(this.pendingPlayback=!1,this.isPlaying=!1,!this.paused){var t=this.currentMarker;""!==this.currentMarker&&this.onMarkerComplete.dispatch(this.currentMarker,this),this.currentMarker="",null!==this.fadeTween&&this.fadeTween.stop(),this.onStop.dispatch(this,t)}},fadeIn:function(t,e,i){void 0===e&&(e=!1),void 0===i&&(i=this.currentMarker),this.paused||(this.play(i,0,0,e),this.fadeTo(t,1))},fadeOut:function(t){this.fadeTo(t,0)},fadeTo:function(t,e){if(this.isPlaying&&!this.paused&&e!==this.volume){if(void 0===t&&(t=1e3),void 0===e)return void console.warn("Phaser.Sound.fadeTo: No Volume Specified.");this.fadeTween=this.game.add.tween(this).to({volume:e},t,n.Easing.Linear.None,!0),this.fadeTween.onComplete.add(this.fadeComplete,this)}},fadeComplete:function(){this.onFadeComplete.dispatch(this,this.volume),0===this.volume&&this.stop()},updateGlobalVolume:function(t){this.usingAudioTag&&this._sound&&(this._sound.volume=t*this._volume)},destroy:function(t){void 0===t&&(t=!0),this.stop(),t?this.game.sound.remove(this):(this.markers={},this.context=null,this._buffer=null,this.externalNode=null,this.onDecoded.dispose(),this.onPlay.dispose(),this.onPause.dispose(),this.onResume.dispose(),this.onLoop.dispose(),this.onStop.dispose(),this.onMute.dispose(),this.onMarkerComplete.dispose())}},n.Sound.prototype.constructor=n.Sound,Object.defineProperty(n.Sound.prototype,"isDecoding",{get:function(){return this.game.cache.getSound(this.key).isDecoding}}),Object.defineProperty(n.Sound.prototype,"isDecoded",{get:function(){return this.game.cache.isSoundDecoded(this.key)}}),Object.defineProperty(n.Sound.prototype,"mute",{get:function(){return this._muted||this.game.sound.mute},set:function(t){(t=t||!1)!==this._muted&&(t?(this._muted=!0,this._muteVolume=this._tempVolume,this.usingWebAudio?this.gainNode.gain.value=0:this.usingAudioTag&&this._sound&&(this._sound.volume=0)):(this._muted=!1,this.usingWebAudio?this.gainNode.gain.value=this._muteVolume:this.usingAudioTag&&this._sound&&(this._sound.volume=this._muteVolume)),this.onMute.dispatch(this))}}),Object.defineProperty(n.Sound.prototype,"volume",{get:function(){return this._volume},set:function(t){if(this.game.device.firefox&&this.usingAudioTag&&(t=this.game.math.clamp(t,0,1)),this._muted)return void(this._muteVolume=t);this._tempVolume=t,this._volume=t,this.usingWebAudio?this.gainNode.gain.value=t:this.usingAudioTag&&this._sound&&(this._sound.volume=t)}}),n.SoundManager=function(t){this.game=t,this.onSoundDecode=new n.Signal,this.onVolumeChange=new n.Signal,this.onMute=new n.Signal,this.onUnMute=new n.Signal,this.context=null,this.usingWebAudio=!1,this.usingAudioTag=!1,this.noAudio=!1,this.connectToMaster=!0,this.touchLocked=!1,this.channels=32,this.muteOnPause=!0,this._codeMuted=!1,this._muted=!1,this._unlockSource=null,this._volume=1,this._sounds=[],this._watchList=new n.ArraySet,this._watching=!1,this._watchCallback=null,this._watchContext=null},n.SoundManager.prototype={boot:function(){if(this.game.device.iOS&&!1===this.game.device.webAudio&&(this.channels=1),window.PhaserGlobal){if(!0===window.PhaserGlobal.disableAudio)return this.noAudio=!0,void(this.touchLocked=!1);if(!0===window.PhaserGlobal.disableWebAudio)return this.usingAudioTag=!0,void(this.touchLocked=!1)}if(window.PhaserGlobal&&window.PhaserGlobal.audioContext)this.context=window.PhaserGlobal.audioContext;else if(window.AudioContext)try{this.context=new window.AudioContext}catch(t){this.context=null,this.usingWebAudio=!1,this.touchLocked=!1}else if(window.webkitAudioContext)try{this.context=new window.webkitAudioContext}catch(t){this.context=null,this.usingWebAudio=!1,this.touchLocked=!1}if(null===this.context){if(void 0===window.Audio)return void(this.noAudio=!0);this.usingAudioTag=!0}else this.usingWebAudio=!0,void 0===this.context.createGain?this.masterGain=this.context.createGainNode():this.masterGain=this.context.createGain(),this.masterGain.gain.value=1,this.masterGain.connect(this.context.destination);this.noAudio||(!this.game.device.cocoonJS&&this.game.device.iOS||window.PhaserGlobal&&window.PhaserGlobal.fakeiOSTouchLock)&&this.setTouchLock()},setTouchLock:function(){this.noAudio||window.PhaserGlobal&&!0===window.PhaserGlobal.disableAudio||(this.game.device.iOSVersion>8?this.game.input.touch.addTouchLockCallback(this.unlock,this,!0):this.game.input.touch.addTouchLockCallback(this.unlock,this),this.touchLocked=!0)},unlock:function(){if(this.noAudio||!this.touchLocked||null!==this._unlockSource)return!0;if(this.usingAudioTag)this.touchLocked=!1,this._unlockSource=null;else if(this.usingWebAudio){var t=this.context.createBuffer(1,1,22050);this._unlockSource=this.context.createBufferSource(),this._unlockSource.buffer=t,this._unlockSource.connect(this.context.destination),void 0===this._unlockSource.start?this._unlockSource.noteOn(0):this._unlockSource.start(0)}return!0},stopAll:function(){if(!this.noAudio)for(var t=0;t<this._sounds.length;t++)this._sounds[t]&&this._sounds[t].stop()},pauseAll:function(){if(!this.noAudio)for(var t=0;t<this._sounds.length;t++)this._sounds[t]&&this._sounds[t].pause()},resumeAll:function(){if(!this.noAudio)for(var t=0;t<this._sounds.length;t++)this._sounds[t]&&this._sounds[t].resume()},decode:function(t,e){e=e||null;var i=this.game.cache.getSoundData(t);if(i&&!1===this.game.cache.isSoundDecoded(t)){this.game.cache.updateSound(t,"isDecoding",!0);var s=this;try{this.context.decodeAudioData(i,function(i){i&&(s.game.cache.decodedSound(t,i),s.onSoundDecode.dispatch(t,e))})}catch(t){}}},setDecodedCallback:function(t,e,i){"string"==typeof t&&(t=[t]),this._watchList.reset();for(var s=0;s<t.length;s++)t[s]instanceof n.Sound?this.game.cache.isSoundDecoded(t[s].key)||this._watchList.add(t[s].key):this.game.cache.isSoundDecoded(t[s])||this._watchList.add(t[s]);0===this._watchList.total?(this._watching=!1,e.call(i)):(this._watching=!0,this._watchCallback=e,this._watchContext=i)},update:function(){if(!this.noAudio){!this.touchLocked||null===this._unlockSource||this._unlockSource.playbackState!==this._unlockSource.PLAYING_STATE&&this._unlockSource.playbackState!==this._unlockSource.FINISHED_STATE||(this.touchLocked=!1,this._unlockSource=null);for(var t=0;t<this._sounds.length;t++)this._sounds[t].update();if(this._watching){for(var e=this._watchList.first;e;)this.game.cache.isSoundDecoded(e)&&this._watchList.remove(e),e=this._watchList.next;0===this._watchList.total&&(this._watching=!1,this._watchCallback.call(this._watchContext))}}},add:function(t,e,i,s){void 0===e&&(e=1),void 0===i&&(i=!1),void 0===s&&(s=this.connectToMaster);var r=new n.Sound(this.game,t,e,i,s);return this._sounds.push(r),r},addSprite:function(t){return new n.AudioSprite(this.game,t)},remove:function(t){for(var e=this._sounds.length;e--;)if(this._sounds[e]===t)return this._sounds[e].destroy(!1),this._sounds.splice(e,1),!0;return!1},removeByKey:function(t){for(var e=this._sounds.length,i=0;e--;)this._sounds[e].key===t&&(this._sounds[e].destroy(!1),this._sounds.splice(e,1),i++);return i},play:function(t,e,i){if(!this.noAudio){var s=this.add(t,e,i);return s.play(),s}},setMute:function(){if(!this._muted){this._muted=!0,this.usingWebAudio&&(this._muteVolume=this.masterGain.gain.value,this.masterGain.gain.value=0);for(var t=0;t<this._sounds.length;t++)this._sounds[t].usingAudioTag&&(this._sounds[t].mute=!0);this.onMute.dispatch()}},unsetMute:function(){if(this._muted&&!this._codeMuted){this._muted=!1,this.usingWebAudio&&(this.masterGain.gain.value=this._muteVolume);for(var t=0;t<this._sounds.length;t++)this._sounds[t].usingAudioTag&&(this._sounds[t].mute=!1);this.onUnMute.dispatch()}},destroy:function(){this.stopAll();for(var t=0;t<this._sounds.length;t++)this._sounds[t]&&this._sounds[t].destroy();this._sounds=[],this.onSoundDecode.dispose(),this.context&&(window.PhaserGlobal?window.PhaserGlobal.audioContext=this.context:this.context.close&&this.context.close())}},n.SoundManager.prototype.constructor=n.SoundManager,Object.defineProperty(n.SoundManager.prototype,"mute",{get:function(){return this._muted},set:function(t){if(t=t||!1){if(this._muted)return;this._codeMuted=!0,this.setMute()}else{if(!this._muted)return;this._codeMuted=!1,this.unsetMute()}}}),Object.defineProperty(n.SoundManager.prototype,"volume",{get:function(){return this._volume},set:function(t){if(t<0?t=0:t>1&&(t=1),this._volume!==t){if(this._volume=t,this.usingWebAudio)this.masterGain.gain.value=t;else for(var e=0;e<this._sounds.length;e++)this._sounds[e].usingAudioTag&&this._sounds[e].updateGlobalVolume(t);this.onVolumeChange.dispatch(t)}}}),n.ScaleManager=function(t,e,i){this.game=t,this.dom=n.DOM,this.grid=null,this.width=0,this.height=0,this.minWidth=null,this.maxWidth=null,this.minHeight=null,this.maxHeight=null,this.offset=new n.Point,this.forceLandscape=!1,this.forcePortrait=!1,this.incorrectOrientation=!1,this._pageAlignHorizontally=!1,this._pageAlignVertically=!1,this.onOrientationChange=new n.Signal,this.enterIncorrectOrientation=new n.Signal,this.leaveIncorrectOrientation=new n.Signal,this.hasPhaserSetFullScreen=!1,this.fullScreenTarget=null,this._createdFullScreenTarget=null,this.onFullScreenInit=new n.Signal,this.onFullScreenChange=new n.Signal,this.onFullScreenError=new n.Signal,this.screenOrientation=this.dom.getScreenOrientation(),this.scaleFactor=new n.Point(1,1),this.scaleFactorInversed=new n.Point(1,1),this.margin={left:0,top:0,right:0,bottom:0,x:0,y:0},this.bounds=new n.Rectangle,this.aspectRatio=0,this.sourceAspectRatio=0,this.event=null,this.windowConstraints={right:"layout",bottom:""},this.compatibility={supportsFullScreen:!1,orientationFallback:null,noMargins:!1,scrollTo:null,forceMinimumDocumentHeight:!1,canExpandParent:!0,clickTrampoline:""},this._scaleMode=n.ScaleManager.NO_SCALE,this._fullScreenScaleMode=n.ScaleManager.NO_SCALE,this.parentIsWindow=!1,this.parentNode=null,this.parentScaleFactor=new n.Point(1,1),this.trackParentInterval=2e3,this.onSizeChange=new n.Signal,this.onResize=null,this.onResizeContext=null,this._pendingScaleMode=null,this._fullScreenRestore=null,this._gameSize=new n.Rectangle,this._userScaleFactor=new n.Point(1,1),this._userScaleTrim=new n.Point(0,0),this._lastUpdate=0,this._updateThrottle=0,this._updateThrottleReset=100,this._parentBounds=new n.Rectangle,this._tempBounds=new n.Rectangle,this._lastReportedCanvasSize=new n.Rectangle,this._lastReportedGameSize=new n.Rectangle,this._booted=!1,t.config&&this.parseConfig(t.config),this.setupScale(e,i)},n.ScaleManager.EXACT_FIT=0,n.ScaleManager.NO_SCALE=1,n.ScaleManager.SHOW_ALL=2,n.ScaleManager.RESIZE=3,n.ScaleManager.USER_SCALE=4,n.ScaleManager.prototype={boot:function(){var t=this.compatibility;t.supportsFullScreen=this.game.device.fullscreen&&!this.game.device.cocoonJS,this.game.device.iPad||this.game.device.webApp||this.game.device.desktop||(this.game.device.android&&!this.game.device.chrome?t.scrollTo=new n.Point(0,1):t.scrollTo=new n.Point(0,0)),this.game.device.desktop?(t.orientationFallback="screen",t.clickTrampoline="when-not-mouse"):(t.orientationFallback="",t.clickTrampoline="");var e=this;this._orientationChange=function(t){return e.orientationChange(t)},this._windowResize=function(t){return e.windowResize(t)},window.addEventListener("orientationchange",this._orientationChange,!1),window.addEventListener("resize",this._windowResize,!1),this.compatibility.supportsFullScreen&&(this._fullScreenChange=function(t){return e.fullScreenChange(t)},this._fullScreenError=function(t){return e.fullScreenError(t)},document.addEventListener("webkitfullscreenchange",this._fullScreenChange,!1),document.addEventListener("mozfullscreenchange",this._fullScreenChange,!1),document.addEventListener("MSFullscreenChange",this._fullScreenChange,!1),document.addEventListener("fullscreenchange",this._fullScreenChange,!1),document.addEventListener("webkitfullscreenerror",this._fullScreenError,!1),document.addEventListener("mozfullscreenerror",this._fullScreenError,!1),document.addEventListener("MSFullscreenError",this._fullScreenError,!1),document.addEventListener("fullscreenerror",this._fullScreenError,!1)),this.game.onResume.add(this._gameResumed,this),this.dom.getOffset(this.game.canvas,this.offset),this.bounds.setTo(this.offset.x,this.offset.y,this.width,this.height),this.setGameSize(this.game.width,this.game.height),this.screenOrientation=this.dom.getScreenOrientation(this.compatibility.orientationFallback),n.FlexGrid&&(this.grid=new n.FlexGrid(this,this.width,this.height)),this._booted=!0,null!==this._pendingScaleMode&&(this.scaleMode=this._pendingScaleMode,this._pendingScaleMode=null)},parseConfig:function(t){void 0!==t.scaleMode&&(this._booted?this.scaleMode=t.scaleMode:this._pendingScaleMode=t.scaleMode),void 0!==t.fullScreenScaleMode&&(this.fullScreenScaleMode=t.fullScreenScaleMode),t.fullScreenTarget&&(this.fullScreenTarget=t.fullScreenTarget)},setupScale:function(t,e){var i,s=new n.Rectangle;""!==this.game.parent&&("string"==typeof this.game.parent?i=document.getElementById(this.game.parent):this.game.parent&&1===this.game.parent.nodeType&&(i=this.game.parent)),i?(this.parentNode=i,this.parentIsWindow=!1,this.getParentBounds(this._parentBounds),s.width=this._parentBounds.width,s.height=this._parentBounds.height,this.offset.set(this._parentBounds.x,this._parentBounds.y)):(this.parentNode=null,this.parentIsWindow=!0,s.width=this.dom.visualBounds.width,s.height=this.dom.visualBounds.height,this.offset.set(0,0));var r=0,o=0;"number"==typeof t?r=t:(this.parentScaleFactor.x=parseInt(t,10)/100,r=s.width*this.parentScaleFactor.x),"number"==typeof e?o=e:(this.parentScaleFactor.y=parseInt(e,10)/100,o=s.height*this.parentScaleFactor.y),r=Math.floor(r),o=Math.floor(o),this._gameSize.setTo(0,0,r,o),this.updateDimensions(r,o,!1)},_gameResumed:function(){this.queueUpdate(!0)},setGameSize:function(t,e){this._gameSize.setTo(0,0,t,e),this.currentScaleMode!==n.ScaleManager.RESIZE&&this.updateDimensions(t,e,!0),this.queueUpdate(!0)},setUserScale:function(t,e,i,s){this._userScaleFactor.setTo(t,e),this._userScaleTrim.setTo(0|i,0|s),this.queueUpdate(!0)},setResizeCallback:function(t,e){this.onResize=t,this.onResizeContext=e},signalSizeChange:function(){if(!n.Rectangle.sameDimensions(this,this._lastReportedCanvasSize)||!n.Rectangle.sameDimensions(this.game,this._lastReportedGameSize)){var t=this.width,e=this.height;this._lastReportedCanvasSize.setTo(0,0,t,e),this._lastReportedGameSize.setTo(0,0,this.game.width,this.game.height),this.grid&&this.grid.onResize(t,e),this.onSizeChange.dispatch(this,t,e),this.currentScaleMode===n.ScaleManager.RESIZE&&(this.game.state.resize(t,e),this.game.load.resize(t,e))}},setMinMax:function(t,e,i,s){this.minWidth=t,this.minHeight=e,void 0!==i&&(this.maxWidth=i),void 0!==s&&(this.maxHeight=s)},preUpdate:function(){if(!(this.game.time.time<this._lastUpdate+this._updateThrottle)){var t=this._updateThrottle;this._updateThrottleReset=t>=400?0:100,this.dom.getOffset(this.game.canvas,this.offset);var e=this._parentBounds.width,i=this._parentBounds.height,s=this.getParentBounds(this._parentBounds),r=s.width!==e||s.height!==i,o=this.updateOrientationState();(r||o)&&(this.onResize&&this.onResize.call(this.onResizeContext,this,s),this.updateLayout(),this.signalSizeChange());var a=2*this._updateThrottle;this._updateThrottle<t&&(a=Math.min(t,this._updateThrottleReset)),this._updateThrottle=n.Math.clamp(a,25,this.trackParentInterval),this._lastUpdate=this.game.time.time}},pauseUpdate:function(){this.preUpdate(),this._updateThrottle=this.trackParentInterval},updateDimensions:function(t,e,i){this.width=t*this.parentScaleFactor.x,this.height=e*this.parentScaleFactor.y,this.game.width=this.width,this.game.height=this.height,this.sourceAspectRatio=this.width/this.height,this.updateScalingAndBounds(),i&&(this.game.renderer.resize(this.width,this.height),this.game.camera.setSize(this.width,this.height),this.game.world.resize(this.width,this.height))},updateScalingAndBounds:function(){this.scaleFactor.x=this.game.width/this.width,this.scaleFactor.y=this.game.height/this.height,this.scaleFactorInversed.x=this.width/this.game.width,this.scaleFactorInversed.y=this.height/this.game.height,this.aspectRatio=this.width/this.height,this.game.canvas&&this.dom.getOffset(this.game.canvas,this.offset),this.bounds.setTo(this.offset.x,this.offset.y,this.width,this.height),this.game.input&&this.game.input.scale&&this.game.input.scale.setTo(this.scaleFactor.x,this.scaleFactor.y)},forceOrientation:function(t,e){void 0===e&&(e=!1),this.forceLandscape=t,this.forcePortrait=e,this.queueUpdate(!0)},classifyOrientation:function(t){return"portrait-primary"===t||"portrait-secondary"===t?"portrait":"landscape-primary"===t||"landscape-secondary"===t?"landscape":null},updateOrientationState:function(){var t=this.screenOrientation,e=this.incorrectOrientation;this.screenOrientation=this.dom.getScreenOrientation(this.compatibility.orientationFallback),this.incorrectOrientation=this.forceLandscape&&!this.isLandscape||this.forcePortrait&&!this.isPortrait;var i=t!==this.screenOrientation,s=e!==this.incorrectOrientation;return s&&(this.incorrectOrientation?this.enterIncorrectOrientation.dispatch():this.leaveIncorrectOrientation.dispatch()),(i||s)&&this.onOrientationChange.dispatch(this,t,e),i||s},orientationChange:function(t){this.event=t,this.queueUpdate(!0)},windowResize:function(t){this.event=t,this.queueUpdate(!0)},scrollTop:function(){var t=this.compatibility.scrollTo;t&&window.scrollTo(t.x,t.y)},refresh:function(){this.scrollTop(),this.queueUpdate(!0)},updateLayout:function(){var t=this.currentScaleMode;if(t===n.ScaleManager.RESIZE)return void this.reflowGame();if(this.scrollTop(),this.compatibility.forceMinimumDocumentHeight&&(document.documentElement.style.minHeight=window.innerHeight+"px"),this.incorrectOrientation?this.setMaximum():t===n.ScaleManager.EXACT_FIT?this.setExactFit():t===n.ScaleManager.SHOW_ALL?!this.isFullScreen&&this.boundingParent&&this.compatibility.canExpandParent?(this.setShowAll(!0),this.resetCanvas(),this.setShowAll()):this.setShowAll():t===n.ScaleManager.NO_SCALE?(this.width=this.game.width,this.height=this.game.height):t===n.ScaleManager.USER_SCALE&&(this.width=this.game.width*this._userScaleFactor.x-this._userScaleTrim.x,this.height=this.game.height*this._userScaleFactor.y-this._userScaleTrim.y),!this.compatibility.canExpandParent&&(t===n.ScaleManager.SHOW_ALL||t===n.ScaleManager.USER_SCALE)){var e=this.getParentBounds(this._tempBounds);this.width=Math.min(this.width,e.width),this.height=Math.min(this.height,e.height)}this.width=0|this.width,this.height=0|this.height,this.reflowCanvas()},getParentBounds:function(t){var e=t||new n.Rectangle,i=this.boundingParent,s=this.dom.visualBounds,r=this.dom.layoutBounds;if(i){var o=i.getBoundingClientRect(),a=i.offsetParent?i.offsetParent.getBoundingClientRect():i.getBoundingClientRect();e.setTo(o.left-a.left,o.top-a.top,o.width,o.height);var h=this.windowConstraints;if(h.right){var l="layout"===h.right?r:s;e.right=Math.min(e.right,l.width)}if(h.bottom){var l="layout"===h.bottom?r:s;e.bottom=Math.min(e.bottom,l.height)}}else e.setTo(0,0,s.width,s.height);return e.setTo(Math.round(e.x),Math.round(e.y),Math.round(e.width),Math.round(e.height)),e},alignCanvas:function(t,e){var i=this.getParentBounds(this._tempBounds),s=this.game.canvas,n=this.margin;if(t){n.left=n.right=0;var r=s.getBoundingClientRect();if(this.width<i.width&&!this.incorrectOrientation){var o=r.left-i.x,a=i.width/2-this.width/2;a=Math.max(a,0);var h=a-o;n.left=Math.round(h)}s.style.marginLeft=n.left+"px",0!==n.left&&(n.right=-(i.width-r.width-n.left),s.style.marginRight=n.right+"px")}if(e){n.top=n.bottom=0;var r=s.getBoundingClientRect();if(this.height<i.height&&!this.incorrectOrientation){var o=r.top-i.y,a=i.height/2-this.height/2;a=Math.max(a,0);var h=a-o;n.top=Math.round(h)}s.style.marginTop=n.top+"px",0!==n.top&&(n.bottom=-(i.height-r.height-n.top),s.style.marginBottom=n.bottom+"px")}n.x=n.left,n.y=n.top},reflowGame:function(){this.resetCanvas("","");var t=this.getParentBounds(this._tempBounds);this.updateDimensions(t.width,t.height,!0)},reflowCanvas:function(){this.incorrectOrientation||(this.width=n.Math.clamp(this.width,this.minWidth||0,this.maxWidth||this.width),this.height=n.Math.clamp(this.height,this.minHeight||0,this.maxHeight||this.height)),this.resetCanvas(),this.compatibility.noMargins||(this.isFullScreen&&this._createdFullScreenTarget?this.alignCanvas(!0,!0):this.alignCanvas(this.pageAlignHorizontally,this.pageAlignVertically)),this.updateScalingAndBounds()},resetCanvas:function(t,e){void 0===t&&(t=this.width+"px"),void 0===e&&(e=this.height+"px");var i=this.game.canvas;this.compatibility.noMargins||(i.style.marginLeft="",i.style.marginTop="",i.style.marginRight="",i.style.marginBottom=""),i.style.width=t,i.style.height=e},queueUpdate:function(t){t&&(this._parentBounds.width=0,this._parentBounds.height=0),this._updateThrottle=this._updateThrottleReset},reset:function(t){t&&this.grid&&this.grid.reset()},setMaximum:function(){this.width=this.dom.visualBounds.width,this.height=this.dom.visualBounds.height},setShowAll:function(t){var e,i=this.getParentBounds(this._tempBounds),s=i.width,n=i.height;e=t?Math.max(n/this.game.height,s/this.game.width):Math.min(n/this.game.height,s/this.game.width),this.width=Math.round(this.game.width*e),this.height=Math.round(this.game.height*e)},setExactFit:function(){var t=this.getParentBounds(this._tempBounds);this.width=t.width,this.height=t.height,this.isFullScreen||(this.maxWidth&&(this.width=Math.min(this.width,this.maxWidth)),this.maxHeight&&(this.height=Math.min(this.height,this.maxHeight)))},createFullScreenTarget:function(){var t=document.createElement("div");return t.style.margin="0",t.style.padding="0",t.style.background="#000",t},startFullScreen:function(t,e){if(this.isFullScreen)return!1;if(!this.compatibility.supportsFullScreen){var i=this;return void setTimeout(function(){i.fullScreenError()},10)}if("when-not-mouse"===this.compatibility.clickTrampoline){var s=this.game.input;if(s.activePointer&&s.activePointer!==s.mousePointer&&(e||!1!==e))return void s.activePointer.addClickTrampoline("startFullScreen",this.startFullScreen,this,[t,!1])}void 0!==t&&this.game.renderType===n.CANVAS&&(this.game.stage.smoothed=t);var r=this.fullScreenTarget;r||(this.cleanupCreatedTarget(),this._createdFullScreenTarget=this.createFullScreenTarget(),r=this._createdFullScreenTarget);var o={targetElement:r};if(this.hasPhaserSetFullScreen=!0,this.onFullScreenInit.dispatch(this,o),this._createdFullScreenTarget){var a=this.game.canvas;a.parentNode.insertBefore(r,a),r.appendChild(a)}return this.game.device.fullscreenKeyboard?r[this.game.device.requestFullscreen](Element.ALLOW_KEYBOARD_INPUT):r[this.game.device.requestFullscreen](),!0},stopFullScreen:function(){return!(!this.isFullScreen||!this.compatibility.supportsFullScreen)&&(this.hasPhaserSetFullScreen=!1,document[this.game.device.cancelFullscreen](),!0)},cleanupCreatedTarget:function(){var t=this._createdFullScreenTarget;if(t&&t.parentNode){var e=t.parentNode;e.insertBefore(this.game.canvas,t),e.removeChild(t)}this._createdFullScreenTarget=null},prepScreenMode:function(t){var e=!!this._createdFullScreenTarget,i=this._createdFullScreenTarget||this.fullScreenTarget;t?(e||this.fullScreenScaleMode===n.ScaleManager.EXACT_FIT)&&i!==this.game.canvas&&(this._fullScreenRestore={targetWidth:i.style.width,targetHeight:i.style.height},i.style.width="100%",i.style.height="100%"):(this._fullScreenRestore&&(i.style.width=this._fullScreenRestore.targetWidth,i.style.height=this._fullScreenRestore.targetHeight,this._fullScreenRestore=null),this.updateDimensions(this._gameSize.width,this._gameSize.height,!0),this.resetCanvas())},fullScreenChange:function(t){this.event=t,this.isFullScreen?(this.prepScreenMode(!0),this.updateLayout(),this.queueUpdate(!0)):(this.prepScreenMode(!1),this.cleanupCreatedTarget(),this.updateLayout(),this.queueUpdate(!0)),this.onFullScreenChange.dispatch(this,this.width,this.height)},fullScreenError:function(t){this.event=t,this.cleanupCreatedTarget(),console.warn("Phaser.ScaleManager: requestFullscreen failed or device does not support the Fullscreen API"),this.onFullScreenError.dispatch(this)},scaleSprite:function(t,e,i,s){if(void 0===e&&(e=this.width),void 0===i&&(i=this.height),void 0===s&&(s=!1),!t||!t.scale)return t;if(t.scale.x=1,t.scale.y=1,t.width<=0||t.height<=0||e<=0||i<=0)return t;var n=e,r=t.height*e/t.width,o=t.width*i/t.height,a=i,h=o>e;return h=h?s:!s,h?(t.width=Math.floor(n),t.height=Math.floor(r)):(t.width=Math.floor(o),t.height=Math.floor(a)),t},destroy:function(){this.game.onResume.remove(this._gameResumed,this),window.removeEventListener("orientationchange",this._orientationChange,!1),window.removeEventListener("resize",this._windowResize,!1),this.compatibility.supportsFullScreen&&(document.removeEventListener("webkitfullscreenchange",this._fullScreenChange,!1),document.removeEventListener("mozfullscreenchange",this._fullScreenChange,!1),document.removeEventListener("MSFullscreenChange",this._fullScreenChange,!1),document.removeEventListener("fullscreenchange",this._fullScreenChange,!1),document.removeEventListener("webkitfullscreenerror",this._fullScreenError,!1),document.removeEventListener("mozfullscreenerror",this._fullScreenError,!1),document.removeEventListener("MSFullscreenError",this._fullScreenError,!1),document.removeEventListener("fullscreenerror",this._fullScreenError,!1))}},n.ScaleManager.prototype.constructor=n.ScaleManager,Object.defineProperty(n.ScaleManager.prototype,"boundingParent",{get:function(){return this.parentIsWindow||this.isFullScreen&&this.hasPhaserSetFullScreen&&!this._createdFullScreenTarget?null:this.game.canvas&&this.game.canvas.parentNode||null}}),Object.defineProperty(n.ScaleManager.prototype,"scaleMode",{get:function(){return this._scaleMode},set:function(t){return t!==this._scaleMode&&(this.isFullScreen||(this.updateDimensions(this._gameSize.width,this._gameSize.height,!0),this.queueUpdate(!0)),this._scaleMode=t),this._scaleMode}}),Object.defineProperty(n.ScaleManager.prototype,"fullScreenScaleMode",{get:function(){return this._fullScreenScaleMode},set:function(t){return t!==this._fullScreenScaleMode&&(this.isFullScreen?(this.prepScreenMode(!1),this._fullScreenScaleMode=t,this.prepScreenMode(!0),this.queueUpdate(!0)):this._fullScreenScaleMode=t),this._fullScreenScaleMode}}),Object.defineProperty(n.ScaleManager.prototype,"currentScaleMode",{get:function(){return this.isFullScreen?this._fullScreenScaleMode:this._scaleMode}}),Object.defineProperty(n.ScaleManager.prototype,"pageAlignHorizontally",{get:function(){return this._pageAlignHorizontally},set:function(t){t!==this._pageAlignHorizontally&&(this._pageAlignHorizontally=t,this.queueUpdate(!0))}}),Object.defineProperty(n.ScaleManager.prototype,"pageAlignVertically",{get:function(){return this._pageAlignVertically},set:function(t){t!==this._pageAlignVertically&&(this._pageAlignVertically=t,this.queueUpdate(!0))}}),Object.defineProperty(n.ScaleManager.prototype,"isFullScreen",{get:function(){return!!(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)}}),Object.defineProperty(n.ScaleManager.prototype,"isPortrait",{get:function(){return"portrait"===this.classifyOrientation(this.screenOrientation)}}),Object.defineProperty(n.ScaleManager.prototype,"isLandscape",{get:function(){return"landscape"===this.classifyOrientation(this.screenOrientation)}}),Object.defineProperty(n.ScaleManager.prototype,"isGamePortrait",{get:function(){return this.height>this.width}}),Object.defineProperty(n.ScaleManager.prototype,"isGameLandscape",{get:function(){return this.width>this.height}}),n.Utils.Debug=function(t){this.game=t,this.sprite=null,this.bmd=null,this.canvas=null,this.context=null,this.font="14px Courier",this.columnWidth=100,this.lineHeight=16,this.renderShadow=!0,this.currentX=0,this.currentY=0,this.currentAlpha=1,this.dirty=!1},n.Utils.Debug.prototype={boot:function(){this.game.renderType===n.CANVAS?this.context=this.game.context:(this.bmd=new n.BitmapData(this.game,"__DEBUG",this.game.width,this.game.height,!0),this.sprite=this.game.make.image(0,0,this.bmd),this.game.stage.addChild(this.sprite),this.game.scale.onSizeChange.add(this.resize,this),this.canvas=PIXI.CanvasPool.create(this,this.game.width,this.game.height),this.context=this.canvas.getContext("2d"))},resize:function(t,e,i){this.bmd.resize(e,i),this.canvas.width=e,this.canvas.height=i},preUpdate:function(){this.dirty&&this.sprite&&(this.bmd.clear(),this.bmd.draw(this.canvas,0,0),this.context.clearRect(0,0,this.game.width,this.game.height),this.dirty=!1)},reset:function(){this.context&&this.context.clearRect(0,0,this.game.width,this.game.height),this.sprite&&this.bmd.clear()},start:function(t,e,i,s){"number"!=typeof t&&(t=0),"number"!=typeof e&&(e=0),i=i||"rgb(255,255,255)",void 0===s&&(s=0),this.currentX=t,this.currentY=e,this.currentColor=i,this.columnWidth=s,this.dirty=!0,this.context.save(),this.context.setTransform(1,0,0,1,0,0),this.context.strokeStyle=i,this.context.fillStyle=i,this.context.font=this.font,this.context.globalAlpha=this.currentAlpha},stop:function(){this.context.restore()},line:function(){for(var t=this.currentX,e=0;e<arguments.length;e++)this.renderShadow&&(this.context.fillStyle="rgb(0,0,0)",this.context.fillText(arguments[e],t+1,this.currentY+1),this.context.fillStyle=this.currentColor),this.context.fillText(arguments[e],t,this.currentY),t+=this.columnWidth;this.currentY+=this.lineHeight},soundInfo:function(t,e,i,s){this.start(e,i,s),this.line("Sound: "+t.key+" Locked: "+t.game.sound.touchLocked),this.line("Is Ready?: "+this.game.cache.isSoundReady(t.key)+" Pending Playback: "+t.pendingPlayback),this.line("Decoded: "+t.isDecoded+" Decoding: "+t.isDecoding),this.line("Total Duration: "+t.totalDuration+" Playing: "+t.isPlaying),this.line("Time: "+t.currentTime),this.line("Volume: "+t.volume+" Muted: "+t.mute),this.line("WebAudio: "+t.usingWebAudio+" Audio: "+t.usingAudioTag),""!==t.currentMarker&&(this.line("Marker: "+t.currentMarker+" Duration: "+t.duration+" (ms: "+t.durationMS+")"),this.line("Start: "+t.markers[t.currentMarker].start+" Stop: "+t.markers[t.currentMarker].stop),this.line("Position: "+t.position)),this.stop()},cameraInfo:function(t,e,i,s){this.start(e,i,s),this.line("Camera ("+t.width+" x "+t.height+")"),this.line("X: "+t.x+" Y: "+t.y),t.bounds&&this.line("Bounds x: "+t.bounds.x+" Y: "+t.bounds.y+" w: "+t.bounds.width+" h: "+t.bounds.height),this.line("View x: "+t.view.x+" Y: "+t.view.y+" w: "+t.view.width+" h: "+t.view.height),this.line("Total in view: "+t.totalInView),this.stop()},timer:function(t,e,i,s){this.start(e,i,s),this.line("Timer (running: "+t.running+" expired: "+t.expired+")"),this.line("Next Tick: "+t.next+" Duration: "+t.duration),this.line("Paused: "+t.paused+" Length: "+t.length),this.stop()},pointer:function(t,e,i,s,n){null!=t&&(void 0===e&&(e=!1),i=i||"rgba(0,255,0,0.5)",s=s||"rgba(255,0,0,0.5)",!0===e&&!0===t.isUp||(this.start(t.x,t.y-100,n),this.context.beginPath(),this.context.arc(t.x,t.y,t.circle.radius,0,2*Math.PI),t.active?this.context.fillStyle=i:this.context.fillStyle=s,this.context.fill(),this.context.closePath(),this.context.beginPath(),this.context.moveTo(t.positionDown.x,t.positionDown.y),this.context.lineTo(t.position.x,t.position.y),this.context.lineWidth=2,this.context.stroke(),this.context.closePath(),this.line("ID: "+t.id+" Active: "+t.active),this.line("World X: "+t.worldX+" World Y: "+t.worldY),this.line("Screen X: "+t.x+" Screen Y: "+t.y+" In: "+t.withinGame),this.line("Duration: "+t.duration+" ms"),this.line("is Down: "+t.isDown+" is Up: "+t.isUp),this.stop()))},spriteInputInfo:function(t,e,i,s){this.start(e,i,s),this.line("Sprite Input: ("+t.width+" x "+t.height+")"),this.line("x: "+t.input.pointerX().toFixed(1)+" y: "+t.input.pointerY().toFixed(1)),this.line("over: "+t.input.pointerOver()+" duration: "+t.input.overDuration().toFixed(0)),this.line("down: "+t.input.pointerDown()+" duration: "+t.input.downDuration().toFixed(0)),this.line("just over: "+t.input.justOver()+" just out: "+t.input.justOut()),this.stop()},key:function(t,e,i,s){this.start(e,i,s,150),this.line("Key:",t.keyCode,"isDown:",t.isDown),this.line("justDown:",t.justDown,"justUp:",t.justUp),this.line("Time Down:",t.timeDown.toFixed(0),"duration:",t.duration.toFixed(0)),this.stop()},inputInfo:function(t,e,i){this.start(t,e,i),this.line("Input"),this.line("X: "+this.game.input.x+" Y: "+this.game.input.y),this.line("World X: "+this.game.input.worldX+" World Y: "+this.game.input.worldY),this.line("Scale X: "+this.game.input.scale.x.toFixed(1)+" Scale Y: "+this.game.input.scale.x.toFixed(1)),this.line("Screen X: "+this.game.input.activePointer.screenX+" Screen Y: "+this.game.input.activePointer.screenY),this.stop()},spriteBounds:function(t,e,i){var s=t.getBounds();s.x+=this.game.camera.x,s.y+=this.game.camera.y,this.rectangle(s,e,i)},ropeSegments:function(t,e,i){var s=this;t.segments.forEach(function(t){s.rectangle(t,e,i)},this)},spriteInfo:function(t,e,i,s){this.start(e,i,s),this.line("Sprite: ("+t.width+" x "+t.height+") anchor: "+t.anchor.x+" x "+t.anchor.y),this.line("x: "+t.x.toFixed(1)+" y: "+t.y.toFixed(1)),this.line("angle: "+t.angle.toFixed(1)+" rotation: "+t.rotation.toFixed(1)),this.line("visible: "+t.visible+" in camera: "+t.inCamera),this.line("bounds x: "+t._bounds.x.toFixed(1)+" y: "+t._bounds.y.toFixed(1)+" w: "+t._bounds.width.toFixed(1)+" h: "+t._bounds.height.toFixed(1)),this.stop()},spriteCoords:function(t,e,i,s){this.start(e,i,s,100),t.name&&this.line(t.name),this.line("x:",t.x.toFixed(2),"y:",t.y.toFixed(2)),this.line("pos x:",t.position.x.toFixed(2),"pos y:",t.position.y.toFixed(2)),this.line("world x:",t.world.x.toFixed(2),"world y:",t.world.y.toFixed(2)),this.stop()},lineInfo:function(t,e,i,s){this.start(e,i,s,80),this.line("start.x:",t.start.x.toFixed(2),"start.y:",t.start.y.toFixed(2)),this.line("end.x:",t.end.x.toFixed(2),"end.y:",t.end.y.toFixed(2)),this.line("length:",t.length.toFixed(2),"angle:",t.angle),this.stop()},pixel:function(t,e,i,s){s=s||2,this.start(),this.context.fillStyle=i,this.context.fillRect(t,e,s,s),this.stop()},geom:function(t,e,i,s){void 0===i&&(i=!0),void 0===s&&(s=0),e=e||"rgba(0,255,0,0.4)",this.start(),this.context.fillStyle=e,this.context.strokeStyle=e,t instanceof n.Rectangle||1===s?i?this.context.fillRect(t.x-this.game.camera.x,t.y-this.game.camera.y,t.width,t.height):this.context.strokeRect(t.x-this.game.camera.x,t.y-this.game.camera.y,t.width,t.height):t instanceof n.Circle||2===s?(this.context.beginPath(),this.context.arc(t.x-this.game.camera.x,t.y-this.game.camera.y,t.radius,0,2*Math.PI,!1),this.context.closePath(),i?this.context.fill():this.context.stroke()):t instanceof n.Point||3===s?this.context.fillRect(t.x-this.game.camera.x,t.y-this.game.camera.y,4,4):(t instanceof n.Line||4===s)&&(this.context.lineWidth=1,this.context.beginPath(),this.context.moveTo(t.start.x+.5-this.game.camera.x,t.start.y+.5-this.game.camera.y),this.context.lineTo(t.end.x+.5-this.game.camera.x,t.end.y+.5-this.game.camera.y),this.context.closePath(),this.context.stroke()),this.stop()},rectangle:function(t,e,i){void 0===i&&(i=!0),e=e||"rgba(0, 255, 0, 0.4)",this.start(),i?(this.context.fillStyle=e,this.context.fillRect(t.x-this.game.camera.x,t.y-this.game.camera.y,t.width,t.height)):(this.context.strokeStyle=e,this.context.strokeRect(t.x-this.game.camera.x,t.y-this.game.camera.y,t.width,t.height)),this.stop()},text:function(t,e,i,s,n){s=s||"rgb(255,255,255)",n=n||"16px Courier",this.start(),this.context.font=n,this.renderShadow&&(this.context.fillStyle="rgb(0,0,0)",this.context.fillText(t,e+1,i+1)),this.context.fillStyle=s,this.context.fillText(t,e,i),this.stop()},quadTree:function(t,e){e=e||"rgba(255,0,0,0.3)",this.start();var i=t.bounds;if(0===t.nodes.length){this.context.strokeStyle=e,this.context.strokeRect(i.x,i.y,i.width,i.height),this.text("size: "+t.objects.length,i.x+4,i.y+16,"rgb(0,200,0)","12px Courier"),this.context.strokeStyle="rgb(0,255,0)";for(var s=0;s<t.objects.length;s++)this.context.strokeRect(t.objects[s].x,t.objects[s].y,t.objects[s].width,t.objects[s].height)}else for(var s=0;s<t.nodes.length;s++)this.quadTree(t.nodes[s]);this.stop()},body:function(t,e,i){t.body&&(this.start(),t.body.type===n.Physics.ARCADE?n.Physics.Arcade.Body.render(this.context,t.body,e,i):t.body.type===n.Physics.NINJA?n.Physics.Ninja.Body.render(this.context,t.body,e,i):t.body.type===n.Physics.BOX2D&&n.Physics.Box2D.renderBody(this.context,t.body,e),this.stop())},bodyInfo:function(t,e,i,s){t.body&&(this.start(e,i,s,210),t.body.type===n.Physics.ARCADE?n.Physics.Arcade.Body.renderBodyInfo(this,t.body):t.body.type===n.Physics.BOX2D&&this.game.physics.box2d.renderBodyInfo(this,t.body),this.stop())},box2dWorld:function(){this.start(),this.context.translate(-this.game.camera.view.x,-this.game.camera.view.y,0),this.game.physics.box2d.renderDebugDraw(this.context),this.stop()},box2dBody:function(t,e){this.start(),n.Physics.Box2D.renderBody(this.context,t,e),this.stop()},displayList:function(t){if(void 0===t&&(t=this.game.world),t.hasOwnProperty("renderOrderID")?console.log("["+t.renderOrderID+"]",t):console.log("[]",t),t.children&&t.children.length>0)for(var e=0;e<t.children.length;e++)this.game.debug.displayList(t.children[e])},destroy:function(){PIXI.CanvasPool.remove(this)}},n.Utils.Debug.prototype.constructor=n.Utils.Debug,n.DOM={getOffset:function(t,e){e=e||new n.Point;var i=t.getBoundingClientRect(),s=n.DOM.scrollY,r=n.DOM.scrollX,o=document.documentElement.clientTop,a=document.documentElement.clientLeft;return e.x=i.left+r-a,e.y=i.top+s-o,e},getBounds:function(t,e){return void 0===e&&(e=0),!(!(t=t&&!t.nodeType?t[0]:t)||1!==t.nodeType)&&this.calibrate(t.getBoundingClientRect(),e)},calibrate:function(t,e){e=+e||0;var i={width:0,height:0,left:0,right:0,top:0,bottom:0};return i.width=(i.right=t.right+e)-(i.left=t.left-e),i.height=(i.bottom=t.bottom+e)-(i.top=t.top-e),i},getAspectRatio:function(t){t=null==t?this.visualBounds:1===t.nodeType?this.getBounds(t):t;var e=t.width,i=t.height;return"function"==typeof e&&(e=e.call(t)),"function"==typeof i&&(i=i.call(t)),e/i},inLayoutViewport:function(t,e){var i=this.getBounds(t,e);return!!i&&i.bottom>=0&&i.right>=0&&i.top<=this.layoutBounds.width&&i.left<=this.layoutBounds.height},getScreenOrientation:function(t){var e=window.screen,i=e.orientation||e.mozOrientation||e.msOrientation;if(i&&"string"==typeof i.type)return i.type;if("string"==typeof i)return i;var s="portrait-primary",n="landscape-primary";if("screen"===t)return e.height>e.width?s:n;if("viewport"===t)return this.visualBounds.height>this.visualBounds.width?s:n;if("window.orientation"===t&&"number"==typeof window.orientation)return 0===window.orientation||180===window.orientation?s:n;if(window.matchMedia){if(window.matchMedia("(orientation: portrait)").matches)return s;if(window.matchMedia("(orientation: landscape)").matches)return n}return this.visualBounds.height>this.visualBounds.width?s:n},visualBounds:new n.Rectangle,layoutBounds:new n.Rectangle,documentBounds:new n.Rectangle},n.Device.whenReady(function(t){var e=window&&"pageXOffset"in window?function(){return window.pageXOffset}:function(){return document.documentElement.scrollLeft},i=window&&"pageYOffset"in window?function(){return window.pageYOffset}:function(){return document.documentElement.scrollTop};if(Object.defineProperty(n.DOM,"scrollX",{get:e}),Object.defineProperty(n.DOM,"scrollY",{get:i}),Object.defineProperty(n.DOM.visualBounds,"x",{get:e}),Object.defineProperty(n.DOM.visualBounds,"y",{get:i}),Object.defineProperty(n.DOM.layoutBounds,"x",{value:0}),Object.defineProperty(n.DOM.layoutBounds,"y",{value:0}),t.desktop&&document.documentElement.clientWidth<=window.innerWidth&&document.documentElement.clientHeight<=window.innerHeight){var s=function(){return Math.max(window.innerWidth,document.documentElement.clientWidth)},r=function(){return Math.max(window.innerHeight,document.documentElement.clientHeight)};Object.defineProperty(n.DOM.visualBounds,"width",{get:s}),Object.defineProperty(n.DOM.visualBounds,"height",{get:r}),Object.defineProperty(n.DOM.layoutBounds,"width",{get:s}),Object.defineProperty(n.DOM.layoutBounds,"height",{get:r})}else Object.defineProperty(n.DOM.visualBounds,"width",{get:function(){return window.innerWidth}}),Object.defineProperty(n.DOM.visualBounds,"height",{get:function(){return window.innerHeight}}),Object.defineProperty(n.DOM.layoutBounds,"width",{get:function(){var t=document.documentElement.clientWidth,e=window.innerWidth;return t<e?e:t}}),Object.defineProperty(n.DOM.layoutBounds,"height",{get:function(){var t=document.documentElement.clientHeight,e=window.innerHeight;return t<e?e:t}});Object.defineProperty(n.DOM.documentBounds,"x",{value:0}),Object.defineProperty(n.DOM.documentBounds,"y",{value:0}),Object.defineProperty(n.DOM.documentBounds,"width",{get:function(){var t=document.documentElement;return Math.max(t.clientWidth,t.offsetWidth,t.scrollWidth)}}),Object.defineProperty(n.DOM.documentBounds,"height",{get:function(){var t=document.documentElement;return Math.max(t.clientHeight,t.offsetHeight,t.scrollHeight)}})},null,!0),n.ArraySet=function(t){this.position=0,this.list=t||[]},n.ArraySet.prototype={add:function(t){return this.exists(t)||this.list.push(t),t},getIndex:function(t){return this.list.indexOf(t)},getByKey:function(t,e){for(var i=this.list.length;i--;)if(this.list[i][t]===e)return this.list[i];return null},exists:function(t){return this.list.indexOf(t)>-1},reset:function(){this.list.length=0},remove:function(t){var e=this.list.indexOf(t);if(e>-1)return this.list.splice(e,1),t},setAll:function(t,e){for(var i=this.list.length;i--;)this.list[i]&&(this.list[i][t]=e)},callAll:function(t){for(var e=Array.prototype.slice.call(arguments,1),i=this.list.length;i--;)this.list[i]&&this.list[i][t]&&this.list[i][t].apply(this.list[i],e)},removeAll:function(t){void 0===t&&(t=!1);for(var e=this.list.length;e--;)if(this.list[e]){var i=this.remove(this.list[e]);t&&i.destroy()}this.position=0,this.list=[]}},Object.defineProperty(n.ArraySet.prototype,"total",{get:function(){return this.list.length}}),Object.defineProperty(n.ArraySet.prototype,"first",{get:function(){return this.position=0,this.list.length>0?this.list[0]:null}}),Object.defineProperty(n.ArraySet.prototype,"next",{get:function(){return this.position<this.list.length?(this.position++,this.list[this.position]):null}}),n.ArraySet.prototype.constructor=n.ArraySet,n.ArrayUtils={getRandomItem:function(t,e,i){if(null===t)return null;void 0===e&&(e=0),void 0===i&&(i=t.length);var s=e+Math.floor(Math.random()*i);return void 0===t[s]?null:t[s]},removeRandomItem:function(t,e,i){if(null==t)return null;void 0===e&&(e=0),void 0===i&&(i=t.length);var s=e+Math.floor(Math.random()*i);if(s<t.length){var n=t.splice(s,1);return void 0===n[0]?null:n[0]}return null},shuffle:function(t){for(var e=t.length-1;e>0;e--){var i=Math.floor(Math.random()*(e+1)),s=t[e];t[e]=t[i],t[i]=s}return t},transposeMatrix:function(t){for(var e=t.length,i=t[0].length,s=new Array(i),n=0;n<i;n++){s[n]=new Array(e);for(var r=e-1;r>-1;r--)s[n][r]=t[r][n]}return s},rotateMatrix:function(t,e){if("string"!=typeof e&&(e=(e%360+360)%360),90===e||-270===e||"rotateLeft"===e)t=n.ArrayUtils.transposeMatrix(t),t=t.reverse();else if(-90===e||270===e||"rotateRight"===e)t=t.reverse(),t=n.ArrayUtils.transposeMatrix(t);else if(180===Math.abs(e)||"rotate180"===e){for(var i=0;i<t.length;i++)t[i].reverse();t=t.reverse()}return t},findClosest:function(t,e){if(!e.length)return NaN;if(1===e.length||t<e[0])return e[0];for(var i=1;e[i]<t;)i++;var s=e[i-1],n=i<e.length?e[i]:Number.POSITIVE_INFINITY;return n-t<=t-s?n:s},rotateRight:function(t){var e=t.pop();return t.unshift(e),e},rotateLeft:function(t){var e=t.shift();return t.push(e),e},rotate:function(t){var e=t.shift();return t.push(e),e},numberArray:function(t,e){for(var i=[],s=t;s<=e;s++)i.push(s);return i},numberArrayStep:function(t,e,i){void 0!==t&&null!==t||(t=0),void 0!==e&&null!==e||(e=t,t=0),void 0===i&&(i=1);for(var s=[],r=Math.max(n.Math.roundAwayFromZero((e-t)/(i||1)),0),o=0;o<r;o++)s.push(t),t+=i;return s}},n.LinkedList=function(){this.next=null,this.prev=null,this.first=null,this.last=null,this.total=0},n.LinkedList.prototype={add:function(t){return 0===this.total&&null===this.first&&null===this.last?(this.first=t,this.last=t,this.next=t,t.prev=this,this.total++,t):(this.last.next=t,t.prev=this.last,this.last=t,this.total++,t)},reset:function(){this.first=null,this.last=null,this.next=null,this.prev=null,this.total=0},remove:function(t){if(1===this.total)return this.reset(),void(t.next=t.prev=null);t===this.first?this.first=this.first.next:t===this.last&&(this.last=this.last.prev),t.prev&&(t.prev.next=t.next),t.next&&(t.next.prev=t.prev),t.next=t.prev=null,null===this.first&&(this.last=null),this.total--},callAll:function(t){if(this.first&&this.last){var e=this.first;do{e&&e[t]&&e[t].call(e),e=e.next}while(e!==this.last.next)}}},n.LinkedList.prototype.constructor=n.LinkedList,n.Create=function(t){this.game=t,this.bmd=null,this.canvas=null,this.ctx=null,this.palettes=[{0:"#000",1:"#9D9D9D",2:"#FFF",3:"#BE2633",4:"#E06F8B",5:"#493C2B",6:"#A46422",7:"#EB8931",8:"#F7E26B",9:"#2F484E",A:"#44891A",B:"#A3CE27",C:"#1B2632",D:"#005784",E:"#31A2F2",F:"#B2DCEF"},{0:"#000",1:"#191028",2:"#46af45",3:"#a1d685",4:"#453e78",5:"#7664fe",6:"#833129",7:"#9ec2e8",8:"#dc534b",9:"#e18d79",A:"#d6b97b",B:"#e9d8a1",C:"#216c4b",D:"#d365c8",E:"#afaab9",F:"#f5f4eb"},{0:"#000",1:"#2234d1",2:"#0c7e45",3:"#44aacc",4:"#8a3622",5:"#5c2e78",6:"#aa5c3d",7:"#b5b5b5",8:"#5e606e",9:"#4c81fb",A:"#6cd947",B:"#7be2f9",C:"#eb8a60",D:"#e23d69",E:"#ffd93f",F:"#fff"},{0:"#000",1:"#fff",2:"#8b4131",3:"#7bbdc5",4:"#8b41ac",5:"#6aac41",6:"#3931a4",7:"#d5de73",8:"#945a20",9:"#5a4100",A:"#bd736a",B:"#525252",C:"#838383",D:"#acee8b",E:"#7b73de",F:"#acacac"},{0:"#000",1:"#191028",2:"#46af45",3:"#a1d685",4:"#453e78",5:"#7664fe",6:"#833129",7:"#9ec2e8",8:"#dc534b",9:"#e18d79",A:"#d6b97b",B:"#e9d8a1",C:"#216c4b",D:"#d365c8",E:"#afaab9",F:"#fff"}]},n.Create.PALETTE_ARNE=0,n.Create.PALETTE_JMP=1,n.Create.PALETTE_CGA=2,n.Create.PALETTE_C64=3,n.Create.PALETTE_JAPANESE_MACHINE=4,n.Create.prototype={texture:function(t,e,i,s,n){void 0===i&&(i=8),void 0===s&&(s=i),void 0===n&&(n=0);var r=e[0].length*i,o=e.length*s;null===this.bmd&&(this.bmd=this.game.make.bitmapData(),this.canvas=this.bmd.canvas,this.ctx=this.bmd.context),this.bmd.resize(r,o),this.bmd.clear();for(var a=0;a<e.length;a++)for(var h=e[a],l=0;l<h.length;l++){var c=h[l];"."!==c&&" "!==c&&(this.ctx.fillStyle=this.palettes[n][c],this.ctx.fillRect(l*i,a*s,i,s))}return this.bmd.generateTexture(t)},grid:function(t,e,i,s,n,r){null===this.bmd&&(this.bmd=this.game.make.bitmapData(),this.canvas=this.bmd.canvas,this.ctx=this.bmd.context),this.bmd.resize(e,i),this.ctx.fillStyle=r;for(var o=0;o<i;o+=n)this.ctx.fillRect(0,o,e,1);for(var a=0;a<e;a+=s)this.ctx.fillRect(a,0,1,i);return this.bmd.generateTexture(t)}},n.Create.prototype.constructor=n.Create,n.FlexGrid=function(t,e,i){this.game=t.game,this.manager=t,this.width=e,this.height=i,this.boundsCustom=new n.Rectangle(0,0,e,i),this.boundsFluid=new n.Rectangle(0,0,e,i),this.boundsFull=new n.Rectangle(0,0,e,i),this.boundsNone=new n.Rectangle(0,0,e,i),this.positionCustom=new n.Point(0,0),this.positionFluid=new n.Point(0,0),this.positionFull=new n.Point(0,0),this.positionNone=new n.Point(0,0),this.scaleCustom=new n.Point(1,1),this.scaleFluid=new n.Point(1,1),this.scaleFluidInversed=new n.Point(1,1),this.scaleFull=new n.Point(1,1),this.scaleNone=new n.Point(1,1),this.customWidth=0,this.customHeight=0,this.customOffsetX=0,this.customOffsetY=0,this.ratioH=e/i,this.ratioV=i/e,this.multiplier=0,this.layers=[]},n.FlexGrid.prototype={setSize:function(t,e){this.width=t,this.height=e,this.ratioH=t/e,this.ratioV=e/t,this.scaleNone=new n.Point(1,1),this.boundsNone.width=this.width,this.boundsNone.height=this.height,this.refresh()},createCustomLayer:function(t,e,i,s){void 0===s&&(s=!0),this.customWidth=t,this.customHeight=e,this.boundsCustom.width=t,this.boundsCustom.height=e;var r=new n.FlexLayer(this,this.positionCustom,this.boundsCustom,this.scaleCustom);return s&&this.game.world.add(r),this.layers.push(r),void 0!==i&&null!==typeof i&&r.addMultiple(i),r},createFluidLayer:function(t,e){void 0===e&&(e=!0);var i=new n.FlexLayer(this,this.positionFluid,this.boundsFluid,this.scaleFluid);return e&&this.game.world.add(i),this.layers.push(i),void 0!==t&&null!==typeof t&&i.addMultiple(t),i},createFullLayer:function(t){var e=new n.FlexLayer(this,this.positionFull,this.boundsFull,this.scaleFluid);return this.game.world.add(e),this.layers.push(e),void 0!==t&&e.addMultiple(t),e},createFixedLayer:function(t){var e=new n.FlexLayer(this,this.positionNone,this.boundsNone,this.scaleNone);return this.game.world.add(e),this.layers.push(e),void 0!==t&&e.addMultiple(t),e},reset:function(){for(var t=this.layers.length;t--;)this.layers[t].persist||(this.layers[t].position=null,this.layers[t].scale=null,this.layers.slice(t,1))},onResize:function(t,e){this.ratioH=t/e,this.ratioV=e/t,this.refresh(t,e)},refresh:function(){this.multiplier=Math.min(this.manager.height/this.height,this.manager.width/this.width),this.boundsFluid.width=Math.round(this.width*this.multiplier),this.boundsFluid.height=Math.round(this.height*this.multiplier),this.scaleFluid.set(this.boundsFluid.width/this.width,this.boundsFluid.height/this.height),this.scaleFluidInversed.set(this.width/this.boundsFluid.width,this.height/this.boundsFluid.height),this.scaleFull.set(this.boundsFull.width/this.width,this.boundsFull.height/this.height),this.boundsFull.width=Math.round(this.manager.width*this.scaleFluidInversed.x),this.boundsFull.height=Math.round(this.manager.height*this.scaleFluidInversed.y),this.boundsFluid.centerOn(this.manager.bounds.centerX,this.manager.bounds.centerY),this.boundsNone.centerOn(this.manager.bounds.centerX,this.manager.bounds.centerY),this.positionFluid.set(this.boundsFluid.x,this.boundsFluid.y),this.positionNone.set(this.boundsNone.x,this.boundsNone.y)},fitSprite:function(t){this.manager.scaleSprite(t),t.x=this.manager.bounds.centerX,t.y=this.manager.bounds.centerY},debug:function(){this.game.debug.text(this.boundsFluid.width+" x "+this.boundsFluid.height,this.boundsFluid.x+4,this.boundsFluid.y+16),this.game.debug.geom(this.boundsFluid,"rgba(255,0,0,0.9",!1)}},n.FlexGrid.prototype.constructor=n.FlexGrid,n.FlexLayer=function(t,e,i,s){n.Group.call(this,t.game,null,"__flexLayer"+t.game.rnd.uuid(),!1),this.manager=t.manager,this.grid=t,this.persist=!1,this.position=e,this.bounds=i,this.scale=s,this.topLeft=i.topLeft,this.topMiddle=new n.Point(i.halfWidth,0),this.topRight=i.topRight,this.bottomLeft=i.bottomLeft,this.bottomMiddle=new n.Point(i.halfWidth,i.bottom),this.bottomRight=i.bottomRight},n.FlexLayer.prototype=Object.create(n.Group.prototype),n.FlexLayer.prototype.constructor=n.FlexLayer,n.FlexLayer.prototype.resize=function(){},n.FlexLayer.prototype.debug=function(){this.game.debug.text(this.bounds.width+" x "+this.bounds.height,this.bounds.x+4,this.bounds.y+16),this.game.debug.geom(this.bounds,"rgba(0,0,255,0.9",!1),this.game.debug.geom(this.topLeft,"rgba(255,255,255,0.9"),this.game.debug.geom(this.topMiddle,"rgba(255,255,255,0.9"),this.game.debug.geom(this.topRight,"rgba(255,255,255,0.9")},n.Color={packPixel:function(t,e,i,s){return n.Device.LITTLE_ENDIAN?(s<<24|i<<16|e<<8|t)>>>0:(t<<24|e<<16|i<<8|s)>>>0},unpackPixel:function(t,e,i,s){return void 0!==e&&null!==e||(e=n.Color.createColor()),void 0!==i&&null!==i||(i=!1),void 0!==s&&null!==s||(s=!1),n.Device.LITTLE_ENDIAN?(e.a=(4278190080&t)>>>24,e.b=(16711680&t)>>>16,e.g=(65280&t)>>>8,e.r=255&t):(e.r=(4278190080&t)>>>24,e.g=(16711680&t)>>>16,e.b=(65280&t)>>>8,e.a=255&t),e.color=t,e.rgba="rgba("+e.r+","+e.g+","+e.b+","+e.a/255+")",i&&n.Color.RGBtoHSL(e.r,e.g,e.b,e),s&&n.Color.RGBtoHSV(e.r,e.g,e.b,e),e},fromRGBA:function(t,e){return e||(e=n.Color.createColor()),e.r=(4278190080&t)>>>24,e.g=(16711680&t)>>>16,e.b=(65280&t)>>>8,e.a=255&t,e.rgba="rgba("+e.r+","+e.g+","+e.b+","+e.a+")",e},toRGBA:function(t,e,i,s){return t<<24|e<<16|i<<8|s},toABGR:function(t,e,i,s){return(s<<24|i<<16|e<<8|t)>>>0},RGBtoHSL:function(t,e,i,s){s||(s=n.Color.createColor(t,e,i,1)),t/=255,e/=255,i/=255;var r=Math.min(t,e,i),o=Math.max(t,e,i);if(s.h=0,s.s=0,s.l=(o+r)/2,o!==r){var a=o-r;s.s=s.l>.5?a/(2-o-r):a/(o+r),o===t?s.h=(e-i)/a+(e<i?6:0):o===e?s.h=(i-t)/a+2:o===i&&(s.h=(t-e)/a+4),s.h/=6}return s},HSLtoRGB:function(t,e,i,s){if(s?(s.r=i,s.g=i,s.b=i):s=n.Color.createColor(i,i,i),0!==e){var r=i<.5?i*(1+e):i+e-i*e,o=2*i-r;s.r=n.Color.hueToColor(o,r,t+1/3),s.g=n.Color.hueToColor(o,r,t),s.b=n.Color.hueToColor(o,r,t-1/3)}return s.r=Math.floor(255*s.r|0),s.g=Math.floor(255*s.g|0),s.b=Math.floor(255*s.b|0),n.Color.updateColor(s),s},RGBtoHSV:function(t,e,i,s){s||(s=n.Color.createColor(t,e,i,255)),t/=255,e/=255,i/=255;var r=Math.min(t,e,i),o=Math.max(t,e,i),a=o-r;return s.h=0,s.s=0===o?0:a/o,s.v=o,o!==r&&(o===t?s.h=(e-i)/a+(e<i?6:0):o===e?s.h=(i-t)/a+2:o===i&&(s.h=(t-e)/a+4),s.h/=6),s},HSVtoRGB:function(t,e,i,s){void 0===s&&(s=n.Color.createColor(0,0,0,1,t,e,0,i));var r,o,a,h=Math.floor(6*t),l=6*t-h,c=i*(1-e),u=i*(1-l*e),d=i*(1-(1-l)*e);switch(h%6){case 0:r=i,o=d,a=c;break;case 1:r=u,o=i,a=c;break;case 2:r=c,o=i,a=d;break;case 3:r=c,o=u,a=i;break;case 4:r=d,o=c,a=i;break;case 5:r=i,o=c,a=u}return s.r=Math.floor(255*r),s.g=Math.floor(255*o),s.b=Math.floor(255*a),n.Color.updateColor(s),s},hueToColor:function(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t},createColor:function(t,e,i,s,r,o,a,h){var l={r:t||0,g:e||0,b:i||0,a:s||1,h:r||0,s:o||0,l:a||0,v:h||0,color:0,color32:0,rgba:""};return n.Color.updateColor(l)},updateColor:function(t){return t.rgba="rgba("+t.r.toString()+","+t.g.toString()+","+t.b.toString()+","+t.a.toString()+")",t.color=n.Color.getColor(t.r,t.g,t.b),t.color32=n.Color.getColor32(255*t.a,t.r,t.g,t.b),t},getColor32:function(t,e,i,s){return t<<24|e<<16|i<<8|s},getColor:function(t,e,i){return t<<16|e<<8|i},RGBtoString:function(t,e,i,s,r){return void 0===s&&(s=255),void 0===r&&(r="#"),"#"===r?"#"+((1<<24)+(t<<16)+(e<<8)+i).toString(16).slice(1):"0x"+n.Color.componentToHex(s)+n.Color.componentToHex(t)+n.Color.componentToHex(e)+n.Color.componentToHex(i)},hexToRGB:function(t){var e=n.Color.hexToColor(t);if(e)return n.Color.getColor32(e.a,e.r,e.g,e.b)},hexToColor:function(t,e){t=t.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i,function(t,e,i,s){return e+e+i+i+s+s});var i=/^(?:#|0x)?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);if(i){var s=parseInt(i[1],16),r=parseInt(i[2],16),o=parseInt(i[3],16);e?(e.r=s,e.g=r,e.b=o):e=n.Color.createColor(s,r,o)}return e},webToColor:function(t,e){e||(e=n.Color.createColor());var i=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?))?\s*\)$/.exec(t);return i&&(e.r=parseInt(i[1],10),e.g=parseInt(i[2],10),e.b=parseInt(i[3],10),e.a=void 0!==i[4]?parseFloat(i[4]):1,n.Color.updateColor(e)),e},valueToColor:function(t,e){if(e||(e=n.Color.createColor()),"string"==typeof t)return 0===t.indexOf("rgb")?n.Color.webToColor(t,e):(e.a=1,n.Color.hexToColor(t,e));if("number"==typeof t){var i=n.Color.getRGB(t);return e.r=i.r,e.g=i.g,e.b=i.b,e.a=i.a/255,e}return e},componentToHex:function(t){var e=t.toString(16);return 1===e.length?"0"+e:e},HSVColorWheel:function(t,e){void 0===t&&(t=1),void 0===e&&(e=1);for(var i=[],s=0;s<=359;s++)i.push(n.Color.HSVtoRGB(s/359,t,e));return i},HSLColorWheel:function(t,e){void 0===t&&(t=.5),void 0===e&&(e=.5);for(var i=[],s=0;s<=359;s++)i.push(n.Color.HSLtoRGB(s/359,t,e));return i},interpolateColor:function(t,e,i,s,r){void 0===r&&(r=255);var o=n.Color.getRGB(t),a=n.Color.getRGB(e),h=(a.red-o.red)*s/i+o.red,l=(a.green-o.green)*s/i+o.green,c=(a.blue-o.blue)*s/i+o.blue;return n.Color.getColor32(r,h,l,c)},interpolateColorWithRGB:function(t,e,i,s,r,o){var a=n.Color.getRGB(t),h=(e-a.red)*o/r+a.red,l=(i-a.green)*o/r+a.green,c=(s-a.blue)*o/r+a.blue;return n.Color.getColor(h,l,c)},interpolateRGB:function(t,e,i,s,r,o,a,h){var l=(s-t)*h/a+t,c=(r-e)*h/a+e,u=(o-i)*h/a+i;return n.Color.getColor(l,c,u)},getRandomColor:function(t,e,i){if(void 0===t&&(t=0),void 0===e&&(e=255),void 0===i&&(i=255),e>255||t>e)return n.Color.getColor(255,255,255);var s=t+Math.round(Math.random()*(e-t)),r=t+Math.round(Math.random()*(e-t)),o=t+Math.round(Math.random()*(e-t));return n.Color.getColor32(i,s,r,o)},getRGB:function(t){return t>16777215?{alpha:t>>>24,red:t>>16&255,green:t>>8&255,blue:255&t,a:t>>>24,r:t>>16&255,g:t>>8&255,b:255&t}:{alpha:255,red:t>>16&255,green:t>>8&255,blue:255&t,a:255,r:t>>16&255,g:t>>8&255,b:255&t}},getWebRGB:function(t){if("object"==typeof t)return"rgba("+t.r.toString()+","+t.g.toString()+","+t.b.toString()+","+(t.a/255).toString()+")";var e=n.Color.getRGB(t);return"rgba("+e.r.toString()+","+e.g.toString()+","+e.b.toString()+","+(e.a/255).toString()+")"},getAlpha:function(t){return t>>>24},getAlphaFloat:function(t){return(t>>>24)/255},getRed:function(t){return t>>16&255},getGreen:function(t){return t>>8&255},getBlue:function(t){return 255&t},blendNormal:function(t){return t},blendLighten:function(t,e){return e>t?e:t},blendDarken:function(t,e){return e>t?t:e},blendMultiply:function(t,e){return t*e/255},blendAverage:function(t,e){return(t+e)/2},blendAdd:function(t,e){return Math.min(255,t+e)},blendSubtract:function(t,e){return Math.max(0,t+e-255)},blendDifference:function(t,e){return Math.abs(t-e)},blendNegation:function(t,e){return 255-Math.abs(255-t-e)},blendScreen:function(t,e){return 255-((255-t)*(255-e)>>8)},blendExclusion:function(t,e){return t+e-2*t*e/255},blendOverlay:function(t,e){return e<128?2*t*e/255:255-2*(255-t)*(255-e)/255},blendSoftLight:function(t,e){return e<128?2*(64+(t>>1))*(e/255):255-2*(255-(64+(t>>1)))*(255-e)/255},blendHardLight:function(t,e){return n.Color.blendOverlay(e,t)},blendColorDodge:function(t,e){return 255===e?e:Math.min(255,(t<<8)/(255-e))},blendColorBurn:function(t,e){return 0===e?e:Math.max(0,255-(255-t<<8)/e)},blendLinearDodge:function(t,e){return n.Color.blendAdd(t,e)},blendLinearBurn:function(t,e){return n.Color.blendSubtract(t,e)},blendLinearLight:function(t,e){return e<128?n.Color.blendLinearBurn(t,2*e):n.Color.blendLinearDodge(t,2*(e-128))},blendVividLight:function(t,e){return e<128?n.Color.blendColorBurn(t,2*e):n.Color.blendColorDodge(t,2*(e-128))},blendPinLight:function(t,e){return e<128?n.Color.blendDarken(t,2*e):n.Color.blendLighten(t,2*(e-128))},blendHardMix:function(t,e){return n.Color.blendVividLight(t,e)<128?0:255},blendReflect:function(t,e){return 255===e?e:Math.min(255,t*t/(255-e))},blendGlow:function(t,e){return n.Color.blendReflect(e,t)},blendPhoenix:function(t,e){return Math.min(t,e)-Math.max(t,e)+255}},n.Physics=function(t,e){e=e||{},this.game=t,this.config=e,this.arcade=null,this.p2=null,this.ninja=null,this.box2d=null,this.chipmunk=null,this.matter=null,this.parseConfig()},n.Physics.ARCADE=0,n.Physics.P2JS=1,n.Physics.NINJA=2,n.Physics.BOX2D=3,n.Physics.CHIPMUNK=4,n.Physics.MATTERJS=5,n.Physics.prototype={parseConfig:function(){this.config.hasOwnProperty("arcade")&&!0!==this.config.arcade||!n.Physics.hasOwnProperty("Arcade")||(this.arcade=new n.Physics.Arcade(this.game)),this.config.hasOwnProperty("ninja")&&!0===this.config.ninja&&n.Physics.hasOwnProperty("Ninja")&&(this.ninja=new n.Physics.Ninja(this.game)),this.config.hasOwnProperty("p2")&&!0===this.config.p2&&n.Physics.hasOwnProperty("P2")&&(this.p2=new n.Physics.P2(this.game,this.config)),this.config.hasOwnProperty("box2d")&&!0===this.config.box2d&&n.Physics.hasOwnProperty("BOX2D")&&(this.box2d=new n.Physics.BOX2D(this.game,this.config)),this.config.hasOwnProperty("matter")&&!0===this.config.matter&&n.Physics.hasOwnProperty("Matter")&&(this.matter=new n.Physics.Matter(this.game,this.config))},startSystem:function(t){t===n.Physics.ARCADE?this.arcade=new n.Physics.Arcade(this.game):t===n.Physics.P2JS?null===this.p2?this.p2=new n.Physics.P2(this.game,this.config):this.p2.reset():t===n.Physics.NINJA?this.ninja=new n.Physics.Ninja(this.game):t===n.Physics.BOX2D?null===this.box2d?this.box2d=new n.Physics.Box2D(this.game,this.config):this.box2d.reset():t===n.Physics.MATTERJS&&(null===this.matter?this.matter=new n.Physics.Matter(this.game,this.config):this.matter.reset())},enable:function(t,e,i){void 0===e&&(e=n.Physics.ARCADE),void 0===i&&(i=!1),e===n.Physics.ARCADE?this.arcade.enable(t):e===n.Physics.P2JS&&this.p2?this.p2.enable(t,i):e===n.Physics.NINJA&&this.ninja?this.ninja.enableAABB(t):e===n.Physics.BOX2D&&this.box2d?this.box2d.enable(t):e===n.Physics.MATTERJS&&this.matter?this.matter.enable(t):console.warn(t.key+" is attempting to enable a physics body using an unknown physics system.")},preUpdate:function(){this.p2&&this.p2.preUpdate(),this.box2d&&this.box2d.preUpdate(),this.matter&&this.matter.preUpdate()},update:function(){this.p2&&this.p2.update(),this.box2d&&this.box2d.update(),this.matter&&this.matter.update()},setBoundsToWorld:function(){this.arcade&&this.arcade.setBoundsToWorld(),this.ninja&&this.ninja.setBoundsToWorld(),this.p2&&this.p2.setBoundsToWorld(),this.box2d&&this.box2d.setBoundsToWorld(),this.matter&&this.matter.setBoundsToWorld()},clear:function(){this.p2&&this.p2.clear(),this.box2d&&this.box2d.clear(),this.matter&&this.matter.clear()},reset:function(){this.p2&&this.p2.reset(),this.box2d&&this.box2d.reset(),this.matter&&this.matter.reset()},destroy:function(){this.p2&&this.p2.destroy(),this.box2d&&this.box2d.destroy(),this.matter&&this.matter.destroy(),this.arcade=null,this.ninja=null,this.p2=null,this.box2d=null,this.matter=null}},n.Physics.prototype.constructor=n.Physics,n.Physics.Arcade=function(t){this.game=t,this.gravity=new n.Point,this.bounds=new n.Rectangle(0,0,t.world.width,t.world.height),this.checkCollision={up:!0,down:!0,left:!0,right:!0},this.maxObjects=10,this.maxLevels=4,this.OVERLAP_BIAS=4,this.forceX=!1,this.sortDirection=n.Physics.Arcade.LEFT_RIGHT,this.skipQuadTree=!0,this.isPaused=!1,this.quadTree=new n.QuadTree(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height,this.maxObjects,this.maxLevels),this._total=0,this.setBoundsToWorld()},n.Physics.Arcade.prototype.constructor=n.Physics.Arcade,n.Physics.Arcade.SORT_NONE=0,n.Physics.Arcade.LEFT_RIGHT=1,n.Physics.Arcade.RIGHT_LEFT=2,n.Physics.Arcade.TOP_BOTTOM=3,n.Physics.Arcade.BOTTOM_TOP=4,n.Physics.Arcade.prototype={setBounds:function(t,e,i,s){this.bounds.setTo(t,e,i,s)},setBoundsToWorld:function(){this.bounds.copyFrom(this.game.world.bounds)},enable:function(t,e){void 0===e&&(e=!0);var i=1;if(Array.isArray(t))for(i=t.length;i--;)t[i]instanceof n.Group?this.enable(t[i].children,e):(this.enableBody(t[i]),e&&t[i].hasOwnProperty("children")&&t[i].children.length>0&&this.enable(t[i],!0));else t instanceof n.Group?this.enable(t.children,e):(this.enableBody(t),e&&t.hasOwnProperty("children")&&t.children.length>0&&this.enable(t.children,!0))},enableBody:function(t){t.hasOwnProperty("body")&&null===t.body&&(t.body=new n.Physics.Arcade.Body(t),t.parent&&t.parent instanceof n.Group&&t.parent.addToHash(t))},updateMotion:function(t){var e=this.computeVelocity(0,t,t.angularVelocity,t.angularAcceleration,t.angularDrag,t.maxAngular)-t.angularVelocity;t.angularVelocity+=e,t.rotation+=t.angularVelocity*this.game.time.physicsElapsed,t.velocity.x=this.computeVelocity(1,t,t.velocity.x,t.acceleration.x,t.drag.x,t.maxVelocity.x),t.velocity.y=this.computeVelocity(2,t,t.velocity.y,t.acceleration.y,t.drag.y,t.maxVelocity.y)},computeVelocity:function(t,e,i,s,n,r){return void 0===r&&(r=1e4),1===t&&e.allowGravity?i+=(this.gravity.x+e.gravity.x)*this.game.time.physicsElapsed:2===t&&e.allowGravity&&(i+=(this.gravity.y+e.gravity.y)*this.game.time.physicsElapsed),s?i+=s*this.game.time.physicsElapsed:n&&(n*=this.game.time.physicsElapsed,i-n>0?i-=n:i+n<0?i+=n:i=0),i>r?i=r:i<-r&&(i=-r),i},overlap:function(t,e,i,s,n){if(i=i||null,s=s||null,n=n||i,this._total=0,!Array.isArray(t)&&Array.isArray(e))for(var r=0;r<e.length;r++)this.collideHandler(t,e[r],i,s,n,!0);else if(Array.isArray(t)&&!Array.isArray(e))for(var r=0;r<t.length;r++)this.collideHandler(t[r],e,i,s,n,!0);else if(Array.isArray(t)&&Array.isArray(e))for(var r=0;r<t.length;r++)for(var o=0;o<e.length;o++)this.collideHandler(t[r],e[o],i,s,n,!0);else this.collideHandler(t,e,i,s,n,!0);return this._total>0},collide:function(t,e,i,s,n){if(i=i||null,s=s||null,n=n||i,this._total=0,!Array.isArray(t)&&Array.isArray(e))for(var r=0;r<e.length;r++)this.collideHandler(t,e[r],i,s,n,!1);else if(Array.isArray(t)&&!Array.isArray(e))for(var r=0;r<t.length;r++)this.collideHandler(t[r],e,i,s,n,!1);else if(Array.isArray(t)&&Array.isArray(e))for(var r=0;r<t.length;r++)for(var o=0;o<e.length;o++)this.collideHandler(t[r],e[o],i,s,n,!1);else this.collideHandler(t,e,i,s,n,!1);return this._total>0},sortLeftRight:function(t,e){return t.body&&e.body?t.body.x-e.body.x:0},sortRightLeft:function(t,e){return t.body&&e.body?e.body.x-t.body.x:0},sortTopBottom:function(t,e){return t.body&&e.body?t.body.y-e.body.y:0},sortBottomTop:function(t,e){return t.body&&e.body?e.body.y-t.body.y:0},sort:function(t,e){null!==t.physicsSortDirection?e=t.physicsSortDirection:void 0===e&&(e=this.sortDirection),e===n.Physics.Arcade.LEFT_RIGHT?t.hash.sort(this.sortLeftRight):e===n.Physics.Arcade.RIGHT_LEFT?t.hash.sort(this.sortRightLeft):e===n.Physics.Arcade.TOP_BOTTOM?t.hash.sort(this.sortTopBottom):e===n.Physics.Arcade.BOTTOM_TOP&&t.hash.sort(this.sortBottomTop)},collideHandler:function(t,e,i,s,r,o){if(void 0===e&&t.physicsType===n.GROUP)return this.sort(t),void this.collideGroupVsSelf(t,i,s,r,o);t&&e&&t.exists&&e.exists&&(this.sortDirection!==n.Physics.Arcade.SORT_NONE&&(t.physicsType===n.GROUP&&this.sort(t),e.physicsType===n.GROUP&&this.sort(e)),t.physicsType===n.SPRITE?e.physicsType===n.SPRITE?this.collideSpriteVsSprite(t,e,i,s,r,o):e.physicsType===n.GROUP?this.collideSpriteVsGroup(t,e,i,s,r,o):e.physicsType===n.TILEMAPLAYER&&this.collideSpriteVsTilemapLayer(t,e,i,s,r,o):t.physicsType===n.GROUP?e.physicsType===n.SPRITE?this.collideSpriteVsGroup(e,t,i,s,r,o):e.physicsType===n.GROUP?this.collideGroupVsGroup(t,e,i,s,r,o):e.physicsType===n.TILEMAPLAYER&&this.collideGroupVsTilemapLayer(t,e,i,s,r,o):t.physicsType===n.TILEMAPLAYER&&(e.physicsType===n.SPRITE?this.collideSpriteVsTilemapLayer(e,t,i,s,r,o):e.physicsType===n.GROUP&&this.collideGroupVsTilemapLayer(e,t,i,s,r,o)))},collideSpriteVsSprite:function(t,e,i,s,n,r){return!(!t.body||!e.body)&&(this.separate(t.body,e.body,s,n,r)&&(i&&i.call(n,t,e),this._total++),!0)},collideSpriteVsGroup:function(t,e,i,s,r,o){if(0!==e.length&&t.body)if(this.skipQuadTree||t.body.skipQuadTree)for(var a={},h=0;h<e.hash.length;h++){var l=e.hash[h];if(l&&l.exists&&l.body){if(a=l.body.getBounds(a),this.sortDirection===n.Physics.Arcade.LEFT_RIGHT){if(t.body.right<a.x)break;if(a.right<t.body.x)continue}else if(this.sortDirection===n.Physics.Arcade.RIGHT_LEFT){if(t.body.x>a.right)break;if(a.x>t.body.right)continue}else if(this.sortDirection===n.Physics.Arcade.TOP_BOTTOM){if(t.body.bottom<a.y)break;if(a.bottom<t.body.y)continue}else if(this.sortDirection===n.Physics.Arcade.BOTTOM_TOP){if(t.body.y>a.bottom)break;if(a.y>t.body.bottom)continue}this.collideSpriteVsSprite(t,l,i,s,r,o)}}else{this.quadTree.clear(),this.quadTree.reset(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height,this.maxObjects,this.maxLevels),this.quadTree.populate(e);for(var c=this.quadTree.retrieve(t),h=0;h<c.length;h++)this.separate(t.body,c[h],s,r,o)&&(i&&i.call(r,t,c[h].sprite),this._total++)}},collideGroupVsSelf:function(t,e,i,s,r){if(0!==t.length)for(var o=0;o<t.hash.length;o++){var a={},h=t.hash[o];if(h&&h.exists&&h.body){a=h.body.getBounds(a);for(var l=o+1;l<t.hash.length;l++){var c={},u=t.hash[l];if(u&&u.exists&&u.body){if(c=u.body.getBounds(c),this.sortDirection===n.Physics.Arcade.LEFT_RIGHT){if(a.right<c.x)break;if(c.right<a.x)continue}else if(this.sortDirection===n.Physics.Arcade.RIGHT_LEFT){if(a.x>c.right)continue;if(c.x>a.right)break}else if(this.sortDirection===n.Physics.Arcade.TOP_BOTTOM){if(a.bottom<c.y)continue;if(c.bottom<a.y)break}else if(this.sortDirection===n.Physics.Arcade.BOTTOM_TOP){if(a.y>c.bottom)continue;if(c.y>h.body.bottom)break}this.collideSpriteVsSprite(h,u,e,i,s,r)}}}}},collideGroupVsGroup:function(t,e,i,s,r,o){if(0!==t.length&&0!==e.length)for(var a=0;a<t.children.length;a++)t.children[a].exists&&(t.children[a].physicsType===n.GROUP?this.collideGroupVsGroup(t.children[a],e,i,s,r,o):this.collideSpriteVsGroup(t.children[a],e,i,s,r,o))},separate:function(t,e,i,s,n){if(!t.enable||!e.enable||t.checkCollision.none||e.checkCollision.none||!this.intersects(t,e))return!1;if(i&&!1===i.call(s,t.sprite,e.sprite))return!1;if(t.isCircle&&e.isCircle)return this.separateCircle(t,e,n);if(t.isCircle!==e.isCircle){var r=t.isCircle?e:t,o=t.isCircle?t:e,a={x:r.x,y:r.y,right:r.right,bottom:r.bottom},h={x:o.x+o.radius,y:o.y+o.radius};if((h.y<a.y||h.y>a.bottom)&&(h.x<a.x||h.x>a.right))return this.separateCircle(t,e,n)}var l=!1,c=!1;this.forceX||Math.abs(this.gravity.y+t.gravity.y)<Math.abs(this.gravity.x+t.gravity.x)?(l=this.separateX(t,e,n),this.intersects(t,e)&&(c=this.separateY(t,e,n))):(c=this.separateY(t,e,n),this.intersects(t,e)&&(l=this.separateX(t,e,n)));var u=l||c;return u&&(n?(t.onOverlap&&t.onOverlap.dispatch(t.sprite,e.sprite),e.onOverlap&&e.onOverlap.dispatch(e.sprite,t.sprite)):(t.onCollide&&t.onCollide.dispatch(t.sprite,e.sprite),e.onCollide&&e.onCollide.dispatch(e.sprite,t.sprite))),u},intersects:function(t,e){return t!==e&&(t.isCircle?e.isCircle?n.Math.distance(t.center.x,t.center.y,e.center.x,e.center.y)<=t.radius+e.radius:this.circleBodyIntersects(t,e):e.isCircle?this.circleBodyIntersects(e,t):!(t.right<=e.position.x)&&(!(t.bottom<=e.position.y)&&(!(t.position.x>=e.right)&&!(t.position.y>=e.bottom))))},circleBodyIntersects:function(t,e){var i=n.Math.clamp(t.center.x,e.left,e.right),s=n.Math.clamp(t.center.y,e.top,e.bottom);return(t.center.x-i)*(t.center.x-i)+(t.center.y-s)*(t.center.y-s)<=t.radius*t.radius},separateCircle:function(t,e,i){this.getOverlapX(t,e),this.getOverlapY(t,e);var s=e.center.x-t.center.x,r=e.center.y-t.center.y,o=Math.atan2(r,s),a=0;if(t.isCircle!==e.isCircle){var h={x:e.isCircle?t.position.x:e.position.x,y:e.isCircle?t.position.y:e.position.y,right:e.isCircle?t.right:e.right,bottom:e.isCircle?t.bottom:e.bottom},l={x:t.isCircle?t.position.x+t.radius:e.position.x+e.radius,y:t.isCircle?t.position.y+t.radius:e.position.y+e.radius,radius:t.isCircle?t.radius:e.radius};l.y<h.y?l.x<h.x?a=n.Math.distance(l.x,l.y,h.x,h.y)-l.radius:l.x>h.right&&(a=n.Math.distance(l.x,l.y,h.right,h.y)-l.radius):l.y>h.bottom&&(l.x<h.x?a=n.Math.distance(l.x,l.y,h.x,h.bottom)-l.radius:l.x>h.right&&(a=n.Math.distance(l.x,l.y,h.right,h.bottom)-l.radius)),a*=-1}else a=t.radius+e.radius-n.Math.distance(t.center.x,t.center.y,e.center.x,e.center.y);if(i||0===a||t.immovable&&e.immovable||t.customSeparateX||e.customSeparateX)return 0!==a&&(t.onOverlap&&t.onOverlap.dispatch(t.sprite,e.sprite),e.onOverlap&&e.onOverlap.dispatch(e.sprite,t.sprite)),0!==a;var c={x:t.velocity.x*Math.cos(o)+t.velocity.y*Math.sin(o),y:t.velocity.x*Math.sin(o)-t.velocity.y*Math.cos(o)},u={x:e.velocity.x*Math.cos(o)+e.velocity.y*Math.sin(o),y:e.velocity.x*Math.sin(o)-e.velocity.y*Math.cos(o)},d=((t.mass-e.mass)*c.x+2*e.mass*u.x)/(t.mass+e.mass),p=(2*t.mass*c.x+(e.mass-t.mass)*u.x)/(t.mass+e.mass);return t.immovable||(t.velocity.x=(d*Math.cos(o)-c.y*Math.sin(o))*t.bounce.x,t.velocity.y=(c.y*Math.cos(o)+d*Math.sin(o))*t.bounce.y),e.immovable||(e.velocity.x=(p*Math.cos(o)-u.y*Math.sin(o))*e.bounce.x,e.velocity.y=(u.y*Math.cos(o)+p*Math.sin(o))*e.bounce.y),Math.abs(o)<Math.PI/2?t.velocity.x>0&&!t.immovable&&e.velocity.x>t.velocity.x?t.velocity.x*=-1:e.velocity.x<0&&!e.immovable&&t.velocity.x<e.velocity.x?e.velocity.x*=-1:t.velocity.y>0&&!t.immovable&&e.velocity.y>t.velocity.y?t.velocity.y*=-1:e.velocity.y<0&&!e.immovable&&t.velocity.y<e.velocity.y&&(e.velocity.y*=-1):Math.abs(o)>Math.PI/2&&(t.velocity.x<0&&!t.immovable&&e.velocity.x<t.velocity.x?t.velocity.x*=-1:e.velocity.x>0&&!e.immovable&&t.velocity.x>e.velocity.x?e.velocity.x*=-1:t.velocity.y<0&&!t.immovable&&e.velocity.y<t.velocity.y?t.velocity.y*=-1:e.velocity.y>0&&!e.immovable&&t.velocity.x>e.velocity.y&&(e.velocity.y*=-1)),t.immovable||(t.x+=t.velocity.x*this.game.time.physicsElapsed-a*Math.cos(o),t.y+=t.velocity.y*this.game.time.physicsElapsed-a*Math.sin(o)),e.immovable||(e.x+=e.velocity.x*this.game.time.physicsElapsed+a*Math.cos(o),e.y+=e.velocity.y*this.game.time.physicsElapsed+a*Math.sin(o)),t.onCollide&&t.onCollide.dispatch(t.sprite,e.sprite),e.onCollide&&e.onCollide.dispatch(e.sprite,t.sprite),!0},getOverlapX:function(t,e,i){var s=0,n=t.deltaAbsX()+e.deltaAbsX()+this.OVERLAP_BIAS;return 0===t.deltaX()&&0===e.deltaX()?(t.embedded=!0,e.embedded=!0):t.deltaX()>e.deltaX()?(s=t.right-e.x,s>n&&!i||!1===t.checkCollision.right||!1===e.checkCollision.left?s=0:(t.touching.none=!1,t.touching.right=!0,e.touching.none=!1,e.touching.left=!0)):t.deltaX()<e.deltaX()&&(s=t.x-e.width-e.x,-s>n&&!i||!1===t.checkCollision.left||!1===e.checkCollision.right?s=0:(t.touching.none=!1,t.touching.left=!0,e.touching.none=!1,e.touching.right=!0)),t.overlapX=s,e.overlapX=s,s},getOverlapY:function(t,e,i){var s=0,n=t.deltaAbsY()+e.deltaAbsY()+this.OVERLAP_BIAS;return 0===t.deltaY()&&0===e.deltaY()?(t.embedded=!0,e.embedded=!0):t.deltaY()>e.deltaY()?(s=t.bottom-e.y,s>n&&!i||!1===t.checkCollision.down||!1===e.checkCollision.up?s=0:(t.touching.none=!1,t.touching.down=!0,e.touching.none=!1,e.touching.up=!0)):t.deltaY()<e.deltaY()&&(s=t.y-e.bottom,-s>n&&!i||!1===t.checkCollision.up||!1===e.checkCollision.down?s=0:(t.touching.none=!1,t.touching.up=!0,e.touching.none=!1,e.touching.down=!0)),t.overlapY=s,e.overlapY=s,s},separateX:function(t,e,i){var s=this.getOverlapX(t,e,i);if(i||0===s||t.immovable&&e.immovable||t.customSeparateX||e.customSeparateX)return 0!==s||t.embedded&&e.embedded;var n=t.velocity.x,r=e.velocity.x;if(t.immovable||e.immovable)t.immovable?(e.x+=s,e.velocity.x=n-r*e.bounce.x,t.moves&&(e.y+=(t.y-t.prev.y)*t.friction.y)):(t.x-=s,t.velocity.x=r-n*t.bounce.x,e.moves&&(t.y+=(e.y-e.prev.y)*e.friction.y));else{s*=.5,t.x-=s,e.x+=s;var o=Math.sqrt(r*r*e.mass/t.mass)*(r>0?1:-1),a=Math.sqrt(n*n*t.mass/e.mass)*(n>0?1:-1),h=.5*(o+a);o-=h,a-=h,t.velocity.x=h+o*t.bounce.x,e.velocity.x=h+a*e.bounce.x}return!0},separateY:function(t,e,i){var s=this.getOverlapY(t,e,i);if(i||0===s||t.immovable&&e.immovable||t.customSeparateY||e.customSeparateY)return 0!==s||t.embedded&&e.embedded;var n=t.velocity.y,r=e.velocity.y;if(t.immovable||e.immovable)t.immovable?(e.y+=s,e.velocity.y=n-r*e.bounce.y,t.moves&&(e.x+=(t.x-t.prev.x)*t.friction.x)):(t.y-=s,t.velocity.y=r-n*t.bounce.y,e.moves&&(t.x+=(e.x-e.prev.x)*e.friction.x));else{s*=.5,t.y-=s,e.y+=s;var o=Math.sqrt(r*r*e.mass/t.mass)*(r>0?1:-1),a=Math.sqrt(n*n*t.mass/e.mass)*(n>0?1:-1),h=.5*(o+a);o-=h,a-=h,t.velocity.y=h+o*t.bounce.y,e.velocity.y=h+a*e.bounce.y}return!0},getObjectsUnderPointer:function(t,e,i,s){if(0!==e.length&&t.exists)return this.getObjectsAtLocation(t.x,t.y,e,i,s,t)},getObjectsAtLocation:function(t,e,i,s,r,o){this.quadTree.clear(),this.quadTree.reset(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height,this.maxObjects,this.maxLevels),this.quadTree.populate(i);for(var a=new n.Rectangle(t,e,1,1),h=[],l=this.quadTree.retrieve(a),c=0;c<l.length;c++)l[c].hitTest(t,e)&&(s&&s.call(r,o,l[c].sprite),h.push(l[c].sprite));return h},moveToObject:function(t,e,i,s){void 0===i&&(i=60),void 0===s&&(s=0);var n=Math.atan2(e.y-t.y,e.x-t.x);return s>0&&(i=this.distanceBetween(t,e)/(s/1e3)),t.body.velocity.x=Math.cos(n)*i,t.body.velocity.y=Math.sin(n)*i,n},moveToPointer:function(t,e,i,s){void 0===e&&(e=60),i=i||this.game.input.activePointer,void 0===s&&(s=0);var n=this.angleToPointer(t,i);return s>0&&(e=this.distanceToPointer(t,i)/(s/1e3)),t.body.velocity.x=Math.cos(n)*e,t.body.velocity.y=Math.sin(n)*e,n},moveToXY:function(t,e,i,s,n){void 0===s&&(s=60),void 0===n&&(n=0);var r=Math.atan2(i-t.y,e-t.x);return n>0&&(s=this.distanceToXY(t,e,i)/(n/1e3)),t.body.velocity.x=Math.cos(r)*s,t.body.velocity.y=Math.sin(r)*s,r},velocityFromAngle:function(t,e,i){return void 0===e&&(e=60),i=i||new n.Point,i.setTo(Math.cos(this.game.math.degToRad(t))*e,Math.sin(this.game.math.degToRad(t))*e)},velocityFromRotation:function(t,e,i){return void 0===e&&(e=60),i=i||new n.Point,i.setTo(Math.cos(t)*e,Math.sin(t)*e)},accelerationFromRotation:function(t,e,i){return void 0===e&&(e=60),i=i||new n.Point,i.setTo(Math.cos(t)*e,Math.sin(t)*e)},accelerateToObject:function(t,e,i,s,n){void 0===i&&(i=60),void 0===s&&(s=1e3),void 0===n&&(n=1e3);var r=this.angleBetween(t,e);return t.body.acceleration.setTo(Math.cos(r)*i,Math.sin(r)*i),t.body.maxVelocity.setTo(s,n),r},accelerateToPointer:function(t,e,i,s,n){void 0===i&&(i=60),void 0===e&&(e=this.game.input.activePointer),void 0===s&&(s=1e3),void 0===n&&(n=1e3);var r=this.angleToPointer(t,e);return t.body.acceleration.setTo(Math.cos(r)*i,Math.sin(r)*i),t.body.maxVelocity.setTo(s,n),r},accelerateToXY:function(t,e,i,s,n,r){void 0===s&&(s=60),void 0===n&&(n=1e3),void 0===r&&(r=1e3);var o=this.angleToXY(t,e,i);return t.body.acceleration.setTo(Math.cos(o)*s,Math.sin(o)*s),t.body.maxVelocity.setTo(n,r),o},distanceBetween:function(t,e,i){void 0===i&&(i=!1);var s=i?t.world.x-e.world.x:t.x-e.x,n=i?t.world.y-e.world.y:t.y-e.y;return Math.sqrt(s*s+n*n)},distanceToXY:function(t,e,i,s){void 0===s&&(s=!1);var n=s?t.world.x-e:t.x-e,r=s?t.world.y-i:t.y-i;return Math.sqrt(n*n+r*r)},distanceToPointer:function(t,e,i){void 0===e&&(e=this.game.input.activePointer),void 0===i&&(i=!1);var s=i?t.world.x-e.worldX:t.x-e.worldX,n=i?t.world.y-e.worldY:t.y-e.worldY;return Math.sqrt(s*s+n*n)},angleBetween:function(t,e,i){return void 0===i&&(i=!1),i?Math.atan2(e.world.y-t.world.y,e.world.x-t.world.x):Math.atan2(e.y-t.y,e.x-t.x)},angleBetweenCenters:function(t,e){var i=e.centerX-t.centerX,s=e.centerY-t.centerY;return Math.atan2(s,i)},angleToXY:function(t,e,i,s){return void 0===s&&(s=!1),s?Math.atan2(i-t.world.y,e-t.world.x):Math.atan2(i-t.y,e-t.x)},angleToPointer:function(t,e,i){return void 0===e&&(e=this.game.input.activePointer),void 0===i&&(i=!1),i?Math.atan2(e.worldY-t.world.y,e.worldX-t.world.x):Math.atan2(e.worldY-t.y,e.worldX-t.x)},worldAngleToPointer:function(t,e){return this.angleToPointer(t,e,!0)}},n.Physics.Arcade.Body=function(t){this.sprite=t,this.game=t.game,this.type=n.Physics.ARCADE,this.enable=!0,this.isCircle=!1,this.radius=0,this.offset=new n.Point,this.position=new n.Point(t.x,t.y),this.prev=new n.Point(this.position.x,this.position.y),this.allowRotation=!0,this.rotation=t.angle,this.preRotation=t.angle,this.width=t.width,this.height=t.height,this.sourceWidth=t.width,this.sourceHeight=t.height,t.texture&&(this.sourceWidth=t.texture.frame.width,this.sourceHeight=t.texture.frame.height),this.halfWidth=Math.abs(t.width/2),this.halfHeight=Math.abs(t.height/2),this.center=new n.Point(t.x+this.halfWidth,t.y+this.halfHeight),this.velocity=new n.Point,this.newVelocity=new n.Point,this.deltaMax=new n.Point,this.acceleration=new n.Point,this.drag=new n.Point,this.allowGravity=!0,this.gravity=new n.Point,this.bounce=new n.Point,this.worldBounce=null,this.onWorldBounds=null,this.onCollide=null,this.onOverlap=null,this.maxVelocity=new n.Point(1e4,1e4),this.friction=new n.Point(1,0),this.angularVelocity=0,this.angularAcceleration=0,this.angularDrag=0,this.maxAngular=1e3,this.mass=1,this.angle=0,this.speed=0,this.facing=n.NONE,this.immovable=!1,this.moves=!0,this.customSeparateX=!1,this.customSeparateY=!1,this.overlapX=0,this.overlapY=0,this.overlapR=0,this.embedded=!1,this.collideWorldBounds=!1,this.checkCollision={none:!1,any:!0,up:!0,down:!0,left:!0,right:!0},this.touching={none:!0,up:!1,down:!1,left:!1,right:!1},this.wasTouching={none:!0,up:!1,down:!1,left:!1,right:!1},this.blocked={up:!1,down:!1,left:!1,right:!1},this.tilePadding=new n.Point,this.dirty=!1,this.skipQuadTree=!1,this.syncBounds=!1,this.isMoving=!1,this.stopVelocityOnCollide=!0,this.moveTimer=0,this.moveDistance=0,this.moveDuration=0,this.moveTarget=null,this.moveEnd=null,this.onMoveComplete=new n.Signal,this.movementCallback=null,this.movementCallbackContext=null,this._reset=!0,this._sx=t.scale.x,this._sy=t.scale.y,this._dx=0,this._dy=0},n.Physics.Arcade.Body.prototype={updateBounds:function(){if(this.syncBounds){var t=this.sprite.getBounds();t.ceilAll(),t.width===this.width&&t.height===this.height||(this.width=t.width,this.height=t.height,this._reset=!0)}else{var e=Math.abs(this.sprite.scale.x),i=Math.abs(this.sprite.scale.y);e===this._sx&&i===this._sy||(this.width=this.sourceWidth*e,this.height=this.sourceHeight*i,this._sx=e,this._sy=i,this._reset=!0)}this._reset&&(this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight))},preUpdate:function(){this.enable&&!this.game.physics.arcade.isPaused&&(this.dirty=!0,this.wasTouching.none=this.touching.none,this.wasTouching.up=this.touching.up,this.wasTouching.down=this.touching.down,this.wasTouching.left=this.touching.left,this.wasTouching.right=this.touching.right,this.touching.none=!0,this.touching.up=!1,this.touching.down=!1,this.touching.left=!1,this.touching.right=!1,this.blocked.up=!1,this.blocked.down=!1,this.blocked.left=!1,this.blocked.right=!1,this.embedded=!1,this.updateBounds(),this.position.x=this.sprite.world.x-this.sprite.anchor.x*this.sprite.width+this.sprite.scale.x*this.offset.x,this.position.x-=this.sprite.scale.x<0?this.width:0,this.position.y=this.sprite.world.y-this.sprite.anchor.y*this.sprite.height+this.sprite.scale.y*this.offset.y,this.position.y-=this.sprite.scale.y<0?this.height:0,this.rotation=this.sprite.angle,this.preRotation=this.rotation,(this._reset||this.sprite.fresh)&&(this.prev.x=this.position.x,this.prev.y=this.position.y),this.moves&&(this.game.physics.arcade.updateMotion(this),this.newVelocity.set(this.velocity.x*this.game.time.physicsElapsed,this.velocity.y*this.game.time.physicsElapsed),this.position.x+=this.newVelocity.x,this.position.y+=this.newVelocity.y,this.position.x===this.prev.x&&this.position.y===this.prev.y||(this.angle=Math.atan2(this.velocity.y,this.velocity.x)),this.speed=Math.sqrt(this.velocity.x*this.velocity.x+this.velocity.y*this.velocity.y),this.collideWorldBounds&&this.checkWorldBounds()&&this.onWorldBounds&&this.onWorldBounds.dispatch(this.sprite,this.blocked.up,this.blocked.down,this.blocked.left,this.blocked.right)),this._dx=this.deltaX(),this._dy=this.deltaY(),this._reset=!1)},updateMovement:function(){var t=0,e=0!==this.overlapX||0!==this.overlapY;if(this.moveDuration>0?(this.moveTimer+=this.game.time.elapsedMS,t=this.moveTimer/this.moveDuration):(this.moveTarget.end.set(this.position.x,this.position.y),t=this.moveTarget.length/this.moveDistance),this.movementCallback)var i=this.movementCallback.call(this.movementCallbackContext,this,this.velocity,t);return!(e||t>=1||void 0!==i&&!0!==i)||(this.stopMovement(t>=1||this.stopVelocityOnCollide&&e),!1)},stopMovement:function(t){this.isMoving&&(this.isMoving=!1,t&&this.velocity.set(0),this.onMoveComplete.dispatch(this.sprite,0!==this.overlapX||0!==this.overlapY))},postUpdate:function(){this.enable&&this.dirty&&(this.isMoving&&this.updateMovement(),this.dirty=!1,this.deltaX()<0?this.facing=n.LEFT:this.deltaX()>0&&(this.facing=n.RIGHT),this.deltaY()<0?this.facing=n.UP:this.deltaY()>0&&(this.facing=n.DOWN),this.moves&&(this._dx=this.deltaX(),this._dy=this.deltaY(),0!==this.deltaMax.x&&0!==this._dx&&(this._dx<0&&this._dx<-this.deltaMax.x?this._dx=-this.deltaMax.x:this._dx>0&&this._dx>this.deltaMax.x&&(this._dx=this.deltaMax.x)),0!==this.deltaMax.y&&0!==this._dy&&(this._dy<0&&this._dy<-this.deltaMax.y?this._dy=-this.deltaMax.y:this._dy>0&&this._dy>this.deltaMax.y&&(this._dy=this.deltaMax.y)),this.sprite.position.x+=this._dx,this.sprite.position.y+=this._dy,this._reset=!0),this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight),this.allowRotation&&(this.sprite.angle+=this.deltaZ()),this.prev.x=this.position.x,this.prev.y=this.position.y)},checkWorldBounds:function(){var t=this.position,e=this.game.physics.arcade.bounds,i=this.game.physics.arcade.checkCollision,s=this.worldBounce?-this.worldBounce.x:-this.bounce.x,n=this.worldBounce?-this.worldBounce.y:-this.bounce.y;if(this.isCircle){var r={x:this.center.x-this.radius,y:this.center.y-this.radius,right:this.center.x+this.radius,bottom:this.center.y+this.radius};r.x<e.x&&i.left?(t.x=e.x-this.halfWidth+this.radius,this.velocity.x*=s,this.blocked.left=!0):r.right>e.right&&i.right&&(t.x=e.right-this.halfWidth-this.radius,this.velocity.x*=s,this.blocked.right=!0),r.y<e.y&&i.up?(t.y=e.y-this.halfHeight+this.radius,this.velocity.y*=n,this.blocked.up=!0):r.bottom>e.bottom&&i.down&&(t.y=e.bottom-this.halfHeight-this.radius,this.velocity.y*=n,this.blocked.down=!0)}else t.x<e.x&&i.left?(t.x=e.x,this.velocity.x*=s,this.blocked.left=!0):this.right>e.right&&i.right&&(t.x=e.right-this.width,this.velocity.x*=s,this.blocked.right=!0),t.y<e.y&&i.up?(t.y=e.y,this.velocity.y*=n,this.blocked.up=!0):this.bottom>e.bottom&&i.down&&(t.y=e.bottom-this.height,this.velocity.y*=n,this.blocked.down=!0);return this.blocked.up||this.blocked.down||this.blocked.left||this.blocked.right},moveFrom:function(t,e,i){if(void 0===e&&(e=this.speed),0===e)return!1;var s;return void 0===i?(s=this.angle,i=this.game.math.radToDeg(s)):s=this.game.math.degToRad(i),this.moveTimer=0,this.moveDuration=t,0===i||180===i?this.velocity.set(Math.cos(s)*e,0):90===i||270===i?this.velocity.set(0,Math.sin(s)*e):this.velocity.set(Math.cos(s)*e,Math.sin(s)*e),this.isMoving=!0,!0},moveTo:function(t,e,i){var s=e/(t/1e3);if(0===s)return!1;var r;return void 0===i?(r=this.angle,i=this.game.math.radToDeg(r)):r=this.game.math.degToRad(i),e=Math.abs(e),this.moveDuration=0,this.moveDistance=e,null===this.moveTarget&&(this.moveTarget=new n.Line,this.moveEnd=new n.Point),this.moveTarget.fromAngle(this.x,this.y,r,e),this.moveEnd.set(this.moveTarget.end.x,this.moveTarget.end.y),this.moveTarget.setTo(this.x,this.y,this.x,this.y),0===i||180===i?this.velocity.set(Math.cos(r)*s,0):90===i||270===i?this.velocity.set(0,Math.sin(r)*s):this.velocity.set(Math.cos(r)*s,Math.sin(r)*s),this.isMoving=!0,!0},setSize:function(t,e,i,s){void 0===i&&(i=this.offset.x),void 0===s&&(s=this.offset.y),this.sourceWidth=t,this.sourceHeight=e,this.width=this.sourceWidth*this._sx,this.height=this.sourceHeight*this._sy,this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.offset.setTo(i,s),this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight),this.isCircle=!1,this.radius=0},setCircle:function(t,e,i){void 0===e&&(e=this.offset.x),void 0===i&&(i=this.offset.y),t>0?(this.isCircle=!0,this.radius=t,this.sourceWidth=2*t,this.sourceHeight=2*t,this.width=this.sourceWidth*this._sx,this.height=this.sourceHeight*this._sy,this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.offset.setTo(e,i),this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight)):this.isCircle=!1},reset:function(t,e){this.velocity.set(0),this.acceleration.set(0),this.speed=0,this.angularVelocity=0,this.angularAcceleration=0,this.position.x=t-this.sprite.anchor.x*this.sprite.width+this.sprite.scale.x*this.offset.x,this.position.x-=this.sprite.scale.x<0?this.width:0,this.position.y=e-this.sprite.anchor.y*this.sprite.height+this.sprite.scale.y*this.offset.y,this.position.y-=this.sprite.scale.y<0?this.height:0,this.prev.x=this.position.x,this.prev.y=this.position.y,this.rotation=this.sprite.angle,this.preRotation=this.rotation,this._sx=this.sprite.scale.x,this._sy=this.sprite.scale.y,this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight)},getBounds:function(t){return this.isCircle?(t.x=this.center.x-this.radius,t.y=this.center.y-this.radius,t.right=this.center.x+this.radius,t.bottom=this.center.y+this.radius):(t.x=this.x,t.y=this.y,t.right=this.right,t.bottom=this.bottom),t},hitTest:function(t,e){return this.isCircle?n.Circle.contains(this,t,e):n.Rectangle.contains(this,t,e)},onFloor:function(){return this.blocked.down},onCeiling:function(){return this.blocked.up},onWall:function(){return this.blocked.left||this.blocked.right},deltaAbsX:function(){return this.deltaX()>0?this.deltaX():-this.deltaX()},deltaAbsY:function(){return this.deltaY()>0?this.deltaY():-this.deltaY()},deltaX:function(){return this.position.x-this.prev.x},deltaY:function(){return this.position.y-this.prev.y},deltaZ:function(){return this.rotation-this.preRotation},destroy:function(){this.sprite.parent&&this.sprite.parent instanceof n.Group&&this.sprite.parent.removeFromHash(this.sprite),this.sprite.body=null,this.sprite=null}},Object.defineProperty(n.Physics.Arcade.Body.prototype,"left",{get:function(){return this.position.x}}),Object.defineProperty(n.Physics.Arcade.Body.prototype,"right",{get:function(){return this.position.x+this.width}}),Object.defineProperty(n.Physics.Arcade.Body.prototype,"top",{get:function(){return this.position.y}}),Object.defineProperty(n.Physics.Arcade.Body.prototype,"bottom",{get:function(){return this.position.y+this.height}}),Object.defineProperty(n.Physics.Arcade.Body.prototype,"x",{get:function(){return this.position.x},set:function(t){this.position.x=t}}),Object.defineProperty(n.Physics.Arcade.Body.prototype,"y",{get:function(){return this.position.y},set:function(t){this.position.y=t}}),n.Physics.Arcade.Body.render=function(t,e,i,s){void 0===s&&(s=!0),i=i||"rgba(0,255,0,0.4)",t.fillStyle=i,t.strokeStyle=i,e.isCircle?(t.beginPath(),t.arc(e.center.x-e.game.camera.x,e.center.y-e.game.camera.y,e.radius,0,2*Math.PI),s?t.fill():t.stroke()):s?t.fillRect(e.position.x-e.game.camera.x,e.position.y-e.game.camera.y,e.width,e.height):t.strokeRect(e.position.x-e.game.camera.x,e.position.y-e.game.camera.y,e.width,e.height)},n.Physics.Arcade.Body.renderBodyInfo=function(t,e){t.line("x: "+e.x.toFixed(2),"y: "+e.y.toFixed(2),"width: "+e.width,"height: "+e.height),t.line("velocity x: "+e.velocity.x.toFixed(2),"y: "+e.velocity.y.toFixed(2),"deltaX: "+e._dx.toFixed(2),"deltaY: "+e._dy.toFixed(2)),t.line("acceleration x: "+e.acceleration.x.toFixed(2),"y: "+e.acceleration.y.toFixed(2),"speed: "+e.speed.toFixed(2),"angle: "+e.angle.toFixed(2)),t.line("gravity x: "+e.gravity.x,"y: "+e.gravity.y,"bounce x: "+e.bounce.x.toFixed(2),"y: "+e.bounce.y.toFixed(2)),t.line("touching left: "+e.touching.left,"right: "+e.touching.right,"up: "+e.touching.up,"down: "+e.touching.down),t.line("blocked left: "+e.blocked.left,"right: "+e.blocked.right,"up: "+e.blocked.up,"down: "+e.blocked.down)},n.Physics.Arcade.Body.prototype.constructor=n.Physics.Arcade.Body,n.Physics.Arcade.TilemapCollision=function(){},n.Physics.Arcade.TilemapCollision.prototype={TILE_BIAS:16,collideSpriteVsTilemapLayer:function(t,e,i,s,n,r){if(t.body){var o=e.getTiles(t.body.position.x-t.body.tilePadding.x,t.body.position.y-t.body.tilePadding.y,t.body.width+t.body.tilePadding.x,t.body.height+t.body.tilePadding.y,!1,!1);if(0!==o.length)for(var a=0;a<o.length;a++)s?s.call(n,t,o[a])&&this.separateTile(a,t.body,o[a],e,r)&&(this._total++,i&&i.call(n,t,o[a])):this.separateTile(a,t.body,o[a],e,r)&&(this._total++,i&&i.call(n,t,o[a]))}},collideGroupVsTilemapLayer:function(t,e,i,s,n,r){if(0!==t.length)for(var o=0;o<t.children.length;o++)t.children[o].exists&&this.collideSpriteVsTilemapLayer(t.children[o],e,i,s,n,r)},separateTile:function(t,e,i,s,n){if(!e.enable)return!1;var r=s.fixedToCamera?0:s.position.x,o=s.fixedToCamera?0:s.position.y;if(!i.intersects(e.position.x-r,e.position.y-o,e.right-r,e.bottom-o))return!1;if(n)return!0;if(i.collisionCallback&&!i.collisionCallback.call(i.collisionCallbackContext,e.sprite,i))return!1;if(void 0!==i.layer.callbacks&&i.layer.callbacks[i.index]&&!i.layer.callbacks[i.index].callback.call(i.layer.callbacks[i.index].callbackContext,e.sprite,i))return!1;if(!(i.faceLeft||i.faceRight||i.faceTop||i.faceBottom))return!1;var a=0,h=0,l=0,c=1;if(e.deltaAbsX()>e.deltaAbsY()?l=-1:e.deltaAbsX()<e.deltaAbsY()&&(c=-1),0!==e.deltaX()&&0!==e.deltaY()&&(i.faceLeft||i.faceRight)&&(i.faceTop||i.faceBottom)&&(l=Math.min(Math.abs(e.position.x-r-i.right),Math.abs(e.right-r-i.left)),c=Math.min(Math.abs(e.position.y-o-i.bottom),Math.abs(e.bottom-o-i.top))),l<c){if((i.faceLeft||i.faceRight)&&0!==(a=this.tileCheckX(e,i,s))&&!i.intersects(e.position.x-r,e.position.y-o,e.right-r,e.bottom-o))return!0;(i.faceTop||i.faceBottom)&&(h=this.tileCheckY(e,i,s))}else{if((i.faceTop||i.faceBottom)&&0!==(h=this.tileCheckY(e,i,s))&&!i.intersects(e.position.x-r,e.position.y-o,e.right-r,e.bottom-o))return!0;(i.faceLeft||i.faceRight)&&(a=this.tileCheckX(e,i,s))}return 0!==a||0!==h},tileCheckX:function(t,e,i){var s=0,n=i.fixedToCamera?0:i.position.x;return t.deltaX()<0&&!t.blocked.left&&e.collideRight&&t.checkCollision.left?e.faceRight&&t.x-n<e.right&&(s=t.x-n-e.right)<-this.TILE_BIAS&&(s=0):t.deltaX()>0&&!t.blocked.right&&e.collideLeft&&t.checkCollision.right&&e.faceLeft&&t.right-n>e.left&&(s=t.right-n-e.left)>this.TILE_BIAS&&(s=0),0!==s&&(t.customSeparateX?t.overlapX=s:this.processTileSeparationX(t,s)),s},tileCheckY:function(t,e,i){var s=0,n=i.fixedToCamera?0:i.position.y;return t.deltaY()<0&&!t.blocked.up&&e.collideDown&&t.checkCollision.up?e.faceBottom&&t.y-n<e.bottom&&(s=t.y-n-e.bottom)<-this.TILE_BIAS&&(s=0):t.deltaY()>0&&!t.blocked.down&&e.collideUp&&t.checkCollision.down&&e.faceTop&&t.bottom-n>e.top&&(s=t.bottom-n-e.top)>this.TILE_BIAS&&(s=0),0!==s&&(t.customSeparateY?t.overlapY=s:this.processTileSeparationY(t,s)),s},processTileSeparationX:function(t,e){e<0?t.blocked.left=!0:e>0&&(t.blocked.right=!0),t.position.x-=e,0===t.bounce.x?t.velocity.x=0:t.velocity.x=-t.velocity.x*t.bounce.x},processTileSeparationY:function(t,e){e<0?t.blocked.up=!0:e>0&&(t.blocked.down=!0),t.position.y-=e,0===t.bounce.y?t.velocity.y=0:t.velocity.y=-t.velocity.y*t.bounce.y}},n.Utils.mixinPrototype(n.Physics.Arcade.prototype,n.Physics.Arcade.TilemapCollision.prototype),p2.Body.prototype.parent=null,p2.Spring.prototype.parent=null,n.Physics.P2=function(t,e){this.game=t,void 0===e?e={gravity:[0,0],broadphase:new p2.SAPBroadphase}:(e.hasOwnProperty("gravity")||(e.gravity=[0,0]),e.hasOwnProperty("broadphase")||(e.broadphase=new p2.SAPBroadphase)),this.config=e,this.world=new p2.World(this.config),this.frameRate=1/60,this.useElapsedTime=!1,this.paused=!1,this.materials=[],this.gravity=new n.Physics.P2.InversePointProxy(this,this.world.gravity),this.walls={left:null,right:null,top:null,bottom:null},this.onBodyAdded=new n.Signal,this.onBodyRemoved=new n.Signal,this.onSpringAdded=new n.Signal,this.onSpringRemoved=new n.Signal,this.onConstraintAdded=new n.Signal,this.onConstraintRemoved=new n.Signal,this.onContactMaterialAdded=new n.Signal,this.onContactMaterialRemoved=new n.Signal,this.postBroadphaseCallback=null,this.callbackContext=null,this.onBeginContact=new n.Signal,this.onEndContact=new n.Signal,e.hasOwnProperty("mpx")&&e.hasOwnProperty("pxm")&&e.hasOwnProperty("mpxi")&&e.hasOwnProperty("pxmi")&&(this.mpx=e.mpx,this.mpxi=e.mpxi,this.pxm=e.pxm,this.pxmi=e.pxmi),this.world.on("beginContact",this.beginContactHandler,this),this.world.on("endContact",this.endContactHandler,this),this.collisionGroups=[],this.nothingCollisionGroup=new n.Physics.P2.CollisionGroup(1),this.boundsCollisionGroup=new n.Physics.P2.CollisionGroup(2),this.everythingCollisionGroup=new n.Physics.P2.CollisionGroup(2147483648),this.boundsCollidesWith=[],this._toRemove=[],this._collisionGroupID=2,this._boundsLeft=!0,this._boundsRight=!0,this._boundsTop=!0,this._boundsBottom=!0,this._boundsOwnGroup=!1,this.setBoundsToWorld(!0,!0,!0,!0,!1)},n.Physics.P2.prototype={removeBodyNextStep:function(t){this._toRemove.push(t)},preUpdate:function(){for(var t=this._toRemove.length;t--;)this.removeBody(this._toRemove[t]);this._toRemove.length=0},enable:function(t,e,i){void 0===e&&(e=!1),void 0===i&&(i=!0);var s=1;if(Array.isArray(t))for(s=t.length;s--;)t[s]instanceof n.Group?this.enable(t[s].children,e,i):(this.enableBody(t[s],e),i&&t[s].hasOwnProperty("children")&&t[s].children.length>0&&this.enable(t[s],e,!0));else t instanceof n.Group?this.enable(t.children,e,i):(this.enableBody(t,e),i&&t.hasOwnProperty("children")&&t.children.length>0&&this.enable(t.children,e,!0))},enableBody:function(t,e){t.hasOwnProperty("body")&&null===t.body&&(t.body=new n.Physics.P2.Body(this.game,t,t.x,t.y,1),t.body.debug=e,void 0!==t.anchor&&t.anchor.set(.5))},setImpactEvents:function(t){t?this.world.on("impact",this.impactHandler,this):this.world.off("impact",this.impactHandler,this)},setPostBroadphaseCallback:function(t,e){this.postBroadphaseCallback=t,this.callbackContext=e,null!==t?this.world.on("postBroadphase",this.postBroadphaseHandler,this):this.world.off("postBroadphase",this.postBroadphaseHandler,this)},postBroadphaseHandler:function(t){if(this.postBroadphaseCallback&&0!==t.pairs.length)for(var e=t.pairs.length-2;e>=0;e-=2)t.pairs[e].parent&&t.pairs[e+1].parent&&!this.postBroadphaseCallback.call(this.callbackContext,t.pairs[e].parent,t.pairs[e+1].parent)&&t.pairs.splice(e,2)},impactHandler:function(t){if(t.bodyA.parent&&t.bodyB.parent){var e=t.bodyA.parent,i=t.bodyB.parent;e._bodyCallbacks[t.bodyB.id]&&e._bodyCallbacks[t.bodyB.id].call(e._bodyCallbackContext[t.bodyB.id],e,i,t.shapeA,t.shapeB),i._bodyCallbacks[t.bodyA.id]&&i._bodyCallbacks[t.bodyA.id].call(i._bodyCallbackContext[t.bodyA.id],i,e,t.shapeB,t.shapeA),e._groupCallbacks[t.shapeB.collisionGroup]&&e._groupCallbacks[t.shapeB.collisionGroup].call(e._groupCallbackContext[t.shapeB.collisionGroup],e,i,t.shapeA,t.shapeB),i._groupCallbacks[t.shapeA.collisionGroup]&&i._groupCallbacks[t.shapeA.collisionGroup].call(i._groupCallbackContext[t.shapeA.collisionGroup],i,e,t.shapeB,t.shapeA)}},beginContactHandler:function(t){t.bodyA&&t.bodyB&&(this.onBeginContact.dispatch(t.bodyA,t.bodyB,t.shapeA,t.shapeB,t.contactEquations),t.bodyA.parent&&t.bodyA.parent.onBeginContact.dispatch(t.bodyB.parent,t.bodyB,t.shapeA,t.shapeB,t.contactEquations),t.bodyB.parent&&t.bodyB.parent.onBeginContact.dispatch(t.bodyA.parent,t.bodyA,t.shapeB,t.shapeA,t.contactEquations))},endContactHandler:function(t){t.bodyA&&t.bodyB&&(this.onEndContact.dispatch(t.bodyA,t.bodyB,t.shapeA,t.shapeB),t.bodyA.parent&&t.bodyA.parent.onEndContact.dispatch(t.bodyB.parent,t.bodyB,t.shapeA,t.shapeB),t.bodyB.parent&&t.bodyB.parent.onEndContact.dispatch(t.bodyA.parent,t.bodyA,t.shapeB,t.shapeA))},setBoundsToWorld:function(t,e,i,s,n){this.setBounds(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height,t,e,i,s,n)},setWorldMaterial:function(t,e,i,s,n){void 0===e&&(e=!0),void 0===i&&(i=!0),void 0===s&&(s=!0),void 0===n&&(n=!0),e&&this.walls.left&&(this.walls.left.shapes[0].material=t),i&&this.walls.right&&(this.walls.right.shapes[0].material=t),s&&this.walls.top&&(this.walls.top.shapes[0].material=t),n&&this.walls.bottom&&(this.walls.bottom.shapes[0].material=t)},updateBoundsCollisionGroup:function(t){void 0===t&&(t=!0);var e=t?this.boundsCollisionGroup.mask:this.everythingCollisionGroup.mask;this.walls.left&&(this.walls.left.shapes[0].collisionGroup=e),this.walls.right&&(this.walls.right.shapes[0].collisionGroup=e),this.walls.top&&(this.walls.top.shapes[0].collisionGroup=e),this.walls.bottom&&(this.walls.bottom.shapes[0].collisionGroup=e),this._boundsOwnGroup=t},setBounds:function(t,e,i,s,n,r,o,a,h){void 0===n&&(n=this._boundsLeft),void 0===r&&(r=this._boundsRight),void 0===o&&(o=this._boundsTop),void 0===a&&(a=this._boundsBottom),void 0===h&&(h=this._boundsOwnGroup),this.setupWall(n,"left",t,e,1.5707963267948966,h),this.setupWall(r,"right",t+i,e,-1.5707963267948966,h),this.setupWall(o,"top",t,e,-3.141592653589793,h),this.setupWall(a,"bottom",t,e+s,0,h),this._boundsLeft=n,this._boundsRight=r,this._boundsTop=o,this._boundsBottom=a,this._boundsOwnGroup=h},setupWall:function(t,e,i,s,n,r){t?(this.walls[e]?this.walls[e].position=[this.pxmi(i),this.pxmi(s)]:(this.walls[e]=new p2.Body({mass:0,position:[this.pxmi(i),this.pxmi(s)],angle:n}),this.walls[e].addShape(new p2.Plane),this.world.addBody(this.walls[e])),r&&(this.walls[e].shapes[0].collisionGroup=this.boundsCollisionGroup.mask)):this.walls[e]&&(this.world.removeBody(this.walls[e]),this.walls[e]=null)},pause:function(){this.paused=!0},resume:function(){this.paused=!1},update:function(){this.paused||(this.useElapsedTime?this.world.step(this.game.time.physicsElapsed):this.world.step(this.frameRate))},reset:function(){this.world.on("beginContact",this.beginContactHandler,this),this.world.on("endContact",this.endContactHandler,this),this.nothingCollisionGroup=new n.Physics.P2.CollisionGroup(1),this.boundsCollisionGroup=new n.Physics.P2.CollisionGroup(2),this.everythingCollisionGroup=new n.Physics.P2.CollisionGroup(2147483648),this._collisionGroupID=2,this.setBoundsToWorld(!0,!0,!0,!0,!1)},clear:function(){this.world.time=0,this.world.fixedStepTime=0,this.world.solver&&this.world.solver.equations.length&&this.world.solver.removeAllEquations();for(var t=this.world.constraints,e=t.length-1;e>=0;e--)this.world.removeConstraint(t[e]);for(var i=this.world.bodies,e=i.length-1;e>=0;e--)this.world.removeBody(i[e]);for(var s=this.world.springs,e=s.length-1;e>=0;e--)this.world.removeSpring(s[e]);for(var n=this.world.contactMaterials,e=n.length-1;e>=0;e--)this.world.removeContactMaterial(n[e]);this.world.off("beginContact",this.beginContactHandler,this),this.world.off("endContact",this.endContactHandler,this),this.postBroadphaseCallback=null,this.callbackContext=null,this.impactCallback=null,this.collisionGroups=[],this._toRemove=[],this.boundsCollidesWith=[],this.walls={left:null,right:null,top:null,bottom:null}},destroy:function(){this.clear(),this.game=null},addBody:function(t){return!t.data.world&&(this.world.addBody(t.data),this.onBodyAdded.dispatch(t),!0)},removeBody:function(t){return t.data.world===this.world&&(this.world.removeBody(t.data),this.onBodyRemoved.dispatch(t)),t},addSpring:function(t){return t instanceof n.Physics.P2.Spring||t instanceof n.Physics.P2.RotationalSpring?this.world.addSpring(t.data):this.world.addSpring(t),this.onSpringAdded.dispatch(t),t},removeSpring:function(t){return t instanceof n.Physics.P2.Spring||t instanceof n.Physics.P2.RotationalSpring?this.world.removeSpring(t.data):this.world.removeSpring(t),this.onSpringRemoved.dispatch(t),t},createDistanceConstraint:function(t,e,i,s,r,o){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new n.Physics.P2.DistanceConstraint(this,t,e,i,s,r,o));console.warn("Cannot create Constraint, invalid body objects given")},createGearConstraint:function(t,e,i,s){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new n.Physics.P2.GearConstraint(this,t,e,i,s));console.warn("Cannot create Constraint, invalid body objects given")},createRevoluteConstraint:function(t,e,i,s,r,o){if(t=this.getBody(t),i=this.getBody(i),t&&i)return this.addConstraint(new n.Physics.P2.RevoluteConstraint(this,t,e,i,s,r,o));console.warn("Cannot create Constraint, invalid body objects given")},createLockConstraint:function(t,e,i,s,r){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new n.Physics.P2.LockConstraint(this,t,e,i,s,r));console.warn("Cannot create Constraint, invalid body objects given")},createPrismaticConstraint:function(t,e,i,s,r,o,a){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new n.Physics.P2.PrismaticConstraint(this,t,e,i,s,r,o,a));console.warn("Cannot create Constraint, invalid body objects given")},addConstraint:function(t){return this.world.addConstraint(t),this.onConstraintAdded.dispatch(t),t},removeConstraint:function(t){return this.world.removeConstraint(t),this.onConstraintRemoved.dispatch(t),t},addContactMaterial:function(t){return this.world.addContactMaterial(t),this.onContactMaterialAdded.dispatch(t),t},removeContactMaterial:function(t){return this.world.removeContactMaterial(t),this.onContactMaterialRemoved.dispatch(t),t},getContactMaterial:function(t,e){return this.world.getContactMaterial(t,e)},setMaterial:function(t,e){for(var i=e.length;i--;)e[i].setMaterial(t)},createMaterial:function(t,e){t=t||"";var i=new n.Physics.P2.Material(t);return this.materials.push(i),void 0!==e&&e.setMaterial(i),i},createContactMaterial:function(t,e,i){void 0===t&&(t=this.createMaterial()),void 0===e&&(e=this.createMaterial());var s=new n.Physics.P2.ContactMaterial(t,e,i);return this.addContactMaterial(s)},getBodies:function(){for(var t=[],e=this.world.bodies.length;e--;)t.push(this.world.bodies[e].parent);return t},getBody:function(t){return t instanceof p2.Body?t:t instanceof n.Physics.P2.Body?t.data:t.body&&t.body.type===n.Physics.P2JS?t.body.data:null},getSprings:function(){for(var t=[],e=this.world.springs.length;e--;)t.push(this.world.springs[e].parent);return t},getConstraints:function(){for(var t=[],e=this.world.constraints.length;e--;)t.push(this.world.constraints[e]);return t},hitTest:function(t,e,i,s){void 0===e&&(e=this.world.bodies),void 0===i&&(i=5),void 0===s&&(s=!1);for(var r=[this.pxmi(t.x),this.pxmi(t.y)],o=[],a=e.length;a--;)e[a]instanceof n.Physics.P2.Body&&(!s||e[a].data.type!==p2.Body.STATIC)?o.push(e[a].data):e[a]instanceof p2.Body&&e[a].parent&&(!s||e[a].type!==p2.Body.STATIC)?o.push(e[a]):e[a]instanceof n.Sprite&&e[a].hasOwnProperty("body")&&(!s||e[a].body.data.type!==p2.Body.STATIC)&&o.push(e[a].body.data);return this.world.hitTest(r,o,i)},toJSON:function(){return this.world.toJSON()},createCollisionGroup:function(t){var e=Math.pow(2,this._collisionGroupID);this.walls.left&&(this.walls.left.shapes[0].collisionMask=this.walls.left.shapes[0].collisionMask|e),this.walls.right&&(this.walls.right.shapes[0].collisionMask=this.walls.right.shapes[0].collisionMask|e),this.walls.top&&(this.walls.top.shapes[0].collisionMask=this.walls.top.shapes[0].collisionMask|e),this.walls.bottom&&(this.walls.bottom.shapes[0].collisionMask=this.walls.bottom.shapes[0].collisionMask|e),this._collisionGroupID++;var i=new n.Physics.P2.CollisionGroup(e);return this.collisionGroups.push(i),t&&this.setCollisionGroup(t,i),i},setCollisionGroup:function(t,e){if(t instanceof n.Group)for(var i=0;i<t.total;i++)t.children[i].body&&t.children[i].body.type===n.Physics.P2JS&&t.children[i].body.setCollisionGroup(e);else t.body.setCollisionGroup(e)},createSpring:function(t,e,i,s,r,o,a,h,l){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addSpring(new n.Physics.P2.Spring(this,t,e,i,s,r,o,a,h,l));console.warn("Cannot create Spring, invalid body objects given")},createRotationalSpring:function(t,e,i,s,r){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addSpring(new n.Physics.P2.RotationalSpring(this,t,e,i,s,r));console.warn("Cannot create Rotational Spring, invalid body objects given")},createBody:function(t,e,i,s,r,o){void 0===s&&(s=!1);var a=new n.Physics.P2.Body(this.game,null,t,e,i);if(o){if(!a.addPolygon(r,o))return!1}return s&&this.world.addBody(a.data),a},createParticle:function(t,e,i,s,r,o){void 0===s&&(s=!1);var a=new n.Physics.P2.Body(this.game,null,t,e,i);if(o){if(!a.addPolygon(r,o))return!1}return s&&this.world.addBody(a.data),a},convertCollisionObjects:function(t,e,i){void 0===i&&(i=!0);for(var s=[],n=0,r=t.collision[e].length;n<r;n++){var o=t.collision[e][n],a=this.createBody(o.x,o.y,0,i,{},o.polyline);a&&s.push(a)}return s},clearTilemapLayerBodies:function(t,e){e=t.getLayer(e);for(var i=t.layers[e].bodies.length;i--;)t.layers[e].bodies[i].destroy();t.layers[e].bodies.length=0},convertTilemap:function(t,e,i,s){e=t.getLayer(e),void 0===i&&(i=!0),void 0===s&&(s=!0),this.clearTilemapLayerBodies(t,e);for(var n=0,r=0,o=0,a=0,h=t.layers[e].height;a<h;a++){n=0;for(var l=0,c=t.layers[e].width;l<c;l++){var u=t.layers[e].data[a][l];if(u&&u.index>-1&&u.collides)if(s){var d=t.getTileRight(e,l,a);if(0===n&&(r=u.x*u.width,o=u.y*u.height,n=u.width),d&&d.collides)n+=u.width;else{var p=this.createBody(r,o,0,!1);p.addRectangle(n,u.height,n/2,u.height/2,0),i&&this.addBody(p),t.layers[e].bodies.push(p),n=0}}else{var p=this.createBody(u.x*u.width,u.y*u.height,0,!1);p.addRectangle(u.width,u.height,u.width/2,u.height/2,0),i&&this.addBody(p),t.layers[e].bodies.push(p)}}}return t.layers[e].bodies},mpx:function(t){return t*=20},pxm:function(t){return.05*t},mpxi:function(t){return t*=-20},pxmi:function(t){return-.05*t}},Object.defineProperty(n.Physics.P2.prototype,"friction",{get:function(){return this.world.defaultContactMaterial.friction},set:function(t){this.world.defaultContactMaterial.friction=t}}),Object.defineProperty(n.Physics.P2.prototype,"restitution",{get:function(){return this.world.defaultContactMaterial.restitution},set:function(t){this.world.defaultContactMaterial.restitution=t}}),Object.defineProperty(n.Physics.P2.prototype,"contactMaterial",{get:function(){return this.world.defaultContactMaterial},set:function(t){this.world.defaultContactMaterial=t}}),Object.defineProperty(n.Physics.P2.prototype,"applySpringForces",{get:function(){return this.world.applySpringForces},set:function(t){this.world.applySpringForces=t}}),Object.defineProperty(n.Physics.P2.prototype,"applyDamping",{get:function(){return this.world.applyDamping},set:function(t){this.world.applyDamping=t}}),Object.defineProperty(n.Physics.P2.prototype,"applyGravity",{get:function(){return this.world.applyGravity},set:function(t){this.world.applyGravity=t}}),Object.defineProperty(n.Physics.P2.prototype,"solveConstraints",{get:function(){return this.world.solveConstraints},set:function(t){this.world.solveConstraints=t}}),Object.defineProperty(n.Physics.P2.prototype,"time",{get:function(){return this.world.time}}),Object.defineProperty(n.Physics.P2.prototype,"emitImpactEvent",{get:function(){return this.world.emitImpactEvent},set:function(t){this.world.emitImpactEvent=t}}),Object.defineProperty(n.Physics.P2.prototype,"sleepMode",{get:function(){return this.world.sleepMode},set:function(t){this.world.sleepMode=t}}),Object.defineProperty(n.Physics.P2.prototype,"total",{get:function(){return this.world.bodies.length}}),n.Physics.P2.FixtureList=function(t){Array.isArray(t)||(t=[t]),this.rawList=t,this.init(),this.parse(this.rawList)},n.Physics.P2.FixtureList.prototype={init:function(){this.namedFixtures={},this.groupedFixtures=[],this.allFixtures=[]},setCategory:function(t,e){var i=function(e){e.collisionGroup=t};this.getFixtures(e).forEach(i)},setMask:function(t,e){var i=function(e){e.collisionMask=t};this.getFixtures(e).forEach(i)},setSensor:function(t,e){var i=function(e){e.sensor=t};this.getFixtures(e).forEach(i)},setMaterial:function(t,e){var i=function(e){e.material=t};this.getFixtures(e).forEach(i)},getFixtures:function(t){var e=[];if(t){t instanceof Array||(t=[t]);var i=this;return t.forEach(function(t){i.namedFixtures[t]&&e.push(i.namedFixtures[t])}),this.flatten(e)}return this.allFixtures},getFixtureByKey:function(t){return this.namedFixtures[t]},getGroup:function(t){return this.groupedFixtures[t]},parse:function(){var t,e,i,s;i=this.rawList,s=[];for(t in i)e=i[t],isNaN(t-0)?this.namedFixtures[t]=this.flatten(e):(this.groupedFixtures[t]=this.groupedFixtures[t]||[],this.groupedFixtures[t]=this.groupedFixtures[t].concat(e)),s.push(this.allFixtures=this.flatten(this.groupedFixtures))},flatten:function(t){var e,i;return e=[],i=arguments.callee,t.forEach(function(t){return Array.prototype.push.apply(e,Array.isArray(t)?i(t):[t])}),e}},n.Physics.P2.PointProxy=function(t,e){this.world=t,this.destination=e},n.Physics.P2.PointProxy.prototype.constructor=n.Physics.P2.PointProxy,Object.defineProperty(n.Physics.P2.PointProxy.prototype,"x",{get:function(){return this.world.mpx(this.destination[0])},set:function(t){this.destination[0]=this.world.pxm(t)}}),Object.defineProperty(n.Physics.P2.PointProxy.prototype,"y",{get:function(){return this.world.mpx(this.destination[1])},set:function(t){this.destination[1]=this.world.pxm(t)}}),Object.defineProperty(n.Physics.P2.PointProxy.prototype,"mx",{get:function(){return this.destination[0]},set:function(t){this.destination[0]=t}}),Object.defineProperty(n.Physics.P2.PointProxy.prototype,"my",{get:function(){return this.destination[1]},set:function(t){this.destination[1]=t}}),n.Physics.P2.InversePointProxy=function(t,e){this.world=t,this.destination=e},n.Physics.P2.InversePointProxy.prototype.constructor=n.Physics.P2.InversePointProxy,Object.defineProperty(n.Physics.P2.InversePointProxy.prototype,"x",{get:function(){return this.world.mpxi(this.destination[0])},set:function(t){this.destination[0]=this.world.pxmi(t)}}),Object.defineProperty(n.Physics.P2.InversePointProxy.prototype,"y",{get:function(){return this.world.mpxi(this.destination[1])},set:function(t){this.destination[1]=this.world.pxmi(t)}}),Object.defineProperty(n.Physics.P2.InversePointProxy.prototype,"mx",{get:function(){return this.destination[0]},set:function(t){this.destination[0]=-t}}),Object.defineProperty(n.Physics.P2.InversePointProxy.prototype,"my",{get:function(){return this.destination[1]},set:function(t){this.destination[1]=-t}}),n.Physics.P2.Body=function(t,e,i,s,r){e=e||null,i=i||0,s=s||0,void 0===r&&(r=1),this.game=t,this.world=t.physics.p2,this.sprite=e,this.type=n.Physics.P2JS,this.offset=new n.Point,this.data=new p2.Body({position:[this.world.pxmi(i),this.world.pxmi(s)],mass:r}),this.data.parent=this,this.velocity=new n.Physics.P2.InversePointProxy(this.world,this.data.velocity),this.force=new n.Physics.P2.InversePointProxy(this.world,this.data.force),this.gravity=new n.Point,this.onBeginContact=new n.Signal,this.onEndContact=new n.Signal,this.collidesWith=[],this.removeNextStep=!1,this.debugBody=null,this.dirty=!1,this._collideWorldBounds=!0,this._bodyCallbacks={},this._bodyCallbackContext={},this._groupCallbacks={},this._groupCallbackContext={},this._reset=!1,e&&(this.setRectangleFromSprite(e),e.exists&&this.game.physics.p2.addBody(this))},n.Physics.P2.Body.prototype={createBodyCallback:function(t,e,i){var s=-1;t.id?s=t.id:t.body&&(s=t.body.id),s>-1&&(null===e?(delete this._bodyCallbacks[s],delete this._bodyCallbackContext[s]):(this._bodyCallbacks[s]=e,this._bodyCallbackContext[s]=i))},createGroupCallback:function(t,e,i){null===e?(delete this._groupCallbacks[t.mask],delete this._groupCallbackContext[t.mask]):(this._groupCallbacks[t.mask]=e,this._groupCallbackContext[t.mask]=i)},getCollisionMask:function(){var t=0;this._collideWorldBounds&&(t=this.game.physics.p2.boundsCollisionGroup.mask);for(var e=0;e<this.collidesWith.length;e++)t|=this.collidesWith[e].mask;return t},updateCollisionMask:function(t){var e=this.getCollisionMask();if(void 0===t)for(var i=this.data.shapes.length-1;i>=0;i--)this.data.shapes[i].collisionMask=e;else t.collisionMask=e},setCollisionGroup:function(t,e){var i=this.getCollisionMask();if(void 0===e)for(var s=this.data.shapes.length-1;s>=0;s--)this.data.shapes[s].collisionGroup=t.mask,this.data.shapes[s].collisionMask=i;else e.collisionGroup=t.mask,e.collisionMask=i},clearCollision:function(t,e,i){if(void 0===t&&(t=!0),void 0===e&&(e=!0),void 0===i)for(var s=this.data.shapes.length-1;s>=0;s--)t&&(this.data.shapes[s].collisionGroup=null),e&&(this.data.shapes[s].collisionMask=null);else t&&(i.collisionGroup=null),e&&(i.collisionMask=null);t&&(this.collidesWith.length=0)},removeCollisionGroup:function(t,e,i){void 0===e&&(e=!0);var s;if(Array.isArray(t))for(var n=0;n<t.length;n++)(s=this.collidesWith.indexOf(t[n]))>-1&&(this.collidesWith.splice(s,1),e&&(delete this._groupCallbacks[t.mask],delete this._groupCallbackContext[t.mask]));else(s=this.collidesWith.indexOf(t))>-1&&(this.collidesWith.splice(s,1),e&&(delete this._groupCallbacks[t.mask],delete this._groupCallbackContext[t.mask]));var r=this.getCollisionMask();if(void 0===i)for(var n=this.data.shapes.length-1;n>=0;n--)this.data.shapes[n].collisionMask=r;else i.collisionMask=r},collides:function(t,e,i,s){if(Array.isArray(t))for(var n=0;n<t.length;n++)-1===this.collidesWith.indexOf(t[n])&&(this.collidesWith.push(t[n]),e&&this.createGroupCallback(t[n],e,i));else-1===this.collidesWith.indexOf(t)&&(this.collidesWith.push(t),e&&this.createGroupCallback(t,e,i));var r=this.getCollisionMask();if(void 0===s)for(var n=this.data.shapes.length-1;n>=0;n--)this.data.shapes[n].collisionMask=r;else s.collisionMask=r},adjustCenterOfMass:function(){this.data.adjustCenterOfMass(),this.shapeChanged()},getVelocityAtPoint:function(t,e){return this.data.getVelocityAtPoint(t,e)},applyDamping:function(t){this.data.applyDamping(t)},applyImpulse:function(t,e,i){this.data.applyImpulse(t,[this.world.pxmi(e),this.world.pxmi(i)])},applyImpulseLocal:function(t,e,i){this.data.applyImpulseLocal(t,[this.world.pxmi(e),this.world.pxmi(i)])},applyForce:function(t,e,i){this.data.applyForce(t,[this.world.pxmi(e),this.world.pxmi(i)])},setZeroForce:function(){this.data.setZeroForce()},setZeroRotation:function(){this.data.angularVelocity=0},setZeroVelocity:function(){this.data.velocity[0]=0,this.data.velocity[1]=0},setZeroDamping:function(){this.data.damping=0,this.data.angularDamping=0},toLocalFrame:function(t,e){return this.data.toLocalFrame(t,e)},toWorldFrame:function(t,e){return this.data.toWorldFrame(t,e)},rotateLeft:function(t){this.data.angularVelocity=this.world.pxm(-t)},rotateRight:function(t){this.data.angularVelocity=this.world.pxm(t)},moveForward:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.velocity[0]=e*Math.cos(i),this.data.velocity[1]=e*Math.sin(i)},moveBackward:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.velocity[0]=-e*Math.cos(i),this.data.velocity[1]=-e*Math.sin(i)},thrust:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.force[0]+=e*Math.cos(i),this.data.force[1]+=e*Math.sin(i)},thrustLeft:function(t){var e=this.world.pxmi(-t),i=this.data.angle;this.data.force[0]+=e*Math.cos(i),this.data.force[1]+=e*Math.sin(i)},thrustRight:function(t){var e=this.world.pxmi(-t),i=this.data.angle;this.data.force[0]-=e*Math.cos(i),this.data.force[1]-=e*Math.sin(i)},reverse:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.force[0]-=e*Math.cos(i),this.data.force[1]-=e*Math.sin(i)},moveLeft:function(t){this.data.velocity[0]=this.world.pxmi(-t)},moveRight:function(t){this.data.velocity[0]=this.world.pxmi(t)},moveUp:function(t){this.data.velocity[1]=this.world.pxmi(-t)},moveDown:function(t){this.data.velocity[1]=this.world.pxmi(t)},preUpdate:function(){this.dirty=!0,this.removeNextStep&&(this.removeFromWorld(),this.removeNextStep=!1)},postUpdate:function(){this.sprite.x=this.world.mpxi(this.data.position[0])+this.offset.x,this.sprite.y=this.world.mpxi(this.data.position[1])+this.offset.y,this.fixedRotation||(this.sprite.rotation=this.data.angle),this.debugBody&&this.debugBody.updateSpriteTransform(),this.dirty=!1},reset:function(t,e,i,s){void 0===i&&(i=!1),void 0===s&&(s=!1),this.setZeroForce(),this.setZeroVelocity(),this.setZeroRotation(),i&&this.setZeroDamping(),s&&(this.mass=1),this.x=t,this.y=e},addToWorld:function(){if(this.game.physics.p2._toRemove)for(var t=0;t<this.game.physics.p2._toRemove.length;t++)this.game.physics.p2._toRemove[t]===this&&this.game.physics.p2._toRemove.splice(t,1);this.data.world!==this.game.physics.p2.world&&this.game.physics.p2.addBody(this)},removeFromWorld:function(){this.data.world===this.game.physics.p2.world&&this.game.physics.p2.removeBodyNextStep(this)},destroy:function(){this.removeFromWorld(),this.clearShapes(),this._bodyCallbacks={},this._bodyCallbackContext={},this._groupCallbacks={},this._groupCallbackContext={},this.debugBody&&this.debugBody.destroy(!0,!0),this.debugBody=null,this.sprite&&(this.sprite.body=null,this.sprite=null)},clearShapes:function(){for(var t=this.data.shapes.length;t--;)this.data.removeShape(this.data.shapes[t]);this.shapeChanged()},addShape:function(t,e,i,s){return void 0===e&&(e=0),void 0===i&&(i=0),void 0===s&&(s=0),this.data.addShape(t,[this.world.pxmi(e),this.world.pxmi(i)],s),this.shapeChanged(),t},addCircle:function(t,e,i,s){var n=new p2.Circle({radius:this.world.pxm(t)});return this.addShape(n,e,i,s)},addRectangle:function(t,e,i,s,n){var r=new p2.Box({width:this.world.pxm(t),height:this.world.pxm(e)});return this.addShape(r,i,s,n)},addPlane:function(t,e,i){var s=new p2.Plane;return this.addShape(s,t,e,i)},addParticle:function(t,e,i){var s=new p2.Particle;return this.addShape(s,t,e,i)},addLine:function(t,e,i,s){var n=new p2.Line({length:this.world.pxm(t)});return this.addShape(n,e,i,s)},addCapsule:function(t,e,i,s,n){var r=new p2.Capsule({length:this.world.pxm(t),radius:this.world.pxm(e)});return this.addShape(r,i,s,n)},addPolygon:function(t,e){t=t||{},Array.isArray(e)||(e=Array.prototype.slice.call(arguments,1));var i=[];if(1===e.length&&Array.isArray(e[0]))i=e[0].slice(0);else if(Array.isArray(e[0]))i=e.slice();else if("number"==typeof e[0])for(var s=0,n=e.length;s<n;s+=2)i.push([e[s],e[s+1]]);var r=i.length-1;i[r][0]===i[0][0]&&i[r][1]===i[0][1]&&i.pop();for(var o=0;o<i.length;o++)i[o][0]=this.world.pxmi(i[o][0]),i[o][1]=this.world.pxmi(i[o][1]);var a=this.data.fromPolygon(i,t);return this.shapeChanged(),a},removeShape:function(t){var e=this.data.removeShape(t);return this.shapeChanged(),e},setCircle:function(t,e,i,s){return this.clearShapes(),this.addCircle(t,e,i,s)},setRectangle:function(t,e,i,s,n){return void 0===t&&(t=16),void 0===e&&(e=16),this.clearShapes(),this.addRectangle(t,e,i,s,n)},setRectangleFromSprite:function(t){return void 0===t&&(t=this.sprite),this.clearShapes(),this.addRectangle(t.width,t.height,0,0,t.rotation)},setMaterial:function(t,e){if(void 0===e)for(var i=this.data.shapes.length-1;i>=0;i--)this.data.shapes[i].material=t;else e.material=t},shapeChanged:function(){this.debugBody&&this.debugBody.draw()},addPhaserPolygon:function(t,e){for(var i=this.game.cache.getPhysicsData(t,e),s=[],n=0;n<i.length;n++){var r=i[n],o=this.addFixture(r);s[r.filter.group]=s[r.filter.group]||[],s[r.filter.group]=s[r.filter.group].concat(o),r.fixtureKey&&(s[r.fixtureKey]=o)}return this.data.aabbNeedsUpdate=!0,this.shapeChanged(),s},addFixture:function(t){var e=[];if(t.circle){var i=new p2.Circle({radius:this.world.pxm(t.circle.radius)});i.collisionGroup=t.filter.categoryBits,i.collisionMask=t.filter.maskBits,i.sensor=t.isSensor;var s=p2.vec2.create();s[0]=this.world.pxmi(t.circle.position[0]-this.sprite.width/2),s[1]=this.world.pxmi(t.circle.position[1]-this.sprite.height/2),this.data.addShape(i,s),e.push(i)}else for(var n=t.polygons,r=p2.vec2.create(),o=0;o<n.length;o++){for(var a=n[o],h=[],l=0;l<a.length;l+=2)h.push([this.world.pxmi(a[l]),this.world.pxmi(a[l+1])]);for(var i=new p2.Convex({vertices:h}),c=0;c!==i.vertices.length;c++){var u=i.vertices[c];p2.vec2.sub(u,u,i.centerOfMass)}p2.vec2.scale(r,i.centerOfMass,1),r[0]-=this.world.pxmi(this.sprite.width/2),r[1]-=this.world.pxmi(this.sprite.height/2),i.updateTriangles(),i.updateCenterOfMass(),i.updateBoundingRadius(),i.collisionGroup=t.filter.categoryBits,i.collisionMask=t.filter.maskBits,i.sensor=t.isSensor,this.data.addShape(i,r),e.push(i)}return e},loadPolygon:function(t,e){if(null===t)var i=e;else var i=this.game.cache.getPhysicsData(t,e);for(var s=p2.vec2.create(),n=0;n<i.length;n++){for(var r=[],o=0;o<i[n].shape.length;o+=2)r.push([this.world.pxmi(i[n].shape[o]),this.world.pxmi(i[n].shape[o+1])]);for(var a=new p2.Convex({vertices:r}),h=0;h!==a.vertices.length;h++){var l=a.vertices[h];p2.vec2.sub(l,l,a.centerOfMass)}p2.vec2.scale(s,a.centerOfMass,1),s[0]-=this.world.pxmi(this.sprite.width/2),s[1]-=this.world.pxmi(this.sprite.height/2),a.updateTriangles(),a.updateCenterOfMass(),a.updateBoundingRadius(),this.data.addShape(a,s)}return this.data.aabbNeedsUpdate=!0,this.shapeChanged(),!0}},n.Physics.P2.Body.prototype.constructor=n.Physics.P2.Body,n.Physics.P2.Body.DYNAMIC=1,n.Physics.P2.Body.STATIC=2,n.Physics.P2.Body.KINEMATIC=4,Object.defineProperty(n.Physics.P2.Body.prototype,"static",{get:function(){return this.data.type===n.Physics.P2.Body.STATIC},set:function(t){t&&this.data.type!==n.Physics.P2.Body.STATIC?(this.data.type=n.Physics.P2.Body.STATIC,this.mass=0):t||this.data.type!==n.Physics.P2.Body.STATIC||(this.data.type=n.Physics.P2.Body.DYNAMIC,this.mass=1)}}),Object.defineProperty(n.Physics.P2.Body.prototype,"dynamic",{get:function(){return this.data.type===n.Physics.P2.Body.DYNAMIC},set:function(t){t&&this.data.type!==n.Physics.P2.Body.DYNAMIC?(this.data.type=n.Physics.P2.Body.DYNAMIC,this.mass=1):t||this.data.type!==n.Physics.P2.Body.DYNAMIC||(this.data.type=n.Physics.P2.Body.STATIC,this.mass=0)}}),Object.defineProperty(n.Physics.P2.Body.prototype,"kinematic",{get:function(){return this.data.type===n.Physics.P2.Body.KINEMATIC},set:function(t){t&&this.data.type!==n.Physics.P2.Body.KINEMATIC?(this.data.type=n.Physics.P2.Body.KINEMATIC,this.mass=4):t||this.data.type!==n.Physics.P2.Body.KINEMATIC||(this.data.type=n.Physics.P2.Body.STATIC,this.mass=0)}}),Object.defineProperty(n.Physics.P2.Body.prototype,"allowSleep",{get:function(){return this.data.allowSleep},set:function(t){t!==this.data.allowSleep&&(this.data.allowSleep=t)}}),Object.defineProperty(n.Physics.P2.Body.prototype,"angle",{get:function(){return n.Math.wrapAngle(n.Math.radToDeg(this.data.angle))},set:function(t){this.data.angle=n.Math.degToRad(n.Math.wrapAngle(t))}}),Object.defineProperty(n.Physics.P2.Body.prototype,"angularDamping",{get:function(){return this.data.angularDamping},set:function(t){this.data.angularDamping=t}}),Object.defineProperty(n.Physics.P2.Body.prototype,"angularForce",{get:function(){return this.data.angularForce},set:function(t){this.data.angularForce=t}}),Object.defineProperty(n.Physics.P2.Body.prototype,"angularVelocity",{get:function(){return this.data.angularVelocity},set:function(t){this.data.angularVelocity=t}}),Object.defineProperty(n.Physics.P2.Body.prototype,"damping",{get:function(){return this.data.damping},set:function(t){this.data.damping=t}}),Object.defineProperty(n.Physics.P2.Body.prototype,"fixedRotation",{get:function(){return this.data.fixedRotation},set:function(t){t!==this.data.fixedRotation&&(this.data.fixedRotation=t)}}),Object.defineProperty(n.Physics.P2.Body.prototype,"inertia",{get:function(){return this.data.inertia},set:function(t){this.data.inertia=t}}),Object.defineProperty(n.Physics.P2.Body.prototype,"mass",{get:function(){return this.data.mass},set:function(t){t!==this.data.mass&&(this.data.mass=t,this.data.updateMassProperties())}}),Object.defineProperty(n.Physics.P2.Body.prototype,"motionState",{get:function(){return this.data.type},set:function(t){t!==this.data.type&&(this.data.type=t)}}),Object.defineProperty(n.Physics.P2.Body.prototype,"rotation",{get:function(){return this.data.angle},set:function(t){this.data.angle=t}}),Object.defineProperty(n.Physics.P2.Body.prototype,"sleepSpeedLimit",{get:function(){return this.data.sleepSpeedLimit},set:function(t){this.data.sleepSpeedLimit=t}}),Object.defineProperty(n.Physics.P2.Body.prototype,"x",{get:function(){return this.world.mpxi(this.data.position[0])},set:function(t){this.data.position[0]=this.world.pxmi(t)}}),Object.defineProperty(n.Physics.P2.Body.prototype,"y",{get:function(){return this.world.mpxi(this.data.position[1])},set:function(t){this.data.position[1]=this.world.pxmi(t)}}),Object.defineProperty(n.Physics.P2.Body.prototype,"id",{get:function(){return this.data.id}}),Object.defineProperty(n.Physics.P2.Body.prototype,"debug",{get:function(){return null!==this.debugBody},set:function(t){t&&!this.debugBody?this.debugBody=new n.Physics.P2.BodyDebug(this.game,this.data):!t&&this.debugBody&&(this.debugBody.destroy(),this.debugBody=null)}}),Object.defineProperty(n.Physics.P2.Body.prototype,"collideWorldBounds",{get:function(){return this._collideWorldBounds},set:function(t){t&&!this._collideWorldBounds?(this._collideWorldBounds=!0,this.updateCollisionMask()):!t&&this._collideWorldBounds&&(this._collideWorldBounds=!1,this.updateCollisionMask())}}),n.Physics.P2.BodyDebug=function(t,e,i){n.Group.call(this,t);var s={pixelsPerLengthUnit:t.physics.p2.mpx(1),debugPolygons:!1,lineWidth:1,alpha:.5};this.settings=n.Utils.extend(s,i),this.ppu=this.settings.pixelsPerLengthUnit,this.ppu=-1*this.ppu,this.body=e,this.canvas=new n.Graphics(t),this.canvas.alpha=this.settings.alpha,this.add(this.canvas),this.draw(),this.updateSpriteTransform()},n.Physics.P2.BodyDebug.prototype=Object.create(n.Group.prototype),n.Physics.P2.BodyDebug.prototype.constructor=n.Physics.P2.BodyDebug,n.Utils.extend(n.Physics.P2.BodyDebug.prototype,{updateSpriteTransform:function(){this.position.x=this.body.position[0]*this.ppu,this.position.y=this.body.position[1]*this.ppu,this.rotation=this.body.angle},draw:function(){var t,e,i,s,n,r,o,a,h,l,c,u,d,p,f;if(a=this.body,l=this.canvas,l.clear(),i=parseInt(this.randomPastelHex(),16),r=16711680,o=this.lineWidth,a instanceof p2.Body&&a.shapes.length){var g=a.shapes.length;for(s=0;s!==g;){if(e=a.shapes[s],h=e.position||0,t=e.angle||0,e instanceof p2.Circle)this.drawCircle(l,h[0]*this.ppu,h[1]*this.ppu,t,e.radius*this.ppu,i,o);else if(e instanceof p2.Capsule)this.drawCapsule(l,h[0]*this.ppu,h[1]*this.ppu,t,e.length*this.ppu,e.radius*this.ppu,r,i,o);else if(e instanceof p2.Plane)this.drawPlane(l,h[0]*this.ppu,-h[1]*this.ppu,i,r,5*o,10*o,10*o,100*this.ppu,t);else if(e instanceof p2.Line)this.drawLine(l,e.length*this.ppu,r,o);else if(e instanceof p2.Box)this.drawRectangle(l,h[0]*this.ppu,h[1]*this.ppu,t,e.width*this.ppu,e.height*this.ppu,r,i,o);else if(e instanceof p2.Convex){for(u=[],d=p2.vec2.create(),n=p=0,f=e.vertices.length;0<=f?p<f:p>f;n=0<=f?++p:--p)c=e.vertices[n],p2.vec2.rotate(d,c,t),u.push([(d[0]+h[0])*this.ppu,-(d[1]+h[1])*this.ppu]);this.drawConvex(l,u,e.triangles,r,i,o,this.settings.debugPolygons,[h[0]*this.ppu,-h[1]*this.ppu])}s++}}},drawRectangle:function(t,e,i,s,n,r,o,a,h){void 0===h&&(h=1),void 0===o&&(o=0),t.lineStyle(h,o,1),t.beginFill(a),t.drawRect(e-n/2,i-r/2,n,r)},drawCircle:function(t,e,i,s,n,r,o){void 0===o&&(o=1),void 0===r&&(r=16777215),t.lineStyle(o,0,1),t.beginFill(r,1),t.drawCircle(e,i,2*-n),t.endFill(),t.moveTo(e,i),t.lineTo(e+n*Math.cos(-s),i+n*Math.sin(-s))},drawLine:function(t,e,i,s){void 0===s&&(s=1),void 0===i&&(i=0),t.lineStyle(5*s,i,1),t.moveTo(-e/2,0),t.lineTo(e/2,0)},drawConvex:function(t,e,i,s,n,r,o,a){var h,l,c,u,d,p,f,g,m,y,v;if(void 0===r&&(r=1),void 0===s&&(s=0),o){for(h=[16711680,65280,255],l=0;l!==e.length+1;)u=e[l%e.length],d=e[(l+1)%e.length],f=u[0],y=u[1],g=d[0],v=d[1],t.lineStyle(r,h[l%h.length],1),t.moveTo(f,-y),t.lineTo(g,-v),t.drawCircle(f,-y,2*r),l++;return t.lineStyle(r,0,1),t.drawCircle(a[0],a[1],2*r)}for(t.lineStyle(r,s,1),t.beginFill(n),l=0;l!==e.length;)c=e[l],p=c[0],m=c[1],0===l?t.moveTo(p,-m):t.lineTo(p,-m),l++;if(t.endFill(),e.length>2)return t.moveTo(e[e.length-1][0],-e[e.length-1][1]),t.lineTo(e[0][0],-e[0][1])},drawPath:function(t,e,i,s,n){var r,o,a,h,l,c,u,d,p,f,g,m;for(void 0===n&&(n=1),void 0===i&&(i=0),t.lineStyle(n,i,1),"number"==typeof s&&t.beginFill(s),o=null,a=null,r=0;r<e.length;)f=e[r],g=f[0],m=f[1],g===o&&m===a||(0===r?t.moveTo(g,m):(h=o,l=a,c=g,u=m,d=e[(r+1)%e.length][0],p=e[(r+1)%e.length][1],0!==(c-h)*(p-l)-(d-h)*(u-l)&&t.lineTo(g,m)),o=g,a=m),r++;"number"==typeof s&&t.endFill(),e.length>2&&"number"==typeof s&&(t.moveTo(e[e.length-1][0],e[e.length-1][1]),t.lineTo(e[0][0],e[0][1]))},drawPlane:function(t,e,i,s,n,r,o,a,h,l){var c,u;void 0===r&&(r=1),void 0===s&&(s=16777215),t.lineStyle(r,n,11),t.beginFill(s),t.moveTo(e,-i),c=e+Math.cos(l)*this.game.width,u=i+Math.sin(l)*this.game.height,t.lineTo(c,-u),t.moveTo(e,-i),c=e+Math.cos(l)*-this.game.width,u=i+Math.sin(l)*-this.game.height,t.lineTo(c,-u)},drawCapsule:function(t,e,i,s,n,r,o,a,h){void 0===h&&(h=1),void 0===o&&(o=0),t.lineStyle(h,o,1);var l=Math.cos(s),c=Math.sin(s);t.beginFill(a,1),t.drawCircle(-n/2*l+e,-n/2*c+i,2*-r),t.drawCircle(n/2*l+e,n/2*c+i,2*-r),t.endFill(),t.lineStyle(h,o,0),t.beginFill(a,1),t.moveTo(-n/2*l+r*c+e,-n/2*c+r*l+i),t.lineTo(n/2*l+r*c+e,n/2*c+r*l+i),t.lineTo(n/2*l-r*c+e,n/2*c-r*l+i),t.lineTo(-n/2*l-r*c+e,-n/2*c-r*l+i),t.endFill(),t.lineStyle(h,o,1),t.moveTo(-n/2*l+r*c+e,-n/2*c+r*l+i),t.lineTo(n/2*l+r*c+e,n/2*c+r*l+i),t.moveTo(-n/2*l-r*c+e,-n/2*c-r*l+i),t.lineTo(n/2*l-r*c+e,n/2*c-r*l+i)},randomPastelHex:function(){var t,e,i,s;return i=[255,255,255],s=Math.floor(256*Math.random()),e=Math.floor(256*Math.random()),t=Math.floor(256*Math.random()),s=Math.floor((s+3*i[0])/4),e=Math.floor((e+3*i[1])/4),t=Math.floor((t+3*i[2])/4),this.rgbToHex(s,e,t)},rgbToHex:function(t,e,i){return this.componentToHex(t)+this.componentToHex(e)+this.componentToHex(i)},componentToHex:function(t){var e;return e=t.toString(16),2===e.length?e:e+"0"}}),n.Physics.P2.Spring=function(t,e,i,s,n,r,o,a,h,l){this.game=t.game,this.world=t,void 0===s&&(s=1),void 0===n&&(n=100),void 0===r&&(r=1),s=t.pxm(s);var c={restLength:s,stiffness:n,damping:r};void 0!==o&&null!==o&&(c.worldAnchorA=[t.pxm(o[0]),t.pxm(o[1])]),void 0!==a&&null!==a&&(c.worldAnchorB=[t.pxm(a[0]),t.pxm(a[1])]),void 0!==h&&null!==h&&(c.localAnchorA=[t.pxm(h[0]),t.pxm(h[1])]),void 0!==l&&null!==l&&(c.localAnchorB=[t.pxm(l[0]),t.pxm(l[1])]),this.data=new p2.LinearSpring(e,i,c),this.data.parent=this},n.Physics.P2.Spring.prototype.constructor=n.Physics.P2.Spring,n.Physics.P2.RotationalSpring=function(t,e,i,s,n,r){this.game=t.game,this.world=t,void 0===s&&(s=null),void 0===n&&(n=100),void 0===r&&(r=1),s&&(s=t.pxm(s));var o={restAngle:s,stiffness:n,damping:r};this.data=new p2.RotationalSpring(e,i,o),this.data.parent=this},n.Physics.P2.Spring.prototype.constructor=n.Physics.P2.Spring,n.Physics.P2.Material=function(t){this.name=t,p2.Material.call(this)},n.Physics.P2.Material.prototype=Object.create(p2.Material.prototype),n.Physics.P2.Material.prototype.constructor=n.Physics.P2.Material,n.Physics.P2.ContactMaterial=function(t,e,i){p2.ContactMaterial.call(this,t,e,i)},n.Physics.P2.ContactMaterial.prototype=Object.create(p2.ContactMaterial.prototype),n.Physics.P2.ContactMaterial.prototype.constructor=n.Physics.P2.ContactMaterial,n.Physics.P2.CollisionGroup=function(t){this.mask=t},n.Physics.P2.DistanceConstraint=function(t,e,i,s,n,r,o){void 0===s&&(s=100),void 0===n&&(n=[0,0]),void 0===r&&(r=[0,0]),void 0===o&&(o=Number.MAX_VALUE),this.game=t.game,this.world=t,s=t.pxm(s),n=[t.pxmi(n[0]),t.pxmi(n[1])],r=[t.pxmi(r[0]),t.pxmi(r[1])];var a={distance:s,localAnchorA:n,localAnchorB:r,maxForce:o};p2.DistanceConstraint.call(this,e,i,a)},n.Physics.P2.DistanceConstraint.prototype=Object.create(p2.DistanceConstraint.prototype),n.Physics.P2.DistanceConstraint.prototype.constructor=n.Physics.P2.DistanceConstraint,n.Physics.P2.GearConstraint=function(t,e,i,s,n){void 0===s&&(s=0),void 0===n&&(n=1),this.game=t.game,this.world=t;var r={angle:s,ratio:n};p2.GearConstraint.call(this,e,i,r)},n.Physics.P2.GearConstraint.prototype=Object.create(p2.GearConstraint.prototype),n.Physics.P2.GearConstraint.prototype.constructor=n.Physics.P2.GearConstraint,n.Physics.P2.LockConstraint=function(t,e,i,s,n,r){void 0===s&&(s=[0,0]),void 0===n&&(n=0),void 0===r&&(r=Number.MAX_VALUE),this.game=t.game,this.world=t,s=[t.pxm(s[0]),t.pxm(s[1])];var o={localOffsetB:s,localAngleB:n,maxForce:r};p2.LockConstraint.call(this,e,i,o)},n.Physics.P2.LockConstraint.prototype=Object.create(p2.LockConstraint.prototype),n.Physics.P2.LockConstraint.prototype.constructor=n.Physics.P2.LockConstraint,n.Physics.P2.PrismaticConstraint=function(t,e,i,s,n,r,o,a){void 0===s&&(s=!0),void 0===n&&(n=[0,0]),void 0===r&&(r=[0,0]),void 0===o&&(o=[0,0]),void 0===a&&(a=Number.MAX_VALUE),this.game=t.game,this.world=t,n=[t.pxmi(n[0]),t.pxmi(n[1])],r=[t.pxmi(r[0]),t.pxmi(r[1])];var h={localAnchorA:n,localAnchorB:r,localAxisA:o,maxForce:a,disableRotationalLock:!s};p2.PrismaticConstraint.call(this,e,i,h)},n.Physics.P2.PrismaticConstraint.prototype=Object.create(p2.PrismaticConstraint.prototype),n.Physics.P2.PrismaticConstraint.prototype.constructor=n.Physics.P2.PrismaticConstraint,n.Physics.P2.RevoluteConstraint=function(t,e,i,s,n,r,o){void 0===r&&(r=Number.MAX_VALUE),void 0===o&&(o=null),this.game=t.game,this.world=t,i=[t.pxmi(i[0]),t.pxmi(i[1])],n=[t.pxmi(n[0]),t.pxmi(n[1])],o&&(o=[t.pxmi(o[0]),t.pxmi(o[1])]);var a={worldPivot:o,localPivotA:i,localPivotB:n,maxForce:r};p2.RevoluteConstraint.call(this,e,s,a)},n.Physics.P2.RevoluteConstraint.prototype=Object.create(p2.RevoluteConstraint.prototype),n.Physics.P2.RevoluteConstraint.prototype.constructor=n.Physics.P2.RevoluteConstraint,n.ImageCollection=function(t,e,i,s,n,r,o){(void 0===i||i<=0)&&(i=32),(void 0===s||s<=0)&&(s=32),void 0===n&&(n=0),void 0===r&&(r=0),this.name=t,this.firstgid=0|e,this.imageWidth=0|i,this.imageHeight=0|s,this.imageMargin=0|n,this.imageSpacing=0|r,this.properties=o||{},this.images=[],this.total=0},n.ImageCollection.prototype={containsImageIndex:function(t){return t>=this.firstgid&&t<this.firstgid+this.total},addImage:function(t,e){this.images.push({gid:t,image:e}),this.total++}},n.ImageCollection.prototype.constructor=n.ImageCollection,n.Tile=function(t,e,i,s,n,r){this.layer=t,this.index=e,this.x=i,this.y=s,this.rotation=0,this.flipped=!1,this.worldX=i*n,this.worldY=s*r,this.width=n,this.height=r,this.centerX=Math.abs(n/2),this.centerY=Math.abs(r/2),this.alpha=1,this.properties={},this.scanned=!1,this.faceTop=!1,this.faceBottom=!1,this.faceLeft=!1,this.faceRight=!1,this.collideLeft=!1,this.collideRight=!1,this.collideUp=!1,this.collideDown=!1,this.collisionCallback=null,this.collisionCallbackContext=this},n.Tile.prototype={containsPoint:function(t,e){return!(t<this.worldX||e<this.worldY||t>this.right||e>this.bottom)},intersects:function(t,e,i,s){return!(i<=this.worldX)&&(!(s<=this.worldY)&&(!(t>=this.worldX+this.width)&&!(e>=this.worldY+this.height)))},setCollisionCallback:function(t,e){this.collisionCallback=t,this.collisionCallbackContext=e},destroy:function(){this.collisionCallback=null,this.collisionCallbackContext=null,this.properties=null},setCollision:function(t,e,i,s){this.collideLeft=t,this.collideRight=e,this.collideUp=i,this.collideDown=s,this.faceLeft=t,this.faceRight=e,this.faceTop=i,this.faceBottom=s},resetCollision:function(){this.collideLeft=!1,this.collideRight=!1,this.collideUp=!1,this.collideDown=!1,this.faceTop=!1,this.faceBottom=!1,this.faceLeft=!1,this.faceRight=!1},isInteresting:function(t,e){return t&&e?this.collideLeft||this.collideRight||this.collideUp||this.collideDown||this.faceTop||this.faceBottom||this.faceLeft||this.faceRight||this.collisionCallback:t?this.collideLeft||this.collideRight||this.collideUp||this.collideDown:!!e&&(this.faceTop||this.faceBottom||this.faceLeft||this.faceRight)},copy:function(t){this.index=t.index,this.alpha=t.alpha,this.properties=t.properties,this.collideUp=t.collideUp,this.collideDown=t.collideDown,this.collideLeft=t.collideLeft,this.collideRight=t.collideRight,this.collisionCallback=t.collisionCallback,this.collisionCallbackContext=t.collisionCallbackContext}},n.Tile.prototype.constructor=n.Tile,Object.defineProperty(n.Tile.prototype,"collides",{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown}}),Object.defineProperty(n.Tile.prototype,"canCollide",{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown||this.collisionCallback}}),Object.defineProperty(n.Tile.prototype,"left",{get:function(){return this.worldX}}),Object.defineProperty(n.Tile.prototype,"right",{get:function(){return this.worldX+this.width}}),Object.defineProperty(n.Tile.prototype,"top",{get:function(){return this.worldY}}),Object.defineProperty(n.Tile.prototype,"bottom",{get:function(){return this.worldY+this.height}}),n.Tilemap=function(t,e,i,s,r,o){this.game=t,this.key=e;var a=n.TilemapParser.parse(this.game,e,i,s,r,o);null!==a&&(this.width=a.width,this.height=a.height,this.tileWidth=a.tileWidth,this.tileHeight=a.tileHeight,this.orientation=a.orientation,this.format=a.format,this.version=a.version,this.properties=a.properties,this.widthInPixels=a.widthInPixels,this.heightInPixels=a.heightInPixels,this.layers=a.layers,this.tilesets=a.tilesets,this.imagecollections=a.imagecollections,this.tiles=a.tiles,this.objects=a.objects,this.collideIndexes=[],this.collision=a.collision,this.images=a.images,this.enableDebug=!1,this.currentLayer=0,this.debugMap=[],this._results=[],this._tempA=0,this._tempB=0)},n.Tilemap.CSV=0,n.Tilemap.TILED_JSON=1,n.Tilemap.NORTH=0,n.Tilemap.EAST=1,n.Tilemap.SOUTH=2,n.Tilemap.WEST=3,n.Tilemap.prototype={create:function(t,e,i,s,n,r){return void 0===r&&(r=this.game.world),this.width=e,this.height=i,this.setTileSize(s,n),this.layers.length=0,this.createBlankLayer(t,e,i,s,n,r)},setTileSize:function(t,e){this.tileWidth=t,this.tileHeight=e,this.widthInPixels=this.width*t,this.heightInPixels=this.height*e},addTilesetImage:function(t,e,i,s,r,o,a){if(void 0===t)return null;void 0===i&&(i=this.tileWidth),void 0===s&&(s=this.tileHeight),void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=0),0===i&&(i=32),0===s&&(s=32);var h=null;if(void 0!==e&&null!==e||(e=t),e instanceof n.BitmapData)h=e.canvas;else{if(!this.game.cache.checkImageKey(e))return console.warn('Phaser.Tilemap.addTilesetImage: Invalid image key given: "'+e+'"'),null;h=this.game.cache.getImage(e)}var l=this.getTilesetIndex(t);if(null===l&&this.format===n.Tilemap.TILED_JSON)return console.warn('Phaser.Tilemap.addTilesetImage: No data found in the JSON matching the tileset name: "'+t+'"'),null;if(this.tilesets[l])return this.tilesets[l].setImage(h),this.tilesets[l];var c=new n.Tileset(t,a,i,s,r,o,{});c.setImage(h),this.tilesets.push(c);for(var u=this.tilesets.length-1,d=r,p=r,f=0,g=0,m=0,y=a;y<a+c.total&&(this.tiles[y]=[d,p,u],d+=i+o,++f!==c.total)&&(++g!==c.columns||(d=r,p+=s+o,g=0,++m!==c.rows));y++);return c},createFromObjects:function(t,e,i,s,r,o,a,h,l){if(void 0===r&&(r=!0),void 0===o&&(o=!1),void 0===a&&(a=this.game.world),void 0===h&&(h=n.Sprite),void 0===l&&(l=!0),!this.objects[t])return void console.warn("Tilemap.createFromObjects: Invalid objectgroup name given: "+t);for(var c=0;c<this.objects[t].length;c++){var u=!1,d=this.objects[t][c];if(void 0!==d.gid&&"number"==typeof e&&d.gid===e?u=!0:void 0!==d.id&&"number"==typeof e&&d.id===e?u=!0:void 0!==d.name&&"string"==typeof e&&d.name===e&&(u=!0),u){var p=new h(this.game,parseFloat(d.x,10),parseFloat(d.y,10),i,s);p.name=d.name,p.visible=d.visible,p.autoCull=o,p.exists=r,d.width&&(p.width=d.width),d.height&&(p.height=d.height),d.rotation&&(p.angle=d.rotation),l&&(p.y-=p.height),a.add(p);for(var f in d.properties)a.set(p,f,d.properties[f],!1,!1,0,!0)}}},createFromTiles:function(t,e,i,s,r,o){"number"==typeof t&&(t=[t]),void 0===e||null===e?e=[]:"number"==typeof e&&(e=[e]),s=this.getLayer(s),void 0===r&&(r=this.game.world),void 0===o&&(o={}),void 0===o.customClass&&(o.customClass=n.Sprite),void 0===o.adjustY&&(o.adjustY=!0);var a=this.layers[s].width,h=this.layers[s].height;if(this.copy(0,0,a,h,s),this._results.length<2)return 0;for(var l,c=0,u=1,d=this._results.length;u<d;u++)if(-1!==t.indexOf(this._results[u].index)){l=new o.customClass(this.game,this._results[u].worldX,this._results[u].worldY,i);for(var p in o)l[p]=o[p];r.add(l),c++}if(1===e.length)for(u=0;u<t.length;u++)this.replace(t[u],e[0],0,0,a,h,s);else if(e.length>1)for(u=0;u<t.length;u++)this.replace(t[u],e[u],0,0,a,h,s);return c},createLayer:function(t,e,i,s){void 0===e&&(e=this.game.width),void 0===i&&(i=this.game.height),void 0===s&&(s=this.game.world);var r=t;if("string"==typeof t&&(r=this.getLayerIndex(t)),null===r||r>this.layers.length)return void console.warn("Tilemap.createLayer: Invalid layer ID given: "+r);void 0===e||e<=0?e=Math.min(this.game.width,this.layers[r].widthInPixels):e>this.game.width&&(e=this.game.width),void 0===i||i<=0?i=Math.min(this.game.height,this.layers[r].heightInPixels):i>this.game.height&&(i=this.game.height),this.enableDebug&&(console.group("Tilemap.createLayer"),console.log("Name:",this.layers[r].name),console.log("Size:",e,"x",i),console.log("Tileset:",this.tilesets[0].name,"index:",r));var o=s.add(new n.TilemapLayer(this.game,this,r,e,i));return this.enableDebug&&console.groupEnd(),o},createBlankLayer:function(t,e,i,s,r,o){if(void 0===o&&(o=this.game.world),null!==this.getLayerIndex(t))return void console.warn("Tilemap.createBlankLayer: Layer with matching name already exists: "+t);for(var a,h={name:t,x:0,y:0,width:e,height:i,widthInPixels:e*s,heightInPixels:i*r,alpha:1,visible:!0,properties:{},indexes:[],callbacks:[],bodies:[],data:null},l=[],c=0;c<i;c++){a=[];for(var u=0;u<e;u++)a.push(new n.Tile(h,-1,u,c,s,r));l.push(a)}h.data=l,this.layers.push(h),this.currentLayer=this.layers.length-1;var d=h.widthInPixels,p=h.heightInPixels;d>this.game.width&&(d=this.game.width),p>this.game.height&&(p=this.game.height);var l=new n.TilemapLayer(this.game,this,this.layers.length-1,d,p);return l.name=t,o.add(l)},getIndex:function(t,e){for(var i=0;i<t.length;i++)if(t[i].name===e)return i;return null},getLayerIndex:function(t){return this.getIndex(this.layers,t)},getTilesetIndex:function(t){return this.getIndex(this.tilesets,t)},getImageIndex:function(t){return this.getIndex(this.images,t)},setTileIndexCallback:function(t,e,i,s){if(s=this.getLayer(s),"number"==typeof t)this.layers[s].callbacks[t]={callback:e,callbackContext:i};else for(var n=0,r=t.length;n<r;n++)this.layers[s].callbacks[t[n]]={callback:e,callbackContext:i}},setTileLocationCallback:function(t,e,i,s,n,r,o){if(o=this.getLayer(o),this.copy(t,e,i,s,o),!(this._results.length<2))for(var a=1;a<this._results.length;a++)this._results[a].setCollisionCallback(n,r)},setCollision:function(t,e,i,s){if(void 0===e&&(e=!0),void 0===s&&(s=!0),i=this.getLayer(i),"number"==typeof t)return this.setCollisionByIndex(t,e,i,!0);if(Array.isArray(t)){for(var n=0;n<t.length;n++)this.setCollisionByIndex(t[n],e,i,!1);s&&this.calculateFaces(i)}},setCollisionBetween:function(t,e,i,s,n){if(void 0===i&&(i=!0),void 0===n&&(n=!0),s=this.getLayer(s),!(t>e)){for(var r=t;r<=e;r++)this.setCollisionByIndex(r,i,s,!1);n&&this.calculateFaces(s)}},setCollisionByExclusion:function(t,e,i,s){void 0===e&&(e=!0),void 0===s&&(s=!0),i=this.getLayer(i);for(var n=0,r=this.tiles.length;n<r;n++)-1===t.indexOf(n)&&this.setCollisionByIndex(n,e,i,!1);s&&this.calculateFaces(i)},setCollisionByIndex:function(t,e,i,s){if(void 0===e&&(e=!0),void 0===i&&(i=this.currentLayer),void 0===s&&(s=!0),e)this.collideIndexes.push(t);else{var n=this.collideIndexes.indexOf(t);n>-1&&this.collideIndexes.splice(n,1)}for(var r=0;r<this.layers[i].height;r++)for(var o=0;o<this.layers[i].width;o++){var a=this.layers[i].data[r][o];a&&a.index===t&&(e?a.setCollision(!0,!0,!0,!0):a.resetCollision(),a.faceTop=e,a.faceBottom=e,a.faceLeft=e,a.faceRight=e)}return s&&this.calculateFaces(i),i},getLayer:function(t){return void 0===t?t=this.currentLayer:"string"==typeof t?t=this.getLayerIndex(t):t instanceof n.TilemapLayer&&(t=t.index),t},setPreventRecalculate:function(t){if(!0===t&&!0!==this.preventingRecalculate&&(this.preventingRecalculate=!0,this.needToRecalculate={}),!1===t&&!0===this.preventingRecalculate){this.preventingRecalculate=!1;for(var e in this.needToRecalculate)this.calculateFaces(e);this.needToRecalculate=!1}},calculateFaces:function(t){if(this.preventingRecalculate)return void(this.needToRecalculate[t]=!0);for(var e=null,i=null,s=null,n=null,r=0,o=this.layers[t].height;r<o;r++)for(var a=0,h=this.layers[t].width;a<h;a++){var l=this.layers[t].data[r][a];l&&(e=this.getTileAbove(t,a,r),i=this.getTileBelow(t,a,r),s=this.getTileLeft(t,a,r),n=this.getTileRight(t,a,r),l.collides&&(l.faceTop=!0,l.faceBottom=!0,l.faceLeft=!0,l.faceRight=!0),e&&e.collides&&(l.faceTop=!1),i&&i.collides&&(l.faceBottom=!1),s&&s.collides&&(l.faceLeft=!1),n&&n.collides&&(l.faceRight=!1))}},getTileAbove:function(t,e,i){return i>0?this.layers[t].data[i-1][e]:null},getTileBelow:function(t,e,i){return i<this.layers[t].height-1?this.layers[t].data[i+1][e]:null},getTileLeft:function(t,e,i){return e>0?this.layers[t].data[i][e-1]:null},getTileRight:function(t,e,i){return e<this.layers[t].width-1?this.layers[t].data[i][e+1]:null},setLayer:function(t){t=this.getLayer(t),this.layers[t]&&(this.currentLayer=t)},hasTile:function(t,e,i){return i=this.getLayer(i),void 0!==this.layers[i].data[e]&&void 0!==this.layers[i].data[e][t]&&this.layers[i].data[e][t].index>-1},removeTile:function(t,e,i){if(i=this.getLayer(i),t>=0&&t<this.layers[i].width&&e>=0&&e<this.layers[i].height&&this.hasTile(t,e,i)){var s=this.layers[i].data[e][t];return this.layers[i].data[e][t]=new n.Tile(this.layers[i],-1,t,e,this.tileWidth,this.tileHeight),this.layers[i].dirty=!0,this.calculateFaces(i),s}},removeTileWorldXY:function(t,e,i,s,n){return n=this.getLayer(n),t=this.game.math.snapToFloor(t,i)/i,e=this.game.math.snapToFloor(e,s)/s,this.removeTile(t,e,n)},putTile:function(t,e,i,s){if(null===t)return this.removeTile(e,i,s);if(s=this.getLayer(s),e>=0&&e<this.layers[s].width&&i>=0&&i<this.layers[s].height){var r;return t instanceof n.Tile?(r=t.index,this.hasTile(e,i,s)?this.layers[s].data[i][e].copy(t):this.layers[s].data[i][e]=new n.Tile(s,r,e,i,t.width,t.height)):(r=t,this.hasTile(e,i,s)?this.layers[s].data[i][e].index=r:this.layers[s].data[i][e]=new n.Tile(this.layers[s],r,e,i,this.tileWidth,this.tileHeight)),this.collideIndexes.indexOf(r)>-1?this.layers[s].data[i][e].setCollision(!0,!0,!0,!0):this.layers[s].data[i][e].resetCollision(),this.layers[s].dirty=!0,this.calculateFaces(s),this.layers[s].data[i][e]}return null},putTileWorldXY:function(t,e,i,s,n,r){return r=this.getLayer(r),e=this.game.math.snapToFloor(e,s)/s,i=this.game.math.snapToFloor(i,n)/n,this.putTile(t,e,i,r)},searchTileIndex:function(t,e,i,s){void 0===e&&(e=0),void 0===i&&(i=!1),s=this.getLayer(s);var n=0;if(i){for(var r=this.layers[s].height-1;r>=0;r--)for(var o=this.layers[s].width-1;o>=0;o--)if(this.layers[s].data[r][o].index===t){if(n===e)return this.layers[s].data[r][o];n++}}else for(var r=0;r<this.layers[s].height;r++)for(var o=0;o<this.layers[s].width;o++)if(this.layers[s].data[r][o].index===t){if(n===e)return this.layers[s].data[r][o];n++}return null},getTile:function(t,e,i,s){return void 0===s&&(s=!1),i=this.getLayer(i),t>=0&&t<this.layers[i].width&&e>=0&&e<this.layers[i].height?-1===this.layers[i].data[e][t].index?s?this.layers[i].data[e][t]:null:this.layers[i].data[e][t]:null},getTileWorldXY:function(t,e,i,s,n,r){return void 0===i&&(i=this.tileWidth),void 0===s&&(s=this.tileHeight),n=this.getLayer(n),t=this.game.math.snapToFloor(t,i)/i,e=this.game.math.snapToFloor(e,s)/s,this.getTile(t,e,n,r)},copy:function(t,e,i,s,n){if(n=this.getLayer(n),!this.layers[n])return void(this._results.length=0);void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=this.layers[n].width),void 0===s&&(s=this.layers[n].height),t<0&&(t=0),e<0&&(e=0),i>this.layers[n].width&&(i=this.layers[n].width),s>this.layers[n].height&&(s=this.layers[n].height),this._results.length=0,this._results.push({x:t,y:e,width:i,height:s,layer:n});for(var r=e;r<e+s;r++)for(var o=t;o<t+i;o++)this._results.push(this.layers[n].data[r][o]);return this._results},paste:function(t,e,i,s){if(void 0===t&&(t=0),void 0===e&&(e=0),s=this.getLayer(s),i&&!(i.length<2)){for(var n=t-i[1].x,r=e-i[1].y,o=1;o<i.length;o++)this.layers[s].data[r+i[o].y][n+i[o].x].copy(i[o]);this.layers[s].dirty=!0,this.calculateFaces(s)}},swap:function(t,e,i,s,n,r,o){o=this.getLayer(o),this.copy(i,s,n,r,o),this._results.length<2||(this._tempA=t,this._tempB=e,this._results.forEach(this.swapHandler,this),this.paste(i,s,this._results,o))},swapHandler:function(t){t.index===this._tempA?t.index=this._tempB:t.index===this._tempB&&(t.index=this._tempA)},forEach:function(t,e,i,s,n,r,o){o=this.getLayer(o),this.copy(i,s,n,r,o),this._results.length<2||(this._results.forEach(t,e),this.paste(i,s,this._results,o))},replace:function(t,e,i,s,n,r,o){if(o=this.getLayer(o),this.copy(i,s,n,r,o),!(this._results.length<2)){for(var a=1;a<this._results.length;a++)this._results[a].index===t&&(this._results[a].index=e);this.paste(i,s,this._results,o)}},random:function(t,e,i,s,n){if(n=this.getLayer(n),this.copy(t,e,i,s,n),!(this._results.length<2)){for(var r=[],o=1;o<this._results.length;o++)if(this._results[o].index){var a=this._results[o].index;-1===r.indexOf(a)&&r.push(a)}for(var h=1;h<this._results.length;h++)this._results[h].index=this.game.rnd.pick(r);this.paste(t,e,this._results,n)}},shuffle:function(t,e,i,s,r){if(r=this.getLayer(r),this.copy(t,e,i,s,r),!(this._results.length<2)){for(var o=[],a=1;a<this._results.length;a++)this._results[a].index&&o.push(this._results[a].index);n.ArrayUtils.shuffle(o);for(var h=1;h<this._results.length;h++)this._results[h].index=o[h-1];this.paste(t,e,this._results,r)}},fill:function(t,e,i,s,n,r){if(r=this.getLayer(r),this.copy(e,i,s,n,r),!(this._results.length<2)){for(var o=1;o<this._results.length;o++)this._results[o].index=t;this.paste(e,i,this._results,r)}},removeAllLayers:function(){this.layers.length=0,this.currentLayer=0},dump:function(){for(var t="",e=[""],i=0;i<this.layers[this.currentLayer].height;i++){for(var s=0;s<this.layers[this.currentLayer].width;s++)t+="%c ",this.layers[this.currentLayer].data[i][s]>1?this.debugMap[this.layers[this.currentLayer].data[i][s]]?e.push("background: "+this.debugMap[this.layers[this.currentLayer].data[i][s]]):e.push("background: #ffffff"):e.push("background: rgb(0, 0, 0)");t+="\n"}e[0]=t,console.log.apply(console,e)},destroy:function(){this.removeAllLayers(),this.data=[],this.game=null}},n.Tilemap.prototype.constructor=n.Tilemap,Object.defineProperty(n.Tilemap.prototype,"layer",{get:function(){return this.layers[this.currentLayer]},set:function(t){t!==this.currentLayer&&this.setLayer(t)}}),n.TilemapLayer=function(t,e,i,s,r){s|=0,r|=0,n.Sprite.call(this,t,0,0),this.map=e,this.index=i,this.layer=e.layers[i],this.canvas=PIXI.CanvasPool.create(this,s,r),this.context=this.canvas.getContext("2d"),this.setTexture(new PIXI.Texture(new PIXI.BaseTexture(this.canvas))),this.type=n.TILEMAPLAYER,this.physicsType=n.TILEMAPLAYER,this.renderSettings={enableScrollDelta:!1,overdrawRatio:.2,copyCanvas:null},this.debug=!1,this.exists=!0,this.debugSettings={missingImageFill:"rgb(255,255,255)",debuggedTileOverfill:"rgba(0,255,0,0.4)",forceFullRedraw:!0,debugAlpha:.5,facingEdgeStroke:"rgba(0,255,0,1)",collidingTileOverfill:"rgba(0,255,0,0.2)"},this.scrollFactorX=1,this.scrollFactorY=1,this.dirty=!0,this.rayStepRate=4,this._wrap=!1,this._mc={scrollX:0,scrollY:0,renderWidth:0,renderHeight:0,tileWidth:e.tileWidth,tileHeight:e.tileHeight,cw:e.tileWidth,ch:e.tileHeight,tilesets:[]},this._scrollX=0,this._scrollY=0,this._results=[],t.device.canvasBitBltShift||(this.renderSettings.copyCanvas=n.TilemapLayer.ensureSharedCopyCanvas()),this.fixedToCamera=!0},n.TilemapLayer.prototype=Object.create(n.Sprite.prototype),n.TilemapLayer.prototype.constructor=n.TilemapLayer,n.TilemapLayer.prototype.preUpdateCore=n.Component.Core.preUpdate,n.TilemapLayer.sharedCopyCanvas=null,n.TilemapLayer.ensureSharedCopyCanvas=function(){return this.sharedCopyCanvas||(this.sharedCopyCanvas=PIXI.CanvasPool.create(this,2,2)),this.sharedCopyCanvas},n.TilemapLayer.prototype.preUpdate=function(){return this.preUpdateCore()},n.TilemapLayer.prototype.postUpdate=function(){this.fixedToCamera&&(this.position.x=(this.game.camera.view.x+this.cameraOffset.x)/this.game.camera.scale.x,this.position.y=(this.game.camera.view.y+this.cameraOffset.y)/this.game.camera.scale.y),this._scrollX=this.game.camera.view.x*this.scrollFactorX/this.scale.x,this._scrollY=this.game.camera.view.y*this.scrollFactorY/this.scale.y},n.TilemapLayer.prototype._renderCanvas=function(t){this.fixedToCamera&&(this.position.x=(this.game.camera.view.x+this.cameraOffset.x)/this.game.camera.scale.x,this.position.y=(this.game.camera.view.y+this.cameraOffset.y)/this.game.camera.scale.y),this._scrollX=this.game.camera.view.x*this.scrollFactorX/this.scale.x,this._scrollY=this.game.camera.view.y*this.scrollFactorY/this.scale.y,this.render(),PIXI.Sprite.prototype._renderCanvas.call(this,t)},n.TilemapLayer.prototype._renderWebGL=function(t){this.fixedToCamera&&(this.position.x=(this.game.camera.view.x+this.cameraOffset.x)/this.game.camera.scale.x,this.position.y=(this.game.camera.view.y+this.cameraOffset.y)/this.game.camera.scale.y),this._scrollX=this.game.camera.view.x*this.scrollFactorX/this.scale.x,this._scrollY=this.game.camera.view.y*this.scrollFactorY/this.scale.y,this.render(),PIXI.Sprite.prototype._renderWebGL.call(this,t)},n.TilemapLayer.prototype.destroy=function(){PIXI.CanvasPool.remove(this),n.Component.Destroy.prototype.destroy.call(this)},n.TilemapLayer.prototype.resize=function(t,e){this.canvas.width=t,this.canvas.height=e,this.texture.frame.resize(t,e),this.texture.width=t,this.texture.height=e,this.texture.crop.width=t,this.texture.crop.height=e,this.texture.baseTexture.width=t,this.texture.baseTexture.height=e,this.texture.baseTexture.dirty(),this.texture.requiresUpdate=!0,this.texture._updateUvs(),this.dirty=!0},n.TilemapLayer.prototype.resizeWorld=function(){this.game.world.setBounds(0,0,this.layer.widthInPixels*this.scale.x,this.layer.heightInPixels*this.scale.y)},n.TilemapLayer.prototype._fixX=function(t){return 1===this.scrollFactorX||0===this.scrollFactorX&&0===this.position.x?t:0===this.scrollFactorX&&0!==this.position.x?t-this.position.x:this._scrollX+(t-this._scrollX/this.scrollFactorX)},n.TilemapLayer.prototype._unfixX=function(t){return 1===this.scrollFactorX?t:this._scrollX/this.scrollFactorX+(t-this._scrollX)},n.TilemapLayer.prototype._fixY=function(t){return 1===this.scrollFactorY||0===this.scrollFactorY&&0===this.position.y?t:0===this.scrollFactorY&&0!==this.position.y?t-this.position.y:this._scrollY+(t-this._scrollY/this.scrollFactorY)},n.TilemapLayer.prototype._unfixY=function(t){return 1===this.scrollFactorY?t:this._scrollY/this.scrollFactorY+(t-this._scrollY)},n.TilemapLayer.prototype.getTileX=function(t){return Math.floor(this._fixX(t)/this._mc.tileWidth)},n.TilemapLayer.prototype.getTileY=function(t){return Math.floor(this._fixY(t)/this._mc.tileHeight)},n.TilemapLayer.prototype.getTileXY=function(t,e,i){return i.x=this.getTileX(t),i.y=this.getTileY(e),i},n.TilemapLayer.prototype.getRayCastTiles=function(t,e,i,s){e||(e=this.rayStepRate),void 0===i&&(i=!1),void 0===s&&(s=!1);var n=this.getTiles(t.x,t.y,t.width,t.height,i,s);if(0===n.length)return[];for(var r=t.coordinatesOnLine(e),o=[],a=0;a<n.length;a++)for(var h=0;h<r.length;h++){var l=n[a],c=r[h];if(l.containsPoint(c[0],c[1])){o.push(l);break}}return o},n.TilemapLayer.prototype.getTiles=function(t,e,i,s,n,r){void 0===n&&(n=!1),void 0===r&&(r=!1);var o=!(n||r);t=this._fixX(t),e=this._fixY(e);for(var a=Math.floor(t/(this._mc.cw*this.scale.x)),h=Math.floor(e/(this._mc.ch*this.scale.y)),l=Math.ceil((t+i)/(this._mc.cw*this.scale.x))-a,c=Math.ceil((e+s)/(this._mc.ch*this.scale.y))-h;this._results.length;)this._results.pop();for(var u=h;u<h+c;u++)for(var d=a;d<a+l;d++){var p=this.layer.data[u];p&&p[d]&&(o||p[d].isInteresting(n,r))&&this._results.push(p[d])}return this._results.slice()},n.TilemapLayer.prototype.resolveTileset=function(t){var e=this._mc.tilesets;if(t<2e3)for(;e.length<t;)e.push(void 0);var i=this.map.tiles[t]&&this.map.tiles[t][2];if(null!==i){var s=this.map.tilesets[i];if(s&&s.containsTileIndex(t))return e[t]=s}return e[t]=null},n.TilemapLayer.prototype.resetTilesetCache=function(){for(var t=this._mc.tilesets;t.length;)t.pop()},n.TilemapLayer.prototype.setScale=function(t,e){t=t||1,e=e||t;for(var i=0;i<this.layer.data.length;i++)for(var s=this.layer.data[i],n=0;n<s.length;n++){var r=s[n];r.width=this.map.tileWidth*t,r.height=this.map.tileHeight*e,r.worldX=r.x*r.width,r.worldY=r.y*r.height}this.scale.setTo(t,e)},n.TilemapLayer.prototype.shiftCanvas=function(t,e,i){var s=t.canvas,n=s.width-Math.abs(e),r=s.height-Math.abs(i),o=0,a=0,h=e,l=i;e<0&&(o=-e,h=0),i<0&&(a=-i,l=0);var c=this.renderSettings.copyCanvas;if(c){(c.width<n||c.height<r)&&(c.width=n,c.height=r);var u=c.getContext("2d");u.clearRect(0,0,n,r),u.drawImage(s,o,a,n,r,0,0,n,r),t.clearRect(h,l,n,r),t.drawImage(c,0,0,n,r,h,l,n,r)}else t.save(),t.globalCompositeOperation="copy",t.drawImage(s,o,a,n,r,h,l,n,r),t.restore()},n.TilemapLayer.prototype.renderRegion=function(t,e,i,s,n,r){var o=this.context,a=this.layer.width,h=this.layer.height,l=this._mc.tileWidth,c=this._mc.tileHeight,u=this._mc.tilesets,d=NaN;this._wrap||(i<=n&&(i=Math.max(0,i),n=Math.min(a-1,n)),s<=r&&(s=Math.max(0,s),r=Math.min(h-1,r)));var p,f,g,m,y,v,b=i*l-t,x=s*c-e,w=(i+(1<<20)*a)%a,_=(s+(1<<20)*h)%h;for(m=_,v=r-s,f=x;v>=0;m++,v--,f+=c){m>=h&&(m-=h);var P=this.layer.data[m];for(g=w,y=n-i,p=b;y>=0;g++,y--,p+=l){g>=a&&(g-=a);var T=P[g];if(T&&!(T.index<0)){var C=T.index,S=u[C];void 0===S&&(S=this.resolveTileset(C)),T.alpha===d||this.debug||(o.globalAlpha=T.alpha,d=T.alpha),S?T.rotation||T.flipped?(o.save(),o.translate(p+T.centerX,f+T.centerY),o.rotate(T.rotation),T.flipped&&o.scale(-1,1),S.draw(o,-T.centerX,-T.centerY,C),o.restore()):S.draw(o,p,f,C):this.debugSettings.missingImageFill&&(o.fillStyle=this.debugSettings.missingImageFill,o.fillRect(p,f,l,c)),T.debug&&this.debugSettings.debuggedTileOverfill&&(o.fillStyle=this.debugSettings.debuggedTileOverfill,o.fillRect(p,f,l,c))}}}},n.TilemapLayer.prototype.renderDeltaScroll=function(t,e){var i=this._mc.scrollX,s=this._mc.scrollY,n=this.canvas.width,r=this.canvas.height,o=this._mc.tileWidth,a=this._mc.tileHeight,h=0,l=-o,c=0,u=-a;if(t<0?(h=n+t,l=n-1):t>0&&(l=t),e<0?(c=r+e,u=r-1):e>0&&(u=e),this.shiftCanvas(this.context,t,e),h=Math.floor((h+i)/o),l=Math.floor((l+i)/o),c=Math.floor((c+s)/a),u=Math.floor((u+s)/a),h<=l){this.context.clearRect(h*o-i,0,(l-h+1)*o,r);var d=Math.floor((0+s)/a),p=Math.floor((r-1+s)/a);this.renderRegion(i,s,h,d,l,p)}if(c<=u){this.context.clearRect(0,c*a-s,n,(u-c+1)*a);var f=Math.floor((0+i)/o),g=Math.floor((n-1+i)/o);this.renderRegion(i,s,f,c,g,u)}},n.TilemapLayer.prototype.renderFull=function(){var t=this._mc.scrollX,e=this._mc.scrollY,i=this.canvas.width,s=this.canvas.height,n=this._mc.tileWidth,r=this._mc.tileHeight,o=Math.floor(t/n),a=Math.floor((i-1+t)/n),h=Math.floor(e/r),l=Math.floor((s-1+e)/r);this.context.clearRect(0,0,i,s),this.renderRegion(t,e,o,h,a,l)},n.TilemapLayer.prototype.render=function(){var t=!1;if(this.visible){(this.dirty||this.layer.dirty)&&(this.layer.dirty=!1,t=!0);var e=this.canvas.width,i=this.canvas.height,s=0|this._scrollX,n=0|this._scrollY,r=this._mc,o=r.scrollX-s,a=r.scrollY-n;if(t||0!==o||0!==a||r.renderWidth!==e||r.renderHeight!==i)return this.context.save(),r.scrollX=s,r.scrollY=n,r.renderWidth===e&&r.renderHeight===i||(r.renderWidth=e,r.renderHeight=i),this.debug&&(this.context.globalAlpha=this.debugSettings.debugAlpha,this.debugSettings.forceFullRedraw&&(t=!0)),!t&&this.renderSettings.enableScrollDelta&&Math.abs(o)+Math.abs(a)<Math.min(e,i)?this.renderDeltaScroll(o,a):this.renderFull(),this.debug&&(this.context.globalAlpha=1,this.renderDebug()),this.texture.baseTexture.dirty(),this.dirty=!1,this.context.restore(),!0}},n.TilemapLayer.prototype.renderDebug=function(){var t,e,i,s,n,r,o=this._mc.scrollX,a=this._mc.scrollY,h=this.context,l=this.canvas.width,c=this.canvas.height,u=this.layer.width,d=this.layer.height,p=this._mc.tileWidth,f=this._mc.tileHeight,g=Math.floor(o/p),m=Math.floor((l-1+o)/p),y=Math.floor(a/f),v=Math.floor((c-1+a)/f),b=g*p-o,x=y*f-a,w=(g+(1<<20)*u)%u,_=(y+(1<<20)*d)%d;for(h.strokeStyle=this.debugSettings.facingEdgeStroke,s=_,r=v-y,e=x;r>=0;s++,r--,e+=f){s>=d&&(s-=d);var P=this.layer.data[s];for(i=w,n=m-g,t=b;n>=0;i++,n--,t+=p){i>=u&&(i-=u);var T=P[i];!T||T.index<0||!T.collides||(this.debugSettings.collidingTileOverfill&&(h.fillStyle=this.debugSettings.collidingTileOverfill,h.fillRect(t,e,this._mc.cw,this._mc.ch)),this.debugSettings.facingEdgeStroke&&(h.beginPath(),T.faceTop&&(h.moveTo(t,e),h.lineTo(t+this._mc.cw,e)),T.faceBottom&&(h.moveTo(t,e+this._mc.ch),h.lineTo(t+this._mc.cw,e+this._mc.ch)),T.faceLeft&&(h.moveTo(t,e),h.lineTo(t,e+this._mc.ch)),T.faceRight&&(h.moveTo(t+this._mc.cw,e),h.lineTo(t+this._mc.cw,e+this._mc.ch)),h.closePath(),h.stroke()))}}},Object.defineProperty(n.TilemapLayer.prototype,"wrap",{get:function(){return this._wrap},set:function(t){this._wrap=t,this.dirty=!0}}),Object.defineProperty(n.TilemapLayer.prototype,"scrollX",{get:function(){return this._scrollX},set:function(t){this._scrollX=t}}),Object.defineProperty(n.TilemapLayer.prototype,"scrollY",{get:function(){return this._scrollY},set:function(t){this._scrollY=t}}),Object.defineProperty(n.TilemapLayer.prototype,"collisionWidth",{get:function(){return this._mc.cw},set:function(t){this._mc.cw=0|t,this.dirty=!0}}),Object.defineProperty(n.TilemapLayer.prototype,"collisionHeight",{get:function(){return this._mc.ch},set:function(t){this._mc.ch=0|t,this.dirty=!0}}),n.TilemapParser={INSERT_NULL:!1,parse:function(t,e,i,s,r,o){if(void 0===i&&(i=32),void 0===s&&(s=32),void 0===r&&(r=10),void 0===o&&(o=10),void 0===e)return this.getEmptyData();if(null===e)return this.getEmptyData(i,s,r,o);var a=t.cache.getTilemapData(e);if(a){if(a.format===n.Tilemap.CSV)return this.parseCSV(e,a.data,i,s);if(!a.format||a.format===n.Tilemap.TILED_JSON)return this.parseTiledJSON(a.data)}else console.warn("Phaser.TilemapParser.parse - No map data found for key "+e)},parseCSV:function(t,e,i,s){var r=this.getEmptyData();e=e.trim();for(var o=[],a=e.split("\n"),h=a.length,l=0,c=0;c<a.length;c++){o[c]=[];for(var u=a[c].split(","),d=0;d<u.length;d++)o[c][d]=new n.Tile(r.layers[0],parseInt(u[d],10),d,c,i,s);0===l&&(l=u.length)}return r.format=n.Tilemap.CSV,r.name=t,r.width=l,r.height=h,r.tileWidth=i,r.tileHeight=s,r.widthInPixels=l*i,r.heightInPixels=h*s,r.layers[0].width=l,r.layers[0].height=h,r.layers[0].widthInPixels=r.widthInPixels,r.layers[0].heightInPixels=r.heightInPixels,r.layers[0].data=o,r},getEmptyData:function(t,e,i,s){return{width:void 0!==i&&null!==i?i:0,height:void 0!==s&&null!==s?s:0,tileWidth:void 0!==t&&null!==t?t:0,tileHeight:void 0!==e&&null!==e?e:0,orientation:"orthogonal",version:"1",properties:{},widthInPixels:0,heightInPixels:0,layers:[{name:"layer",x:0,y:0,width:0,height:0,widthInPixels:0,heightInPixels:0,alpha:1,visible:!0,properties:{},indexes:[],callbacks:[],bodies:[],data:[]}],images:[],objects:{},collision:{},tilesets:[],tiles:[]}},parseTiledJSON:function(t){function e(t,e){var i={};for(var s in e){var n=e[s];void 0!==t[n]&&(i[n]=t[n])}return i}if("orthogonal"!==t.orientation)return console.warn("TilemapParser.parseTiledJSON - Only orthogonal map types are supported in this version of Phaser"),null;for(var i={width:t.width,height:t.height,tileWidth:t.tilewidth,tileHeight:t.tileheight,orientation:t.orientation,format:n.Tilemap.TILED_JSON,version:t.version,properties:t.properties,widthInPixels:t.width*t.tilewidth,heightInPixels:t.height*t.tileheight},s=[],r=0;r<t.layers.length;r++)if("tilelayer"===t.layers[r].type){var o=t.layers[r];if(!o.compression&&o.encoding&&"base64"===o.encoding){for(var a=window.atob(o.data),h=a.length,l=new Array(h),c=0;c<h;c+=4)l[c/4]=(a.charCodeAt(c)|a.charCodeAt(c+1)<<8|a.charCodeAt(c+2)<<16|a.charCodeAt(c+3)<<24)>>>0;o.data=l,delete o.encoding}else if(o.compression){console.warn("TilemapParser.parseTiledJSON - Layer compression is unsupported, skipping layer '"+o.name+"'");continue}var u={name:o.name,x:o.x,y:o.y,width:o.width,height:o.height,widthInPixels:o.width*t.tilewidth,heightInPixels:o.height*t.tileheight,alpha:o.opacity,visible:o.visible,properties:{},indexes:[],callbacks:[],bodies:[]};o.properties&&(u.properties=o.properties);for(var d,p,f,g,m=0,y=[],v=[],b=0,h=o.data.length;b<h;b++){if(d=0,p=!1,g=o.data[b],f=0,g>536870912)switch(g>2147483648&&(g-=2147483648,f+=4),g>1073741824&&(g-=1073741824,f+=2),g>536870912&&(g-=536870912,f+=1),f){case 5:d=Math.PI/2;break;case 6:d=Math.PI;break;case 3:d=3*Math.PI/2;break;case 4:d=0,p=!0;break;case 7:d=Math.PI/2,p=!0;break;case 2:d=Math.PI,p=!0;break;case 1:d=3*Math.PI/2,p=!0}if(g>0){var x=new n.Tile(u,g,m,v.length,t.tilewidth,t.tileheight);x.rotation=d,x.flipped=p,0!==f&&(x.flippedVal=f),y.push(x)}else n.TilemapParser.INSERT_NULL?y.push(null):y.push(new n.Tile(u,-1,m,v.length,t.tilewidth,t.tileheight));m++,m===o.width&&(v.push(y),m=0,y=[])}u.data=v,s.push(u)}i.layers=s;for(var w=[],r=0;r<t.layers.length;r++)if("imagelayer"===t.layers[r].type){var _=t.layers[r],P={name:_.name,image:_.image,x:_.x,y:_.y,alpha:_.opacity,visible:_.visible,properties:{}};_.properties&&(P.properties=_.properties),w.push(P)}i.images=w;for(var T=[],C=[],S=null,r=0;r<t.tilesets.length;r++){var A=t.tilesets[r];if(A.image){var E=new n.Tileset(A.name,A.firstgid,A.tilewidth,A.tileheight,A.margin,A.spacing,A.properties);A.tileproperties&&(E.tileProperties=A.tileproperties),E.updateTileData(A.imagewidth,A.imageheight),T.push(E)}else{var I=new n.ImageCollection(A.name,A.firstgid,A.tilewidth,A.tileheight,A.margin,A.spacing,A.properties);for(var M in A.tiles){var P=A.tiles[M].image,g=A.firstgid+parseInt(M,10);I.addImage(g,P)}C.push(I)}S&&(S.lastgid=A.firstgid-1),S=A}i.tilesets=T,i.imagecollections=C;for(var R={},B={},r=0;r<t.layers.length;r++)if("objectgroup"===t.layers[r].type){var L=t.layers[r];R[L.name]=[],B[L.name]=[];for(var O=0,h=L.objects.length;O<h;O++)if(L.objects[O].gid){var k={gid:L.objects[O].gid,name:L.objects[O].name,type:L.objects[O].hasOwnProperty("type")?L.objects[O].type:"",x:L.objects[O].x,y:L.objects[O].y,visible:L.objects[O].visible,properties:L.objects[O].properties};L.objects[O].rotation&&(k.rotation=L.objects[O].rotation),R[L.name].push(k)}else if(L.objects[O].polyline){var k={name:L.objects[O].name,type:L.objects[O].type,x:L.objects[O].x,y:L.objects[O].y,width:L.objects[O].width,height:L.objects[O].height,visible:L.objects[O].visible,properties:L.objects[O].properties};L.objects[O].rotation&&(k.rotation=L.objects[O].rotation),k.polyline=[];for(var F=0;F<L.objects[O].polyline.length;F++)k.polyline.push([L.objects[O].polyline[F].x,L.objects[O].polyline[F].y]);B[L.name].push(k),R[L.name].push(k)}else if(L.objects[O].polygon){var k=e(L.objects[O],["name","type","x","y","visible","rotation","properties"]);k.polygon=[];for(var F=0;F<L.objects[O].polygon.length;F++)k.polygon.push([L.objects[O].polygon[F].x,L.objects[O].polygon[F].y]);R[L.name].push(k)}else if(L.objects[O].ellipse){var k=e(L.objects[O],["name","type","ellipse","x","y","width","height","visible","rotation","properties"]);R[L.name].push(k)}else{var k=e(L.objects[O],["name","type","x","y","width","height","visible","rotation","properties"]);k.rectangle=!0,R[L.name].push(k)}}i.objects=R,i.collision=B,i.tiles=[];for(var r=0;r<i.tilesets.length;r++)for(var A=i.tilesets[r],m=A.tileMargin,D=A.tileMargin,U=0,G=0,N=0,b=A.firstgid;b<A.firstgid+A.total&&(i.tiles[b]=[m,D,r],m+=A.tileWidth+A.tileSpacing,++U!==A.total)&&(++G!==A.columns||(m=A.tileMargin,D+=A.tileHeight+A.tileSpacing,G=0,++N!==A.rows));b++);for(var u,x,X,A,r=0;r<i.layers.length;r++){u=i.layers[r],A=null;for(var c=0;c<u.data.length;c++){y=u.data[c];for(var W=0;W<y.length;W++)null===(x=y[W])||x.index<0||(X=i.tiles[x.index][2],A=i.tilesets[X],A.tileProperties&&A.tileProperties[x.index-A.firstgid]&&(x.properties=n.Utils.mixin(A.tileProperties[x.index-A.firstgid],x.properties)))}}return i}},n.Tileset=function(t,e,i,s,n,r,o){(void 0===i||i<=0)&&(i=32),(void 0===s||s<=0)&&(s=32),void 0===n&&(n=0),void 0===r&&(r=0),this.name=t,this.firstgid=0|e,this.tileWidth=0|i,this.tileHeight=0|s,this.tileMargin=0|n,this.tileSpacing=0|r,this.properties=o||{},this.image=null,this.rows=0,this.columns=0,this.total=0,this.drawCoords=[]},n.Tileset.prototype={draw:function(t,e,i,s){var n=s-this.firstgid<<1;n>=0&&n+1<this.drawCoords.length&&t.drawImage(this.image,this.drawCoords[n],this.drawCoords[n+1],this.tileWidth,this.tileHeight,e,i,this.tileWidth,this.tileHeight)},containsTileIndex:function(t){return t>=this.firstgid&&t<this.firstgid+this.total},setImage:function(t){this.image=t,this.updateTileData(t.width,t.height)},setSpacing:function(t,e){this.tileMargin=0|t,this.tileSpacing=0|e,this.image&&this.updateTileData(this.image.width,this.image.height)},updateTileData:function(t,e){var i=(e-2*this.tileMargin+this.tileSpacing)/(this.tileHeight+this.tileSpacing),s=(t-2*this.tileMargin+this.tileSpacing)/(this.tileWidth+this.tileSpacing);i%1==0&&s%1==0||console.warn("Phaser.Tileset - "+this.name+" image tile area is not an even multiple of tile size"),i=Math.floor(i),s=Math.floor(s),(this.rows&&this.rows!==i||this.columns&&this.columns!==s)&&console.warn("Phaser.Tileset - actual and expected number of tile rows and columns differ"),this.rows=i,this.columns=s,this.total=i*s,this.drawCoords.length=0;for(var n=this.tileMargin,r=this.tileMargin,o=0;o<this.rows;o++){for(var a=0;a<this.columns;a++)this.drawCoords.push(n),this.drawCoords.push(r),n+=this.tileWidth+this.tileSpacing;n=this.tileMargin,r+=this.tileHeight+this.tileSpacing}}},n.Tileset.prototype.constructor=n.Tileset,n.Particle=function(t,e,i,s,r){n.Sprite.call(this,t,e,i,s,r),this.autoScale=!1,this.scaleData=null,this._s=0,this.autoAlpha=!1,this.alphaData=null,this._a=0},n.Particle.prototype=Object.create(n.Sprite.prototype),n.Particle.prototype.constructor=n.Particle,n.Particle.prototype.update=function(){this.autoScale&&(this._s--,this._s?this.scale.set(this.scaleData[this._s].x,this.scaleData[this._s].y):this.autoScale=!1),this.autoAlpha&&(this._a--,this._a?this.alpha=this.alphaData[this._a].v:this.autoAlpha=!1)},n.Particle.prototype.onEmit=function(){},n.Particle.prototype.setAlphaData=function(t){this.alphaData=t,this._a=t.length-1,this.alpha=this.alphaData[this._a].v,this.autoAlpha=!0},n.Particle.prototype.setScaleData=function(t){this.scaleData=t,this._s=t.length-1,this.scale.set(this.scaleData[this._s].x,this.scaleData[this._s].y),this.autoScale=!0},n.Particle.prototype.reset=function(t,e,i){return n.Component.Reset.prototype.reset.call(this,t,e,i),this.alpha=1,this.scale.set(1),this.autoScale=!1,this.autoAlpha=!1,this},n.Particles=function(t){this.game=t,this.emitters={},this.ID=0},n.Particles.prototype={add:function(t){return this.emitters[t.name]=t,t},remove:function(t){delete this.emitters[t.name]},update:function(){for(var t in this.emitters)this.emitters[t].exists&&this.emitters[t].update()}},n.Particles.prototype.constructor=n.Particles,n.Particles.Arcade={},n.Particles.Arcade.Emitter=function(t,e,i,s){this.maxParticles=s||50,n.Group.call(this,t),this.name="emitter"+this.game.particles.ID++,this.type=n.EMITTER,this.physicsType=n.GROUP,this.area=new n.Rectangle(e,i,1,1),this.minParticleSpeed=new n.Point(-100,-100),this.maxParticleSpeed=new n.Point(100,100),this.minParticleScale=1,this.maxParticleScale=1,this.scaleData=null,this.minRotation=-360,this.maxRotation=360,this.minParticleAlpha=1,this.maxParticleAlpha=1,this.alphaData=null,this.gravity=100,this.particleClass=n.Particle,this.particleDrag=new n.Point,this.angularDrag=0,this.frequency=100,this.lifespan=2e3,this.bounce=new n.Point,this.on=!1,this.particleAnchor=new n.Point(.5,.5),this.blendMode=n.blendModes.NORMAL,this.emitX=e,this.emitY=i,this.autoScale=!1,this.autoAlpha=!1,this.particleBringToTop=!1,this.particleSendToBack=!1,this._minParticleScale=new n.Point(1,1),this._maxParticleScale=new n.Point(1,1),this._quantity=0,this._timer=0,this._counter=0,this._flowQuantity=0,this._flowTotal=0,this._explode=!0,this._frames=null},n.Particles.Arcade.Emitter.prototype=Object.create(n.Group.prototype),n.Particles.Arcade.Emitter.prototype.constructor=n.Particles.Arcade.Emitter,n.Particles.Arcade.Emitter.prototype.update=function(){if(this.on&&this.game.time.time>=this._timer)if(this._timer=this.game.time.time+this.frequency*this.game.time.slowMotion,0!==this._flowTotal)if(this._flowQuantity>0){for(var t=0;t<this._flowQuantity;t++)if(this.emitParticle()&&(this._counter++,-1!==this._flowTotal&&this._counter>=this._flowTotal)){this.on=!1;break}}else this.emitParticle()&&(this._counter++,-1!==this._flowTotal&&this._counter>=this._flowTotal&&(this.on=!1));else this.emitParticle()&&(this._counter++,this._quantity>0&&this._counter>=this._quantity&&(this.on=!1));for(var t=this.children.length;t--;)this.children[t].exists&&this.children[t].update()},n.Particles.Arcade.Emitter.prototype.makeParticles=function(t,e,i,s,n){void 0===e&&(e=0),void 0===i&&(i=this.maxParticles),void 0===s&&(s=!1),void 0===n&&(n=!1);var r,o=0,a=t,h=e;for(this._frames=e,i>this.maxParticles&&(this.maxParticles=i);o<i;)Array.isArray(t)&&(a=this.game.rnd.pick(t)),Array.isArray(e)&&(h=this.game.rnd.pick(e)),r=new this.particleClass(this.game,0,0,a,h),this.game.physics.arcade.enable(r,!1),s?(r.body.checkCollision.any=!0,r.body.checkCollision.none=!1):r.body.checkCollision.none=!0,r.body.collideWorldBounds=n,r.body.skipQuadTree=!0,r.exists=!1,r.visible=!1,r.anchor.copyFrom(this.particleAnchor),this.add(r),o++;return this},n.Particles.Arcade.Emitter.prototype.kill=function(){return this.on=!1,this.alive=!1,this.exists=!1,this},n.Particles.Arcade.Emitter.prototype.revive=function(){return this.alive=!0,this.exists=!0,this},n.Particles.Arcade.Emitter.prototype.explode=function(t,e){return this._flowTotal=0,this.start(!0,t,0,e,!1),this},n.Particles.Arcade.Emitter.prototype.flow=function(t,e,i,s,n){return void 0!==i&&0!==i||(i=1),void 0===s&&(s=-1),void 0===n&&(n=!0),i>this.maxParticles&&(i=this.maxParticles),this._counter=0,this._flowQuantity=i,this._flowTotal=s,n?(this.start(!0,t,e,i),this._counter+=i,this.on=!0,this._timer=this.game.time.time+e*this.game.time.slowMotion):this.start(!1,t,e,i),this},n.Particles.Arcade.Emitter.prototype.start=function(t,e,i,s,n){if(void 0===t&&(t=!0),void 0===e&&(e=0),void 0!==i&&null!==i||(i=250),void 0===s&&(s=0),void 0===n&&(n=!1),s>this.maxParticles&&(s=this.maxParticles),this.revive(),this.visible=!0,this.lifespan=e,this.frequency=i,t||n)for(var r=0;r<s;r++)this.emitParticle();else this.on=!0,this._quantity=s,this._counter=0,this._timer=this.game.time.time+i*this.game.time.slowMotion;return this},n.Particles.Arcade.Emitter.prototype.emitParticle=function(t,e,i,s){void 0===t&&(t=null),void 0===e&&(e=null);var n=this.getFirstExists(!1);if(null===n)return!1;var r=this.game.rnd;void 0!==i&&void 0!==s?n.loadTexture(i,s):void 0!==i&&n.loadTexture(i);var o=this.emitX,a=this.emitY;null!==t?o=t:this.width>1&&(o=r.between(this.left,this.right)),null!==e?a=e:this.height>1&&(a=r.between(this.top,this.bottom)),n.reset(o,a),n.angle=0,n.lifespan=this.lifespan,this.particleBringToTop?this.bringToTop(n):this.particleSendToBack&&this.sendToBack(n),this.autoScale?n.setScaleData(this.scaleData):1!==this.minParticleScale||1!==this.maxParticleScale?n.scale.set(r.realInRange(this.minParticleScale,this.maxParticleScale)):this._minParticleScale.x===this._maxParticleScale.x&&this._minParticleScale.y===this._maxParticleScale.y||n.scale.set(r.realInRange(this._minParticleScale.x,this._maxParticleScale.x),r.realInRange(this._minParticleScale.y,this._maxParticleScale.y)),void 0===s&&(Array.isArray(this._frames)?n.frame=this.game.rnd.pick(this._frames):n.frame=this._frames),this.autoAlpha?n.setAlphaData(this.alphaData):n.alpha=r.realInRange(this.minParticleAlpha,this.maxParticleAlpha),n.blendMode=this.blendMode;var h=n.body;return h.updateBounds(),h.bounce.copyFrom(this.bounce),h.drag.copyFrom(this.particleDrag),h.velocity.x=r.between(this.minParticleSpeed.x,this.maxParticleSpeed.x),h.velocity.y=r.between(this.minParticleSpeed.y,this.maxParticleSpeed.y),h.angularVelocity=r.between(this.minRotation,this.maxRotation),h.gravity.y=this.gravity,h.angularDrag=this.angularDrag,n.onEmit(),!0},n.Particles.Arcade.Emitter.prototype.destroy=function(){this.game.particles.remove(this),n.Group.prototype.destroy.call(this,!0,!1)},n.Particles.Arcade.Emitter.prototype.setSize=function(t,e){return this.area.width=t,this.area.height=e,this},n.Particles.Arcade.Emitter.prototype.setXSpeed=function(t,e){return t=t||0,e=e||0,this.minParticleSpeed.x=t,this.maxParticleSpeed.x=e,this},n.Particles.Arcade.Emitter.prototype.setYSpeed=function(t,e){return t=t||0,e=e||0,this.minParticleSpeed.y=t,this.maxParticleSpeed.y=e,this},n.Particles.Arcade.Emitter.prototype.setRotation=function(t,e){return t=t||0,e=e||0,this.minRotation=t,this.maxRotation=e,this},n.Particles.Arcade.Emitter.prototype.setAlpha=function(t,e,i,s,r){if(void 0===t&&(t=1),void 0===e&&(e=1),void 0===i&&(i=0),void 0===s&&(s=n.Easing.Linear.None),void 0===r&&(r=!1),this.minParticleAlpha=t,this.maxParticleAlpha=e,this.autoAlpha=!1,i>0&&t!==e){var o={v:t},a=this.game.make.tween(o).to({v:e},i,s);a.yoyo(r),this.alphaData=a.generateData(60),this.alphaData.reverse(),this.autoAlpha=!0}return this},n.Particles.Arcade.Emitter.prototype.setScale=function(t,e,i,s,r,o,a){if(void 0===t&&(t=1),void 0===e&&(e=1),void 0===i&&(i=1),void 0===s&&(s=1),void 0===r&&(r=0),void 0===o&&(o=n.Easing.Linear.None),void 0===a&&(a=!1),this.minParticleScale=1,this.maxParticleScale=1,this._minParticleScale.set(t,i),this._maxParticleScale.set(e,s),this.autoScale=!1,r>0&&(t!==e||i!==s)){var h={x:t,y:i},l=this.game.make.tween(h).to({x:e,y:s},r,o);l.yoyo(a),this.scaleData=l.generateData(60),this.scaleData.reverse(),this.autoScale=!0}return this},n.Particles.Arcade.Emitter.prototype.at=function(t){return t.center?(this.emitX=t.center.x,this.emitY=t.center.y):(this.emitX=t.world.x+t.anchor.x*t.width,this.emitY=t.world.y+t.anchor.y*t.height),this},Object.defineProperty(n.Particles.Arcade.Emitter.prototype,"width",{get:function(){return this.area.width},set:function(t){this.area.width=t}}),Object.defineProperty(n.Particles.Arcade.Emitter.prototype,"height",{get:function(){return this.area.height},set:function(t){this.area.height=t}}),Object.defineProperty(n.Particles.Arcade.Emitter.prototype,"x",{get:function(){return this.emitX},set:function(t){this.emitX=t}}),Object.defineProperty(n.Particles.Arcade.Emitter.prototype,"y",{get:function(){return this.emitY},set:function(t){this.emitY=t}}),Object.defineProperty(n.Particles.Arcade.Emitter.prototype,"left",{get:function(){return Math.floor(this.x-this.area.width/2)}}),Object.defineProperty(n.Particles.Arcade.Emitter.prototype,"right",{get:function(){return Math.floor(this.x+this.area.width/2)}}),Object.defineProperty(n.Particles.Arcade.Emitter.prototype,"top",{get:function(){return Math.floor(this.y-this.area.height/2)}}),Object.defineProperty(n.Particles.Arcade.Emitter.prototype,"bottom",{get:function(){return Math.floor(this.y+this.area.height/2)}}),n.Weapon=function(t,e){n.Plugin.call(this,t,e),this.bullets=null,this.autoExpandBulletsGroup=!1,this.autofire=!1,this.shots=0,this.fireLimit=0,this.fireRate=100,this.fireRateVariance=0,this.fireFrom=new n.Rectangle(0,0,1,1),this.fireAngle=n.ANGLE_UP,this.bulletInheritSpriteSpeed=!1,this.bulletAnimation="",this.bulletFrameRandom=!1,this.bulletFrameCycle=!1,this.bulletWorldWrap=!1,this.bulletWorldWrapPadding=0,this.bulletAngleOffset=0,this.bulletAngleVariance=0,this.bulletSpeed=200,this.bulletSpeedVariance=0,this.bulletLifespan=0,this.bulletKillDistance=0,this.bulletGravity=new n.Point(0,0),this.bulletRotateToVelocity=!1,this.bulletKey="",this.bulletFrame="",this._bulletClass=n.Bullet,this._bulletCollideWorldBounds=!1,this._bulletKillType=n.Weapon.KILL_WORLD_BOUNDS,this._data={customBody:!1,width:0,height:0,offsetX:0,offsetY:0},this.bounds=new n.Rectangle,this.bulletBounds=t.world.bounds,this.bulletFrames=[],this.bulletFrameIndex=0,this.anims={},this.onFire=new n.Signal,this.onKill=new n.Signal,this.onFireLimit=new n.Signal,this.trackedSprite=null,this.trackedPointer=null,this.trackRotation=!1,this.trackOffset=new n.Point,this._nextFire=0,this._rotatedPoint=new n.Point},n.Weapon.prototype=Object.create(n.Plugin.prototype),n.Weapon.prototype.constructor=n.Weapon,n.Weapon.KILL_NEVER=0,n.Weapon.KILL_LIFESPAN=1,n.Weapon.KILL_DISTANCE=2,n.Weapon.KILL_WEAPON_BOUNDS=3,n.Weapon.KILL_CAMERA_BOUNDS=4,n.Weapon.KILL_WORLD_BOUNDS=5,n.Weapon.KILL_STATIC_BOUNDS=6,n.Weapon.prototype.createBullets=function(t,e,i,s){return void 0===t&&(t=1),void 0===s&&(s=this.game.world),this.bullets||(this.bullets=this.game.add.physicsGroup(n.Physics.ARCADE,s),this.bullets.classType=this._bulletClass),0!==t&&(-1===t&&(this.autoExpandBulletsGroup=!0,t=1),this.bullets.createMultiple(t,e,i),this.bullets.setAll("data.bulletManager",this),this.bulletKey=e,this.bulletFrame=i),this},n.Weapon.prototype.forEach=function(t,e){return this.bullets.forEachExists(t,e,arguments),this},n.Weapon.prototype.pauseAll=function(){return this.bullets.setAll("body.enable",!1),this},n.Weapon.prototype.resumeAll=function(){return this.bullets.setAll("body.enable",!0),this},n.Weapon.prototype.killAll=function(){return this.bullets.callAllExists("kill",!0),this.bullets.setAll("body.enable",!0),this},n.Weapon.prototype.resetShots=function(t){return this.shots=0,void 0!==t&&(this.fireLimit=t),this},n.Weapon.prototype.destroy=function(){this.parent.remove(this,!1),this.bullets.destroy(),this.game=null,this.parent=null,this.active=!1,this.visible=!1},n.Weapon.prototype.update=function(){this._bulletKillType===n.Weapon.KILL_WEAPON_BOUNDS&&(this.trackedSprite?(this.trackedSprite.updateTransform(),this.bounds.centerOn(this.trackedSprite.worldPosition.x,this.trackedSprite.worldPosition.y)):this.trackedPointer&&this.bounds.centerOn(this.trackedPointer.worldX,this.trackedPointer.worldY)),this.autofire&&this.fire()},n.Weapon.prototype.trackSprite=function(t,e,i,s){return void 0===e&&(e=0),void 0===i&&(i=0),void 0===s&&(s=!1),this.trackedPointer=null,this.trackedSprite=t,this.trackRotation=s,this.trackOffset.set(e,i),this},n.Weapon.prototype.trackPointer=function(t,e,i){return void 0===t&&(t=this.game.input.activePointer),void 0===e&&(e=0),void 0===i&&(i=0),this.trackedPointer=t,this.trackedSprite=null,this.trackRotation=!1,this.trackOffset.set(e,i),this},n.Weapon.prototype.fire=function(t,e,i){if(this.game.time.now<this._nextFire||this.fireLimit>0&&this.shots===this.fireLimit)return!1;var s=this.bulletSpeed;0!==this.bulletSpeedVariance&&(s+=n.Math.between(-this.bulletSpeedVariance,this.bulletSpeedVariance)),t?this.fireFrom.width>1?this.fireFrom.centerOn(t.x,t.y):(this.fireFrom.x=t.x,this.fireFrom.y=t.y):this.trackedSprite?(this.trackRotation?(this._rotatedPoint.set(this.trackedSprite.world.x+this.trackOffset.x,this.trackedSprite.world.y+this.trackOffset.y),this._rotatedPoint.rotate(this.trackedSprite.world.x,this.trackedSprite.world.y,this.trackedSprite.rotation),this.fireFrom.width>1?this.fireFrom.centerOn(this._rotatedPoint.x,this._rotatedPoint.y):(this.fireFrom.x=this._rotatedPoint.x,this.fireFrom.y=this._rotatedPoint.y)):this.fireFrom.width>1?this.fireFrom.centerOn(this.trackedSprite.world.x+this.trackOffset.x,this.trackedSprite.world.y+this.trackOffset.y):(this.fireFrom.x=this.trackedSprite.world.x+this.trackOffset.x,this.fireFrom.y=this.trackedSprite.world.y+this.trackOffset.y),this.bulletInheritSpriteSpeed&&(s+=this.trackedSprite.body.speed)):this.trackedPointer&&(this.fireFrom.width>1?this.fireFrom.centerOn(this.trackedPointer.world.x+this.trackOffset.x,this.trackedPointer.world.y+this.trackOffset.y):(this.fireFrom.x=this.trackedPointer.world.x+this.trackOffset.x,this.fireFrom.y=this.trackedPointer.world.y+this.trackOffset.y));var r=this.fireFrom.width>1?this.fireFrom.randomX:this.fireFrom.x,o=this.fireFrom.height>1?this.fireFrom.randomY:this.fireFrom.y,a=this.trackRotation?this.trackedSprite.angle:this.fireAngle;void 0!==e&&void 0!==i&&(a=this.game.math.radToDeg(Math.atan2(i-o,e-r))),0!==this.bulletAngleVariance&&(a+=n.Math.between(-this.bulletAngleVariance,this.bulletAngleVariance));var h=0,l=0;0===a||180===a?h=Math.cos(this.game.math.degToRad(a))*s:90===a||270===a?l=Math.sin(this.game.math.degToRad(a))*s:(h=Math.cos(this.game.math.degToRad(a))*s,l=Math.sin(this.game.math.degToRad(a))*s);var c=null;if(this.autoExpandBulletsGroup?(c=this.bullets.getFirstExists(!1,!0,r,o,this.bulletKey,this.bulletFrame),c.data.bulletManager=this):c=this.bullets.getFirstExists(!1),c){if(c.reset(r,o),c.data.fromX=r,c.data.fromY=o,c.data.killType=this.bulletKillType,c.data.killDistance=this.bulletKillDistance,c.data.rotateToVelocity=this.bulletRotateToVelocity,this.bulletKillType===n.Weapon.KILL_LIFESPAN&&(c.lifespan=this.bulletLifespan),c.angle=a+this.bulletAngleOffset,""!==this.bulletAnimation){if(null===c.animations.getAnimation(this.bulletAnimation)){var u=this.anims[this.bulletAnimation];c.animations.add(u.name,u.frames,u.frameRate,u.loop,u.useNumericIndex)}c.animations.play(this.bulletAnimation)}else this.bulletFrameCycle?(c.frame=this.bulletFrames[this.bulletFrameIndex],++this.bulletFrameIndex>=this.bulletFrames.length&&(this.bulletFrameIndex=0)):this.bulletFrameRandom&&(c.frame=this.bulletFrames[Math.floor(Math.random()*this.bulletFrames.length)]);if(c.data.bodyDirty&&(this._data.customBody&&c.body.setSize(this._data.width,this._data.height,this._data.offsetX,this._data.offsetY),c.body.collideWorldBounds=this.bulletCollideWorldBounds,c.data.bodyDirty=!1),c.body.velocity.set(h,l),c.body.gravity.set(this.bulletGravity.x,this.bulletGravity.y),0!==this.bulletSpeedVariance){var d=this.fireRate;d+=n.Math.between(-this.fireRateVariance,this.fireRateVariance),d<0&&(d=0),this._nextFire=this.game.time.now+d}else this._nextFire=this.game.time.now+this.fireRate;this.shots++,this.onFire.dispatch(c,this,s),this.fireLimit>0&&this.shots===this.fireLimit&&this.onFireLimit.dispatch(this,this.fireLimit)}return c},n.Weapon.prototype.fireAtPointer=function(t){return void 0===t&&(t=this.game.input.activePointer),this.fire(null,t.worldX,t.worldY)},n.Weapon.prototype.fireAtSprite=function(t){return this.fire(null,t.world.x,t.world.y)},n.Weapon.prototype.fireAtXY=function(t,e){return this.fire(null,t,e)},n.Weapon.prototype.setBulletBodyOffset=function(t,e,i,s){return void 0===i&&(i=0),void 0===s&&(s=0),this._data.customBody=!0,this._data.width=t,this._data.height=e,this._data.offsetX=i,this._data.offsetY=s,this.bullets.callAll("body.setSize","body",t,e,i,s),this.bullets.setAll("data.bodyDirty",!1),this},n.Weapon.prototype.setBulletFrames=function(t,e,i,s){return void 0===i&&(i=!0),void 0===s&&(s=!1),this.bulletFrames=n.ArrayUtils.numberArray(t,e),this.bulletFrameIndex=0,this.bulletFrameCycle=i,this.bulletFrameRandom=s,this},n.Weapon.prototype.addBulletAnimation=function(t,e,i,s,n){return this.anims[t]={name:t,frames:e,frameRate:i,loop:s,useNumericIndex:n},this.bullets.callAll("animations.add","animations",t,e,i,s,n),this.bulletAnimation=t,this},n.Weapon.prototype.debug=function(t,e,i){void 0===t&&(t=16),void 0===e&&(e=32),void 0===i&&(i=!1),this.game.debug.text("Weapon Plugin",t,e),this.game.debug.text("Bullets Alive: "+this.bullets.total+" - Total: "+this.bullets.length,t,e+24),i&&this.bullets.forEachExists(this.game.debug.body,this.game.debug,"rgba(255, 0, 255, 0.8)")},Object.defineProperty(n.Weapon.prototype,"bulletClass",{get:function(){return this._bulletClass},set:function(t){this._bulletClass=t,this.bullets.classType=this._bulletClass}}),Object.defineProperty(n.Weapon.prototype,"bulletKillType",{get:function(){return this._bulletKillType},set:function(t){switch(t){case n.Weapon.KILL_STATIC_BOUNDS:case n.Weapon.KILL_WEAPON_BOUNDS:this.bulletBounds=this.bounds;break;case n.Weapon.KILL_CAMERA_BOUNDS:this.bulletBounds=this.game.camera.view;break;case n.Weapon.KILL_WORLD_BOUNDS:this.bulletBounds=this.game.world.bounds}this._bulletKillType=t}}),Object.defineProperty(n.Weapon.prototype,"bulletCollideWorldBounds",{get:function(){return this._bulletCollideWorldBounds},set:function(t){this._bulletCollideWorldBounds=t,this.bullets.setAll("body.collideWorldBounds",t),this.bullets.setAll("data.bodyDirty",!1)}}),Object.defineProperty(n.Weapon.prototype,"x",{get:function(){return this.fireFrom.x},set:function(t){this.fireFrom.x=t}}),Object.defineProperty(n.Weapon.prototype,"y",{get:function(){return this.fireFrom.y},set:function(t){this.fireFrom.y=t}}),n.Bullet=function(t,e,i,s,r){n.Sprite.call(this,t,e,i,s,r),this.anchor.set(.5),this.data={bulletManager:null,fromX:0,fromY:0,bodyDirty:!0,rotateToVelocity:!1,killType:0,killDistance:0}},n.Bullet.prototype=Object.create(n.Sprite.prototype),n.Bullet.prototype.constructor=n.Bullet,n.Bullet.prototype.kill=function(){return this.alive=!1,this.exists=!1,this.visible=!1,this.data.bulletManager.onKill.dispatch(this),this},n.Bullet.prototype.update=function(){this.exists&&(this.data.killType>n.Weapon.KILL_LIFESPAN&&(this.data.killType===n.Weapon.KILL_DISTANCE?this.game.physics.arcade.distanceToXY(this,this.data.fromX,this.data.fromY,!0)>this.data.killDistance&&this.kill():this.data.bulletManager.bulletBounds.intersects(this)||this.kill()),this.data.rotateToVelocity&&(this.rotation=Math.atan2(this.body.velocity.y,this.body.velocity.x)),this.data.bulletManager.bulletWorldWrap&&this.game.world.wrap(this,this.data.bulletManager.bulletWorldWrapPadding))},n.Video=function(t,e,i){if(void 0===e&&(e=null),void 0===i&&(i=null),this.game=t,this.key=e,this.width=0,this.height=0,this.type=n.VIDEO,this.disableTextureUpload=!1,this.touchLocked=!1,this.onPlay=new n.Signal,this.onChangeSource=new n.Signal,this.onComplete=new n.Signal,this.onAccess=new n.Signal,this.onError=new n.Signal,this.onTimeout=new n.Signal,this.timeout=15e3,this._timeOutID=null,this.video=null,this.videoStream=null,this.isStreaming=!1,this.retryLimit=20,this.retry=0,this.retryInterval=500,this._retryID=null,this._codeMuted=!1,this._muted=!1,this._codePaused=!1,this._paused=!1,this._pending=!1,this._autoplay=!1,this._endCallback=null,this._playCallback=null,e&&this.game.cache.checkVideoKey(e)){var s=this.game.cache.getVideo(e);s.isBlob?this.createVideoFromBlob(s.data):this.video=s.data,this.width=this.video.videoWidth,this.height=this.video.videoHeight}else i&&this.createVideoFromURL(i,!1);this.video&&!i?(this.baseTexture=new PIXI.BaseTexture(this.video),this.baseTexture.forceLoaded(this.width,this.height)):(this.baseTexture=new PIXI.BaseTexture(n.Cache.DEFAULT.baseTexture.source),this.baseTexture.forceLoaded(this.width,this.height)),this.texture=new PIXI.Texture(this.baseTexture),this.textureFrame=new n.Frame(0,0,0,this.width,this.height,"video"),this.texture.setFrame(this.textureFrame),this.texture.valid=!1,null!==e&&this.video&&(this.texture.valid=this.video.canplay),this.snapshot=null,n.BitmapData&&(this.snapshot=new n.BitmapData(this.game,"",this.width,this.height)),!this.game.device.cocoonJS&&(this.game.device.iOS||this.game.device.android)||window.PhaserGlobal&&window.PhaserGlobal.fakeiOSTouchLock?this.setTouchLock():s&&(s.locked=!1)},n.Video.prototype={connectToMediaStream:function(t,e){return t&&e&&(this.video=t,this.videoStream=e,this.isStreaming=!0,this.baseTexture.source=this.video,this.updateTexture(null,this.video.videoWidth,this.video.videoHeight),this.onAccess.dispatch(this)),this},startMediaStream:function(t,e,i){if(void 0===t&&(t=!1),void 0===e&&(e=null),void 0===i&&(i=null),!this.game.device.getUserMedia)return this.onError.dispatch(this,"No getUserMedia"),!1;null!==this.videoStream&&(this.videoStream.active?this.videoStream.active=!1:this.videoStream.stop()),this.removeVideoElement(),this.video=document.createElement("video"),this.video.setAttribute("autoplay","autoplay"),null!==e&&(this.video.width=e),null!==i&&(this.video.height=i),this._timeOutID=window.setTimeout(this.getUserMediaTimeout.bind(this),this.timeout);try{navigator.getUserMedia({audio:t,video:!0},this.getUserMediaSuccess.bind(this),this.getUserMediaError.bind(this))}catch(t){this.getUserMediaError(t)}return this},getUserMediaTimeout:function(){clearTimeout(this._timeOutID),this.onTimeout.dispatch(this)},getUserMediaError:function(t){clearTimeout(this._timeOutID),this.onError.dispatch(this,t)},getUserMediaSuccess:function(t){clearTimeout(this._timeOutID),this.videoStream=t,void 0!==this.video.mozSrcObject?this.video.mozSrcObject=t:this.video.src=window.URL&&window.URL.createObjectURL(t)||t;var e=this;this.video.onloadeddata=function(){function t(){if(i>0)if(e.video.videoWidth>0){var s=e.video.videoWidth,n=e.video.videoHeight;isNaN(e.video.videoHeight)&&(n=s/(4/3)),e.video.play(),e.isStreaming=!0,e.baseTexture.source=e.video,e.updateTexture(null,s,n),e.onAccess.dispatch(e)}else window.setTimeout(t,500);else console.warn("Unable to connect to video stream. Webcam error?");i--}var i=10;t()}},createVideoFromBlob:function(t){var e=this;return this.video=document.createElement("video"),this.video.controls=!1,this.video.setAttribute("autoplay","autoplay"),this.video.addEventListener("loadeddata",function(t){e.updateTexture(t)},!0),this.video.src=window.URL.createObjectURL(t),this.video.canplay=!0,this},createVideoFromURL:function(t,e){return void 0===e&&(e=!1),this.texture&&(this.texture.valid=!1),this.video=document.createElement("video"),this.video.controls=!1,e&&this.video.setAttribute("autoplay","autoplay"),this.video.src=t,this.video.canplay=!0,this.video.load(),this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval),this.key=t,this},updateTexture:function(t,e,i){var s=!1;void 0!==e&&null!==e||(e=this.video.videoWidth,s=!0),void 0!==i&&null!==i||(i=this.video.videoHeight),this.width=e,this.height=i,this.baseTexture.source!==this.video&&(this.baseTexture.source=this.video),this.baseTexture.forceLoaded(e,i),this.texture.frame.resize(e,i),this.texture.width=e,this.texture.height=i,this.texture.valid=!0,this.snapshot&&this.snapshot.resize(e,i),s&&null!==this.key&&(this.onChangeSource.dispatch(this,e,i),this._autoplay&&(this.video.play(),this.onPlay.dispatch(this,this.loop,this.playbackRate)))},complete:function(){this.onComplete.dispatch(this)},play:function(t,e){return void 0===t&&(t=!1),void 0===e&&(e=1),this.game.sound.onMute&&(this.game.sound.onMute.add(this.setMute,this),this.game.sound.onUnMute.add(this.unsetMute,this),this.game.sound.mute&&this.setMute()),this.game.onPause.add(this.setPause,this),this.game.onResume.add(this.setResume,this),this._endCallback=this.complete.bind(this),this.video.addEventListener("ended",this._endCallback,!0),this.video.addEventListener("webkitendfullscreen",this._endCallback,!0),this.video.loop=t?"loop":"",this.video.playbackRate=e,this.touchLocked?this._pending=!0:(this._pending=!1,null!==this.key&&(4!==this.video.readyState?(this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval)):(this._playCallback=this.playHandler.bind(this),this.video.addEventListener("playing",this._playCallback,!0))),this.video.play(),this.onPlay.dispatch(this,t,e)),this},playHandler:function(){this.video.removeEventListener("playing",this._playCallback,!0),this.updateTexture()},stop:function(){return this.game.sound.onMute&&(this.game.sound.onMute.remove(this.setMute,this),this.game.sound.onUnMute.remove(this.unsetMute,this)),this.game.onPause.remove(this.setPause,this),this.game.onResume.remove(this.setResume,this),this.isStreaming?(this.video.mozSrcObject?(this.video.mozSrcObject.stop(),this.video.src=null):(this.video.src="",this.videoStream.active?this.videoStream.active=!1:this.videoStream.getTracks?this.videoStream.getTracks().forEach(function(t){t.stop()}):this.videoStream.stop()),this.videoStream=null,this.isStreaming=!1):(this.video.removeEventListener("ended",this._endCallback,!0),this.video.removeEventListener("webkitendfullscreen",this._endCallback,!0),this.video.removeEventListener("playing",this._playCallback,!0),this.touchLocked?this._pending=!1:this.video.pause()),this},add:function(t){if(Array.isArray(t))for(var e=0;e<t.length;e++)t[e].loadTexture&&t[e].loadTexture(this);else t.loadTexture(this);return this},addToWorld:function(t,e,i,s,n,r){n=n||1,r=r||1;var o=this.game.add.image(t,e,this);return o.anchor.set(i,s),o.scale.set(n,r),o},render:function(){!this.disableTextureUpload&&this.playing&&this.baseTexture.dirty()},setMute:function(){this._muted||(this._muted=!0,this.video.muted=!0)},unsetMute:function(){this._muted&&!this._codeMuted&&(this._muted=!1,this.video.muted=!1)},setPause:function(){this._paused||this.touchLocked||(this._paused=!0,this.video.pause())},setResume:function(){!this._paused||this._codePaused||this.touchLocked||(this._paused=!1,this.video.ended||this.video.play())},changeSource:function(t,e){return void 0===e&&(e=!0),this.texture.valid=!1,this.video.pause(),this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval),this.video.src=t,this.video.load(),this._autoplay=e,e||(this.paused=!0),this},checkVideoProgress:function(){4===this.video.readyState?this.updateTexture():(this.retry--,this.retry>0?this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval):console.warn("Phaser.Video: Unable to start downloading video in time",this.isStreaming))},setTouchLock:function(){this.game.input.touch.addTouchLockCallback(this.unlock,this),this.touchLocked=!0},unlock:function(){if(this.touchLocked=!1,this.video.play(),this.onPlay.dispatch(this,this.loop,this.playbackRate),this.key){var t=this.game.cache.getVideo(this.key);t&&!t.isBlob&&(t.locked=!1)}return!0},grab:function(t,e,i){return void 0===t&&(t=!1),void 0===e&&(e=1),void 0===i&&(i=null),null===this.snapshot?void console.warn("Video.grab cannot run because Phaser.BitmapData is unavailable"):(t&&this.snapshot.cls(),this.snapshot.copy(this.video,0,0,this.width,this.height,0,0,this.width,this.height,0,0,0,1,1,e,i),this.snapshot)},removeVideoElement:function(){if(this.video){for(this.video.parentNode&&this.video.parentNode.removeChild(this.video);this.video.hasChildNodes();)this.video.removeChild(this.video.firstChild);this.video.removeAttribute("autoplay"),this.video.removeAttribute("src"),this.video=null}},destroy:function(){this.stop(),this.removeVideoElement(),this.touchLocked&&this.game.input.touch.removeTouchLockCallback(this.unlock,this),this._retryID&&window.clearTimeout(this._retryID)}},Object.defineProperty(n.Video.prototype,"currentTime",{get:function(){return this.video?this.video.currentTime:0},set:function(t){this.video.currentTime=t}}),Object.defineProperty(n.Video.prototype,"duration",{get:function(){return this.video?this.video.duration:0}}),Object.defineProperty(n.Video.prototype,"progress",{get:function(){return this.video?this.video.currentTime/this.video.duration:0}}),Object.defineProperty(n.Video.prototype,"mute",{get:function(){return this._muted},set:function(t){if(t=t||null){if(this._muted)return;this._codeMuted=!0,this.setMute()}else{if(!this._muted)return;this._codeMuted=!1,this.unsetMute()}}}),Object.defineProperty(n.Video.prototype,"paused",{get:function(){return this._paused},set:function(t){if(t=t||null,!this.touchLocked)if(t){if(this._paused)return;this._codePaused=!0,this.setPause()}else{if(!this._paused)return;this._codePaused=!1,this.setResume()}}}),Object.defineProperty(n.Video.prototype,"volume",{get:function(){return this.video?this.video.volume:1},set:function(t){t<0?t=0:t>1&&(t=1),this.video&&(this.video.volume=t)}}),Object.defineProperty(n.Video.prototype,"playbackRate",{get:function(){return this.video?this.video.playbackRate:1},set:function(t){this.video&&(this.video.playbackRate=t)}}),Object.defineProperty(n.Video.prototype,"loop",{get:function(){return!!this.video&&this.video.loop},set:function(t){t&&this.video?this.video.loop="loop":this.video&&(this.video.loop="")}}),Object.defineProperty(n.Video.prototype,"playing",{get:function(){return!(this.video.paused&&this.video.ended)}}),n.Video.prototype.constructor=n.Video,void 0===PIXI.blendModes&&(PIXI.blendModes=n.blendModes),void 0===PIXI.scaleModes&&(PIXI.scaleModes=n.scaleModes),void 0===PIXI.Texture.emptyTexture&&(PIXI.Texture.emptyTexture=new PIXI.Texture(new PIXI.BaseTexture)),void 0===PIXI.DisplayObject._tempMatrix&&(PIXI.DisplayObject._tempMatrix=new PIXI.Matrix),void 0===PIXI.RenderTexture.tempMatrix&&(PIXI.RenderTexture.tempMatrix=new PIXI.Matrix),PIXI.Graphics&&void 0===PIXI.Graphics.POLY&&(PIXI.Graphics.POLY=n.POLYGON,PIXI.Graphics.RECT=n.RECTANGLE,PIXI.Graphics.CIRC=n.CIRCLE,PIXI.Graphics.ELIP=n.ELLIPSE,PIXI.Graphics.RREC=n.ROUNDEDRECTANGLE),PIXI.TextureSilentFail=!0,void 0!==t&&t.exports&&(e=t.exports=n),e.Phaser=n,n}).call(this)}).call(e,i(4))},function(t,e,i){/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*
* @overview
*
* Phaser - http://phaser.io
*
* v2.6.2 "Kore Springs" - Built: Fri Aug 26 2016 01:03:18
*
* By Richard Davey http://www.photonstorm.com @photonstorm
*
* Phaser is a fun, free and fast 2D game framework for making HTML5 games
* for desktop and mobile web browsers, supporting Canvas and WebGL rendering.
*
* Phaser uses Pixi.js for rendering, created by Mat Groves http://matgroves.com @Doormat23
* Phaser uses p2.js for full-body physics, created by Stefan Hedman https://github.com/schteppe/p2.js @schteppe
* Phaser contains a port of N+ Physics, converted by Richard Davey, original by http://www.metanetsoftware.com
*
* Many thanks to Adam Saltsman (@ADAMATOMIC) for releasing Flixel, from which both Phaser and my love of framework development originate.
*
* Follow development at http://phaser.io and on our forum
*
* "If you want your children to be intelligent, read them fairy tales."
* "If you want them to be more intelligent, read them more fairy tales."
* -- Albert Einstein
*/
(function(){var i=i||{};/**
* @author Mat Groves http://matgroves.com @Doormat23
* @author Richard Davey <[email protected]>
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* @author Richard Davey <[email protected]>
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
return i.game=null,i.WEBGL_RENDERER=0,i.CANVAS_RENDERER=1,i.VERSION="v2.2.9",i._UID=0,"undefined"!=typeof Float32Array?(i.Float32Array=Float32Array,i.Uint16Array=Uint16Array,i.Uint32Array=Uint32Array,i.ArrayBuffer=ArrayBuffer):(i.Float32Array=Array,i.Uint16Array=Array),i.PI_2=2*Math.PI,i.RAD_TO_DEG=180/Math.PI,i.DEG_TO_RAD=Math.PI/180,i.RETINA_PREFIX="@2x",i.DisplayObject=function(){this.position=new i.Point(0,0),this.scale=new i.Point(1,1),this.pivot=new i.Point(0,0),this.rotation=0,this.alpha=1,this.visible=!0,this.hitArea=null,this.renderable=!1,this.parent=null,this.worldAlpha=1,this.worldTransform=new i.Matrix,this.worldPosition=new i.Point(0,0),this.worldScale=new i.Point(1,1),this.worldRotation=0,this.filterArea=null,this._sr=0,this._cr=1,this._bounds=new i.Rectangle(0,0,0,0),this._currentBounds=null,this._mask=null,this._cacheAsBitmap=!1,this._cacheIsDirty=!1},i.DisplayObject.prototype.constructor=i.DisplayObject,i.DisplayObject.prototype={destroy:function(){if(this.children){for(var t=this.children.length;t--;)this.children[t].destroy();this.children=[]}this.hitArea=null,this.parent=null,this.worldTransform=null,this.filterArea=null,this.renderable=!1,this._bounds=null,this._currentBounds=null,this._mask=null,this._destroyCachedSprite()},updateTransform:function(t){if(!t&&!this.parent&&!this.game)return this;var e=this.parent;t?e=t:this.parent||(e=this.game.world);var s,n,r,o,a,h,l=e.worldTransform,c=this.worldTransform;return this.rotation%i.PI_2?(this.rotation!==this.rotationCache&&(this.rotationCache=this.rotation,this._sr=Math.sin(this.rotation),this._cr=Math.cos(this.rotation)),s=this._cr*this.scale.x,n=this._sr*this.scale.x,r=-this._sr*this.scale.y,o=this._cr*this.scale.y,a=this.position.x,h=this.position.y,(this.pivot.x||this.pivot.y)&&(a-=this.pivot.x*s+this.pivot.y*r,h-=this.pivot.x*n+this.pivot.y*o),c.a=s*l.a+n*l.c,c.b=s*l.b+n*l.d,c.c=r*l.a+o*l.c,c.d=r*l.b+o*l.d,c.tx=a*l.a+h*l.c+l.tx,c.ty=a*l.b+h*l.d+l.ty):(s=this.scale.x,o=this.scale.y,a=this.position.x-this.pivot.x*s,h=this.position.y-this.pivot.y*o,c.a=s*l.a,c.b=s*l.b,c.c=o*l.c,c.d=o*l.d,c.tx=a*l.a+h*l.c+l.tx,c.ty=a*l.b+h*l.d+l.ty),this.worldAlpha=this.alpha*e.worldAlpha,this.worldPosition.set(c.tx,c.ty),this.worldScale.set(this.scale.x*Math.sqrt(c.a*c.a+c.c*c.c),this.scale.y*Math.sqrt(c.b*c.b+c.d*c.d)),this.worldRotation=Math.atan2(-c.c,c.d),this._currentBounds=null,this.transformCallback&&this.transformCallback.call(this.transformCallbackContext,c,l),this},preUpdate:function(){},generateTexture:function(t,e,s){var n=this.getLocalBounds(),r=new i.RenderTexture(0|n.width,0|n.height,s,e,t);return i.DisplayObject._tempMatrix.tx=-n.x,i.DisplayObject._tempMatrix.ty=-n.y,r.render(this,i.DisplayObject._tempMatrix),r},updateCache:function(){return this._generateCachedSprite(),this},toGlobal:function(t){return this.updateTransform(),this.worldTransform.apply(t)},toLocal:function(t,e){return e&&(t=e.toGlobal(t)),this.updateTransform(),this.worldTransform.applyInverse(t)},_renderCachedSprite:function(t){this._cachedSprite.worldAlpha=this.worldAlpha,t.gl?i.Sprite.prototype._renderWebGL.call(this._cachedSprite,t):i.Sprite.prototype._renderCanvas.call(this._cachedSprite,t)},_generateCachedSprite:function(){this._cacheAsBitmap=!1;var t=this.getLocalBounds();if(t.width=Math.max(1,Math.ceil(t.width)),t.height=Math.max(1,Math.ceil(t.height)),this.updateTransform(),this._cachedSprite)this._cachedSprite.texture.resize(t.width,t.height);else{var e=new i.RenderTexture(t.width,t.height);this._cachedSprite=new i.Sprite(e),this._cachedSprite.worldTransform=this.worldTransform}var s=this._filters;this._filters=null,this._cachedSprite.filters=s,i.DisplayObject._tempMatrix.tx=-t.x,i.DisplayObject._tempMatrix.ty=-t.y,this._cachedSprite.texture.render(this,i.DisplayObject._tempMatrix,!0),this._cachedSprite.anchor.x=-t.x/t.width,this._cachedSprite.anchor.y=-t.y/t.height,this._filters=s,this._cacheAsBitmap=!0},_destroyCachedSprite:function(){this._cachedSprite&&(this._cachedSprite.texture.destroy(!0),this._cachedSprite=null)}},i.DisplayObject.prototype.displayObjectUpdateTransform=i.DisplayObject.prototype.updateTransform,Object.defineProperties(i.DisplayObject.prototype,{x:{get:function(){return this.position.x},set:function(t){this.position.x=t}},y:{get:function(){return this.position.y},set:function(t){this.position.y=t}},worldVisible:{get:function(){if(this.visible){var t=this.parent;if(!t)return this.visible;do{if(!t.visible)return!1;t=t.parent}while(t);return!0}return!1}},mask:{get:function(){return this._mask},set:function(t){this._mask&&(this._mask.isMask=!1),this._mask=t,t&&(this._mask.isMask=!0)}},filters:{get:function(){return this._filters},set:function(t){if(Array.isArray(t)){for(var e=[],s=0;s<t.length;s++)for(var n=t[s].passes,r=0;r<n.length;r++)e.push(n[r]);this._filterBlock={target:this,filterPasses:e}}this._filters=t,this.blendMode&&this.blendMode===i.blendModes.MULTIPLY&&(this.blendMode=i.blendModes.NORMAL)}},cacheAsBitmap:{get:function(){return this._cacheAsBitmap},set:function(t){this._cacheAsBitmap!==t&&(t?this._generateCachedSprite():this._destroyCachedSprite(),this._cacheAsBitmap=t)}}}),i.DisplayObjectContainer=function(){i.DisplayObject.call(this),this.children=[],this.ignoreChildInput=!1},i.DisplayObjectContainer.prototype=Object.create(i.DisplayObject.prototype),i.DisplayObjectContainer.prototype.constructor=i.DisplayObjectContainer,i.DisplayObjectContainer.prototype.addChild=function(t){return this.addChildAt(t,this.children.length)},i.DisplayObjectContainer.prototype.addChildAt=function(t,e){if(e>=0&&e<=this.children.length)return t.parent&&t.parent.removeChild(t),t.parent=this,this.children.splice(e,0,t),t;throw new Error(t+"addChildAt: The index "+e+" supplied is out of bounds "+this.children.length)},i.DisplayObjectContainer.prototype.swapChildren=function(t,e){if(t!==e){var i=this.getChildIndex(t),s=this.getChildIndex(e);if(i<0||s<0)throw new Error("swapChildren: Both the supplied DisplayObjects must be a child of the caller.");this.children[i]=e,this.children[s]=t}},i.DisplayObjectContainer.prototype.getChildIndex=function(t){var e=this.children.indexOf(t);if(-1===e)throw new Error("The supplied DisplayObject must be a child of the caller");return e},i.DisplayObjectContainer.prototype.setChildIndex=function(t,e){if(e<0||e>=this.children.length)throw new Error("The supplied index is out of bounds");var i=this.getChildIndex(t);this.children.splice(i,1),this.children.splice(e,0,t)},i.DisplayObjectContainer.prototype.getChildAt=function(t){if(t<0||t>=this.children.length)throw new Error("getChildAt: Supplied index "+t+" does not exist in the child list, or the supplied DisplayObject must be a child of the caller");return this.children[t]},i.DisplayObjectContainer.prototype.removeChild=function(t){var e=this.children.indexOf(t);if(-1!==e)return this.removeChildAt(e)},i.DisplayObjectContainer.prototype.removeChildAt=function(t){var e=this.getChildAt(t);return e&&(e.parent=void 0,this.children.splice(t,1)),e},i.DisplayObjectContainer.prototype.removeChildren=function(t,e){void 0===t&&(t=0),void 0===e&&(e=this.children.length);var i=e-t;if(i>0&&i<=e){for(var s=this.children.splice(begin,i),n=0;n<s.length;n++){s[n].parent=void 0}return s}if(0===i&&0===this.children.length)return[];throw new Error("removeChildren: Range Error, numeric values are outside the acceptable range")},i.DisplayObjectContainer.prototype.updateTransform=function(){if(this.visible&&(this.displayObjectUpdateTransform(),!this._cacheAsBitmap))for(var t=0;t<this.children.length;t++)this.children[t].updateTransform()},i.DisplayObjectContainer.prototype.displayObjectContainerUpdateTransform=i.DisplayObjectContainer.prototype.updateTransform,i.DisplayObjectContainer.prototype.getBounds=function(t){var e=t&&t instanceof i.DisplayObject,s=!0;e?s=t instanceof i.DisplayObjectContainer&&t.contains(this):t=this;var n;if(e){var r=t.worldTransform;for(t.worldTransform=i.identityMatrix,n=0;n<t.children.length;n++)t.children[n].updateTransform()}var o,a,h,l=1/0,c=1/0,u=-1/0,d=-1/0,p=!1;for(n=0;n<this.children.length;n++){this.children[n].visible&&(p=!0,o=this.children[n].getBounds(),l=l<o.x?l:o.x,c=c<o.y?c:o.y,a=o.width+o.x,h=o.height+o.y,u=u>a?u:a,d=d>h?d:h)}var f=this._bounds;if(!p){f=new i.Rectangle;var g=f.x,m=f.width+f.x,y=f.y,v=f.height+f.y,b=this.worldTransform,x=b.a,w=b.b,_=b.c,P=b.d,T=b.tx,C=b.ty,S=x*m+_*v+T,A=P*v+w*m+C,E=x*g+_*v+T,I=P*v+w*g+C,M=x*g+_*y+T,R=P*y+w*g+C,B=x*m+_*y+T,L=P*y+w*m+C;u=S,d=A,l=S,c=A,l=E<l?E:l,l=M<l?M:l,l=B<l?B:l,c=I<c?I:c,c=R<c?R:c,c=L<c?L:c,u=E>u?E:u,u=M>u?M:u,u=B>u?B:u,d=I>d?I:d,d=R>d?R:d,d=L>d?L:d}if(f.x=l,f.y=c,f.width=u-l,f.height=d-c,e)for(t.worldTransform=r,n=0;n<t.children.length;n++)t.children[n].updateTransform();if(!s){var O=t.getBounds();f.x-=O.x,f.y-=O.y}return f},i.DisplayObjectContainer.prototype.getLocalBounds=function(){return this.getBounds(this)},i.DisplayObjectContainer.prototype.contains=function(t){return!!t&&(t===this||this.contains(t.parent))},i.DisplayObjectContainer.prototype._renderWebGL=function(t){if(this.visible&&!(this.alpha<=0)){if(this._cacheAsBitmap)return void this._renderCachedSprite(t);var e;if(this._mask||this._filters){for(this._filters&&(t.spriteBatch.flush(),t.filterManager.pushFilter(this._filterBlock)),this._mask&&(t.spriteBatch.stop(),t.maskManager.pushMask(this.mask,t),t.spriteBatch.start()),e=0;e<this.children.length;e++)this.children[e]._renderWebGL(t);t.spriteBatch.stop(),this._mask&&t.maskManager.popMask(this._mask,t),this._filters&&t.filterManager.popFilter(),t.spriteBatch.start()}else for(e=0;e<this.children.length;e++)this.children[e]._renderWebGL(t)}},i.DisplayObjectContainer.prototype._renderCanvas=function(t){if(!1!==this.visible&&0!==this.alpha){if(this._cacheAsBitmap)return void this._renderCachedSprite(t);this._mask&&t.maskManager.pushMask(this._mask,t);for(var e=0;e<this.children.length;e++)this.children[e]._renderCanvas(t);this._mask&&t.maskManager.popMask(t)}},Object.defineProperty(i.DisplayObjectContainer.prototype,"width",{get:function(){return this.getLocalBounds().width*this.scale.x},set:function(t){var e=this.getLocalBounds().width;this.scale.x=0!==e?t/e:1,this._width=t}}),Object.defineProperty(i.DisplayObjectContainer.prototype,"height",{get:function(){return this.getLocalBounds().height*this.scale.y},set:function(t){var e=this.getLocalBounds().height;this.scale.y=0!==e?t/e:1,this._height=t}}),i.Sprite=function(t){i.DisplayObjectContainer.call(this),this.anchor=new i.Point,this.texture=t||i.Texture.emptyTexture,this._width=0,this._height=0,this.tint=16777215,this.cachedTint=-1,this.tintedTexture=null,this.blendMode=i.blendModes.NORMAL,this.shader=null,this.exists=!0,this.texture.baseTexture.hasLoaded&&this.onTextureUpdate(),this.renderable=!0},i.Sprite.prototype=Object.create(i.DisplayObjectContainer.prototype),i.Sprite.prototype.constructor=i.Sprite,Object.defineProperty(i.Sprite.prototype,"width",{get:function(){return this.scale.x*this.texture.frame.width},set:function(t){this.scale.x=t/this.texture.frame.width,this._width=t}}),Object.defineProperty(i.Sprite.prototype,"height",{get:function(){return this.scale.y*this.texture.frame.height},set:function(t){this.scale.y=t/this.texture.frame.height,this._height=t}}),i.Sprite.prototype.setTexture=function(t,e){void 0!==e&&this.texture.baseTexture.destroy(),this.texture.baseTexture.skipRender=!1,this.texture=t,this.texture.valid=!0,this.cachedTint=-1},i.Sprite.prototype.onTextureUpdate=function(){this._width&&(this.scale.x=this._width/this.texture.frame.width),this._height&&(this.scale.y=this._height/this.texture.frame.height)},i.Sprite.prototype.getBounds=function(t){var e=this.texture.frame.width,i=this.texture.frame.height,s=e*(1-this.anchor.x),n=e*-this.anchor.x,r=i*(1-this.anchor.y),o=i*-this.anchor.y,a=t||this.worldTransform,h=a.a,l=a.b,c=a.c,u=a.d,d=a.tx,p=a.ty,f=-1/0,g=-1/0,m=1/0,y=1/0;if(0===l&&0===c){if(h<0){h*=-1;var v=s;s=-n,n=-v}if(u<0){u*=-1;var v=r;r=-o,o=-v}m=h*n+d,f=h*s+d,y=u*o+p,g=u*r+p}else{var b=h*n+c*o+d,x=u*o+l*n+p,w=h*s+c*o+d,_=u*o+l*s+p,P=h*s+c*r+d,T=u*r+l*s+p,C=h*n+c*r+d,S=u*r+l*n+p;m=b<m?b:m,m=w<m?w:m,m=P<m?P:m,m=C<m?C:m,y=x<y?x:y,y=_<y?_:y,y=T<y?T:y,y=S<y?S:y,f=b>f?b:f,f=w>f?w:f,f=P>f?P:f,f=C>f?C:f,g=x>g?x:g,g=_>g?_:g,g=T>g?T:g,g=S>g?S:g}var A=this._bounds;return A.x=m,A.width=f-m,A.y=y,A.height=g-y,this._currentBounds=A,A},i.Sprite.prototype.getLocalBounds=function(){var t=this.worldTransform;this.worldTransform=i.identityMatrix;for(var e=0;e<this.children.length;e++)this.children[e].updateTransform();var s=this.getBounds();for(this.worldTransform=t,e=0;e<this.children.length;e++)this.children[e].updateTransform();return s},i.Sprite.prototype._renderWebGL=function(t,e){if(this.visible&&!(this.alpha<=0)&&this.renderable){var i=this.worldTransform;if(e&&(i=e),this._mask||this._filters){var s=t.spriteBatch;this._filters&&(s.flush(),t.filterManager.pushFilter(this._filterBlock)),this._mask&&(s.stop(),t.maskManager.pushMask(this.mask,t),s.start()),s.render(this);for(var n=0;n<this.children.length;n++)this.children[n]._renderWebGL(t);s.stop(),this._mask&&t.maskManager.popMask(this._mask,t),this._filters&&t.filterManager.popFilter(),s.start()}else{t.spriteBatch.render(this);for(var n=0;n<this.children.length;n++)this.children[n]._renderWebGL(t,i)}}},i.Sprite.prototype._renderCanvas=function(t,e){if(!(!this.visible||0===this.alpha||!this.renderable||this.texture.crop.width<=0||this.texture.crop.height<=0)){var s=this.worldTransform;if(e&&(s=e),this.blendMode!==t.currentBlendMode&&(t.currentBlendMode=this.blendMode,t.context.globalCompositeOperation=i.blendModesCanvas[t.currentBlendMode]),this._mask&&t.maskManager.pushMask(this._mask,t),this.texture.valid){var n=this.texture.baseTexture.resolution/t.resolution;t.context.globalAlpha=this.worldAlpha,t.smoothProperty&&t.scaleMode!==this.texture.baseTexture.scaleMode&&(t.scaleMode=this.texture.baseTexture.scaleMode,t.context[t.smoothProperty]=t.scaleMode===i.scaleModes.LINEAR);var r=this.texture.trim?this.texture.trim.x-this.anchor.x*this.texture.trim.width:this.anchor.x*-this.texture.frame.width,o=this.texture.trim?this.texture.trim.y-this.anchor.y*this.texture.trim.height:this.anchor.y*-this.texture.frame.height,a=s.tx*t.resolution+t.shakeX,h=s.ty*t.resolution+t.shakeY;t.roundPixels?(t.context.setTransform(s.a,s.b,s.c,s.d,0|a,0|h),r|=0,o|=0):t.context.setTransform(s.a,s.b,s.c,s.d,a,h);var l=this.texture.crop.width,c=this.texture.crop.height;if(r/=n,o/=n,16777215!==this.tint)(this.texture.requiresReTint||this.cachedTint!==this.tint)&&(this.tintedTexture=i.CanvasTinter.getTintedTexture(this,this.tint),this.cachedTint=this.tint,this.texture.requiresReTint=!1),t.context.drawImage(this.tintedTexture,0,0,l,c,r,o,l/n,c/n);else{var u=this.texture.crop.x,d=this.texture.crop.y;t.context.drawImage(this.texture.baseTexture.source,u,d,l,c,r,o,l/n,c/n)}}for(var p=0;p<this.children.length;p++)this.children[p]._renderCanvas(t);this._mask&&t.maskManager.popMask(t)}},i.SpriteBatch=function(t){i.DisplayObjectContainer.call(this),this.textureThing=t,this.ready=!1},i.SpriteBatch.prototype=Object.create(i.DisplayObjectContainer.prototype),i.SpriteBatch.prototype.constructor=i.SpriteBatch,i.SpriteBatch.prototype.initWebGL=function(t){this.fastSpriteBatch=new i.WebGLFastSpriteBatch(t),this.ready=!0},i.SpriteBatch.prototype.updateTransform=function(){this.displayObjectUpdateTransform()},i.SpriteBatch.prototype._renderWebGL=function(t){!this.visible||this.alpha<=0||!this.children.length||(this.ready||this.initWebGL(t.gl),this.fastSpriteBatch.gl!==t.gl&&this.fastSpriteBatch.setContext(t.gl),t.spriteBatch.stop(),t.shaderManager.setShader(t.shaderManager.fastShader),this.fastSpriteBatch.begin(this,t),this.fastSpriteBatch.render(this),t.spriteBatch.start())},i.SpriteBatch.prototype._renderCanvas=function(t){if(this.visible&&!(this.alpha<=0)&&this.children.length){var e=t.context;e.globalAlpha=this.worldAlpha,this.displayObjectUpdateTransform();for(var i=this.worldTransform,s=!0,n=0;n<this.children.length;n++){var r=this.children[n];if(r.visible){var o=r.texture,a=o.frame;if(e.globalAlpha=this.worldAlpha*r.alpha,r.rotation%(2*Math.PI)==0)s&&(e.setTransform(i.a,i.b,i.c,i.d,i.tx,i.ty),s=!1),e.drawImage(o.baseTexture.source,a.x,a.y,a.width,a.height,r.anchor.x*(-a.width*r.scale.x)+r.position.x+.5+t.shakeX|0,r.anchor.y*(-a.height*r.scale.y)+r.position.y+.5+t.shakeY|0,a.width*r.scale.x,a.height*r.scale.y);else{s||(s=!0),r.displayObjectUpdateTransform();var h=r.worldTransform,l=h.tx*t.resolution+t.shakeX,c=h.ty*t.resolution+t.shakeY;t.roundPixels?e.setTransform(h.a,h.b,h.c,h.d,0|l,0|c):e.setTransform(h.a,h.b,h.c,h.d,l,c),e.drawImage(o.baseTexture.source,a.x,a.y,a.width,a.height,r.anchor.x*-a.width+.5|0,r.anchor.y*-a.height+.5|0,a.width,a.height)}}}}},i.hex2rgb=function(t){return[(t>>16&255)/255,(t>>8&255)/255,(255&t)/255]},i.rgb2hex=function(t){return(255*t[0]<<16)+(255*t[1]<<8)+255*t[2]},i.canUseNewCanvasBlendModes=function(){if(void 0===document)return!1;var t="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAABAQMAAADD8p2OAAAAA1BMVEX/",e="AAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJggg==",s=new Image;s.src=t+"AP804Oa6"+e;var n=new Image;n.src=t+"/wCKxvRF"+e;var r=i.CanvasPool.create(this,6,1),o=r.getContext("2d");if(o.globalCompositeOperation="multiply",o.drawImage(s,0,0),o.drawImage(n,2,0),!o.getImageData(2,0,1,1))return!1;var a=o.getImageData(2,0,1,1).data;return i.CanvasPool.remove(this),255===a[0]&&0===a[1]&&0===a[2]},i.getNextPowerOfTwo=function(t){if(t>0&&0==(t&t-1))return t;for(var e=1;e<t;)e<<=1;return e},i.isPowerOfTwo=function(t,e){return t>0&&0==(t&t-1)&&e>0&&0==(e&e-1)},i.CanvasPool={create:function(t,e,s){var n,r=i.CanvasPool.getFirst();if(-1===r){var o={parent:t,canvas:document.createElement("canvas")};i.CanvasPool.pool.push(o),n=o.canvas}else i.CanvasPool.pool[r].parent=t,n=i.CanvasPool.pool[r].canvas;return void 0!==e&&(n.width=e,n.height=s),n},getFirst:function(){for(var t=i.CanvasPool.pool,e=0;e<t.length;e++)if(!t[e].parent)return e;return-1},remove:function(t){for(var e=i.CanvasPool.pool,s=0;s<e.length;s++)e[s].parent===t&&(e[s].parent=null,e[s].canvas.width=1,e[s].canvas.height=1)},removeByCanvas:function(t){for(var e=i.CanvasPool.pool,s=0;s<e.length;s++)e[s].canvas===t&&(e[s].parent=null,e[s].canvas.width=1,e[s].canvas.height=1)},getTotal:function(){for(var t=i.CanvasPool.pool,e=0,s=0;s<t.length;s++)t[s].parent&&e++;return e},getFree:function(){for(var t=i.CanvasPool.pool,e=0,s=0;s<t.length;s++)t[s].parent||e++;return e}},i.CanvasPool.pool=[],i.initDefaultShaders=function(){},i.CompileVertexShader=function(t,e){return i._CompileShader(t,e,t.VERTEX_SHADER)},i.CompileFragmentShader=function(t,e){return i._CompileShader(t,e,t.FRAGMENT_SHADER)},i._CompileShader=function(t,e,i){var s=e;Array.isArray(e)&&(s=e.join("\n"));var n=t.createShader(i);return t.shaderSource(n,s),t.compileShader(n),t.getShaderParameter(n,t.COMPILE_STATUS)?n:(window.console.log(t.getShaderInfoLog(n)),null)},i.compileProgram=function(t,e,s){var n=i.CompileFragmentShader(t,s),r=i.CompileVertexShader(t,e),o=t.createProgram();return t.attachShader(o,r),t.attachShader(o,n),t.linkProgram(o),t.getProgramParameter(o,t.LINK_STATUS)||(window.console.log(t.getProgramInfoLog(o)),window.console.log("Could not initialise shaders")),o},i.PixiShader=function(t){this._UID=i._UID++,this.gl=t,this.program=null,this.fragmentSrc=["precision lowp float;","varying vec2 vTextureCoord;","varying vec4 vColor;","uniform sampler2D uSampler;","void main(void) {"," gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;","}"],this.textureCount=0,this.firstRun=!0,this.dirty=!0,this.attributes=[],this.init()},i.PixiShader.prototype.constructor=i.PixiShader,i.PixiShader.prototype.init=function(){var t=this.gl,e=i.compileProgram(t,this.vertexSrc||i.PixiShader.defaultVertexSrc,this.fragmentSrc);t.useProgram(e),this.uSampler=t.getUniformLocation(e,"uSampler"),this.projectionVector=t.getUniformLocation(e,"projectionVector"),this.offsetVector=t.getUniformLocation(e,"offsetVector"),this.dimensions=t.getUniformLocation(e,"dimensions"),this.aVertexPosition=t.getAttribLocation(e,"aVertexPosition"),this.aTextureCoord=t.getAttribLocation(e,"aTextureCoord"),this.colorAttribute=t.getAttribLocation(e,"aColor"),-1===this.colorAttribute&&(this.colorAttribute=2),this.attributes=[this.aVertexPosition,this.aTextureCoord,this.colorAttribute];for(var s in this.uniforms)this.uniforms[s].uniformLocation=t.getUniformLocation(e,s);this.initUniforms(),this.program=e},i.PixiShader.prototype.initUniforms=function(){this.textureCount=1;var t,e=this.gl;for(var i in this.uniforms){t=this.uniforms[i];var s=t.type;"sampler2D"===s?(t._init=!1,null!==t.value&&this.initSampler2D(t)):"mat2"===s||"mat3"===s||"mat4"===s?(t.glMatrix=!0,t.glValueLength=1,"mat2"===s?t.glFunc=e.uniformMatrix2fv:"mat3"===s?t.glFunc=e.uniformMatrix3fv:"mat4"===s&&(t.glFunc=e.uniformMatrix4fv)):(t.glFunc=e["uniform"+s],t.glValueLength="2f"===s||"2i"===s?2:"3f"===s||"3i"===s?3:"4f"===s||"4i"===s?4:1)}},i.PixiShader.prototype.initSampler2D=function(t){if(t.value&&t.value.baseTexture&&t.value.baseTexture.hasLoaded){var e=this.gl;if(e.activeTexture(e["TEXTURE"+this.textureCount]),e.bindTexture(e.TEXTURE_2D,t.value.baseTexture._glTextures[e.id]),t.textureData){var i=t.textureData,s=i.magFilter?i.magFilter:e.LINEAR,n=i.minFilter?i.minFilter:e.LINEAR,r=i.wrapS?i.wrapS:e.CLAMP_TO_EDGE,o=i.wrapT?i.wrapT:e.CLAMP_TO_EDGE,a=i.luminance?e.LUMINANCE:e.RGBA;if(i.repeat&&(r=e.REPEAT,o=e.REPEAT),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!!i.flipY),i.width){var h=i.width?i.width:512,l=i.height?i.height:2,c=i.border?i.border:0;e.texImage2D(e.TEXTURE_2D,0,a,h,l,c,a,e.UNSIGNED_BYTE,null)}else e.texImage2D(e.TEXTURE_2D,0,a,e.RGBA,e.UNSIGNED_BYTE,t.value.baseTexture.source);e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,s),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,n),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,r),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,o)}e.uniform1i(t.uniformLocation,this.textureCount),t._init=!0,this.textureCount++}},i.PixiShader.prototype.syncUniforms=function(){this.textureCount=1;var t,e=this.gl;for(var s in this.uniforms)t=this.uniforms[s],1===t.glValueLength?!0===t.glMatrix?t.glFunc.call(e,t.uniformLocation,t.transpose,t.value):t.glFunc.call(e,t.uniformLocation,t.value):2===t.glValueLength?t.glFunc.call(e,t.uniformLocation,t.value.x,t.value.y):3===t.glValueLength?t.glFunc.call(e,t.uniformLocation,t.value.x,t.value.y,t.value.z):4===t.glValueLength?t.glFunc.call(e,t.uniformLocation,t.value.x,t.value.y,t.value.z,t.value.w):"sampler2D"===t.type&&(t._init?(e.activeTexture(e["TEXTURE"+this.textureCount]),t.value.baseTexture._dirty[e.id]?i.instances[e.id].updateTexture(t.value.baseTexture):e.bindTexture(e.TEXTURE_2D,t.value.baseTexture._glTextures[e.id]),e.uniform1i(t.uniformLocation,this.textureCount),this.textureCount++):this.initSampler2D(t))},i.PixiShader.prototype.destroy=function(){this.gl.deleteProgram(this.program),this.uniforms=null,this.gl=null,this.attributes=null},i.PixiShader.defaultVertexSrc=["attribute vec2 aVertexPosition;","attribute vec2 aTextureCoord;","attribute vec4 aColor;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","varying vec2 vTextureCoord;","varying vec4 vColor;","const vec2 center = vec2(-1.0, 1.0);","void main(void) {"," gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);"," vTextureCoord = aTextureCoord;"," vColor = vec4(aColor.rgb * aColor.a, aColor.a);","}"],i.PixiFastShader=function(t){this._UID=i._UID++,this.gl=t,this.program=null,this.fragmentSrc=["precision lowp float;","varying vec2 vTextureCoord;","varying float vColor;","uniform sampler2D uSampler;","void main(void) {"," gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;","}"],this.vertexSrc=["attribute vec2 aVertexPosition;","attribute vec2 aPositionCoord;","attribute vec2 aScale;","attribute float aRotation;","attribute vec2 aTextureCoord;","attribute float aColor;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","uniform mat3 uMatrix;","varying vec2 vTextureCoord;","varying float vColor;","const vec2 center = vec2(-1.0, 1.0);","void main(void) {"," vec2 v;"," vec2 sv = aVertexPosition * aScale;"," v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);"," v.y = (sv.x) * sin(aRotation) + (sv.y) * cos(aRotation);"," v = ( uMatrix * vec3(v + aPositionCoord , 1.0) ).xy ;"," gl_Position = vec4( ( v / projectionVector) + center , 0.0, 1.0);"," vTextureCoord = aTextureCoord;"," vColor = aColor;","}"],this.textureCount=0,this.init()},i.PixiFastShader.prototype.constructor=i.PixiFastShader,i.PixiFastShader.prototype.init=function(){var t=this.gl,e=i.compileProgram(t,this.vertexSrc,this.fragmentSrc);t.useProgram(e),this.uSampler=t.getUniformLocation(e,"uSampler"),this.projectionVector=t.getUniformLocation(e,"projectionVector"),this.offsetVector=t.getUniformLocation(e,"offsetVector"),this.dimensions=t.getUniformLocation(e,"dimensions"),this.uMatrix=t.getUniformLocation(e,"uMatrix"),this.aVertexPosition=t.getAttribLocation(e,"aVertexPosition"),this.aPositionCoord=t.getAttribLocation(e,"aPositionCoord"),this.aScale=t.getAttribLocation(e,"aScale"),this.aRotation=t.getAttribLocation(e,"aRotation"),this.aTextureCoord=t.getAttribLocation(e,"aTextureCoord"),this.colorAttribute=t.getAttribLocation(e,"aColor"),-1===this.colorAttribute&&(this.colorAttribute=2),this.attributes=[this.aVertexPosition,this.aPositionCoord,this.aScale,this.aRotation,this.aTextureCoord,this.colorAttribute],this.program=e},i.PixiFastShader.prototype.destroy=function(){this.gl.deleteProgram(this.program),this.uniforms=null,this.gl=null,this.attributes=null},i.StripShader=function(t){this._UID=i._UID++,this.gl=t,this.program=null,this.fragmentSrc=["precision mediump float;","varying vec2 vTextureCoord;","uniform float alpha;","uniform sampler2D uSampler;","void main(void) {"," gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;","}"],this.vertexSrc=["attribute vec2 aVertexPosition;","attribute vec2 aTextureCoord;","uniform mat3 translationMatrix;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","varying vec2 vTextureCoord;","void main(void) {"," vec3 v = translationMatrix * vec3(aVertexPosition , 1.0);"," v -= offsetVector.xyx;"," gl_Position = vec4( v.x / projectionVector.x -1.0, v.y / -projectionVector.y + 1.0 , 0.0, 1.0);"," vTextureCoord = aTextureCoord;","}"],this.init()},i.StripShader.prototype.constructor=i.StripShader,i.StripShader.prototype.init=function(){var t=this.gl,e=i.compileProgram(t,this.vertexSrc,this.fragmentSrc);t.useProgram(e),this.uSampler=t.getUniformLocation(e,"uSampler"),this.projectionVector=t.getUniformLocation(e,"projectionVector"),this.offsetVector=t.getUniformLocation(e,"offsetVector"),this.colorAttribute=t.getAttribLocation(e,"aColor"),this.aVertexPosition=t.getAttribLocation(e,"aVertexPosition"),this.aTextureCoord=t.getAttribLocation(e,"aTextureCoord"),this.attributes=[this.aVertexPosition,this.aTextureCoord],this.translationMatrix=t.getUniformLocation(e,"translationMatrix"),this.alpha=t.getUniformLocation(e,"alpha"),this.program=e},i.StripShader.prototype.destroy=function(){this.gl.deleteProgram(this.program),this.uniforms=null,this.gl=null,this.attribute=null},i.PrimitiveShader=function(t){this._UID=i._UID++,this.gl=t,this.program=null,this.fragmentSrc=["precision mediump float;","varying vec4 vColor;","void main(void) {"," gl_FragColor = vColor;","}"],this.vertexSrc=["attribute vec2 aVertexPosition;","attribute vec4 aColor;","uniform mat3 translationMatrix;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","uniform float alpha;","uniform float flipY;","uniform vec3 tint;","varying vec4 vColor;","void main(void) {"," vec3 v = translationMatrix * vec3(aVertexPosition , 1.0);"," v -= offsetVector.xyx;"," gl_Position = vec4( v.x / projectionVector.x -1.0, (v.y / projectionVector.y * -flipY) + flipY , 0.0, 1.0);"," vColor = aColor * vec4(tint * alpha, alpha);","}"],this.init()},i.PrimitiveShader.prototype.constructor=i.PrimitiveShader,i.PrimitiveShader.prototype.init=function(){var t=this.gl,e=i.compileProgram(t,this.vertexSrc,this.fragmentSrc);t.useProgram(e),this.projectionVector=t.getUniformLocation(e,"projectionVector"),this.offsetVector=t.getUniformLocation(e,"offsetVector"),this.tintColor=t.getUniformLocation(e,"tint"),this.flipY=t.getUniformLocation(e,"flipY"),this.aVertexPosition=t.getAttribLocation(e,"aVertexPosition"),this.colorAttribute=t.getAttribLocation(e,"aColor"),this.attributes=[this.aVertexPosition,this.colorAttribute],this.translationMatrix=t.getUniformLocation(e,"translationMatrix"),this.alpha=t.getUniformLocation(e,"alpha"),this.program=e},i.PrimitiveShader.prototype.destroy=function(){this.gl.deleteProgram(this.program),this.uniforms=null,this.gl=null,this.attributes=null},i.ComplexPrimitiveShader=function(t){this._UID=i._UID++,this.gl=t,this.program=null,this.fragmentSrc=["precision mediump float;","varying vec4 vColor;","void main(void) {"," gl_FragColor = vColor;","}"],this.vertexSrc=["attribute vec2 aVertexPosition;","uniform mat3 translationMatrix;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","uniform vec3 tint;","uniform float alpha;","uniform vec3 color;","uniform float flipY;","varying vec4 vColor;","void main(void) {"," vec3 v = translationMatrix * vec3(aVertexPosition , 1.0);"," v -= offsetVector.xyx;"," gl_Position = vec4( v.x / projectionVector.x -1.0, (v.y / projectionVector.y * -flipY) + flipY , 0.0, 1.0);"," vColor = vec4(color * alpha * tint, alpha);","}"],this.init()},i.ComplexPrimitiveShader.prototype.constructor=i.ComplexPrimitiveShader,i.ComplexPrimitiveShader.prototype.init=function(){var t=this.gl,e=i.compileProgram(t,this.vertexSrc,this.fragmentSrc);t.useProgram(e),this.projectionVector=t.getUniformLocation(e,"projectionVector"),this.offsetVector=t.getUniformLocation(e,"offsetVector"),this.tintColor=t.getUniformLocation(e,"tint"),this.color=t.getUniformLocation(e,"color"),this.flipY=t.getUniformLocation(e,"flipY"),this.aVertexPosition=t.getAttribLocation(e,"aVertexPosition"),this.attributes=[this.aVertexPosition,this.colorAttribute],this.translationMatrix=t.getUniformLocation(e,"translationMatrix"),this.alpha=t.getUniformLocation(e,"alpha"),this.program=e},i.ComplexPrimitiveShader.prototype.destroy=function(){this.gl.deleteProgram(this.program),this.uniforms=null,this.gl=null,this.attribute=null},i.glContexts=[],i.instances=[],i.WebGLRenderer=function(t){this.game=t,i.defaultRenderer||(i.defaultRenderer=this),this.type=i.WEBGL_RENDERER,this.resolution=t.resolution,this.transparent=t.transparent,this.autoResize=!1,this.preserveDrawingBuffer=t.preserveDrawingBuffer,this.clearBeforeRender=t.clearBeforeRender,this.width=t.width,this.height=t.height,this.view=t.canvas,this._contextOptions={alpha:this.transparent,antialias:t.antialias,premultipliedAlpha:this.transparent&&"notMultiplied"!==this.transparent,stencil:!0,preserveDrawingBuffer:this.preserveDrawingBuffer},this.projection=new i.Point,this.offset=new i.Point,this.shaderManager=new i.WebGLShaderManager,this.spriteBatch=new i.WebGLSpriteBatch,this.maskManager=new i.WebGLMaskManager,this.filterManager=new i.WebGLFilterManager,this.stencilManager=new i.WebGLStencilManager,this.blendModeManager=new i.WebGLBlendModeManager,this.renderSession={},this.renderSession.game=this.game,this.renderSession.gl=this.gl,this.renderSession.drawCount=0,this.renderSession.shaderManager=this.shaderManager,this.renderSession.maskManager=this.maskManager,this.renderSession.filterManager=this.filterManager,this.renderSession.blendModeManager=this.blendModeManager,this.renderSession.spriteBatch=this.spriteBatch,this.renderSession.stencilManager=this.stencilManager,this.renderSession.renderer=this,this.renderSession.resolution=this.resolution,this.initContext(),this.mapBlendModes()},i.WebGLRenderer.prototype.constructor=i.WebGLRenderer,i.WebGLRenderer.prototype.initContext=function(){var t=this.view.getContext("webgl",this._contextOptions)||this.view.getContext("experimental-webgl",this._contextOptions);if(this.gl=t,!t)throw new Error("This browser does not support webGL. Try using the canvas renderer");this.glContextId=t.id=i.WebGLRenderer.glContextId++,i.glContexts[this.glContextId]=t,i.instances[this.glContextId]=this,t.disable(t.DEPTH_TEST),t.disable(t.CULL_FACE),t.enable(t.BLEND),this.shaderManager.setContext(t),this.spriteBatch.setContext(t),this.maskManager.setContext(t),this.filterManager.setContext(t),this.blendModeManager.setContext(t),this.stencilManager.setContext(t),this.renderSession.gl=this.gl,this.resize(this.width,this.height)},i.WebGLRenderer.prototype.render=function(t){if(!this.contextLost){var e=this.gl;e.viewport(0,0,this.width,this.height),e.bindFramebuffer(e.FRAMEBUFFER,null),this.game.clearBeforeRender&&(e.clearColor(t._bgColor.r,t._bgColor.g,t._bgColor.b,t._bgColor.a),e.clear(e.COLOR_BUFFER_BIT)),this.offset.x=this.game.camera._shake.x,this.offset.y=this.game.camera._shake.y,this.renderDisplayObject(t,this.projection)}},i.WebGLRenderer.prototype.renderDisplayObject=function(t,e,s,n){this.renderSession.blendModeManager.setBlendMode(i.blendModes.NORMAL),this.renderSession.drawCount=0,this.renderSession.flipY=s?-1:1,this.renderSession.projection=e,this.renderSession.offset=this.offset,this.spriteBatch.begin(this.renderSession),this.filterManager.begin(this.renderSession,s),t._renderWebGL(this.renderSession,n),this.spriteBatch.end()},i.WebGLRenderer.prototype.resize=function(t,e){this.width=t*this.resolution,this.height=e*this.resolution,this.view.width=this.width,this.view.height=this.height,this.autoResize&&(this.view.style.width=this.width/this.resolution+"px",this.view.style.height=this.height/this.resolution+"px"),this.gl.viewport(0,0,this.width,this.height),this.projection.x=this.width/2/this.resolution,this.projection.y=-this.height/2/this.resolution},i.WebGLRenderer.prototype.updateTexture=function(t){if(!t.hasLoaded)return!1;var e=this.gl;return t._glTextures[e.id]||(t._glTextures[e.id]=e.createTexture()),e.bindTexture(e.TEXTURE_2D,t._glTextures[e.id]),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultipliedAlpha),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t.source),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t.scaleMode===i.scaleModes.LINEAR?e.LINEAR:e.NEAREST),t.mipmap&&i.isPowerOfTwo(t.width,t.height)?(e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t.scaleMode===i.scaleModes.LINEAR?e.LINEAR_MIPMAP_LINEAR:e.NEAREST_MIPMAP_NEAREST),e.generateMipmap(e.TEXTURE_2D)):e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t.scaleMode===i.scaleModes.LINEAR?e.LINEAR:e.NEAREST),t._powerOf2?(e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT)):(e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),t._dirty[e.id]=!1,!0},i.WebGLRenderer.prototype.destroy=function(){i.glContexts[this.glContextId]=null,this.projection=null,this.offset=null,this.shaderManager.destroy(),this.spriteBatch.destroy(),this.maskManager.destroy(),this.filterManager.destroy(),this.shaderManager=null,this.spriteBatch=null,this.maskManager=null,this.filterManager=null,this.gl=null,this.renderSession=null,i.CanvasPool.remove(this),i.instances[this.glContextId]=null,i.WebGLRenderer.glContextId--},i.WebGLRenderer.prototype.mapBlendModes=function(){var t=this.gl;if(!i.blendModesWebGL){var e=[],s=i.blendModes;e[s.NORMAL]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.ADD]=[t.SRC_ALPHA,t.DST_ALPHA],e[s.MULTIPLY]=[t.DST_COLOR,t.ONE_MINUS_SRC_ALPHA],e[s.SCREEN]=[t.SRC_ALPHA,t.ONE],e[s.OVERLAY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.DARKEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.LIGHTEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.COLOR_DODGE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.COLOR_BURN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.HARD_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.SOFT_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.DIFFERENCE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.EXCLUSION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.HUE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.SATURATION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.COLOR]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.LUMINOSITY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],i.blendModesWebGL=e}},i.WebGLRenderer.glContextId=0,i.WebGLBlendModeManager=function(){this.currentBlendMode=99999},i.WebGLBlendModeManager.prototype.constructor=i.WebGLBlendModeManager,i.WebGLBlendModeManager.prototype.setContext=function(t){this.gl=t},i.WebGLBlendModeManager.prototype.setBlendMode=function(t){if(this.currentBlendMode===t)return!1;this.currentBlendMode=t;var e=i.blendModesWebGL[this.currentBlendMode];return e&&this.gl.blendFunc(e[0],e[1]),!0},i.WebGLBlendModeManager.prototype.destroy=function(){this.gl=null},i.WebGLMaskManager=function(){},i.WebGLMaskManager.prototype.constructor=i.WebGLMaskManager,i.WebGLMaskManager.prototype.setContext=function(t){this.gl=t},i.WebGLMaskManager.prototype.pushMask=function(t,e){var s=e.gl;t.dirty&&i.WebGLGraphics.updateGraphics(t,s),void 0!==t._webGL[s.id]&&void 0!==t._webGL[s.id].data&&0!==t._webGL[s.id].data.length&&e.stencilManager.pushStencil(t,t._webGL[s.id].data[0],e)},i.WebGLMaskManager.prototype.popMask=function(t,e){var i=this.gl;void 0!==t._webGL[i.id]&&void 0!==t._webGL[i.id].data&&0!==t._webGL[i.id].data.length&&e.stencilManager.popStencil(t,t._webGL[i.id].data[0],e)},i.WebGLMaskManager.prototype.destroy=function(){this.gl=null},i.WebGLStencilManager=function(){this.stencilStack=[],this.reverse=!0,this.count=0},i.WebGLStencilManager.prototype.setContext=function(t){this.gl=t},i.WebGLStencilManager.prototype.pushStencil=function(t,e,i){var s=this.gl;this.bindGraphics(t,e,i),0===this.stencilStack.length&&(s.enable(s.STENCIL_TEST),s.clear(s.STENCIL_BUFFER_BIT),this.reverse=!0,this.count=0),this.stencilStack.push(e);var n=this.count;s.colorMask(!1,!1,!1,!1),s.stencilFunc(s.ALWAYS,0,255),s.stencilOp(s.KEEP,s.KEEP,s.INVERT),1===e.mode?(s.drawElements(s.TRIANGLE_FAN,e.indices.length-4,s.UNSIGNED_SHORT,0),this.reverse?(s.stencilFunc(s.EQUAL,255-n,255),s.stencilOp(s.KEEP,s.KEEP,s.DECR)):(s.stencilFunc(s.EQUAL,n,255),s.stencilOp(s.KEEP,s.KEEP,s.INCR)),s.drawElements(s.TRIANGLE_FAN,4,s.UNSIGNED_SHORT,2*(e.indices.length-4)),this.reverse?s.stencilFunc(s.EQUAL,255-(n+1),255):s.stencilFunc(s.EQUAL,n+1,255),this.reverse=!this.reverse):(this.reverse?(s.stencilFunc(s.EQUAL,n,255),s.stencilOp(s.KEEP,s.KEEP,s.INCR)):(s.stencilFunc(s.EQUAL,255-n,255),s.stencilOp(s.KEEP,s.KEEP,s.DECR)),s.drawElements(s.TRIANGLE_STRIP,e.indices.length,s.UNSIGNED_SHORT,0),this.reverse?s.stencilFunc(s.EQUAL,n+1,255):s.stencilFunc(s.EQUAL,255-(n+1),255)),s.colorMask(!0,!0,!0,!0),s.stencilOp(s.KEEP,s.KEEP,s.KEEP),this.count++},i.WebGLStencilManager.prototype.bindGraphics=function(t,e,s){this._currentGraphics=t;var n,r=this.gl,o=s.projection,a=s.offset;1===e.mode?(n=s.shaderManager.complexPrimitiveShader,s.shaderManager.setShader(n),r.uniform1f(n.flipY,s.flipY),r.uniformMatrix3fv(n.translationMatrix,!1,t.worldTransform.toArray(!0)),r.uniform2f(n.projectionVector,o.x,-o.y),r.uniform2f(n.offsetVector,-a.x,-a.y),r.uniform3fv(n.tintColor,i.hex2rgb(t.tint)),r.uniform3fv(n.color,e.color),r.uniform1f(n.alpha,t.worldAlpha*e.alpha),r.bindBuffer(r.ARRAY_BUFFER,e.buffer),r.vertexAttribPointer(n.aVertexPosition,2,r.FLOAT,!1,8,0),r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,e.indexBuffer)):(n=s.shaderManager.primitiveShader,s.shaderManager.setShader(n),r.uniformMatrix3fv(n.translationMatrix,!1,t.worldTransform.toArray(!0)),r.uniform1f(n.flipY,s.flipY),r.uniform2f(n.projectionVector,o.x,-o.y),r.uniform2f(n.offsetVector,-a.x,-a.y),r.uniform3fv(n.tintColor,i.hex2rgb(t.tint)),r.uniform1f(n.alpha,t.worldAlpha),r.bindBuffer(r.ARRAY_BUFFER,e.buffer),r.vertexAttribPointer(n.aVertexPosition,2,r.FLOAT,!1,24,0),r.vertexAttribPointer(n.colorAttribute,4,r.FLOAT,!1,24,8),r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,e.indexBuffer))},i.WebGLStencilManager.prototype.popStencil=function(t,e,i){var s=this.gl;if(this.stencilStack.pop(),this.count--,0===this.stencilStack.length)s.disable(s.STENCIL_TEST);else{var n=this.count;this.bindGraphics(t,e,i),s.colorMask(!1,!1,!1,!1),1===e.mode?(this.reverse=!this.reverse,this.reverse?(s.stencilFunc(s.EQUAL,255-(n+1),255),s.stencilOp(s.KEEP,s.KEEP,s.INCR)):(s.stencilFunc(s.EQUAL,n+1,255),s.stencilOp(s.KEEP,s.KEEP,s.DECR)),s.drawElements(s.TRIANGLE_FAN,4,s.UNSIGNED_SHORT,2*(e.indices.length-4)),s.stencilFunc(s.ALWAYS,0,255),s.stencilOp(s.KEEP,s.KEEP,s.INVERT),s.drawElements(s.TRIANGLE_FAN,e.indices.length-4,s.UNSIGNED_SHORT,0),this.reverse?s.stencilFunc(s.EQUAL,n,255):s.stencilFunc(s.EQUAL,255-n,255)):(this.reverse?(s.stencilFunc(s.EQUAL,n+1,255),s.stencilOp(s.KEEP,s.KEEP,s.DECR)):(s.stencilFunc(s.EQUAL,255-(n+1),255),s.stencilOp(s.KEEP,s.KEEP,s.INCR)),s.drawElements(s.TRIANGLE_STRIP,e.indices.length,s.UNSIGNED_SHORT,0),this.reverse?s.stencilFunc(s.EQUAL,n,255):s.stencilFunc(s.EQUAL,255-n,255)),s.colorMask(!0,!0,!0,!0),s.stencilOp(s.KEEP,s.KEEP,s.KEEP)}},i.WebGLStencilManager.prototype.destroy=function(){this.stencilStack=null,this.gl=null},i.WebGLShaderManager=function(){this.maxAttibs=10,this.attribState=[],this.tempAttribState=[];for(var t=0;t<this.maxAttibs;t++)this.attribState[t]=!1;this.stack=[]},i.WebGLShaderManager.prototype.constructor=i.WebGLShaderManager,i.WebGLShaderManager.prototype.setContext=function(t){this.gl=t,this.primitiveShader=new i.PrimitiveShader(t),this.complexPrimitiveShader=new i.ComplexPrimitiveShader(t),this.defaultShader=new i.PixiShader(t),this.fastShader=new i.PixiFastShader(t),this.stripShader=new i.StripShader(t),this.setShader(this.defaultShader)},i.WebGLShaderManager.prototype.setAttribs=function(t){var e;for(e=0;e<this.tempAttribState.length;e++)this.tempAttribState[e]=!1;for(e=0;e<t.length;e++){var i=t[e];this.tempAttribState[i]=!0}var s=this.gl;for(e=0;e<this.attribState.length;e++)this.attribState[e]!==this.tempAttribState[e]&&(this.attribState[e]=this.tempAttribState[e],this.tempAttribState[e]?s.enableVertexAttribArray(e):s.disableVertexAttribArray(e))},i.WebGLShaderManager.prototype.setShader=function(t){return this._currentId!==t._UID&&(this._currentId=t._UID,this.currentShader=t,this.gl.useProgram(t.program),this.setAttribs(t.attributes),!0)},i.WebGLShaderManager.prototype.destroy=function(){this.attribState=null,this.tempAttribState=null,this.primitiveShader.destroy(),this.complexPrimitiveShader.destroy(),this.defaultShader.destroy(),this.fastShader.destroy(),this.stripShader.destroy(),this.gl=null},i.WebGLSpriteBatch=function(){this.vertSize=5,this.size=2e3;var t=4*this.size*4*this.vertSize,e=6*this.size;this.vertices=new i.ArrayBuffer(t),this.positions=new i.Float32Array(this.vertices),this.colors=new i.Uint32Array(this.vertices),this.indices=new i.Uint16Array(e),this.lastIndexCount=0;for(var s=0,n=0;s<e;s+=6,n+=4)this.indices[s+0]=n+0,this.indices[s+1]=n+1,this.indices[s+2]=n+2,this.indices[s+3]=n+0,this.indices[s+4]=n+2,this.indices[s+5]=n+3;this.drawing=!1,this.currentBatchSize=0,this.currentBaseTexture=null,this.dirty=!0,this.textures=[],this.blendModes=[],this.shaders=[],this.sprites=[],this.defaultShader=new i.AbstractFilter(["precision lowp float;","varying vec2 vTextureCoord;","varying vec4 vColor;","uniform sampler2D uSampler;","void main(void) {"," gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;","}"])},i.WebGLSpriteBatch.prototype.setContext=function(t){this.gl=t,this.vertexBuffer=t.createBuffer(),this.indexBuffer=t.createBuffer(),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,this.indices,t.STATIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),t.bufferData(t.ARRAY_BUFFER,this.vertices,t.DYNAMIC_DRAW),this.currentBlendMode=99999;var e=new i.PixiShader(t);e.fragmentSrc=this.defaultShader.fragmentSrc,e.uniforms={},e.init(),this.defaultShader.shaders[t.id]=e},i.WebGLSpriteBatch.prototype.begin=function(t){this.renderSession=t,this.shader=this.renderSession.shaderManager.defaultShader,this.start()},i.WebGLSpriteBatch.prototype.end=function(){this.flush()},i.WebGLSpriteBatch.prototype.render=function(t,e){var i=t.texture,s=t.worldTransform;e&&(s=e),this.currentBatchSize>=this.size&&(this.flush(),this.currentBaseTexture=i.baseTexture);var n=i._uvs;if(n){var r,o,a,h,l=t.anchor.x,c=t.anchor.y;if(i.trim){var u=i.trim;o=u.x-l*u.width,r=o+i.crop.width,h=u.y-c*u.height,a=h+i.crop.height}else r=i.frame.width*(1-l),o=i.frame.width*-l,a=i.frame.height*(1-c),h=i.frame.height*-c;var d=4*this.currentBatchSize*this.vertSize,p=i.baseTexture.resolution,f=s.a/p,g=s.b/p,m=s.c/p,y=s.d/p,v=s.tx,b=s.ty,x=this.colors,w=this.positions;this.renderSession.roundPixels?(w[d]=f*o+m*h+v|0,w[d+1]=y*h+g*o+b|0,w[d+5]=f*r+m*h+v|0,w[d+6]=y*h+g*r+b|0,w[d+10]=f*r+m*a+v|0,w[d+11]=y*a+g*r+b|0,w[d+15]=f*o+m*a+v|0,w[d+16]=y*a+g*o+b|0):(w[d]=f*o+m*h+v,w[d+1]=y*h+g*o+b,w[d+5]=f*r+m*h+v,w[d+6]=y*h+g*r+b,w[d+10]=f*r+m*a+v,w[d+11]=y*a+g*r+b,w[d+15]=f*o+m*a+v,w[d+16]=y*a+g*o+b),w[d+2]=n.x0,w[d+3]=n.y0,w[d+7]=n.x1,w[d+8]=n.y1,w[d+12]=n.x2,w[d+13]=n.y2,w[d+17]=n.x3,w[d+18]=n.y3;var _=t.tint;x[d+4]=x[d+9]=x[d+14]=x[d+19]=(_>>16)+(65280&_)+((255&_)<<16)+(255*t.worldAlpha<<24),this.sprites[this.currentBatchSize++]=t}},i.WebGLSpriteBatch.prototype.renderTilingSprite=function(t){var e=t.tilingTexture;this.currentBatchSize>=this.size&&(this.flush(),this.currentBaseTexture=e.baseTexture),t._uvs||(t._uvs=new i.TextureUvs);var s=t._uvs,n=e.baseTexture.width,r=e.baseTexture.height;t.tilePosition.x%=n*t.tileScaleOffset.x,t.tilePosition.y%=r*t.tileScaleOffset.y;var o=t.tilePosition.x/(n*t.tileScaleOffset.x),a=t.tilePosition.y/(r*t.tileScaleOffset.y),h=t.width/n/(t.tileScale.x*t.tileScaleOffset.x),l=t.height/r/(t.tileScale.y*t.tileScaleOffset.y);s.x0=0-o,s.y0=0-a,s.x1=1*h-o,s.y1=0-a,s.x2=1*h-o,s.y2=1*l-a,s.x3=0-o,s.y3=1*l-a;var c=t.tint,u=(c>>16)+(65280&c)+((255&c)<<16)+(255*t.worldAlpha<<24),d=this.positions,p=this.colors,f=t.width,g=t.height,m=t.anchor.x,y=t.anchor.y,v=f*(1-m),b=f*-m,x=g*(1-y),w=g*-y,_=4*this.currentBatchSize*this.vertSize,P=e.baseTexture.resolution,T=t.worldTransform,C=T.a/P,S=T.b/P,A=T.c/P,E=T.d/P,I=T.tx,M=T.ty;d[_++]=C*b+A*w+I,d[_++]=E*w+S*b+M,d[_++]=s.x0,d[_++]=s.y0,p[_++]=u,d[_++]=C*v+A*w+I,d[_++]=E*w+S*v+M,d[_++]=s.x1,d[_++]=s.y1,p[_++]=u,d[_++]=C*v+A*x+I,d[_++]=E*x+S*v+M,d[_++]=s.x2,d[_++]=s.y2,p[_++]=u,d[_++]=C*b+A*x+I,d[_++]=E*x+S*b+M,d[_++]=s.x3,d[_++]=s.y3,p[_++]=u,this.sprites[this.currentBatchSize++]=t},i.WebGLSpriteBatch.prototype.flush=function(){if(0!==this.currentBatchSize){var t,e=this.gl;if(this.dirty){this.dirty=!1,e.activeTexture(e.TEXTURE0),e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer),t=this.defaultShader.shaders[e.id];var s=4*this.vertSize;e.vertexAttribPointer(t.aVertexPosition,2,e.FLOAT,!1,s,0),e.vertexAttribPointer(t.aTextureCoord,2,e.FLOAT,!1,s,8),e.vertexAttribPointer(t.colorAttribute,4,e.UNSIGNED_BYTE,!0,s,16)}if(this.currentBatchSize>.5*this.size)e.bufferSubData(e.ARRAY_BUFFER,0,this.vertices);else{var n=this.positions.subarray(0,4*this.currentBatchSize*this.vertSize);e.bufferSubData(e.ARRAY_BUFFER,0,n)}for(var r,o,a,h,l=0,c=0,u=null,d=this.renderSession.blendModeManager.currentBlendMode,p=null,f=!1,g=!1,m=0,y=this.currentBatchSize;m<y;m++){h=this.sprites[m],r=h.tilingTexture?h.tilingTexture.baseTexture:h.texture.baseTexture,o=h.blendMode,a=h.shader||this.defaultShader,f=d!==o,g=p!==a;var v=r.skipRender;if(v&&h.children.length>0&&(v=!1),(u!==r&&!v||f||g)&&(this.renderBatch(u,l,c),c=m,l=0,u=r,f&&(d=o,this.renderSession.blendModeManager.setBlendMode(d)),g)){p=a,t=p.shaders[e.id],t||(t=new i.PixiShader(e),t.fragmentSrc=p.fragmentSrc,t.uniforms=p.uniforms,t.init(),p.shaders[e.id]=t),this.renderSession.shaderManager.setShader(t),t.dirty&&t.syncUniforms();var b=this.renderSession.projection;e.uniform2f(t.projectionVector,b.x,b.y);var x=this.renderSession.offset;e.uniform2f(t.offsetVector,x.x,x.y)}l++}this.renderBatch(u,l,c),this.currentBatchSize=0}},i.WebGLSpriteBatch.prototype.renderBatch=function(t,e,i){if(0!==e){var s=this.gl;if(t._dirty[s.id]){if(!this.renderSession.renderer.updateTexture(t))return}else s.bindTexture(s.TEXTURE_2D,t._glTextures[s.id]);s.drawElements(s.TRIANGLES,6*e,s.UNSIGNED_SHORT,6*i*2),this.renderSession.drawCount++}},i.WebGLSpriteBatch.prototype.stop=function(){this.flush(),this.dirty=!0},i.WebGLSpriteBatch.prototype.start=function(){this.dirty=!0},i.WebGLSpriteBatch.prototype.destroy=function(){this.vertices=null,this.indices=null,this.gl.deleteBuffer(this.vertexBuffer),this.gl.deleteBuffer(this.indexBuffer),this.currentBaseTexture=null,this.gl=null},i.WebGLFastSpriteBatch=function(t){this.vertSize=10,this.maxSize=6e3,this.size=this.maxSize;var e=4*this.size*this.vertSize,s=6*this.maxSize;this.vertices=new i.Float32Array(e),this.indices=new i.Uint16Array(s),this.vertexBuffer=null,this.indexBuffer=null,this.lastIndexCount=0;for(var n=0,r=0;n<s;n+=6,r+=4)this.indices[n+0]=r+0,this.indices[n+1]=r+1,this.indices[n+2]=r+2,this.indices[n+3]=r+0,this.indices[n+4]=r+2,this.indices[n+5]=r+3;this.drawing=!1,this.currentBatchSize=0,this.currentBaseTexture=null,this.currentBlendMode=0,this.renderSession=null,this.shader=null,this.matrix=null,this.setContext(t)},i.WebGLFastSpriteBatch.prototype.constructor=i.WebGLFastSpriteBatch,i.WebGLFastSpriteBatch.prototype.setContext=function(t){this.gl=t,this.vertexBuffer=t.createBuffer(),this.indexBuffer=t.createBuffer(),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,this.indices,t.STATIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),t.bufferData(t.ARRAY_BUFFER,this.vertices,t.DYNAMIC_DRAW)},i.WebGLFastSpriteBatch.prototype.begin=function(t,e){this.renderSession=e,this.shader=this.renderSession.shaderManager.fastShader,this.matrix=t.worldTransform.toArray(!0),this.start()},i.WebGLFastSpriteBatch.prototype.end=function(){this.flush()},i.WebGLFastSpriteBatch.prototype.render=function(t){var e=t.children,i=e[0];if(i.texture._uvs){this.currentBaseTexture=i.texture.baseTexture,i.blendMode!==this.renderSession.blendModeManager.currentBlendMode&&(this.flush(),this.renderSession.blendModeManager.setBlendMode(i.blendMode));for(var s=0,n=e.length;s<n;s++)this.renderSprite(e[s]);this.flush()}},i.WebGLFastSpriteBatch.prototype.renderSprite=function(t){if(t.visible&&(t.texture.baseTexture===this.currentBaseTexture||t.texture.baseTexture.skipRender||(this.flush(),this.currentBaseTexture=t.texture.baseTexture,t.texture._uvs))){var e,i,s,n,r,o,a=this.vertices;if(e=t.texture._uvs,t.texture.frame.width,t.texture.frame.height,t.texture.trim){var h=t.texture.trim;s=h.x-t.anchor.x*h.width,i=s+t.texture.crop.width,r=h.y-t.anchor.y*h.height,n=r+t.texture.crop.height}else i=t.texture.frame.width*(1-t.anchor.x),s=t.texture.frame.width*-t.anchor.x,n=t.texture.frame.height*(1-t.anchor.y),r=t.texture.frame.height*-t.anchor.y;o=4*this.currentBatchSize*this.vertSize,a[o++]=s,a[o++]=r,a[o++]=t.position.x,a[o++]=t.position.y,a[o++]=t.scale.x,a[o++]=t.scale.y,a[o++]=t.rotation,a[o++]=e.x0,a[o++]=e.y1,a[o++]=t.alpha,a[o++]=i,a[o++]=r,a[o++]=t.position.x,a[o++]=t.position.y,a[o++]=t.scale.x,a[o++]=t.scale.y,a[o++]=t.rotation,a[o++]=e.x1,a[o++]=e.y1,a[o++]=t.alpha,a[o++]=i,a[o++]=n,a[o++]=t.position.x,a[o++]=t.position.y,a[o++]=t.scale.x,a[o++]=t.scale.y,a[o++]=t.rotation,a[o++]=e.x2,a[o++]=e.y2,a[o++]=t.alpha,a[o++]=s,a[o++]=n,a[o++]=t.position.x,a[o++]=t.position.y,a[o++]=t.scale.x,a[o++]=t.scale.y,a[o++]=t.rotation,a[o++]=e.x3,a[o++]=e.y3,a[o++]=t.alpha,this.currentBatchSize++,this.currentBatchSize>=this.size&&this.flush()}},i.WebGLFastSpriteBatch.prototype.flush=function(){if(0!==this.currentBatchSize){var t=this.gl;if(this.currentBaseTexture._glTextures[t.id]||this.renderSession.renderer.updateTexture(this.currentBaseTexture,t),t.bindTexture(t.TEXTURE_2D,this.currentBaseTexture._glTextures[t.id]),this.currentBatchSize>.5*this.size)t.bufferSubData(t.ARRAY_BUFFER,0,this.vertices);else{var e=this.vertices.subarray(0,4*this.currentBatchSize*this.vertSize);t.bufferSubData(t.ARRAY_BUFFER,0,e)}t.drawElements(t.TRIANGLES,6*this.currentBatchSize,t.UNSIGNED_SHORT,0),this.currentBatchSize=0,this.renderSession.drawCount++}},i.WebGLFastSpriteBatch.prototype.stop=function(){this.flush()},i.WebGLFastSpriteBatch.prototype.start=function(){var t=this.gl;t.activeTexture(t.TEXTURE0),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer);var e=this.renderSession.projection;t.uniform2f(this.shader.projectionVector,e.x,e.y),t.uniformMatrix3fv(this.shader.uMatrix,!1,this.matrix);var i=4*this.vertSize;t.vertexAttribPointer(this.shader.aVertexPosition,2,t.FLOAT,!1,i,0),t.vertexAttribPointer(this.shader.aPositionCoord,2,t.FLOAT,!1,i,8),t.vertexAttribPointer(this.shader.aScale,2,t.FLOAT,!1,i,16),t.vertexAttribPointer(this.shader.aRotation,1,t.FLOAT,!1,i,24),t.vertexAttribPointer(this.shader.aTextureCoord,2,t.FLOAT,!1,i,28),t.vertexAttribPointer(this.shader.colorAttribute,1,t.FLOAT,!1,i,36)},i.WebGLFilterManager=function(){this.filterStack=[],this.offsetX=0,this.offsetY=0},i.WebGLFilterManager.prototype.constructor=i.WebGLFilterManager,i.WebGLFilterManager.prototype.setContext=function(t){this.gl=t,this.texturePool=[],this.initShaderBuffers()},i.WebGLFilterManager.prototype.begin=function(t,e){this.renderSession=t,this.defaultShader=t.shaderManager.defaultShader;var i=this.renderSession.projection;this.width=2*i.x,this.height=2*-i.y,this.buffer=e},i.WebGLFilterManager.prototype.pushFilter=function(t){var e=this.gl,s=this.renderSession.projection,n=this.renderSession.offset;t._filterArea=t.target.filterArea||t.target.getBounds(),t._previous_stencil_mgr=this.renderSession.stencilManager,this.renderSession.stencilManager=new i.WebGLStencilManager,this.renderSession.stencilManager.setContext(e),e.disable(e.STENCIL_TEST),this.filterStack.push(t);var r=t.filterPasses[0];this.offsetX+=t._filterArea.x,this.offsetY+=t._filterArea.y;var o=this.texturePool.pop();o?o.resize(this.width*this.renderSession.resolution,this.height*this.renderSession.resolution):o=new i.FilterTexture(this.gl,this.width*this.renderSession.resolution,this.height*this.renderSession.resolution),e.bindTexture(e.TEXTURE_2D,o.texture);var a=t._filterArea,h=r.padding;a.x-=h,a.y-=h,a.width+=2*h,a.height+=2*h,a.x<0&&(a.x=0),a.width>this.width&&(a.width=this.width),a.y<0&&(a.y=0),a.height>this.height&&(a.height=this.height),e.bindFramebuffer(e.FRAMEBUFFER,o.frameBuffer),e.viewport(0,0,a.width*this.renderSession.resolution,a.height*this.renderSession.resolution),s.x=a.width/2,s.y=-a.height/2,n.x=-a.x,n.y=-a.y,e.colorMask(!0,!0,!0,!0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT),t._glFilterTexture=o},i.WebGLFilterManager.prototype.popFilter=function(){var t=this.gl,e=this.filterStack.pop(),s=e._filterArea,n=e._glFilterTexture,r=this.renderSession.projection,o=this.renderSession.offset;if(e.filterPasses.length>1){t.viewport(0,0,s.width*this.renderSession.resolution,s.height*this.renderSession.resolution),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),this.vertexArray[0]=0,this.vertexArray[1]=s.height,this.vertexArray[2]=s.width,this.vertexArray[3]=s.height,this.vertexArray[4]=0,this.vertexArray[5]=0,this.vertexArray[6]=s.width,this.vertexArray[7]=0,t.bufferSubData(t.ARRAY_BUFFER,0,this.vertexArray),t.bindBuffer(t.ARRAY_BUFFER,this.uvBuffer),this.uvArray[2]=s.width/this.width,this.uvArray[5]=s.height/this.height,this.uvArray[6]=s.width/this.width,this.uvArray[7]=s.height/this.height,t.bufferSubData(t.ARRAY_BUFFER,0,this.uvArray);var a=n,h=this.texturePool.pop();h||(h=new i.FilterTexture(this.gl,this.width*this.renderSession.resolution,this.height*this.renderSession.resolution)),h.resize(this.width*this.renderSession.resolution,this.height*this.renderSession.resolution),t.bindFramebuffer(t.FRAMEBUFFER,h.frameBuffer),t.clear(t.COLOR_BUFFER_BIT),t.disable(t.BLEND);for(var l=0;l<e.filterPasses.length-1;l++){var c=e.filterPasses[l];t.bindFramebuffer(t.FRAMEBUFFER,h.frameBuffer),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,a.texture),this.applyFilterPass(c,s,s.width,s.height);var u=a;a=h,h=u}t.enable(t.BLEND),n=a,this.texturePool.push(h)}var d=e.filterPasses[e.filterPasses.length-1];this.offsetX-=s.x,this.offsetY-=s.y;var p=this.width,f=this.height,g=0,m=0,y=this.buffer;if(0===this.filterStack.length)t.colorMask(!0,!0,!0,!0);else{var v=this.filterStack[this.filterStack.length-1];s=v._filterArea,p=s.width,f=s.height,g=s.x,m=s.y,y=v._glFilterTexture.frameBuffer}r.x=p/2,r.y=-f/2,o.x=g,o.y=m,s=e._filterArea;var b=s.x-g,x=s.y-m;t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),this.vertexArray[0]=b,this.vertexArray[1]=x+s.height,this.vertexArray[2]=b+s.width,this.vertexArray[3]=x+s.height,this.vertexArray[4]=b,this.vertexArray[5]=x,this.vertexArray[6]=b+s.width,this.vertexArray[7]=x,t.bufferSubData(t.ARRAY_BUFFER,0,this.vertexArray),t.bindBuffer(t.ARRAY_BUFFER,this.uvBuffer),this.uvArray[2]=s.width/this.width,this.uvArray[5]=s.height/this.height,this.uvArray[6]=s.width/this.width,this.uvArray[7]=s.height/this.height,t.bufferSubData(t.ARRAY_BUFFER,0,this.uvArray),t.viewport(0,0,p*this.renderSession.resolution,f*this.renderSession.resolution),t.bindFramebuffer(t.FRAMEBUFFER,y),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,n.texture),this.renderSession.stencilManager&&this.renderSession.stencilManager.destroy(),this.renderSession.stencilManager=e._previous_stencil_mgr,e._previous_stencil_mgr=null,this.renderSession.stencilManager.count>0?t.enable(t.STENCIL_TEST):t.disable(t.STENCIL_TEST),this.applyFilterPass(d,s,p,f),this.texturePool.push(n),e._glFilterTexture=null},i.WebGLFilterManager.prototype.applyFilterPass=function(t,e,s,n){var r=this.gl,o=t.shaders[r.id];o||(o=new i.PixiShader(r),o.fragmentSrc=t.fragmentSrc,o.uniforms=t.uniforms,o.init(),t.shaders[r.id]=o),this.renderSession.shaderManager.setShader(o),r.uniform2f(o.projectionVector,s/2,-n/2),r.uniform2f(o.offsetVector,0,0),t.uniforms.dimensions&&(t.uniforms.dimensions.value[0]=this.width,t.uniforms.dimensions.value[1]=this.height,t.uniforms.dimensions.value[2]=this.vertexArray[0],t.uniforms.dimensions.value[3]=this.vertexArray[5]),o.syncUniforms(),r.bindBuffer(r.ARRAY_BUFFER,this.vertexBuffer),r.vertexAttribPointer(o.aVertexPosition,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ARRAY_BUFFER,this.uvBuffer),r.vertexAttribPointer(o.aTextureCoord,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ARRAY_BUFFER,this.colorBuffer),r.vertexAttribPointer(o.colorAttribute,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,this.indexBuffer),r.drawElements(r.TRIANGLES,6,r.UNSIGNED_SHORT,0),this.renderSession.drawCount++},i.WebGLFilterManager.prototype.initShaderBuffers=function(){var t=this.gl;this.vertexBuffer=t.createBuffer(),this.uvBuffer=t.createBuffer(),this.colorBuffer=t.createBuffer(),this.indexBuffer=t.createBuffer(),this.vertexArray=new i.Float32Array([0,0,1,0,0,1,1,1]),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),t.bufferData(t.ARRAY_BUFFER,this.vertexArray,t.STATIC_DRAW),this.uvArray=new i.Float32Array([0,0,1,0,0,1,1,1]),t.bindBuffer(t.ARRAY_BUFFER,this.uvBuffer),t.bufferData(t.ARRAY_BUFFER,this.uvArray,t.STATIC_DRAW),this.colorArray=new i.Float32Array([1,16777215,1,16777215,1,16777215,1,16777215]),t.bindBuffer(t.ARRAY_BUFFER,this.colorBuffer),t.bufferData(t.ARRAY_BUFFER,this.colorArray,t.STATIC_DRAW),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,new Uint16Array([0,1,2,1,3,2]),t.STATIC_DRAW)},i.WebGLFilterManager.prototype.destroy=function(){var t=this.gl;this.filterStack=null,this.offsetX=0,this.offsetY=0;for(var e=0;e<this.texturePool.length;e++)this.texturePool[e].destroy();this.texturePool=null,t.deleteBuffer(this.vertexBuffer),t.deleteBuffer(this.uvBuffer),t.deleteBuffer(this.colorBuffer),t.deleteBuffer(this.indexBuffer)},i.FilterTexture=function(t,e,s,n){this.gl=t,this.frameBuffer=t.createFramebuffer(),this.texture=t.createTexture(),n=n||i.scaleModes.DEFAULT,t.bindTexture(t.TEXTURE_2D,this.texture),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,n===i.scaleModes.LINEAR?t.LINEAR:t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,n===i.scaleModes.LINEAR?t.LINEAR:t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.bindFramebuffer(t.FRAMEBUFFER,this.frameBuffer),t.bindFramebuffer(t.FRAMEBUFFER,this.frameBuffer),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,this.texture,0),this.renderBuffer=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,this.renderBuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,this.renderBuffer),this.resize(e,s)},i.FilterTexture.prototype.constructor=i.FilterTexture,i.FilterTexture.prototype.clear=function(){var t=this.gl;t.clearColor(0,0,0,0),t.clear(t.COLOR_BUFFER_BIT)},i.FilterTexture.prototype.resize=function(t,e){if(this.width!==t||this.height!==e){this.width=t,this.height=e;var i=this.gl;i.bindTexture(i.TEXTURE_2D,this.texture),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,t,e,0,i.RGBA,i.UNSIGNED_BYTE,null),i.bindRenderbuffer(i.RENDERBUFFER,this.renderBuffer),i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH_STENCIL,t,e)}},i.FilterTexture.prototype.destroy=function(){var t=this.gl;t.deleteFramebuffer(this.frameBuffer),t.deleteTexture(this.texture),this.frameBuffer=null,this.texture=null},i.CanvasBuffer=function(t,e){this.width=t,this.height=e,this.canvas=i.CanvasPool.create(this,this.width,this.height),this.context=this.canvas.getContext("2d"),this.canvas.width=t,this.canvas.height=e},i.CanvasBuffer.prototype.constructor=i.CanvasBuffer,i.CanvasBuffer.prototype.clear=function(){this.context.setTransform(1,0,0,1,0,0),this.context.clearRect(0,0,this.width,this.height)},i.CanvasBuffer.prototype.resize=function(t,e){this.width=this.canvas.width=t,this.height=this.canvas.height=e},i.CanvasBuffer.prototype.destroy=function(){i.CanvasPool.remove(this)},i.CanvasMaskManager=function(){},i.CanvasMaskManager.prototype.constructor=i.CanvasMaskManager,i.CanvasMaskManager.prototype.pushMask=function(t,e){var s=e.context;s.save();var n=t.alpha,r=t.worldTransform,o=e.resolution;s.setTransform(r.a*o,r.b*o,r.c*o,r.d*o,r.tx*o,r.ty*o),i.CanvasGraphics.renderGraphicsMask(t,s),s.clip(),t.worldAlpha=n},i.CanvasMaskManager.prototype.popMask=function(t){t.context.restore()},i.CanvasTinter=function(){},i.CanvasTinter.getTintedTexture=function(t,e){var s=t.tintedTexture||i.CanvasPool.create(this);return i.CanvasTinter.tintMethod(t.texture,e,s),s},i.CanvasTinter.tintWithMultiply=function(t,e,i){var s=i.getContext("2d"),n=t.crop;i.width===n.width&&i.height===n.height||(i.width=n.width,i.height=n.height),s.clearRect(0,0,n.width,n.height),s.fillStyle="#"+("00000"+(0|e).toString(16)).substr(-6),s.fillRect(0,0,n.width,n.height),s.globalCompositeOperation="multiply",s.drawImage(t.baseTexture.source,n.x,n.y,n.width,n.height,0,0,n.width,n.height),s.globalCompositeOperation="destination-atop",s.drawImage(t.baseTexture.source,n.x,n.y,n.width,n.height,0,0,n.width,n.height)},i.CanvasTinter.tintWithPerPixel=function(t,e,s){var n=s.getContext("2d"),r=t.crop;s.width=r.width,s.height=r.height,n.globalCompositeOperation="copy",n.drawImage(t.baseTexture.source,r.x,r.y,r.width,r.height,0,0,r.width,r.height);for(var o=i.hex2rgb(e),a=o[0],h=o[1],l=o[2],c=n.getImageData(0,0,r.width,r.height),u=c.data,d=0;d<u.length;d+=4)if(u[d+0]*=a,u[d+1]*=h,u[d+2]*=l,!i.CanvasTinter.canHandleAlpha){var p=u[d+3];u[d+0]/=255/p,u[d+1]/=255/p,u[d+2]/=255/p}n.putImageData(c,0,0)},i.CanvasTinter.checkInverseAlpha=function(){var t=new i.CanvasBuffer(2,1);t.context.fillStyle="rgba(10, 20, 30, 0.5)",t.context.fillRect(0,0,1,1);var e=t.context.getImageData(0,0,1,1);if(null===e)return!1;t.context.putImageData(e,1,0);var s=t.context.getImageData(1,0,1,1);return s.data[0]===e.data[0]&&s.data[1]===e.data[1]&&s.data[2]===e.data[2]&&s.data[3]===e.data[3]},i.CanvasTinter.canHandleAlpha=i.CanvasTinter.checkInverseAlpha(),i.CanvasTinter.canUseMultiply=i.canUseNewCanvasBlendModes(),i.CanvasTinter.tintMethod=i.CanvasTinter.canUseMultiply?i.CanvasTinter.tintWithMultiply:i.CanvasTinter.tintWithPerPixel,i.CanvasRenderer=function(t){this.game=t,i.defaultRenderer||(i.defaultRenderer=this),this.type=i.CANVAS_RENDERER,this.resolution=t.resolution,this.clearBeforeRender=t.clearBeforeRender,this.transparent=t.transparent,this.autoResize=!1,this.width=t.width*this.resolution,this.height=t.height*this.resolution,this.view=t.canvas,this.context=this.view.getContext("2d",{alpha:this.transparent}),this.refresh=!0,this.count=0,this.maskManager=new i.CanvasMaskManager,this.renderSession={context:this.context,maskManager:this.maskManager,scaleMode:null,smoothProperty:Phaser.Canvas.getSmoothingPrefix(this.context),roundPixels:!1},this.mapBlendModes(),this.resize(this.width,this.height)},i.CanvasRenderer.prototype.constructor=i.CanvasRenderer,i.CanvasRenderer.prototype.render=function(t){this.context.setTransform(1,0,0,1,0,0),this.context.globalAlpha=1,this.renderSession.currentBlendMode=0,this.renderSession.shakeX=this.game.camera._shake.x,this.renderSession.shakeY=this.game.camera._shake.y,this.context.globalCompositeOperation="source-over",navigator.isCocoonJS&&this.view.screencanvas&&(this.context.fillStyle="black",this.context.clear()),this.clearBeforeRender&&(this.transparent?this.context.clearRect(0,0,this.width,this.height):t._bgColor&&(this.context.fillStyle=t._bgColor.rgba,this.context.fillRect(0,0,this.width,this.height))),this.renderDisplayObject(t)},i.CanvasRenderer.prototype.destroy=function(t){void 0===t&&(t=!0),t&&this.view.parent&&this.view.parent.removeChild(this.view),this.view=null,this.context=null,this.maskManager=null,this.renderSession=null},i.CanvasRenderer.prototype.resize=function(t,e){this.width=t*this.resolution,this.height=e*this.resolution,this.view.width=this.width,this.view.height=this.height,this.autoResize&&(this.view.style.width=this.width/this.resolution+"px",this.view.style.height=this.height/this.resolution+"px"),this.renderSession.smoothProperty&&(this.context[this.renderSession.smoothProperty]=this.renderSession.scaleMode===i.scaleModes.LINEAR)},i.CanvasRenderer.prototype.renderDisplayObject=function(t,e,i){this.renderSession.context=e||this.context,this.renderSession.resolution=this.resolution,t._renderCanvas(this.renderSession,i)},i.CanvasRenderer.prototype.mapBlendModes=function(){if(!i.blendModesCanvas){var t=[],e=i.blendModes,s=i.canUseNewCanvasBlendModes();t[e.NORMAL]="source-over",t[e.ADD]="lighter",t[e.MULTIPLY]=s?"multiply":"source-over",t[e.SCREEN]=s?"screen":"source-over",t[e.OVERLAY]=s?"overlay":"source-over",t[e.DARKEN]=s?"darken":"source-over",t[e.LIGHTEN]=s?"lighten":"source-over",t[e.COLOR_DODGE]=s?"color-dodge":"source-over",t[e.COLOR_BURN]=s?"color-burn":"source-over",t[e.HARD_LIGHT]=s?"hard-light":"source-over",t[e.SOFT_LIGHT]=s?"soft-light":"source-over",t[e.DIFFERENCE]=s?"difference":"source-over",t[e.EXCLUSION]=s?"exclusion":"source-over",t[e.HUE]=s?"hue":"source-over",t[e.SATURATION]=s?"saturation":"source-over",t[e.COLOR]=s?"color":"source-over",t[e.LUMINOSITY]=s?"luminosity":"source-over",i.blendModesCanvas=t}},i.BaseTexture=function(t,e){this.resolution=1,this.width=100,this.height=100,this.scaleMode=e||i.scaleModes.DEFAULT,this.hasLoaded=!1,this.source=t,this.premultipliedAlpha=!0,this._glTextures=[],this.mipmap=!1,this._dirty=[!0,!0,!0,!0],t&&((this.source.complete||this.source.getContext)&&this.source.width&&this.source.height&&(this.hasLoaded=!0,this.width=this.source.naturalWidth||this.source.width,this.height=this.source.naturalHeight||this.source.height,this.dirty()),this.skipRender=!1,this._powerOf2=!1)},i.BaseTexture.prototype.constructor=i.BaseTexture,i.BaseTexture.prototype.forceLoaded=function(t,e){this.hasLoaded=!0,this.width=t,this.height=e,this.dirty()},i.BaseTexture.prototype.destroy=function(){this.source&&i.CanvasPool.removeByCanvas(this.source),this.source=null,this.unloadFromGPU()},i.BaseTexture.prototype.updateSourceImage=function(t){console.warn("PIXI.BaseTexture.updateSourceImage is deprecated. Use Phaser.Sprite.loadTexture instead.")},i.BaseTexture.prototype.dirty=function(){for(var t=0;t<this._glTextures.length;t++)this._dirty[t]=!0},i.BaseTexture.prototype.unloadFromGPU=function(){this.dirty();for(var t=this._glTextures.length-1;t>=0;t--){var e=this._glTextures[t],s=i.glContexts[t];s&&e&&s.deleteTexture(e)}this._glTextures.length=0,this.dirty()},i.BaseTexture.fromCanvas=function(t,e){return 0===t.width&&(t.width=1),0===t.height&&(t.height=1),new i.BaseTexture(t,e)},i.TextureSilentFail=!1,i.Texture=function(t,e,s,n){this.noFrame=!1,e||(this.noFrame=!0,e=new i.Rectangle(0,0,1,1)),t instanceof i.Texture&&(t=t.baseTexture),this.baseTexture=t,this.frame=e,this.trim=n,this.valid=!1,this.isTiling=!1,this.requiresUpdate=!1,this.requiresReTint=!1,this._uvs=null,this.width=0,this.height=0,this.crop=s||new i.Rectangle(0,0,1,1),t.hasLoaded&&(this.noFrame&&(e=new i.Rectangle(0,0,t.width,t.height)),this.setFrame(e))},i.Texture.prototype.constructor=i.Texture,i.Texture.prototype.onBaseTextureLoaded=function(){var t=this.baseTexture;this.noFrame&&(this.frame=new i.Rectangle(0,0,t.width,t.height)),this.setFrame(this.frame)},i.Texture.prototype.destroy=function(t){t&&this.baseTexture.destroy(),this.valid=!1},i.Texture.prototype.setFrame=function(t){if(this.noFrame=!1,this.frame=t,this.width=t.width,this.height=t.height,this.crop.x=t.x,this.crop.y=t.y,this.crop.width=t.width,this.crop.height=t.height,!this.trim&&(t.x+t.width>this.baseTexture.width||t.y+t.height>this.baseTexture.height)){if(!i.TextureSilentFail)throw new Error("Texture Error: frame does not fit inside the base Texture dimensions "+this);return void(this.valid=!1)}this.valid=t&&t.width&&t.height&&this.baseTexture.source&&this.baseTexture.hasLoaded,this.trim&&(this.width=this.trim.width,this.height=this.trim.height,this.frame.width=this.trim.width,this.frame.height=this.trim.height),this.valid&&this._updateUvs()},i.Texture.prototype._updateUvs=function(){this._uvs||(this._uvs=new i.TextureUvs);var t=this.crop,e=this.baseTexture.width,s=this.baseTexture.height;this._uvs.x0=t.x/e,this._uvs.y0=t.y/s,this._uvs.x1=(t.x+t.width)/e,this._uvs.y1=t.y/s,this._uvs.x2=(t.x+t.width)/e,this._uvs.y2=(t.y+t.height)/s,this._uvs.x3=t.x/e,this._uvs.y3=(t.y+t.height)/s},i.Texture.fromCanvas=function(t,e){var s=i.BaseTexture.fromCanvas(t,e);return new i.Texture(s)},i.TextureUvs=function(){this.x0=0,this.y0=0,this.x1=0,this.y1=0,this.x2=0,this.y2=0,this.x3=0,this.y3=0},i.RenderTexture=function(t,e,s,n,r){if(this.width=t||100,this.height=e||100,this.resolution=r||1,this.frame=new i.Rectangle(0,0,this.width*this.resolution,this.height*this.resolution),this.crop=new i.Rectangle(0,0,this.width*this.resolution,this.height*this.resolution),this.baseTexture=new i.BaseTexture,this.baseTexture.width=this.width*this.resolution,this.baseTexture.height=this.height*this.resolution,this.baseTexture._glTextures=[],this.baseTexture.resolution=this.resolution,this.baseTexture.scaleMode=n||i.scaleModes.DEFAULT,this.baseTexture.hasLoaded=!0,i.Texture.call(this,this.baseTexture,new i.Rectangle(0,0,this.width*this.resolution,this.height*this.resolution)),this.renderer=s||i.defaultRenderer,this.renderer.type===i.WEBGL_RENDERER){var o=this.renderer.gl;this.baseTexture._dirty[o.id]=!1,this.textureBuffer=new i.FilterTexture(o,this.width,this.height,this.baseTexture.scaleMode),this.baseTexture._glTextures[o.id]=this.textureBuffer.texture,this.render=this.renderWebGL,this.projection=new i.Point(.5*this.width,.5*-this.height)}else this.render=this.renderCanvas,this.textureBuffer=new i.CanvasBuffer(this.width*this.resolution,this.height*this.resolution),this.baseTexture.source=this.textureBuffer.canvas;this.valid=!0,this.tempMatrix=new Phaser.Matrix,this._updateUvs()},i.RenderTexture.prototype=Object.create(i.Texture.prototype),i.RenderTexture.prototype.constructor=i.RenderTexture,i.RenderTexture.prototype.resize=function(t,e,s){t===this.width&&e===this.height||(this.valid=t>0&&e>0,this.width=t,this.height=e,this.frame.width=this.crop.width=t*this.resolution,this.frame.height=this.crop.height=e*this.resolution,s&&(this.baseTexture.width=this.width*this.resolution,this.baseTexture.height=this.height*this.resolution),this.renderer.type===i.WEBGL_RENDERER&&(this.projection.x=this.width/2,this.projection.y=-this.height/2),this.valid&&this.textureBuffer.resize(this.width,this.height))},i.RenderTexture.prototype.clear=function(){this.valid&&(this.renderer.type===i.WEBGL_RENDERER&&this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER,this.textureBuffer.frameBuffer),this.textureBuffer.clear())},i.RenderTexture.prototype.renderWebGL=function(t,e,i){if(this.valid&&0!==t.alpha){var s=t.worldTransform;s.identity(),s.translate(0,2*this.projection.y),e&&s.append(e),s.scale(1,-1);for(var n=0;n<t.children.length;n++)t.children[n].updateTransform();var r=this.renderer.gl;r.viewport(0,0,this.width*this.resolution,this.height*this.resolution),r.bindFramebuffer(r.FRAMEBUFFER,this.textureBuffer.frameBuffer),i&&this.textureBuffer.clear(),this.renderer.spriteBatch.dirty=!0,this.renderer.renderDisplayObject(t,this.projection,this.textureBuffer.frameBuffer,e),this.renderer.spriteBatch.dirty=!0}},i.RenderTexture.prototype.renderCanvas=function(t,e,i){if(this.valid&&0!==t.alpha){var s=t.worldTransform;s.identity(),e&&s.append(e);for(var n=0;n<t.children.length;n++)t.children[n].updateTransform();i&&this.textureBuffer.clear();var r=this.renderer.resolution;this.renderer.resolution=this.resolution,this.renderer.renderDisplayObject(t,this.textureBuffer.context,e),this.renderer.resolution=r}},i.RenderTexture.prototype.getImage=function(){var t=new Image;return t.src=this.getBase64(),t},i.RenderTexture.prototype.getBase64=function(){return this.getCanvas().toDataURL()},i.RenderTexture.prototype.getCanvas=function(){if(this.renderer.type===i.WEBGL_RENDERER){var t=this.renderer.gl,e=this.textureBuffer.width,s=this.textureBuffer.height,n=new Uint8Array(4*e*s);t.bindFramebuffer(t.FRAMEBUFFER,this.textureBuffer.frameBuffer),t.readPixels(0,0,e,s,t.RGBA,t.UNSIGNED_BYTE,n),t.bindFramebuffer(t.FRAMEBUFFER,null);var r=new i.CanvasBuffer(e,s),o=r.context.getImageData(0,0,e,s);return o.data.set(n),r.context.putImageData(o,0,0),r.canvas}return this.textureBuffer.canvas},i.AbstractFilter=function(t,e){this.passes=[this],this.shaders=[],this.dirty=!0,this.padding=0,this.uniforms=e||{},this.fragmentSrc=t||[]},i.AbstractFilter.prototype.constructor=i.AbstractFilter,i.AbstractFilter.prototype.syncUniforms=function(){for(var t=0,e=this.shaders.length;t<e;t++)this.shaders[t].dirty=!0},i.Strip=function(t){i.DisplayObjectContainer.call(this),this.texture=t,this.uvs=new i.Float32Array([0,1,1,1,1,0,0,1]),this.vertices=new i.Float32Array([0,0,100,0,100,100,0,100]),this.colors=new i.Float32Array([1,1,1,1]),this.indices=new i.Uint16Array([0,1,2,3]),this.dirty=!0,this.blendMode=i.blendModes.NORMAL,this.canvasPadding=0,this.drawMode=i.Strip.DrawModes.TRIANGLE_STRIP},i.Strip.prototype=Object.create(i.DisplayObjectContainer.prototype),i.Strip.prototype.constructor=i.Strip,i.Strip.prototype._renderWebGL=function(t){!this.visible||this.alpha<=0||(t.spriteBatch.stop(),this._vertexBuffer||this._initWebGL(t),t.shaderManager.setShader(t.shaderManager.stripShader),this._renderStrip(t),t.spriteBatch.start())},i.Strip.prototype._initWebGL=function(t){var e=t.gl;this._vertexBuffer=e.createBuffer(),this._indexBuffer=e.createBuffer(),this._uvBuffer=e.createBuffer(),this._colorBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this._vertexBuffer),e.bufferData(e.ARRAY_BUFFER,this.vertices,e.DYNAMIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,this._uvBuffer),e.bufferData(e.ARRAY_BUFFER,this.uvs,e.STATIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,this._colorBuffer),e.bufferData(e.ARRAY_BUFFER,this.colors,e.STATIC_DRAW),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this._indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,this.indices,e.STATIC_DRAW)},i.Strip.prototype._renderStrip=function(t){var e=t.gl,s=t.projection,n=t.offset,r=t.shaderManager.stripShader,o=this.drawMode===i.Strip.DrawModes.TRIANGLE_STRIP?e.TRIANGLE_STRIP:e.TRIANGLES;t.blendModeManager.setBlendMode(this.blendMode),e.uniformMatrix3fv(r.translationMatrix,!1,this.worldTransform.toArray(!0)),e.uniform2f(r.projectionVector,s.x,-s.y),e.uniform2f(r.offsetVector,-n.x,-n.y),e.uniform1f(r.alpha,this.worldAlpha),this.dirty?(this.dirty=!1,e.bindBuffer(e.ARRAY_BUFFER,this._vertexBuffer),e.bufferData(e.ARRAY_BUFFER,this.vertices,e.STATIC_DRAW),e.vertexAttribPointer(r.aVertexPosition,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this._uvBuffer),e.bufferData(e.ARRAY_BUFFER,this.uvs,e.STATIC_DRAW),e.vertexAttribPointer(r.aTextureCoord,2,e.FLOAT,!1,0,0),e.activeTexture(e.TEXTURE0),this.texture.baseTexture._dirty[e.id]?t.renderer.updateTexture(this.texture.baseTexture):e.bindTexture(e.TEXTURE_2D,this.texture.baseTexture._glTextures[e.id]),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this._indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,this.indices,e.STATIC_DRAW)):(e.bindBuffer(e.ARRAY_BUFFER,this._vertexBuffer),e.bufferSubData(e.ARRAY_BUFFER,0,this.vertices),e.vertexAttribPointer(r.aVertexPosition,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this._uvBuffer),e.vertexAttribPointer(r.aTextureCoord,2,e.FLOAT,!1,0,0),e.activeTexture(e.TEXTURE0),this.texture.baseTexture._dirty[e.id]?t.renderer.updateTexture(this.texture.baseTexture):e.bindTexture(e.TEXTURE_2D,this.texture.baseTexture._glTextures[e.id]),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this._indexBuffer)),e.drawElements(o,this.indices.length,e.UNSIGNED_SHORT,0)},i.Strip.prototype._renderCanvas=function(t){var e=t.context,s=this.worldTransform,n=s.tx*t.resolution+t.shakeX,r=s.ty*t.resolution+t.shakeY;t.roundPixels?e.setTransform(s.a,s.b,s.c,s.d,0|n,0|r):e.setTransform(s.a,s.b,s.c,s.d,n,r),this.drawMode===i.Strip.DrawModes.TRIANGLE_STRIP?this._renderCanvasTriangleStrip(e):this._renderCanvasTriangles(e)},i.Strip.prototype._renderCanvasTriangleStrip=function(t){var e=this.vertices,i=this.uvs,s=e.length/2;this.count++;for(var n=0;n<s-2;n++){var r=2*n;this._renderCanvasDrawTriangle(t,e,i,r,r+2,r+4)}},i.Strip.prototype._renderCanvasTriangles=function(t){var e=this.vertices,i=this.uvs,s=this.indices,n=s.length;this.count++;for(var r=0;r<n;r+=3){var o=2*s[r],a=2*s[r+1],h=2*s[r+2];this._renderCanvasDrawTriangle(t,e,i,o,a,h)}},i.Strip.prototype._renderCanvasDrawTriangle=function(t,e,i,s,n,r){var o=this.texture.baseTexture.source,a=this.texture.width,h=this.texture.height,l=e[s],c=e[n],u=e[r],d=e[s+1],p=e[n+1],f=e[r+1],g=i[s]*a,m=i[n]*a,y=i[r]*a,v=i[s+1]*h,b=i[n+1]*h,x=i[r+1]*h;if(this.canvasPadding>0){var w=this.canvasPadding/this.worldTransform.a,_=this.canvasPadding/this.worldTransform.d,P=(l+c+u)/3,T=(d+p+f)/3,C=l-P,S=d-T,A=Math.sqrt(C*C+S*S);l=P+C/A*(A+w),d=T+S/A*(A+_),C=c-P,S=p-T,A=Math.sqrt(C*C+S*S),c=P+C/A*(A+w),p=T+S/A*(A+_),C=u-P,S=f-T,A=Math.sqrt(C*C+S*S),u=P+C/A*(A+w),f=T+S/A*(A+_)}t.save(),t.beginPath(),t.moveTo(l,d),t.lineTo(c,p),t.lineTo(u,f),t.closePath(),t.clip();var E=g*b+v*y+m*x-b*y-v*m-g*x,I=l*b+v*u+c*x-b*u-v*c-l*x,M=g*c+l*y+m*u-c*y-l*m-g*u,R=g*b*u+v*c*y+l*m*x-l*b*y-v*m*u-g*c*x,B=d*b+v*f+p*x-b*f-v*p-d*x,L=g*p+d*y+m*f-p*y-d*m-g*f,O=g*b*f+v*p*y+d*m*x-d*b*y-v*m*f-g*p*x;t.transform(I/E,B/E,M/E,L/E,R/E,O/E),t.drawImage(o,0,0),t.restore()},i.Strip.prototype.renderStripFlat=function(t){var e=this.context,i=t.vertices,s=i.length/2;this.count++,e.beginPath();for(var n=1;n<s-2;n++){var r=2*n,o=i[r],a=i[r+2],h=i[r+4],l=i[r+1],c=i[r+3],u=i[r+5];e.moveTo(o,l),e.lineTo(a,c),e.lineTo(h,u)}e.fillStyle="#FF0000",e.fill(),e.closePath()},i.Strip.prototype.onTextureUpdate=function(){this.updateFrame=!0},i.Strip.prototype.getBounds=function(t){for(var e=t||this.worldTransform,s=e.a,n=e.b,r=e.c,o=e.d,a=e.tx,h=e.ty,l=-1/0,c=-1/0,u=1/0,d=1/0,p=this.vertices,f=0,g=p.length;f<g;f+=2){var m=p[f],y=p[f+1],v=s*m+r*y+a,b=o*y+n*m+h;u=v<u?v:u,d=b<d?b:d,l=v>l?v:l,c=b>c?b:c}if(u===-1/0||c===1/0)return i.EmptyRectangle;var x=this._bounds;return x.x=u,x.width=l-u,x.y=d,x.height=c-d,this._currentBounds=x,x},i.Strip.DrawModes={TRIANGLE_STRIP:0,TRIANGLES:1},i.Rope=function(t,e){i.Strip.call(this,t),this.points=e,this.vertices=new i.Float32Array(4*e.length),this.uvs=new i.Float32Array(4*e.length),this.colors=new i.Float32Array(2*e.length),this.indices=new i.Uint16Array(2*e.length),this.refresh()},i.Rope.prototype=Object.create(i.Strip.prototype),i.Rope.prototype.constructor=i.Rope,i.Rope.prototype.refresh=function(){var t=this.points;if(!(t.length<1)){var e=this.uvs,i=(t[0],this.indices),s=this.colors;this.count-=.2,e[0]=0,e[1]=0,e[2]=0,e[3]=1,s[0]=1,s[1]=1,i[0]=0,i[1]=1;for(var n,r,o,a=t.length,h=1;h<a;h++)n=t[h],r=4*h,o=h/(a-1),e[r]=o,e[r+1]=0,e[r+2]=o,e[r+3]=1,r=2*h,s[r]=1,s[r+1]=1,r=2*h,i[r]=r,i[r+1]=r+1,n}},i.Rope.prototype.updateTransform=function(){var t=this.points;if(!(t.length<1)){var e,s=t[0],n={x:0,y:0};this.count-=.2;for(var r,o,a,h,l,c=this.vertices,u=t.length,d=0;d<u;d++)r=t[d],o=4*d,e=d<t.length-1?t[d+1]:r,n.y=-(e.x-s.x),n.x=e.y-s.y,a=10*(1-d/(u-1)),a>1&&(a=1),h=Math.sqrt(n.x*n.x+n.y*n.y),l=this.texture.height/2,n.x/=h,n.y/=h,n.x*=l,n.y*=l,c[o]=r.x+n.x,c[o+1]=r.y+n.y,c[o+2]=r.x-n.x,c[o+3]=r.y-n.y,s=r;i.DisplayObjectContainer.prototype.updateTransform.call(this)}},i.Rope.prototype.setTexture=function(t){this.texture=t},i.TilingSprite=function(t,e,s){i.Sprite.call(this,t),this._width=e||128,this._height=s||128,this.tileScale=new i.Point(1,1),this.tileScaleOffset=new i.Point(1,1),this.tilePosition=new i.Point,this.renderable=!0,this.tint=16777215,this.textureDebug=!1,this.blendMode=i.blendModes.NORMAL,this.canvasBuffer=null,this.tilingTexture=null,this.tilePattern=null,this.refreshTexture=!0,this.frameWidth=0,this.frameHeight=0},i.TilingSprite.prototype=Object.create(i.Sprite.prototype),i.TilingSprite.prototype.constructor=i.TilingSprite,i.TilingSprite.prototype.setTexture=function(t){this.texture!==t&&(this.texture=t,this.refreshTexture=!0,this.cachedTint=16777215)},i.TilingSprite.prototype._renderWebGL=function(t){if(this.visible&&this.renderable&&0!==this.alpha){if(this._mask&&(t.spriteBatch.stop(),t.maskManager.pushMask(this.mask,t),t.spriteBatch.start()),this._filters&&(t.spriteBatch.flush(),t.filterManager.pushFilter(this._filterBlock)),this.refreshTexture){if(this.generateTilingTexture(!0,t),!this.tilingTexture)return;this.tilingTexture.needsUpdate&&(t.renderer.updateTexture(this.tilingTexture.baseTexture),this.tilingTexture.needsUpdate=!1)}t.spriteBatch.renderTilingSprite(this);for(var e=0;e<this.children.length;e++)this.children[e]._renderWebGL(t);t.spriteBatch.stop(),this._filters&&t.filterManager.popFilter(),this._mask&&t.maskManager.popMask(this._mask,t),t.spriteBatch.start()}},i.TilingSprite.prototype._renderCanvas=function(t){if(this.visible&&this.renderable&&0!==this.alpha){var e=t.context;this._mask&&t.maskManager.pushMask(this._mask,t),e.globalAlpha=this.worldAlpha;var s=this.worldTransform,n=t.resolution,r=s.tx*n+t.shakeX,o=s.ty*n+t.shakeY;if(e.setTransform(s.a*n,s.b*n,s.c*n,s.d*n,r,o),this.refreshTexture){if(this.generateTilingTexture(!1,t),!this.tilingTexture)return;this.tilePattern=e.createPattern(this.tilingTexture.baseTexture.source,"repeat")}var a=t.currentBlendMode;this.blendMode!==t.currentBlendMode&&(t.currentBlendMode=this.blendMode,e.globalCompositeOperation=i.blendModesCanvas[t.currentBlendMode]);var h=this.tilePosition,l=this.tileScale;h.x%=this.tilingTexture.baseTexture.width,h.y%=this.tilingTexture.baseTexture.height,e.scale(l.x,l.y),e.translate(h.x+this.anchor.x*-this._width,h.y+this.anchor.y*-this._height),e.fillStyle=this.tilePattern;var r=-h.x,o=-h.y,c=this._width/l.x,u=this._height/l.y;t.roundPixels&&(r|=0,o|=0,c|=0,u|=0),e.fillRect(r,o,c,u),e.scale(1/l.x,1/l.y),e.translate(-h.x+this.anchor.x*this._width,-h.y+this.anchor.y*this._height),this._mask&&t.maskManager.popMask(t);for(var d=0;d<this.children.length;d++)this.children[d]._renderCanvas(t);a!==this.blendMode&&(t.currentBlendMode=a,e.globalCompositeOperation=i.blendModesCanvas[a])}},i.TilingSprite.prototype.onTextureUpdate=function(){},i.TilingSprite.prototype.generateTilingTexture=function(t,e){if(this.texture.baseTexture.hasLoaded){var s=this.texture,n=s.frame,r=this._frame.sourceSizeW||this._frame.width,o=this._frame.sourceSizeH||this._frame.height,a=0,h=0;this._frame.trimmed&&(a=this._frame.spriteSourceSizeX,h=this._frame.spriteSourceSizeY),t&&(r=i.getNextPowerOfTwo(r),o=i.getNextPowerOfTwo(o)),this.canvasBuffer?(this.canvasBuffer.resize(r,o),this.tilingTexture.baseTexture.width=r,this.tilingTexture.baseTexture.height=o,this.tilingTexture.needsUpdate=!0):(this.canvasBuffer=new i.CanvasBuffer(r,o),this.tilingTexture=i.Texture.fromCanvas(this.canvasBuffer.canvas),this.tilingTexture.isTiling=!0,this.tilingTexture.needsUpdate=!0),this.textureDebug&&(this.canvasBuffer.context.strokeStyle="#00ff00",this.canvasBuffer.context.strokeRect(0,0,r,o));var l=s.crop.width,c=s.crop.height;l===r&&c===o||(l=r,c=o),this.canvasBuffer.context.drawImage(s.baseTexture.source,s.crop.x,s.crop.y,s.crop.width,s.crop.height,a,h,l,c),this.tileScaleOffset.x=n.width/r,this.tileScaleOffset.y=n.height/o,this.refreshTexture=!1,this.tilingTexture.baseTexture._powerOf2=!0}},i.TilingSprite.prototype.getBounds=function(){var t=this._width,e=this._height,i=t*(1-this.anchor.x),s=t*-this.anchor.x,n=e*(1-this.anchor.y),r=e*-this.anchor.y,o=this.worldTransform,a=o.a,h=o.b,l=o.c,c=o.d,u=o.tx,d=o.ty,p=a*s+l*r+u,f=c*r+h*s+d,g=a*i+l*r+u,m=c*r+h*i+d,y=a*i+l*n+u,v=c*n+h*i+d,b=a*s+l*n+u,x=c*n+h*s+d,w=-1/0,_=-1/0,P=1/0,T=1/0;P=p<P?p:P,P=g<P?g:P,P=y<P?y:P,P=b<P?b:P,T=f<T?f:T,T=m<T?m:T,T=v<T?v:T,T=x<T?x:T,w=p>w?p:w,w=g>w?g:w,w=y>w?y:w,w=b>w?b:w,_=f>_?f:_,_=m>_?m:_,_=v>_?v:_,_=x>_?x:_;var C=this._bounds;return C.x=P,C.width=w-P,C.y=T,C.height=_-T,this._currentBounds=C,C},i.TilingSprite.prototype.destroy=function(){i.Sprite.prototype.destroy.call(this),this.canvasBuffer&&(this.canvasBuffer.destroy(),this.canvasBuffer=null),this.tileScale=null,this.tileScaleOffset=null,this.tilePosition=null,this.tilingTexture&&(this.tilingTexture.destroy(!0),this.tilingTexture=null)},Object.defineProperty(i.TilingSprite.prototype,"width",{get:function(){return this._width},set:function(t){this._width=t}}),Object.defineProperty(i.TilingSprite.prototype,"height",{get:function(){return this._height},set:function(t){this._height=t}}),void 0!==t&&t.exports&&(e=t.exports=i),e.PIXI=i,i}).call(this)},,,,,,,,,,function(t,e,i){t.exports=i(33)}],[102]); | heroku push
| public/game.js | heroku push | <ide><path>ublic/game.js
<del>webpackJsonp([1],[,function(t,e,i){"use strict";(function(e){function s(t){return"[object Array]"===T.call(t)}function n(t){return void 0!==e&&e.isBuffer&&e.isBuffer(t)}function r(t){return"[object ArrayBuffer]"===T.call(t)}function o(t){return"undefined"!=typeof FormData&&t instanceof FormData}function a(t){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer&&t.buffer instanceof ArrayBuffer}function h(t){return"string"==typeof t}function l(t){return"number"==typeof t}function c(t){return void 0===t}function u(t){return null!==t&&"object"==typeof t}function d(t){return"[object Date]"===T.call(t)}function p(t){return"[object File]"===T.call(t)}function f(t){return"[object Blob]"===T.call(t)}function g(t){return"[object Function]"===T.call(t)}function m(t){return u(t)&&g(t.pipe)}function y(t){return"undefined"!=typeof URLSearchParams&&t instanceof URLSearchParams}function v(t){return t.replace(/^\s*/,"").replace(/\s*$/,"")}function b(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product)&&("undefined"!=typeof window&&"undefined"!=typeof document)}function x(t,e){if(null!==t&&void 0!==t)if("object"==typeof t||s(t)||(t=[t]),s(t))for(var i=0,n=t.length;i<n;i++)e.call(null,t[i],i,t);else for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.call(null,t[r],r,t)}function w(){function t(t,i){"object"==typeof e[i]&&"object"==typeof t?e[i]=w(e[i],t):e[i]=t}for(var e={},i=0,s=arguments.length;i<s;i++)x(arguments[i],t);return e}function _(t,e,i){return x(e,function(e,s){t[s]=i&&"function"==typeof e?P(e,i):e}),t}var P=i(18),T=Object.prototype.toString;t.exports={isArray:s,isArrayBuffer:r,isBuffer:n,isFormData:o,isArrayBufferView:a,isString:h,isNumber:l,isObject:u,isUndefined:c,isDate:d,isFile:p,isBlob:f,isFunction:g,isStream:m,isURLSearchParams:y,isStandardBrowserEnv:b,forEach:x,merge:w,extend:_,trim:v}}).call(e,i(65).Buffer)},,,,function(t,e,i){"use strict";i.d(e,"b",function(){return s}),i.d(e,"a",function(){return r}),i.d(e,"c",function(){return o});var s={BLACK:"#060304",DARKBLUE:"#001440",TEAL:"#427a8b",GREEN:"#39bb8f",YELLOWGREEN:"#e2fda7"},n=function(){var t=!1;return function(e){(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4)))&&(t=!0)}(navigator.userAgent||navigator.vendor||window.opera),t},r={SCREENWIDTH:window.innerWidth*window.devicePixelRatio,SCREENHEIGHT:window.innerHeight*window.devicePixelRatio,SCALERATIO:function(){var t=window.innerWidth/window.innerHeight,e=void 0;return e=t>1?window.innerHeight*window.devicePixelRatio/2048:window.innerWidth*window.devicePixelRatio/2048,n()&&(e+=1),e}(),BRICKSIZE:120},o=n()},,,,function(t,e,i){"use strict";(function(e){function s(t,e){!n.isUndefined(t)&&n.isUndefined(t["Content-Type"])&&(t["Content-Type"]=e)}var n=i(1),r=i(52),o={"Content-Type":"application/x-www-form-urlencoded"},a={adapter:function(){var t;return"undefined"!=typeof XMLHttpRequest?t=i(14):void 0!==e&&(t=i(14)),t}(),transformRequest:[function(t,e){return r(e,"Content-Type"),n.isFormData(t)||n.isArrayBuffer(t)||n.isBuffer(t)||n.isStream(t)||n.isFile(t)||n.isBlob(t)?t:n.isArrayBufferView(t)?t.buffer:n.isURLSearchParams(t)?(s(e,"application/x-www-form-urlencoded;charset=utf-8"),t.toString()):n.isObject(t)?(s(e,"application/json;charset=utf-8"),JSON.stringify(t)):t}],transformResponse:[function(t){if("string"==typeof t)try{t=JSON.parse(t)}catch(t){}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,validateStatus:function(t){return t>=200&&t<300}};a.headers={common:{Accept:"application/json, text/plain, */*"}},n.forEach(["delete","get","head"],function(t){a.headers[t]={}}),n.forEach(["post","put","patch"],function(t){a.headers[t]=n.merge(o)}),t.exports=a}).call(e,i(4))},,,,,function(t,e,i){"use strict";var s=i(1),n=i(44),r=i(47),o=i(53),a=i(51),h=i(17),l="undefined"!=typeof window&&window.btoa&&window.btoa.bind(window)||i(46);t.exports=function(t){return new Promise(function(e,c){var u=t.data,d=t.headers;s.isFormData(u)&&delete d["Content-Type"];var p=new XMLHttpRequest,f="onreadystatechange",g=!1;if("undefined"==typeof window||!window.XDomainRequest||"withCredentials"in p||a(t.url)||(p=new window.XDomainRequest,f="onload",g=!0,p.onprogress=function(){},p.ontimeout=function(){}),t.auth){var m=t.auth.username||"",y=t.auth.password||"";d.Authorization="Basic "+l(m+":"+y)}if(p.open(t.method.toUpperCase(),r(t.url,t.params,t.paramsSerializer),!0),p.timeout=t.timeout,p[f]=function(){if(p&&(4===p.readyState||g)&&(0!==p.status||p.responseURL&&0===p.responseURL.indexOf("file:"))){var i="getAllResponseHeaders"in p?o(p.getAllResponseHeaders()):null,s=t.responseType&&"text"!==t.responseType?p.response:p.responseText,r={data:s,status:1223===p.status?204:p.status,statusText:1223===p.status?"No Content":p.statusText,headers:i,config:t,request:p};n(e,c,r),p=null}},p.onerror=function(){c(h("Network Error",t)),p=null},p.ontimeout=function(){c(h("timeout of "+t.timeout+"ms exceeded",t,"ECONNABORTED")),p=null},s.isStandardBrowserEnv()){var v=i(49),b=(t.withCredentials||a(t.url))&&t.xsrfCookieName?v.read(t.xsrfCookieName):void 0;b&&(d[t.xsrfHeaderName]=b)}if("setRequestHeader"in p&&s.forEach(d,function(t,e){void 0===u&&"content-type"===e.toLowerCase()?delete d[e]:p.setRequestHeader(e,t)}),t.withCredentials&&(p.withCredentials=!0),t.responseType)try{p.responseType=t.responseType}catch(e){if("json"!==t.responseType)throw e}"function"==typeof t.onDownloadProgress&&p.addEventListener("progress",t.onDownloadProgress),"function"==typeof t.onUploadProgress&&p.upload&&p.upload.addEventListener("progress",t.onUploadProgress),t.cancelToken&&t.cancelToken.promise.then(function(t){p&&(p.abort(),c(t),p=null)}),void 0===u&&(u=null),p.send(u)})}},function(t,e,i){"use strict";function s(t){this.message=t}s.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},s.prototype.__CANCEL__=!0,t.exports=s},function(t,e,i){"use strict";t.exports=function(t){return!(!t||!t.__CANCEL__)}},function(t,e,i){"use strict";var s=i(43);t.exports=function(t,e,i,n){var r=new Error(t);return s(r,e,i,n)}},function(t,e,i){"use strict";t.exports=function(t,e){return function(){for(var i=new Array(arguments.length),s=0;s<i.length;s++)i[s]=arguments[s];return t.apply(e,i)}}},function(t,e,i){"use strict";function s(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var n=function(){function t(t,e){for(var i=0;i<e.length;i++){var s=e[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(t,s.key,s)}}return function(e,i,s){return i&&t(e.prototype,i),s&&t(e,s),e}}(),r=function(){function t(e,i,n,r,o){s(this,t),this.game=e,this.scale=i||1,this.color=o,this.x=n,this.y=r,this.sprite=this.game.add.sprite(this.x,this.y,"bricks",this.color),this.sprite.inputEnabled=!0,this.sprite.scale.setTo(this.scale),this.emitter=this.game.add.emitter(0,0,6),this.emitter.makeParticles("bricks",this.color),this.emitter.minParticleScale=this.scale,this.emitter.maxParticleScale=this.scale,this.emitter.gravity=2e3*this.scale}return n(t,[{key:"tweenTo",value:function(t,e){this.game.add.tween(this.sprite).to({x:t,y:e},400,"Bounce",!0)}},{key:"addClickEvent",value:function(t,e){this.sprite.events.onInputDown.add(t,e)}},{key:"enableClickEvents",value:function(){this.sprite.inputEnabled=!0}},{key:"disableClickEvents",value:function(){this.sprite.inputEnabled=!1}},{key:"changePosition",value:function(t){var e=t.x,i=t.y;this.isEmpty()?(this.game.world.sendToBack(this.sprite),this.sprite.x=e||this.sprite.x,this.sprite.y=i||this.sprite.y):this.tweenTo(e,i),this.x=e,this.y=i}},{key:"runDestroyAnim",value:function(){this.game.world.bringToTop(this.emitter),this.emitter.x=this.x+this.sprite.width/2,this.emitter.y=this.y+this.sprite.width/2,this.emitter.start(!1,1e3,1,1)}},{key:"destroy",value:function(){this.runDestroyAnim(),this.sprite.destroy()}},{key:"isEmpty",value:function(){return 7===this.color}}]),t}();e.a=r},,,,,,,,,,,,,,function(t,e,i){"use strict";function s(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function r(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}Object.defineProperty(e,"__esModule",{value:!0});var o=i(79),a=(i.n(o),i(81)),h=(i.n(a),i(80)),l=i.n(h),c=i(60),u=i(5),d=u.a.SCREENWIDTH,p=u.a.SCREENHEIGHT;new(function(t){function e(t,i,r){s(this,e);var o=n(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t,i,r));return o.state.add("Preload",c.a,!1),o.state.add("Main",c.b,!1),o.state.start("Preload"),o}return r(e,t),e}(l.a.Game))(d,p,l.a.CANVAS)},,,,function(t,e,i){t.exports=i(38)},function(t,e,i){"use strict";function s(t){var e=new o(t),i=r(o.prototype.request,e);return n.extend(i,o.prototype,e),n.extend(i,e),i}var n=i(1),r=i(18),o=i(40),a=i(9),h=s(a);h.Axios=o,h.create=function(t){return s(n.merge(a,t))},h.Cancel=i(15),h.CancelToken=i(39),h.isCancel=i(16),h.all=function(t){return Promise.all(t)},h.spread=i(54),t.exports=h,t.exports.default=h},function(t,e,i){"use strict";function s(t){if("function"!=typeof t)throw new TypeError("executor must be a function.");var e;this.promise=new Promise(function(t){e=t});var i=this;t(function(t){i.reason||(i.reason=new n(t),e(i.reason))})}var n=i(15);s.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},s.source=function(){var t;return{token:new s(function(e){t=e}),cancel:t}},t.exports=s},function(t,e,i){"use strict";function s(t){this.defaults=t,this.interceptors={request:new o,response:new o}}var n=i(9),r=i(1),o=i(41),a=i(42),h=i(50),l=i(48);s.prototype.request=function(t){"string"==typeof t&&(t=r.merge({url:arguments[0]},arguments[1])),t=r.merge(n,this.defaults,{method:"get"},t),t.baseURL&&!h(t.url)&&(t.url=l(t.baseURL,t.url));var e=[a,void 0],i=Promise.resolve(t);for(this.interceptors.request.forEach(function(t){e.unshift(t.fulfilled,t.rejected)}),this.interceptors.response.forEach(function(t){e.push(t.fulfilled,t.rejected)});e.length;)i=i.then(e.shift(),e.shift());return i},r.forEach(["delete","get","head","options"],function(t){s.prototype[t]=function(e,i){return this.request(r.merge(i||{},{method:t,url:e}))}}),r.forEach(["post","put","patch"],function(t){s.prototype[t]=function(e,i,s){return this.request(r.merge(s||{},{method:t,url:e,data:i}))}}),t.exports=s},function(t,e,i){"use strict";function s(){this.handlers=[]}var n=i(1);s.prototype.use=function(t,e){return this.handlers.push({fulfilled:t,rejected:e}),this.handlers.length-1},s.prototype.eject=function(t){this.handlers[t]&&(this.handlers[t]=null)},s.prototype.forEach=function(t){n.forEach(this.handlers,function(e){null!==e&&t(e)})},t.exports=s},function(t,e,i){"use strict";function s(t){t.cancelToken&&t.cancelToken.throwIfRequested()}var n=i(1),r=i(45),o=i(16),a=i(9);t.exports=function(t){return s(t),t.headers=t.headers||{},t.data=r(t.data,t.headers,t.transformRequest),t.headers=n.merge(t.headers.common||{},t.headers[t.method]||{},t.headers||{}),n.forEach(["delete","get","head","post","put","patch","common"],function(e){delete t.headers[e]}),(t.adapter||a.adapter)(t).then(function(e){return s(t),e.data=r(e.data,e.headers,t.transformResponse),e},function(e){return o(e)||(s(t),e&&e.response&&(e.response.data=r(e.response.data,e.response.headers,t.transformResponse))),Promise.reject(e)})}},function(t,e,i){"use strict";t.exports=function(t,e,i,s){return t.config=e,i&&(t.code=i),t.response=s,t}},function(t,e,i){"use strict";var s=i(17);t.exports=function(t,e,i){var n=i.config.validateStatus;i.status&&n&&!n(i.status)?e(s("Request failed with status code "+i.status,i.config,null,i)):t(i)}},function(t,e,i){"use strict";var s=i(1);t.exports=function(t,e,i){return s.forEach(i,function(i){t=i(t,e)}),t}},function(t,e,i){"use strict";function s(){this.message="String contains an invalid character"}function n(t){for(var e,i,n=String(t),o="",a=0,h=r;n.charAt(0|a)||(h="=",a%1);o+=h.charAt(63&e>>8-a%1*8)){if((i=n.charCodeAt(a+=.75))>255)throw new s;e=e<<8|i}return o}var r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";s.prototype=new Error,s.prototype.code=5,s.prototype.name="InvalidCharacterError",t.exports=n},function(t,e,i){"use strict";function s(t){return encodeURIComponent(t).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var n=i(1);t.exports=function(t,e,i){if(!e)return t;var r;if(i)r=i(e);else if(n.isURLSearchParams(e))r=e.toString();else{var o=[];n.forEach(e,function(t,e){null!==t&&void 0!==t&&(n.isArray(t)&&(e+="[]"),n.isArray(t)||(t=[t]),n.forEach(t,function(t){n.isDate(t)?t=t.toISOString():n.isObject(t)&&(t=JSON.stringify(t)),o.push(s(e)+"="+s(t))}))}),r=o.join("&")}return r&&(t+=(-1===t.indexOf("?")?"?":"&")+r),t}},function(t,e,i){"use strict";t.exports=function(t,e){return e?t.replace(/\/+$/,"")+"/"+e.replace(/^\/+/,""):t}},function(t,e,i){"use strict";var s=i(1);t.exports=s.isStandardBrowserEnv()?function(){return{write:function(t,e,i,n,r,o){var a=[];a.push(t+"="+encodeURIComponent(e)),s.isNumber(i)&&a.push("expires="+new Date(i).toGMTString()),s.isString(n)&&a.push("path="+n),s.isString(r)&&a.push("domain="+r),!0===o&&a.push("secure"),document.cookie=a.join("; ")},read:function(t){var e=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove:function(t){this.write(t,"",Date.now()-864e5)}}}():function(){return{write:function(){},read:function(){return null},remove:function(){}}}()},function(t,e,i){"use strict";t.exports=function(t){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(t)}},function(t,e,i){"use strict";var s=i(1);t.exports=s.isStandardBrowserEnv()?function(){function t(t){var e=t;return i&&(n.setAttribute("href",e),e=n.href),n.setAttribute("href",e),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:"/"===n.pathname.charAt(0)?n.pathname:"/"+n.pathname}}var e,i=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");return e=t(window.location.href),function(i){var n=s.isString(i)?t(i):i;return n.protocol===e.protocol&&n.host===e.host}}():function(){return function(){return!0}}()},function(t,e,i){"use strict";var s=i(1);t.exports=function(t,e){s.forEach(t,function(i,s){s!==e&&s.toUpperCase()===e.toUpperCase()&&(t[e]=i,delete t[s])})}},function(t,e,i){"use strict";var s=i(1);t.exports=function(t){var e,i,n,r={};return t?(s.forEach(t.split("\n"),function(t){n=t.indexOf(":"),e=s.trim(t.substr(0,n)).toLowerCase(),i=s.trim(t.substr(n+1)),e&&(r[e]=r[e]?r[e]+", "+i:i)}),r):r}},function(t,e,i){"use strict";t.exports=function(t){return function(e){return t.apply(null,e)}}},function(t,e,i){"use strict";function s(t){function e(i,s,n){var r=n||[];return 0==s||t.boardRows[s][i].isEmpty()||(r.push(t.boardRows[s][i]),e(i,s-1,r)),r}var i=t.getBrickLocation(this),s=i.x,n=(i.y,e(s,t.boardRows.length-1)),r=n.length;t.deleteGroup(n),t.addScore(r)}function n(t){for(var e=t.getBrickLocation(this),i=(e.x,e.y),s=[],n=0;n<t.boardRows[i].length;n++)t.boardRows[i][n].isEmpty()||s.push(t.boardRows[i][n]);var r=s.length;t.deleteGroup(s),t.addScore(r)}function r(t){var e=t.getBrickLocation(this),i=e.x,s=e.y,n=[];n.push(t.boardRows[s][i]),i!==t.boardRows[s].length-1&&n.push(t.boardRows[s][i+1]),i!==t.boardRows[s].length-1&&s!==t.boardRows.length-1&&n.push(t.boardRows[s+1][i+1]),i!==t.boardRows[s].length-1&&0!==s&&n.push(t.boardRows[s-1][i+1]),0!==i&&n.push(t.boardRows[s][i-1]),0!==i&&0!==s&&n.push(t.boardRows[s-1][i-1]),0!==i&&s!==t.boardRows.length-1&&n.push(t.boardRows[s+1][i-1]),0!==s&&n.push(t.boardRows[s-1][i]),s!==t.boardRows.length-1&&n.push(t.boardRows[s+1][i]);for(var r=n.length-1;r>0;r--)n[r].isEmpty()&&n.splice(r,1);var o=n.length;t.deleteGroup(n),t.addScore(o)}function o(t){return a[t]}e.a=o;var a={8:s,9:n,10:r}},function(t,e,i){"use strict";function s(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var n=i(19),r=i(57),o=i(5),a=i(37),h=i.n(a),l=function(){function t(t,e){for(var i=0;i<e.length;i++){var s=e[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(t,s.key,s)}}return function(e,i,s){return i&&t(e.prototype,i),s&&t(e,s),e}}(),c=o.a.BRICKSIZE,u=function(){function t(e,i,n,r){s(this,t),this.game=e,this.boardRows=[],this.brickSize=c,this.brickScale=i,this.brickOffset=this.brickSize*this.brickScale,this.boardWidth=8*this.brickOffset,this.boardHeight=12*this.brickOffset,this.boardOffsetW=this.boardWidth/2,this.boardOffsetH=this.boardHeight/2,this.posX=n-this.boardOffsetW,this.posY=r-this.boardOffsetH,this.moves=0,this.numOfColors=5,this.playerScore=0,this.destroyBrickSound=this.game.add.audio("brickDestroy"),this.destroyBrickSound.volume=1.5,this.gameMusic=this.game.add.audio("gameMusic"),this.gameMusic.loop=!0,this.gameMusic.volume=.5,o.c||(this.background=this.makeBackground(),this.background.start(!1,5e3,250,0)),this.scoreBoard=this.game.add.text(this.posX,this.posY-100*this.brickScale,"Score: "+this.playerScore,{fill:"#fff",fontSize:60*this.brickScale}),this.settings={},this.settings.music=!0,this.settings.sound=!0,this.settingsIcon=this.game.add.sprite(this.boardWidth+this.posX-90*this.brickScale,this.posY-90*this.brickScale,"settingsIcon"),this.settingsIcon.width=75*this.brickScale,this.settingsIcon.height=75*this.brickScale,this.settingsIcon.inputEnabled=!0,this.settingsIcon.events.onInputDown.add(this.openSettingsModal,this),this.createBoard(),this.gameMusic.play()}return l(t,[{key:"createSettingsModal",value:function(){var t=this.game.add.graphics(0,0);t.beginFill(3783567),t.drawRect(this.game.world.centerX-150,this.game.world.centerY-200,300,400),t.endFill(),t.beginFill(16777215),t.drawRect(this.game.world.centerX-150+5,this.game.world.centerY-200+5,290,390),t.endFill(),this.disableBoardInput()}},{key:"openSettingsModal",value:function(){}},{key:"makeBackground",value:function(){var t=this.game.add.emitter(this.game.world.centerX,-100,50);return t.width=this.game.world.width,t.minParticleScale=.25*this.brickScale,t.maxParticleScale=.8*this.brickScale,t.makeParticles("bricks",[0,1,2,3,4,5]),t.setYSpeed(50*this.brickScale,150*this.brickScale),t.setXSpeed(0,0),t.minRotation=0,t.maxRotation=0,t}},{key:"brickClickHandler",value:function(t){if(7!==t.frame){var e=this.getBrickLocation(t),i=e.x,s=e.y,n=this.findColorGroup(s,i,t.frame),r=n.length;if(this.deleteGroup(n),2===++this.moves)if(this.isGameOver())this.gameOver();else{var o=this.posX+this.brickOffset,a=this.posY+this.brickOffset;this.boardRows[0]=this.createColorRow(o,a),this.moves=0}this.dropColumns(),this.addScore(r)}}},{key:"powerUpClickHandler",value:function(t){var e=this.getBrickLocation(t),i=e.x,s=e.y;if(this.boardRows[s][i].applyEffect(this),2==++this.moves)if(this.isGameOver())this.gameOver();else{var n=this.posX+this.brickOffset,r=this.posY+this.brickOffset;this.boardRows[0]=this.createColorRow(n,r),this.moves=0}this.dropColumns()}},{key:"runScoreAnim",value:function(t){var e=this,i=this.game.add.text(this.game.input.x,this.game.input.y-50*this.brickScale,"+"+t,{fill:"#fff",fontSize:60*this.brickScale});this.game.world.bringToTop(i);var s=this.game.add.tween(i).to({y:i.y-50*this.brickScale},300,"Quad.easeOut",!0),n=function(){e.game.add.tween(i).to({alpha:0},400,"Quad.easeOut",!0).onComplete.add(function(){return i.destroy()})};s.onComplete.add(n)}},{key:"addScore",value:function(t){var e=Math.floor(t+t/1.5);this.runScoreAnim(e),this.playerScore+=e,this.updateScoreBoard()}},{key:"updateScoreBoard",value:function(){this.scoreBoard.text="Score: "+this.playerScore}},{key:"findColorGroup",value:function(t,e,i,s){var n=s||[],r=function(t){return n.includes(t)};return r(this.boardRows[t][e])||n.push(this.boardRows[t][e]),0!=e&&this.boardRows[t][e-1].color===i&&(r(this.boardRows[t][e-1])||(n.push(this.boardRows[t][e-1]),this.findColorGroup(t,e-1,i,n))),e!=this.boardRows[t].length-1&&this.boardRows[t][e+1].color===i&&(r(this.boardRows[t][e+1])||(n.push(this.boardRows[t][e+1]),this.findColorGroup(t,e+1,i,n))),0!=t&&this.boardRows[t-1][e].color===i&&(r(this.boardRows[t-1][e])||(n.push(this.boardRows[t-1][e]),this.findColorGroup(t-1,e,i,n))),t!=this.boardRows.length-1&&this.boardRows[t+1][e].color===i&&(r(this.boardRows[t+1][e])||(n.push(this.boardRows[t+1][e]),this.findColorGroup(t+1,e,i,n))),n}},{key:"createBoard",value:function(){this.createBoardBackground();for(var t=this.posX+this.brickOffset,e=this.posY+this.brickOffset,i=0;i<10;i++){var s=this.brickOffset*i;i<4?this.boardRows.push(this.createColorRow(t,e+s,7)):this.boardRows.push(this.createColorRow(t,e+s))}}},{key:"renderBoard",value:function(){for(var t=0;t<this.boardRows.length;t++)for(var e=0;e<this.boardRows[t].length;e++){var i=this.posX+this.brickOffset+this.brickOffset*e,s=this.posY+this.brickOffset+this.brickOffset*t;this.boardRows[t][e].changePosition({x:i,y:s})}}},{key:"createBoardBackground",value:function(){for(var t=0;t<12;t++)for(var e=0;e<8;e++){var i=this.brickOffset*e,s=this.brickOffset*t,r=6;e>0&&e<7&&t>0&&t<11&&(r=7),new n.a(this.game,this.brickScale,this.posX+i,this.posY+s,r)}}},{key:"createEmptyBrick",value:function(t,e){var i=this.getBrickLocation(this.boardRows[t][e]),s=i.x,r=i.y;return new n.a(this.game,this.brickScale,s,r,7)}},{key:"createColorRow",value:function(t,e,i){for(var s=[],o=void 0,a=0;a<6;a++){var h=void 0;Math.floor(100*Math.random())<96?(o=i||Math.floor(Math.random()*this.numOfColors),h=new n.a(this.game,this.brickScale,t+this.brickOffset*a,e,o),h.addClickEvent(this.brickClickHandler,this)):(o=i||Math.floor(3*Math.random())+8,h=new r.a(this.game,this.brickScale,t+this.brickOffset*a,e,o),h.addClickEvent(this.powerUpClickHandler,this)),s.push(h)}return s}},{key:"dropColumns",value:function(){for(var t=[[],[],[],[],[],[]],e=0;e<t.length;e++){for(var i=0;i<10;i++)t[e].push(this.boardRows[i][e]);this.moveEmptyTop(t[e])}for(var s=0;s<t.length;s++)for(var n=0;n<t[s].length;n++)this.boardRows[n][s]=t[s][n];this.renderBoard()}},{key:"moveEmptyTop",value:function(t){for(var e=0;e<t.length;e++)if(t[e].isEmpty()){var i=t.splice(e,1)[0];t.unshift(i)}}},{key:"getBrickLocation",value:function(t){return{x:(t.x-this.posX)/this.brickOffset-1,y:(t.y-this.posY)/this.brickOffset-1}}},{key:"deleteBrick",value:function(t,e){var i=this.createEmptyBrick(t,e);this.boardRows[t][e].destroy(),this.boardRows[t].splice(e,1,i)}},{key:"deleteGroup",value:function(t){for(var e=0;e<t.length;e++){var i=this.getBrickLocation(t[e]),s=i.x,n=i.y;this.deleteBrick(n,s)}this.destroyBrickSound.play()}},{key:"isGameOver",value:function(){for(var t=!1,e=0;e<this.boardRows[0].length;e++)if(!this.boardRows[0][e].isEmpty()){t=!0;break}return t}},{key:"disableBoardInput",value:function(){this.boardRows.map(function(t){t.map(function(t){t.disableClickEvents()})})}},{key:"enableBoardInput",value:function(){this.boardRows.map(function(t){t.map(function(t){t.enableClickEvents()})})}},{key:"gameOver",value:function(){this.disableBoardInput(),this.scoreBoard.text="Game Over\nFinal Score: "+this.playerScore,h.a.post("/user/score/new",{score:this.playerScore}).then(function(t){alert("Thanks for playing!"),window.location.replace("/profile")}).catch(function(t){console.log(t)})}}]),t}();e.a=u},function(t,e,i){"use strict";function s(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function r(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}var o=i(19),a=i(55),h=function(){function t(t,e){for(var i=0;i<e.length;i++){var s=e[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(t,s.key,s)}}return function(e,i,s){return i&&t(e.prototype,i),s&&t(e,s),e}}(),l=function(t){function e(t,r,o,h,l){s(this,e);var c=n(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t,r,o,h,l));return c.effect=i.i(a.a)(c.color),c}return r(e,t),h(e,[{key:"applyEffect",value:function(t){this.effect(t)}}]),e}(o.a);e.a=l},function(t,e,i){"use strict";function s(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function r(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}var o=i(5),a=i(56),h=function(){function t(t,e){for(var i=0;i<e.length;i++){var s=e[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(t,s.key,s)}}return function(e,i,s){return i&&t(e.prototype,i),s&&t(e,s),e}}(),l=(o.a.SCREENWIDTH,o.a.SCREENHEIGHT,o.a.SCALERATIO),c=function(t){function e(){return s(this,e),n(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return r(e,t),h(e,[{key:"create",value:function(){this.game.scale.fullScreenScaleMode=Phaser.ScaleManager.SHOW_ALL,this.game.scale.scaleMode=Phaser.ScaleManager.SHOW_ALL,this.game.scale.refresh(),this.game.forceSingleUpdate=!0,this.myBoard=new a.a(this.game,l,this.game.world.centerX,this.game.world.centerY)}}]),e}(Phaser.State);e.a=c},function(t,e,i){"use strict";function s(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function r(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}var o=i(5),a=i(84),h=i.n(a),l=i(82),c=i.n(l),u=i(83),d=i.n(u),p=i(85),f=i.n(p),g=function(){function t(t,e){for(var i=0;i<e.length;i++){var s=e[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(t,s.key,s)}}return function(e,i,s){return i&&t(e.prototype,i),s&&t(e,s),e}}(),m=function(t){function e(){return s(this,e),n(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return r(e,t),g(e,[{key:"preload",value:function(){var t=this;this.load.onLoadComplete.addOnce(function(){return t.ready=!0}),this.loadResources()}},{key:"create",value:function(){this.stage.backgroundColor=o.b.DARKBLUE,this.game.add.text(this.game.world.centerX,this.game.world.centerY,"Loading ...",{fill:"#fff",align:"center",fontSize:50*o.a.SCALERATIO}).anchor.set(.5)}},{key:"loadResources",value:function(){this.game.load.spritesheet("bricks",h.a,o.a.BRICKSIZE,o.a.BRICKSIZE,11),this.game.load.image("settingsIcon",f.a),this.game.load.audio("brickDestroy",c.a),this.game.load.audio("gameMusic",d.a)}},{key:"update",value:function(){this.ready&&this.game.state.start("Main")}}]),e}(Phaser.State);e.a=m},function(t,e,i){"use strict";var s=i(58),n=i(59);i.d(e,"b",function(){return s.a}),i.d(e,"a",function(){return n.a})},,,function(t,e,i){"use strict";function s(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===t[e-2]?2:"="===t[e-1]?1:0}function n(t){return 3*t.length/4-s(t)}function r(t){var e,i,n,r,o,a,h=t.length;o=s(t),a=new u(3*h/4-o),n=o>0?h-4:h;var l=0;for(e=0,i=0;e<n;e+=4,i+=3)r=c[t.charCodeAt(e)]<<18|c[t.charCodeAt(e+1)]<<12|c[t.charCodeAt(e+2)]<<6|c[t.charCodeAt(e+3)],a[l++]=r>>16&255,a[l++]=r>>8&255,a[l++]=255&r;return 2===o?(r=c[t.charCodeAt(e)]<<2|c[t.charCodeAt(e+1)]>>4,a[l++]=255&r):1===o&&(r=c[t.charCodeAt(e)]<<10|c[t.charCodeAt(e+1)]<<4|c[t.charCodeAt(e+2)]>>2,a[l++]=r>>8&255,a[l++]=255&r),a}function o(t){return l[t>>18&63]+l[t>>12&63]+l[t>>6&63]+l[63&t]}function a(t,e,i){for(var s,n=[],r=e;r<i;r+=3)s=(t[r]<<16)+(t[r+1]<<8)+t[r+2],n.push(o(s));return n.join("")}function h(t){for(var e,i=t.length,s=i%3,n="",r=[],o=0,h=i-s;o<h;o+=16383)r.push(a(t,o,o+16383>h?h:o+16383));return 1===s?(e=t[i-1],n+=l[e>>2],n+=l[e<<4&63],n+="=="):2===s&&(e=(t[i-2]<<8)+t[i-1],n+=l[e>>10],n+=l[e>>4&63],n+=l[e<<2&63],n+="="),r.push(n),r.join("")}e.byteLength=n,e.toByteArray=r,e.fromByteArray=h;for(var l=[],c=[],u="undefined"!=typeof Uint8Array?Uint8Array:Array,d="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",p=0,f=d.length;p<f;++p)l[p]=d[p],c[d.charCodeAt(p)]=p;c["-".charCodeAt(0)]=62,c["_".charCodeAt(0)]=63},,function(t,e,i){"use strict";(function(t){function s(){return r.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function n(t,e){if(s()<e)throw new RangeError("Invalid typed array length");return r.TYPED_ARRAY_SUPPORT?(t=new Uint8Array(e),t.__proto__=r.prototype):(null===t&&(t=new r(e)),t.length=e),t}function r(t,e,i){if(!(r.TYPED_ARRAY_SUPPORT||this instanceof r))return new r(t,e,i);if("number"==typeof t){if("string"==typeof e)throw new Error("If encoding is specified then the first argument must be a string");return l(this,t)}return o(this,t,e,i)}function o(t,e,i,s){if("number"==typeof e)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer?d(t,e,i,s):"string"==typeof e?c(t,e,i):p(t,e)}function a(t){if("number"!=typeof t)throw new TypeError('"size" argument must be a number');if(t<0)throw new RangeError('"size" argument must not be negative')}function h(t,e,i,s){return a(e),e<=0?n(t,e):void 0!==i?"string"==typeof s?n(t,e).fill(i,s):n(t,e).fill(i):n(t,e)}function l(t,e){if(a(e),t=n(t,e<0?0:0|f(e)),!r.TYPED_ARRAY_SUPPORT)for(var i=0;i<e;++i)t[i]=0;return t}function c(t,e,i){if("string"==typeof i&&""!==i||(i="utf8"),!r.isEncoding(i))throw new TypeError('"encoding" must be a valid string encoding');var s=0|m(e,i);t=n(t,s);var o=t.write(e,i);return o!==s&&(t=t.slice(0,o)),t}function u(t,e){var i=e.length<0?0:0|f(e.length);t=n(t,i);for(var s=0;s<i;s+=1)t[s]=255&e[s];return t}function d(t,e,i,s){if(e.byteLength,i<0||e.byteLength<i)throw new RangeError("'offset' is out of bounds");if(e.byteLength<i+(s||0))throw new RangeError("'length' is out of bounds");return e=void 0===i&&void 0===s?new Uint8Array(e):void 0===s?new Uint8Array(e,i):new Uint8Array(e,i,s),r.TYPED_ARRAY_SUPPORT?(t=e,t.__proto__=r.prototype):t=u(t,e),t}function p(t,e){if(r.isBuffer(e)){var i=0|f(e.length);return t=n(t,i),0===t.length?t:(e.copy(t,0,0,i),t)}if(e){if("undefined"!=typeof ArrayBuffer&&e.buffer instanceof ArrayBuffer||"length"in e)return"number"!=typeof e.length||K(e.length)?n(t,0):u(t,e);if("Buffer"===e.type&&Z(e.data))return u(t,e.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}function f(t){if(t>=s())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s().toString(16)+" bytes");return 0|t}function g(t){return+t!=t&&(t=0),r.alloc(+t)}function m(t,e){if(r.isBuffer(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var i=t.length;if(0===i)return 0;for(var s=!1;;)switch(e){case"ascii":case"latin1":case"binary":return i;case"utf8":case"utf-8":case void 0:return V(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*i;case"hex":return i>>>1;case"base64":return Y(t).length;default:if(s)return V(t).length;e=(""+e).toLowerCase(),s=!0}}function y(t,e,i){var s=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===i||i>this.length)&&(i=this.length),i<=0)return"";if(i>>>=0,e>>>=0,i<=e)return"";for(t||(t="utf8");;)switch(t){case"hex":return B(this,e,i);case"utf8":case"utf-8":return E(this,e,i);case"ascii":return M(this,e,i);case"latin1":case"binary":return R(this,e,i);case"base64":return A(this,e,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return L(this,e,i);default:if(s)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),s=!0}}function v(t,e,i){var s=t[e];t[e]=t[i],t[i]=s}function b(t,e,i,s,n){if(0===t.length)return-1;if("string"==typeof i?(s=i,i=0):i>2147483647?i=2147483647:i<-2147483648&&(i=-2147483648),i=+i,isNaN(i)&&(i=n?0:t.length-1),i<0&&(i=t.length+i),i>=t.length){if(n)return-1;i=t.length-1}else if(i<0){if(!n)return-1;i=0}if("string"==typeof e&&(e=r.from(e,s)),r.isBuffer(e))return 0===e.length?-1:x(t,e,i,s,n);if("number"==typeof e)return e&=255,r.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?n?Uint8Array.prototype.indexOf.call(t,e,i):Uint8Array.prototype.lastIndexOf.call(t,e,i):x(t,[e],i,s,n);throw new TypeError("val must be string, number or Buffer")}function x(t,e,i,s,n){function r(t,e){return 1===o?t[e]:t.readUInt16BE(e*o)}var o=1,a=t.length,h=e.length;if(void 0!==s&&("ucs2"===(s=String(s).toLowerCase())||"ucs-2"===s||"utf16le"===s||"utf-16le"===s)){if(t.length<2||e.length<2)return-1;o=2,a/=2,h/=2,i/=2}var l;if(n){var c=-1;for(l=i;l<a;l++)if(r(t,l)===r(e,-1===c?0:l-c)){if(-1===c&&(c=l),l-c+1===h)return c*o}else-1!==c&&(l-=l-c),c=-1}else for(i+h>a&&(i=a-h),l=i;l>=0;l--){for(var u=!0,d=0;d<h;d++)if(r(t,l+d)!==r(e,d)){u=!1;break}if(u)return l}return-1}function w(t,e,i,s){i=Number(i)||0;var n=t.length-i;s?(s=Number(s))>n&&(s=n):s=n;var r=e.length;if(r%2!=0)throw new TypeError("Invalid hex string");s>r/2&&(s=r/2);for(var o=0;o<s;++o){var a=parseInt(e.substr(2*o,2),16);if(isNaN(a))return o;t[i+o]=a}return o}function _(t,e,i,s){return z(V(e,t.length-i),t,i,s)}function P(t,e,i,s){return z(q(e),t,i,s)}function T(t,e,i,s){return P(t,e,i,s)}function C(t,e,i,s){return z(Y(e),t,i,s)}function S(t,e,i,s){return z(H(e,t.length-i),t,i,s)}function A(t,e,i){return 0===e&&i===t.length?J.fromByteArray(t):J.fromByteArray(t.slice(e,i))}function E(t,e,i){i=Math.min(t.length,i);for(var s=[],n=e;n<i;){var r=t[n],o=null,a=r>239?4:r>223?3:r>191?2:1;if(n+a<=i){var h,l,c,u;switch(a){case 1:r<128&&(o=r);break;case 2:h=t[n+1],128==(192&h)&&(u=(31&r)<<6|63&h)>127&&(o=u);break;case 3:h=t[n+1],l=t[n+2],128==(192&h)&&128==(192&l)&&(u=(15&r)<<12|(63&h)<<6|63&l)>2047&&(u<55296||u>57343)&&(o=u);break;case 4:h=t[n+1],l=t[n+2],c=t[n+3],128==(192&h)&&128==(192&l)&&128==(192&c)&&(u=(15&r)<<18|(63&h)<<12|(63&l)<<6|63&c)>65535&&u<1114112&&(o=u)}}null===o?(o=65533,a=1):o>65535&&(o-=65536,s.push(o>>>10&1023|55296),o=56320|1023&o),s.push(o),n+=a}return I(s)}function I(t){var e=t.length;if(e<=$)return String.fromCharCode.apply(String,t);for(var i="",s=0;s<e;)i+=String.fromCharCode.apply(String,t.slice(s,s+=$));return i}function M(t,e,i){var s="";i=Math.min(t.length,i);for(var n=e;n<i;++n)s+=String.fromCharCode(127&t[n]);return s}function R(t,e,i){var s="";i=Math.min(t.length,i);for(var n=e;n<i;++n)s+=String.fromCharCode(t[n]);return s}function B(t,e,i){var s=t.length;(!e||e<0)&&(e=0),(!i||i<0||i>s)&&(i=s);for(var n="",r=e;r<i;++r)n+=j(t[r]);return n}function L(t,e,i){for(var s=t.slice(e,i),n="",r=0;r<s.length;r+=2)n+=String.fromCharCode(s[r]+256*s[r+1]);return n}function O(t,e,i){if(t%1!=0||t<0)throw new RangeError("offset is not uint");if(t+e>i)throw new RangeError("Trying to access beyond buffer length")}function k(t,e,i,s,n,o){if(!r.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>n||e<o)throw new RangeError('"value" argument is out of bounds');if(i+s>t.length)throw new RangeError("Index out of range")}function F(t,e,i,s){e<0&&(e=65535+e+1);for(var n=0,r=Math.min(t.length-i,2);n<r;++n)t[i+n]=(e&255<<8*(s?n:1-n))>>>8*(s?n:1-n)}function D(t,e,i,s){e<0&&(e=4294967295+e+1);for(var n=0,r=Math.min(t.length-i,4);n<r;++n)t[i+n]=e>>>8*(s?n:3-n)&255}function U(t,e,i,s,n,r){if(i+s>t.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("Index out of range")}function G(t,e,i,s,n){return n||U(t,e,i,4,3.4028234663852886e38,-3.4028234663852886e38),Q.write(t,e,i,s,23,4),i+4}function N(t,e,i,s,n){return n||U(t,e,i,8,1.7976931348623157e308,-1.7976931348623157e308),Q.write(t,e,i,s,52,8),i+8}function X(t){if(t=W(t).replace(tt,""),t.length<2)return"";for(;t.length%4!=0;)t+="=";return t}function W(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function j(t){return t<16?"0"+t.toString(16):t.toString(16)}function V(t,e){e=e||1/0;for(var i,s=t.length,n=null,r=[],o=0;o<s;++o){if((i=t.charCodeAt(o))>55295&&i<57344){if(!n){if(i>56319){(e-=3)>-1&&r.push(239,191,189);continue}if(o+1===s){(e-=3)>-1&&r.push(239,191,189);continue}n=i;continue}if(i<56320){(e-=3)>-1&&r.push(239,191,189),n=i;continue}i=65536+(n-55296<<10|i-56320)}else n&&(e-=3)>-1&&r.push(239,191,189);if(n=null,i<128){if((e-=1)<0)break;r.push(i)}else if(i<2048){if((e-=2)<0)break;r.push(i>>6|192,63&i|128)}else if(i<65536){if((e-=3)<0)break;r.push(i>>12|224,i>>6&63|128,63&i|128)}else{if(!(i<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;r.push(i>>18|240,i>>12&63|128,i>>6&63|128,63&i|128)}}return r}function q(t){for(var e=[],i=0;i<t.length;++i)e.push(255&t.charCodeAt(i));return e}function H(t,e){for(var i,s,n,r=[],o=0;o<t.length&&!((e-=2)<0);++o)i=t.charCodeAt(o),s=i>>8,n=i%256,r.push(n),r.push(s);return r}function Y(t){return J.toByteArray(X(t))}function z(t,e,i,s){for(var n=0;n<s&&!(n+i>=e.length||n>=t.length);++n)e[n+i]=t[n];return n}function K(t){return t!==t}/*!
<add>webpackJsonp([1],[,function(t,e,i){"use strict";(function(e){function s(t){return"[object Array]"===T.call(t)}function n(t){return void 0!==e&&e.isBuffer&&e.isBuffer(t)}function r(t){return"[object ArrayBuffer]"===T.call(t)}function o(t){return"undefined"!=typeof FormData&&t instanceof FormData}function a(t){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer&&t.buffer instanceof ArrayBuffer}function h(t){return"string"==typeof t}function l(t){return"number"==typeof t}function c(t){return void 0===t}function u(t){return null!==t&&"object"==typeof t}function d(t){return"[object Date]"===T.call(t)}function p(t){return"[object File]"===T.call(t)}function f(t){return"[object Blob]"===T.call(t)}function g(t){return"[object Function]"===T.call(t)}function m(t){return u(t)&&g(t.pipe)}function y(t){return"undefined"!=typeof URLSearchParams&&t instanceof URLSearchParams}function v(t){return t.replace(/^\s*/,"").replace(/\s*$/,"")}function b(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product)&&("undefined"!=typeof window&&"undefined"!=typeof document)}function x(t,e){if(null!==t&&void 0!==t)if("object"==typeof t||s(t)||(t=[t]),s(t))for(var i=0,n=t.length;i<n;i++)e.call(null,t[i],i,t);else for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.call(null,t[r],r,t)}function w(){function t(t,i){"object"==typeof e[i]&&"object"==typeof t?e[i]=w(e[i],t):e[i]=t}for(var e={},i=0,s=arguments.length;i<s;i++)x(arguments[i],t);return e}function _(t,e,i){return x(e,function(e,s){t[s]=i&&"function"==typeof e?P(e,i):e}),t}var P=i(18),T=Object.prototype.toString;t.exports={isArray:s,isArrayBuffer:r,isBuffer:n,isFormData:o,isArrayBufferView:a,isString:h,isNumber:l,isObject:u,isUndefined:c,isDate:d,isFile:p,isBlob:f,isFunction:g,isStream:m,isURLSearchParams:y,isStandardBrowserEnv:b,forEach:x,merge:w,extend:_,trim:v}}).call(e,i(65).Buffer)},,,,function(t,e,i){"use strict";i.d(e,"b",function(){return s}),i.d(e,"a",function(){return r}),i.d(e,"c",function(){return o});var s={BLACK:"#060304",DARKBLUE:"#001440",TEAL:"#427a8b",GREEN:"#39bb8f",YELLOWGREEN:"#e2fda7"},n=function(){var t=!1;return function(e){(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4)))&&(t=!0)}(navigator.userAgent||navigator.vendor||window.opera),t},r={SCREENWIDTH:window.innerWidth*window.devicePixelRatio,SCREENHEIGHT:window.innerHeight*window.devicePixelRatio,SCALERATIO:function(){var t=window.innerWidth/window.innerHeight,e=void 0;return e=t>1?window.innerHeight*window.devicePixelRatio/2048:window.innerWidth*window.devicePixelRatio/2048,n()&&(e+=1),e}(),BRICKSIZE:120},o=n()},,,,function(t,e,i){"use strict";(function(e){function s(t,e){!n.isUndefined(t)&&n.isUndefined(t["Content-Type"])&&(t["Content-Type"]=e)}var n=i(1),r=i(52),o={"Content-Type":"application/x-www-form-urlencoded"},a={adapter:function(){var t;return"undefined"!=typeof XMLHttpRequest?t=i(14):void 0!==e&&(t=i(14)),t}(),transformRequest:[function(t,e){return r(e,"Content-Type"),n.isFormData(t)||n.isArrayBuffer(t)||n.isBuffer(t)||n.isStream(t)||n.isFile(t)||n.isBlob(t)?t:n.isArrayBufferView(t)?t.buffer:n.isURLSearchParams(t)?(s(e,"application/x-www-form-urlencoded;charset=utf-8"),t.toString()):n.isObject(t)?(s(e,"application/json;charset=utf-8"),JSON.stringify(t)):t}],transformResponse:[function(t){if("string"==typeof t)try{t=JSON.parse(t)}catch(t){}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,validateStatus:function(t){return t>=200&&t<300}};a.headers={common:{Accept:"application/json, text/plain, */*"}},n.forEach(["delete","get","head"],function(t){a.headers[t]={}}),n.forEach(["post","put","patch"],function(t){a.headers[t]=n.merge(o)}),t.exports=a}).call(e,i(4))},,,,,function(t,e,i){"use strict";var s=i(1),n=i(44),r=i(47),o=i(53),a=i(51),h=i(17),l="undefined"!=typeof window&&window.btoa&&window.btoa.bind(window)||i(46);t.exports=function(t){return new Promise(function(e,c){var u=t.data,d=t.headers;s.isFormData(u)&&delete d["Content-Type"];var p=new XMLHttpRequest,f="onreadystatechange",g=!1;if("undefined"==typeof window||!window.XDomainRequest||"withCredentials"in p||a(t.url)||(p=new window.XDomainRequest,f="onload",g=!0,p.onprogress=function(){},p.ontimeout=function(){}),t.auth){var m=t.auth.username||"",y=t.auth.password||"";d.Authorization="Basic "+l(m+":"+y)}if(p.open(t.method.toUpperCase(),r(t.url,t.params,t.paramsSerializer),!0),p.timeout=t.timeout,p[f]=function(){if(p&&(4===p.readyState||g)&&(0!==p.status||p.responseURL&&0===p.responseURL.indexOf("file:"))){var i="getAllResponseHeaders"in p?o(p.getAllResponseHeaders()):null,s=t.responseType&&"text"!==t.responseType?p.response:p.responseText,r={data:s,status:1223===p.status?204:p.status,statusText:1223===p.status?"No Content":p.statusText,headers:i,config:t,request:p};n(e,c,r),p=null}},p.onerror=function(){c(h("Network Error",t)),p=null},p.ontimeout=function(){c(h("timeout of "+t.timeout+"ms exceeded",t,"ECONNABORTED")),p=null},s.isStandardBrowserEnv()){var v=i(49),b=(t.withCredentials||a(t.url))&&t.xsrfCookieName?v.read(t.xsrfCookieName):void 0;b&&(d[t.xsrfHeaderName]=b)}if("setRequestHeader"in p&&s.forEach(d,function(t,e){void 0===u&&"content-type"===e.toLowerCase()?delete d[e]:p.setRequestHeader(e,t)}),t.withCredentials&&(p.withCredentials=!0),t.responseType)try{p.responseType=t.responseType}catch(e){if("json"!==t.responseType)throw e}"function"==typeof t.onDownloadProgress&&p.addEventListener("progress",t.onDownloadProgress),"function"==typeof t.onUploadProgress&&p.upload&&p.upload.addEventListener("progress",t.onUploadProgress),t.cancelToken&&t.cancelToken.promise.then(function(t){p&&(p.abort(),c(t),p=null)}),void 0===u&&(u=null),p.send(u)})}},function(t,e,i){"use strict";function s(t){this.message=t}s.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},s.prototype.__CANCEL__=!0,t.exports=s},function(t,e,i){"use strict";t.exports=function(t){return!(!t||!t.__CANCEL__)}},function(t,e,i){"use strict";var s=i(43);t.exports=function(t,e,i,n){var r=new Error(t);return s(r,e,i,n)}},function(t,e,i){"use strict";t.exports=function(t,e){return function(){for(var i=new Array(arguments.length),s=0;s<i.length;s++)i[s]=arguments[s];return t.apply(e,i)}}},function(t,e,i){"use strict";function s(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var n=function(){function t(t,e){for(var i=0;i<e.length;i++){var s=e[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(t,s.key,s)}}return function(e,i,s){return i&&t(e.prototype,i),s&&t(e,s),e}}(),r=function(){function t(e,i,n,r,o){s(this,t),this.game=e,this.scale=i||1,this.color=o,this.x=n,this.y=r,this.sprite=this.game.add.sprite(this.x,this.y,"bricks",this.color),this.sprite.inputEnabled=!0,this.sprite.scale.setTo(this.scale),this.emitter=this.game.add.emitter(0,0,6),this.emitter.makeParticles("bricks",this.color),this.emitter.minParticleScale=this.scale,this.emitter.maxParticleScale=this.scale,this.emitter.gravity=2e3*this.scale}return n(t,[{key:"tweenTo",value:function(t,e){this.game.add.tween(this.sprite).to({x:t,y:e},400,"Bounce",!0)}},{key:"addClickEvent",value:function(t,e){this.sprite.events.onInputDown.add(t,e)}},{key:"enableClickEvents",value:function(){this.sprite.inputEnabled=!0}},{key:"disableClickEvents",value:function(){this.sprite.inputEnabled=!1}},{key:"changePosition",value:function(t){var e=t.x,i=t.y;this.isEmpty()?(this.game.world.sendToBack(this.sprite),this.sprite.x=e||this.sprite.x,this.sprite.y=i||this.sprite.y):this.tweenTo(e,i),this.x=e,this.y=i}},{key:"runDestroyAnim",value:function(){this.game.world.bringToTop(this.emitter),this.emitter.x=this.x+this.sprite.width/2,this.emitter.y=this.y+this.sprite.width/2,this.emitter.start(!1,1e3,1,1)}},{key:"destroy",value:function(){this.runDestroyAnim(),this.sprite.destroy()}},{key:"isEmpty",value:function(){return 7===this.color}}]),t}();e.a=r},,,,,,,,,,,,,,function(t,e,i){"use strict";function s(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function r(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}Object.defineProperty(e,"__esModule",{value:!0});var o=i(79),a=(i.n(o),i(81)),h=(i.n(a),i(80)),l=i.n(h),c=i(60),u=i(5),d=u.a.SCREENWIDTH,p=u.a.SCREENHEIGHT;new(function(t){function e(t,i,r){s(this,e);var o=n(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t,i,r));return o.state.add("Preload",c.a,!1),o.state.add("Main",c.b,!1),o.state.start("Preload"),o}return r(e,t),e}(l.a.Game))(d,p,l.a.CANVAS)},,,,function(t,e,i){t.exports=i(38)},function(t,e,i){"use strict";function s(t){var e=new o(t),i=r(o.prototype.request,e);return n.extend(i,o.prototype,e),n.extend(i,e),i}var n=i(1),r=i(18),o=i(40),a=i(9),h=s(a);h.Axios=o,h.create=function(t){return s(n.merge(a,t))},h.Cancel=i(15),h.CancelToken=i(39),h.isCancel=i(16),h.all=function(t){return Promise.all(t)},h.spread=i(54),t.exports=h,t.exports.default=h},function(t,e,i){"use strict";function s(t){if("function"!=typeof t)throw new TypeError("executor must be a function.");var e;this.promise=new Promise(function(t){e=t});var i=this;t(function(t){i.reason||(i.reason=new n(t),e(i.reason))})}var n=i(15);s.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},s.source=function(){var t;return{token:new s(function(e){t=e}),cancel:t}},t.exports=s},function(t,e,i){"use strict";function s(t){this.defaults=t,this.interceptors={request:new o,response:new o}}var n=i(9),r=i(1),o=i(41),a=i(42),h=i(50),l=i(48);s.prototype.request=function(t){"string"==typeof t&&(t=r.merge({url:arguments[0]},arguments[1])),t=r.merge(n,this.defaults,{method:"get"},t),t.baseURL&&!h(t.url)&&(t.url=l(t.baseURL,t.url));var e=[a,void 0],i=Promise.resolve(t);for(this.interceptors.request.forEach(function(t){e.unshift(t.fulfilled,t.rejected)}),this.interceptors.response.forEach(function(t){e.push(t.fulfilled,t.rejected)});e.length;)i=i.then(e.shift(),e.shift());return i},r.forEach(["delete","get","head","options"],function(t){s.prototype[t]=function(e,i){return this.request(r.merge(i||{},{method:t,url:e}))}}),r.forEach(["post","put","patch"],function(t){s.prototype[t]=function(e,i,s){return this.request(r.merge(s||{},{method:t,url:e,data:i}))}}),t.exports=s},function(t,e,i){"use strict";function s(){this.handlers=[]}var n=i(1);s.prototype.use=function(t,e){return this.handlers.push({fulfilled:t,rejected:e}),this.handlers.length-1},s.prototype.eject=function(t){this.handlers[t]&&(this.handlers[t]=null)},s.prototype.forEach=function(t){n.forEach(this.handlers,function(e){null!==e&&t(e)})},t.exports=s},function(t,e,i){"use strict";function s(t){t.cancelToken&&t.cancelToken.throwIfRequested()}var n=i(1),r=i(45),o=i(16),a=i(9);t.exports=function(t){return s(t),t.headers=t.headers||{},t.data=r(t.data,t.headers,t.transformRequest),t.headers=n.merge(t.headers.common||{},t.headers[t.method]||{},t.headers||{}),n.forEach(["delete","get","head","post","put","patch","common"],function(e){delete t.headers[e]}),(t.adapter||a.adapter)(t).then(function(e){return s(t),e.data=r(e.data,e.headers,t.transformResponse),e},function(e){return o(e)||(s(t),e&&e.response&&(e.response.data=r(e.response.data,e.response.headers,t.transformResponse))),Promise.reject(e)})}},function(t,e,i){"use strict";t.exports=function(t,e,i,s){return t.config=e,i&&(t.code=i),t.response=s,t}},function(t,e,i){"use strict";var s=i(17);t.exports=function(t,e,i){var n=i.config.validateStatus;i.status&&n&&!n(i.status)?e(s("Request failed with status code "+i.status,i.config,null,i)):t(i)}},function(t,e,i){"use strict";var s=i(1);t.exports=function(t,e,i){return s.forEach(i,function(i){t=i(t,e)}),t}},function(t,e,i){"use strict";function s(){this.message="String contains an invalid character"}function n(t){for(var e,i,n=String(t),o="",a=0,h=r;n.charAt(0|a)||(h="=",a%1);o+=h.charAt(63&e>>8-a%1*8)){if((i=n.charCodeAt(a+=.75))>255)throw new s;e=e<<8|i}return o}var r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";s.prototype=new Error,s.prototype.code=5,s.prototype.name="InvalidCharacterError",t.exports=n},function(t,e,i){"use strict";function s(t){return encodeURIComponent(t).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var n=i(1);t.exports=function(t,e,i){if(!e)return t;var r;if(i)r=i(e);else if(n.isURLSearchParams(e))r=e.toString();else{var o=[];n.forEach(e,function(t,e){null!==t&&void 0!==t&&(n.isArray(t)&&(e+="[]"),n.isArray(t)||(t=[t]),n.forEach(t,function(t){n.isDate(t)?t=t.toISOString():n.isObject(t)&&(t=JSON.stringify(t)),o.push(s(e)+"="+s(t))}))}),r=o.join("&")}return r&&(t+=(-1===t.indexOf("?")?"?":"&")+r),t}},function(t,e,i){"use strict";t.exports=function(t,e){return e?t.replace(/\/+$/,"")+"/"+e.replace(/^\/+/,""):t}},function(t,e,i){"use strict";var s=i(1);t.exports=s.isStandardBrowserEnv()?function(){return{write:function(t,e,i,n,r,o){var a=[];a.push(t+"="+encodeURIComponent(e)),s.isNumber(i)&&a.push("expires="+new Date(i).toGMTString()),s.isString(n)&&a.push("path="+n),s.isString(r)&&a.push("domain="+r),!0===o&&a.push("secure"),document.cookie=a.join("; ")},read:function(t){var e=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove:function(t){this.write(t,"",Date.now()-864e5)}}}():function(){return{write:function(){},read:function(){return null},remove:function(){}}}()},function(t,e,i){"use strict";t.exports=function(t){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(t)}},function(t,e,i){"use strict";var s=i(1);t.exports=s.isStandardBrowserEnv()?function(){function t(t){var e=t;return i&&(n.setAttribute("href",e),e=n.href),n.setAttribute("href",e),{href:n.href,protocol:n.protocol?n.protocol.replace(/:$/,""):"",host:n.host,search:n.search?n.search.replace(/^\?/,""):"",hash:n.hash?n.hash.replace(/^#/,""):"",hostname:n.hostname,port:n.port,pathname:"/"===n.pathname.charAt(0)?n.pathname:"/"+n.pathname}}var e,i=/(msie|trident)/i.test(navigator.userAgent),n=document.createElement("a");return e=t(window.location.href),function(i){var n=s.isString(i)?t(i):i;return n.protocol===e.protocol&&n.host===e.host}}():function(){return function(){return!0}}()},function(t,e,i){"use strict";var s=i(1);t.exports=function(t,e){s.forEach(t,function(i,s){s!==e&&s.toUpperCase()===e.toUpperCase()&&(t[e]=i,delete t[s])})}},function(t,e,i){"use strict";var s=i(1);t.exports=function(t){var e,i,n,r={};return t?(s.forEach(t.split("\n"),function(t){n=t.indexOf(":"),e=s.trim(t.substr(0,n)).toLowerCase(),i=s.trim(t.substr(n+1)),e&&(r[e]=r[e]?r[e]+", "+i:i)}),r):r}},function(t,e,i){"use strict";t.exports=function(t){return function(e){return t.apply(null,e)}}},function(t,e,i){"use strict";function s(t){function e(i,s,n){var r=n||[];return 0==s||t.boardRows[s][i].isEmpty()||(r.push(t.boardRows[s][i]),e(i,s-1,r)),r}var i=t.getBrickLocation(this),s=i.x,n=(i.y,e(s,t.boardRows.length-1)),r=n.length;t.deleteGroup(n),t.addScore(r)}function n(t){for(var e=t.getBrickLocation(this),i=(e.x,e.y),s=[],n=0;n<t.boardRows[i].length;n++)t.boardRows[i][n].isEmpty()||s.push(t.boardRows[i][n]);var r=s.length;t.deleteGroup(s),t.addScore(r)}function r(t){var e=t.getBrickLocation(this),i=e.x,s=e.y,n=[];n.push(t.boardRows[s][i]),i!==t.boardRows[s].length-1&&n.push(t.boardRows[s][i+1]),i!==t.boardRows[s].length-1&&s!==t.boardRows.length-1&&n.push(t.boardRows[s+1][i+1]),i!==t.boardRows[s].length-1&&0!==s&&n.push(t.boardRows[s-1][i+1]),0!==i&&n.push(t.boardRows[s][i-1]),0!==i&&0!==s&&n.push(t.boardRows[s-1][i-1]),0!==i&&s!==t.boardRows.length-1&&n.push(t.boardRows[s+1][i-1]),0!==s&&n.push(t.boardRows[s-1][i]),s!==t.boardRows.length-1&&n.push(t.boardRows[s+1][i]);for(var r=n.length-1;r>0;r--)n[r].isEmpty()&&n.splice(r,1);var o=n.length;t.deleteGroup(n),t.addScore(o)}function o(t){return a[t]}e.a=o;var a={8:s,9:n,10:r}},function(t,e,i){"use strict";function s(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var n=i(19),r=i(57),o=i(5),a=i(37),h=i.n(a),l=function(){function t(t,e){for(var i=0;i<e.length;i++){var s=e[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(t,s.key,s)}}return function(e,i,s){return i&&t(e.prototype,i),s&&t(e,s),e}}(),c=o.a.BRICKSIZE,u=function(){function t(e,i,n,r){s(this,t),this.game=e,this.boardRows=[],this.brickSize=c,this.brickScale=i,this.brickOffset=this.brickSize*this.brickScale,this.boardWidth=8*this.brickOffset,this.boardHeight=12*this.brickOffset,this.boardOffsetW=this.boardWidth/2,this.boardOffsetH=this.boardHeight/2,this.posX=n-this.boardOffsetW,this.posY=r-this.boardOffsetH,this.moves=0,this.numOfColors=5,this.playerScore=0,this.destroyBrickSound=this.game.add.audio("brickDestroy"),this.destroyBrickSound.volume=1.5,this.gameMusic=this.game.add.audio("gameMusic"),this.gameMusic.loop=!0,this.gameMusic.volume=.5,o.c||(this.background=this.makeBackground(),this.background.start(!1,5e3,250,0)),this.scoreBoard=this.game.add.text(this.posX,this.posY-100*this.brickScale,"Score: "+this.playerScore,{fill:"#fff",fontSize:60*this.brickScale}),this.settings={},this.settings.music="on",this.settings.sound="on",this.settingsIcon=this.game.add.sprite(this.boardWidth+this.posX-90*this.brickScale,this.posY-90*this.brickScale,"settingsIcon"),this.settingsIcon.width=75*this.brickScale,this.settingsIcon.height=75*this.brickScale,this.settingsIcon.inputEnabled=!0,this.settingsIcon.events.onInputDown.add(this.openSettingsModal,this),this.createBoard(),this.gameMusic.play()}return l(t,[{key:"createSettingsModal",value:function(){this.disableBoardInput();var t=this.game.add.group();t.destroyChildren=!0;var e=600*this.brickScale,i=800*this.brickScale,s=this.game.add.graphics(0,0),n=this.game.world.centerX-e/2,r=this.game.world.centerY-i/2;s.beginFill(3783567),s.drawRect(n,r,e,i),s.endFill(),s.beginFill(16777215),s.drawRect(n+15*this.brickScale,r+15*this.brickScale,e-30*this.brickScale,i-30*this.brickScale),s.endFill(),t.add(s);var o=this.game.add.text(n+e-75*this.brickScale,r+25*this.brickScale,"X",{fill:"#427a8b",fontSize:70*this.brickScale});t.add(o);var a=this.game.add.text(n+s.centerX-175*this.brickScale,r+s.centerY-155*this.brickScale,"Music",{fill:"#427a8b",fontSize:60*this.brickScale});t.add(a);var h=this.game.add.text(n+s.centerX-175*this.brickScale,r+s.centerY+100*this.brickScale,"Sound",{fill:"#427a8b",fontSize:60*this.brickScale});t.add(h);var l=this.game.add.text(n+s.centerX+75*this.brickScale,r+s.centerY-155*this.brickScale,""+this.settings.music,{fill:"#427a8b",fontSize:60*this.brickScale});t.add(l);var c=this.game.add.text(n+s.centerX+75*this.brickScale,r+s.centerY+100*this.brickScale,""+this.settings.sound,{fill:"#427a8b",fontSize:60*this.brickScale});t.add(c),l.inputEnabled=!0,l.events.onInputDown.add(this.toggleSetting.bind(this,"music")),c.inputEnabled=!0,c.events.onInputDown.add(this.toggleSetting.bind(this,"sound")),o.inputEnabled=!0,o.events.onInputDown.add(this.closeSettingsMenu.bind(this,t))}},{key:"toggleSetting",value:function(t,e){"on"===this.settings[t]?(this.settings[t]="off",e.text=this.settings[t],"music"===t&&this.gameMusic.stop()):"off"===this.settings[t]&&(this.settings[t]="on",e.text=this.settings[t],"music"===t&&this.gameMusic.play())}},{key:"openSettingsModal",value:function(){this.createSettingsModal()}},{key:"closeSettingsMenu",value:function(t){t.destroy(),this.enableBoardInput()}},{key:"makeBackground",value:function(){var t=this.game.add.emitter(this.game.world.centerX,-100,50);return t.width=this.game.world.width,t.minParticleScale=.25*this.brickScale,t.maxParticleScale=.8*this.brickScale,t.makeParticles("bricks",[0,1,2,3,4,5]),t.setYSpeed(50*this.brickScale,150*this.brickScale),t.setXSpeed(0,0),t.minRotation=0,t.maxRotation=0,t}},{key:"brickClickHandler",value:function(t){if(7!==t.frame){var e=this.getBrickLocation(t),i=e.x,s=e.y,n=this.findColorGroup(s,i,t.frame),r=n.length;if(this.deleteGroup(n),2===++this.moves)if(this.isGameOver())this.gameOver();else{var o=this.posX+this.brickOffset,a=this.posY+this.brickOffset;this.boardRows[0]=this.createColorRow(o,a),this.moves=0}this.dropColumns(),this.addScore(r)}}},{key:"powerUpClickHandler",value:function(t){var e=this.getBrickLocation(t),i=e.x,s=e.y;if(this.boardRows[s][i].applyEffect(this),2==++this.moves)if(this.isGameOver())this.gameOver();else{var n=this.posX+this.brickOffset,r=this.posY+this.brickOffset;this.boardRows[0]=this.createColorRow(n,r),this.moves=0}this.dropColumns()}},{key:"runScoreAnim",value:function(t){var e=this,i=this.game.add.text(this.game.input.x,this.game.input.y-50*this.brickScale,"+"+t,{fill:"#fff",fontSize:60*this.brickScale});this.game.world.bringToTop(i);var s=this.game.add.tween(i).to({y:i.y-50*this.brickScale},300,"Quad.easeOut",!0),n=function(){e.game.add.tween(i).to({alpha:0},400,"Quad.easeOut",!0).onComplete.add(function(){return i.destroy()})};s.onComplete.add(n)}},{key:"addScore",value:function(t){var e=Math.floor(t+t/1.5);this.runScoreAnim(e),this.playerScore+=e,this.updateScoreBoard()}},{key:"updateScoreBoard",value:function(){this.scoreBoard.text="Score: "+this.playerScore}},{key:"findColorGroup",value:function(t,e,i,s){var n=s||[],r=function(t){return n.includes(t)};return r(this.boardRows[t][e])||n.push(this.boardRows[t][e]),0!=e&&this.boardRows[t][e-1].color===i&&(r(this.boardRows[t][e-1])||(n.push(this.boardRows[t][e-1]),this.findColorGroup(t,e-1,i,n))),e!=this.boardRows[t].length-1&&this.boardRows[t][e+1].color===i&&(r(this.boardRows[t][e+1])||(n.push(this.boardRows[t][e+1]),this.findColorGroup(t,e+1,i,n))),0!=t&&this.boardRows[t-1][e].color===i&&(r(this.boardRows[t-1][e])||(n.push(this.boardRows[t-1][e]),this.findColorGroup(t-1,e,i,n))),t!=this.boardRows.length-1&&this.boardRows[t+1][e].color===i&&(r(this.boardRows[t+1][e])||(n.push(this.boardRows[t+1][e]),this.findColorGroup(t+1,e,i,n))),n}},{key:"createBoard",value:function(){this.createBoardBackground();for(var t=this.posX+this.brickOffset,e=this.posY+this.brickOffset,i=0;i<10;i++){var s=this.brickOffset*i;i<4?this.boardRows.push(this.createColorRow(t,e+s,7)):this.boardRows.push(this.createColorRow(t,e+s))}}},{key:"renderBoard",value:function(){for(var t=0;t<this.boardRows.length;t++)for(var e=0;e<this.boardRows[t].length;e++){var i=this.posX+this.brickOffset+this.brickOffset*e,s=this.posY+this.brickOffset+this.brickOffset*t;this.boardRows[t][e].changePosition({x:i,y:s})}}},{key:"createBoardBackground",value:function(){for(var t=0;t<12;t++)for(var e=0;e<8;e++){var i=this.brickOffset*e,s=this.brickOffset*t,r=6;e>0&&e<7&&t>0&&t<11&&(r=7),new n.a(this.game,this.brickScale,this.posX+i,this.posY+s,r)}}},{key:"createEmptyBrick",value:function(t,e){var i=this.getBrickLocation(this.boardRows[t][e]),s=i.x,r=i.y;return new n.a(this.game,this.brickScale,s,r,7)}},{key:"createColorRow",value:function(t,e,i){for(var s=[],o=void 0,a=0;a<6;a++){var h=void 0;Math.floor(100*Math.random())<96?(o=i||Math.floor(Math.random()*this.numOfColors),h=new n.a(this.game,this.brickScale,t+this.brickOffset*a,e,o),h.addClickEvent(this.brickClickHandler,this)):(o=i||Math.floor(3*Math.random())+8,h=new r.a(this.game,this.brickScale,t+this.brickOffset*a,e,o),h.addClickEvent(this.powerUpClickHandler,this)),s.push(h)}return s}},{key:"dropColumns",value:function(){for(var t=[[],[],[],[],[],[]],e=0;e<t.length;e++){for(var i=0;i<10;i++)t[e].push(this.boardRows[i][e]);this.moveEmptyTop(t[e])}for(var s=0;s<t.length;s++)for(var n=0;n<t[s].length;n++)this.boardRows[n][s]=t[s][n];this.renderBoard()}},{key:"moveEmptyTop",value:function(t){for(var e=0;e<t.length;e++)if(t[e].isEmpty()){var i=t.splice(e,1)[0];t.unshift(i)}}},{key:"getBrickLocation",value:function(t){return{x:(t.x-this.posX)/this.brickOffset-1,y:(t.y-this.posY)/this.brickOffset-1}}},{key:"deleteBrick",value:function(t,e){var i=this.createEmptyBrick(t,e);this.boardRows[t][e].destroy(),this.boardRows[t].splice(e,1,i)}},{key:"deleteGroup",value:function(t){for(var e=0;e<t.length;e++){var i=this.getBrickLocation(t[e]),s=i.x,n=i.y;this.deleteBrick(n,s)}"on"===this.settings.sound&&this.destroyBrickSound.play()}},{key:"isGameOver",value:function(){for(var t=!1,e=0;e<this.boardRows[0].length;e++)if(!this.boardRows[0][e].isEmpty()){t=!0;break}return t}},{key:"disableBoardInput",value:function(){this.boardRows.map(function(t){t.map(function(t){t.disableClickEvents()})})}},{key:"enableBoardInput",value:function(){this.boardRows.map(function(t){t.map(function(t){t.enableClickEvents()})})}},{key:"gameOver",value:function(){this.disableBoardInput(),this.scoreBoard.text="Game Over\nFinal Score: "+this.playerScore,h.a.post("/user/score/new",{score:this.playerScore}).then(function(t){alert("Thanks for playing!"),window.location.replace("/profile")}).catch(function(t){console.log(t)})}}]),t}();e.a=u},function(t,e,i){"use strict";function s(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function r(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}var o=i(19),a=i(55),h=function(){function t(t,e){for(var i=0;i<e.length;i++){var s=e[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(t,s.key,s)}}return function(e,i,s){return i&&t(e.prototype,i),s&&t(e,s),e}}(),l=function(t){function e(t,r,o,h,l){s(this,e);var c=n(this,(e.__proto__||Object.getPrototypeOf(e)).call(this,t,r,o,h,l));return c.effect=i.i(a.a)(c.color),c}return r(e,t),h(e,[{key:"applyEffect",value:function(t){this.effect(t)}}]),e}(o.a);e.a=l},function(t,e,i){"use strict";function s(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function r(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}var o=i(5),a=i(56),h=function(){function t(t,e){for(var i=0;i<e.length;i++){var s=e[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(t,s.key,s)}}return function(e,i,s){return i&&t(e.prototype,i),s&&t(e,s),e}}(),l=(o.a.SCREENWIDTH,o.a.SCREENHEIGHT,o.a.SCALERATIO),c=function(t){function e(){return s(this,e),n(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return r(e,t),h(e,[{key:"create",value:function(){this.game.scale.fullScreenScaleMode=Phaser.ScaleManager.SHOW_ALL,this.game.scale.scaleMode=Phaser.ScaleManager.SHOW_ALL,this.game.scale.refresh(),this.game.forceSingleUpdate=!0,this.myBoard=new a.a(this.game,l,this.game.world.centerX,this.game.world.centerY)}}]),e}(Phaser.State);e.a=c},function(t,e,i){"use strict";function s(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function r(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}var o=i(5),a=i(84),h=i.n(a),l=i(82),c=i.n(l),u=i(83),d=i.n(u),p=i(85),f=i.n(p),g=function(){function t(t,e){for(var i=0;i<e.length;i++){var s=e[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(t,s.key,s)}}return function(e,i,s){return i&&t(e.prototype,i),s&&t(e,s),e}}(),m=function(t){function e(){return s(this,e),n(this,(e.__proto__||Object.getPrototypeOf(e)).apply(this,arguments))}return r(e,t),g(e,[{key:"preload",value:function(){var t=this;this.load.onLoadComplete.addOnce(function(){return t.ready=!0}),this.loadResources()}},{key:"create",value:function(){this.stage.backgroundColor=o.b.DARKBLUE,this.game.add.text(this.game.world.centerX,this.game.world.centerY,"Loading ...",{fill:"#fff",align:"center",fontSize:50*o.a.SCALERATIO}).anchor.set(.5)}},{key:"loadResources",value:function(){this.game.load.spritesheet("bricks",h.a,o.a.BRICKSIZE,o.a.BRICKSIZE,11),this.game.load.image("settingsIcon",f.a),this.game.load.audio("brickDestroy",c.a),this.game.load.audio("gameMusic",d.a)}},{key:"update",value:function(){this.ready&&this.game.state.start("Main")}}]),e}(Phaser.State);e.a=m},function(t,e,i){"use strict";var s=i(58),n=i(59);i.d(e,"b",function(){return s.a}),i.d(e,"a",function(){return n.a})},,,function(t,e,i){"use strict";function s(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");return"="===t[e-2]?2:"="===t[e-1]?1:0}function n(t){return 3*t.length/4-s(t)}function r(t){var e,i,n,r,o,a,h=t.length;o=s(t),a=new u(3*h/4-o),n=o>0?h-4:h;var l=0;for(e=0,i=0;e<n;e+=4,i+=3)r=c[t.charCodeAt(e)]<<18|c[t.charCodeAt(e+1)]<<12|c[t.charCodeAt(e+2)]<<6|c[t.charCodeAt(e+3)],a[l++]=r>>16&255,a[l++]=r>>8&255,a[l++]=255&r;return 2===o?(r=c[t.charCodeAt(e)]<<2|c[t.charCodeAt(e+1)]>>4,a[l++]=255&r):1===o&&(r=c[t.charCodeAt(e)]<<10|c[t.charCodeAt(e+1)]<<4|c[t.charCodeAt(e+2)]>>2,a[l++]=r>>8&255,a[l++]=255&r),a}function o(t){return l[t>>18&63]+l[t>>12&63]+l[t>>6&63]+l[63&t]}function a(t,e,i){for(var s,n=[],r=e;r<i;r+=3)s=(t[r]<<16)+(t[r+1]<<8)+t[r+2],n.push(o(s));return n.join("")}function h(t){for(var e,i=t.length,s=i%3,n="",r=[],o=0,h=i-s;o<h;o+=16383)r.push(a(t,o,o+16383>h?h:o+16383));return 1===s?(e=t[i-1],n+=l[e>>2],n+=l[e<<4&63],n+="=="):2===s&&(e=(t[i-2]<<8)+t[i-1],n+=l[e>>10],n+=l[e>>4&63],n+=l[e<<2&63],n+="="),r.push(n),r.join("")}e.byteLength=n,e.toByteArray=r,e.fromByteArray=h;for(var l=[],c=[],u="undefined"!=typeof Uint8Array?Uint8Array:Array,d="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",p=0,f=d.length;p<f;++p)l[p]=d[p],c[d.charCodeAt(p)]=p;c["-".charCodeAt(0)]=62,c["_".charCodeAt(0)]=63},,function(t,e,i){"use strict";(function(t){function s(){return r.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function n(t,e){if(s()<e)throw new RangeError("Invalid typed array length");return r.TYPED_ARRAY_SUPPORT?(t=new Uint8Array(e),t.__proto__=r.prototype):(null===t&&(t=new r(e)),t.length=e),t}function r(t,e,i){if(!(r.TYPED_ARRAY_SUPPORT||this instanceof r))return new r(t,e,i);if("number"==typeof t){if("string"==typeof e)throw new Error("If encoding is specified then the first argument must be a string");return l(this,t)}return o(this,t,e,i)}function o(t,e,i,s){if("number"==typeof e)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer?d(t,e,i,s):"string"==typeof e?c(t,e,i):p(t,e)}function a(t){if("number"!=typeof t)throw new TypeError('"size" argument must be a number');if(t<0)throw new RangeError('"size" argument must not be negative')}function h(t,e,i,s){return a(e),e<=0?n(t,e):void 0!==i?"string"==typeof s?n(t,e).fill(i,s):n(t,e).fill(i):n(t,e)}function l(t,e){if(a(e),t=n(t,e<0?0:0|f(e)),!r.TYPED_ARRAY_SUPPORT)for(var i=0;i<e;++i)t[i]=0;return t}function c(t,e,i){if("string"==typeof i&&""!==i||(i="utf8"),!r.isEncoding(i))throw new TypeError('"encoding" must be a valid string encoding');var s=0|m(e,i);t=n(t,s);var o=t.write(e,i);return o!==s&&(t=t.slice(0,o)),t}function u(t,e){var i=e.length<0?0:0|f(e.length);t=n(t,i);for(var s=0;s<i;s+=1)t[s]=255&e[s];return t}function d(t,e,i,s){if(e.byteLength,i<0||e.byteLength<i)throw new RangeError("'offset' is out of bounds");if(e.byteLength<i+(s||0))throw new RangeError("'length' is out of bounds");return e=void 0===i&&void 0===s?new Uint8Array(e):void 0===s?new Uint8Array(e,i):new Uint8Array(e,i,s),r.TYPED_ARRAY_SUPPORT?(t=e,t.__proto__=r.prototype):t=u(t,e),t}function p(t,e){if(r.isBuffer(e)){var i=0|f(e.length);return t=n(t,i),0===t.length?t:(e.copy(t,0,0,i),t)}if(e){if("undefined"!=typeof ArrayBuffer&&e.buffer instanceof ArrayBuffer||"length"in e)return"number"!=typeof e.length||K(e.length)?n(t,0):u(t,e);if("Buffer"===e.type&&Z(e.data))return u(t,e.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}function f(t){if(t>=s())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s().toString(16)+" bytes");return 0|t}function g(t){return+t!=t&&(t=0),r.alloc(+t)}function m(t,e){if(r.isBuffer(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var i=t.length;if(0===i)return 0;for(var s=!1;;)switch(e){case"ascii":case"latin1":case"binary":return i;case"utf8":case"utf-8":case void 0:return V(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*i;case"hex":return i>>>1;case"base64":return Y(t).length;default:if(s)return V(t).length;e=(""+e).toLowerCase(),s=!0}}function y(t,e,i){var s=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===i||i>this.length)&&(i=this.length),i<=0)return"";if(i>>>=0,e>>>=0,i<=e)return"";for(t||(t="utf8");;)switch(t){case"hex":return B(this,e,i);case"utf8":case"utf-8":return E(this,e,i);case"ascii":return M(this,e,i);case"latin1":case"binary":return R(this,e,i);case"base64":return A(this,e,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return L(this,e,i);default:if(s)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),s=!0}}function v(t,e,i){var s=t[e];t[e]=t[i],t[i]=s}function b(t,e,i,s,n){if(0===t.length)return-1;if("string"==typeof i?(s=i,i=0):i>2147483647?i=2147483647:i<-2147483648&&(i=-2147483648),i=+i,isNaN(i)&&(i=n?0:t.length-1),i<0&&(i=t.length+i),i>=t.length){if(n)return-1;i=t.length-1}else if(i<0){if(!n)return-1;i=0}if("string"==typeof e&&(e=r.from(e,s)),r.isBuffer(e))return 0===e.length?-1:x(t,e,i,s,n);if("number"==typeof e)return e&=255,r.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?n?Uint8Array.prototype.indexOf.call(t,e,i):Uint8Array.prototype.lastIndexOf.call(t,e,i):x(t,[e],i,s,n);throw new TypeError("val must be string, number or Buffer")}function x(t,e,i,s,n){function r(t,e){return 1===o?t[e]:t.readUInt16BE(e*o)}var o=1,a=t.length,h=e.length;if(void 0!==s&&("ucs2"===(s=String(s).toLowerCase())||"ucs-2"===s||"utf16le"===s||"utf-16le"===s)){if(t.length<2||e.length<2)return-1;o=2,a/=2,h/=2,i/=2}var l;if(n){var c=-1;for(l=i;l<a;l++)if(r(t,l)===r(e,-1===c?0:l-c)){if(-1===c&&(c=l),l-c+1===h)return c*o}else-1!==c&&(l-=l-c),c=-1}else for(i+h>a&&(i=a-h),l=i;l>=0;l--){for(var u=!0,d=0;d<h;d++)if(r(t,l+d)!==r(e,d)){u=!1;break}if(u)return l}return-1}function w(t,e,i,s){i=Number(i)||0;var n=t.length-i;s?(s=Number(s))>n&&(s=n):s=n;var r=e.length;if(r%2!=0)throw new TypeError("Invalid hex string");s>r/2&&(s=r/2);for(var o=0;o<s;++o){var a=parseInt(e.substr(2*o,2),16);if(isNaN(a))return o;t[i+o]=a}return o}function _(t,e,i,s){return z(V(e,t.length-i),t,i,s)}function P(t,e,i,s){return z(q(e),t,i,s)}function T(t,e,i,s){return P(t,e,i,s)}function C(t,e,i,s){return z(Y(e),t,i,s)}function S(t,e,i,s){return z(H(e,t.length-i),t,i,s)}function A(t,e,i){return 0===e&&i===t.length?J.fromByteArray(t):J.fromByteArray(t.slice(e,i))}function E(t,e,i){i=Math.min(t.length,i);for(var s=[],n=e;n<i;){var r=t[n],o=null,a=r>239?4:r>223?3:r>191?2:1;if(n+a<=i){var h,l,c,u;switch(a){case 1:r<128&&(o=r);break;case 2:h=t[n+1],128==(192&h)&&(u=(31&r)<<6|63&h)>127&&(o=u);break;case 3:h=t[n+1],l=t[n+2],128==(192&h)&&128==(192&l)&&(u=(15&r)<<12|(63&h)<<6|63&l)>2047&&(u<55296||u>57343)&&(o=u);break;case 4:h=t[n+1],l=t[n+2],c=t[n+3],128==(192&h)&&128==(192&l)&&128==(192&c)&&(u=(15&r)<<18|(63&h)<<12|(63&l)<<6|63&c)>65535&&u<1114112&&(o=u)}}null===o?(o=65533,a=1):o>65535&&(o-=65536,s.push(o>>>10&1023|55296),o=56320|1023&o),s.push(o),n+=a}return I(s)}function I(t){var e=t.length;if(e<=$)return String.fromCharCode.apply(String,t);for(var i="",s=0;s<e;)i+=String.fromCharCode.apply(String,t.slice(s,s+=$));return i}function M(t,e,i){var s="";i=Math.min(t.length,i);for(var n=e;n<i;++n)s+=String.fromCharCode(127&t[n]);return s}function R(t,e,i){var s="";i=Math.min(t.length,i);for(var n=e;n<i;++n)s+=String.fromCharCode(t[n]);return s}function B(t,e,i){var s=t.length;(!e||e<0)&&(e=0),(!i||i<0||i>s)&&(i=s);for(var n="",r=e;r<i;++r)n+=j(t[r]);return n}function L(t,e,i){for(var s=t.slice(e,i),n="",r=0;r<s.length;r+=2)n+=String.fromCharCode(s[r]+256*s[r+1]);return n}function k(t,e,i){if(t%1!=0||t<0)throw new RangeError("offset is not uint");if(t+e>i)throw new RangeError("Trying to access beyond buffer length")}function O(t,e,i,s,n,o){if(!r.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>n||e<o)throw new RangeError('"value" argument is out of bounds');if(i+s>t.length)throw new RangeError("Index out of range")}function F(t,e,i,s){e<0&&(e=65535+e+1);for(var n=0,r=Math.min(t.length-i,2);n<r;++n)t[i+n]=(e&255<<8*(s?n:1-n))>>>8*(s?n:1-n)}function D(t,e,i,s){e<0&&(e=4294967295+e+1);for(var n=0,r=Math.min(t.length-i,4);n<r;++n)t[i+n]=e>>>8*(s?n:3-n)&255}function U(t,e,i,s,n,r){if(i+s>t.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("Index out of range")}function G(t,e,i,s,n){return n||U(t,e,i,4,3.4028234663852886e38,-3.4028234663852886e38),Q.write(t,e,i,s,23,4),i+4}function N(t,e,i,s,n){return n||U(t,e,i,8,1.7976931348623157e308,-1.7976931348623157e308),Q.write(t,e,i,s,52,8),i+8}function X(t){if(t=W(t).replace(tt,""),t.length<2)return"";for(;t.length%4!=0;)t+="=";return t}function W(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function j(t){return t<16?"0"+t.toString(16):t.toString(16)}function V(t,e){e=e||1/0;for(var i,s=t.length,n=null,r=[],o=0;o<s;++o){if((i=t.charCodeAt(o))>55295&&i<57344){if(!n){if(i>56319){(e-=3)>-1&&r.push(239,191,189);continue}if(o+1===s){(e-=3)>-1&&r.push(239,191,189);continue}n=i;continue}if(i<56320){(e-=3)>-1&&r.push(239,191,189),n=i;continue}i=65536+(n-55296<<10|i-56320)}else n&&(e-=3)>-1&&r.push(239,191,189);if(n=null,i<128){if((e-=1)<0)break;r.push(i)}else if(i<2048){if((e-=2)<0)break;r.push(i>>6|192,63&i|128)}else if(i<65536){if((e-=3)<0)break;r.push(i>>12|224,i>>6&63|128,63&i|128)}else{if(!(i<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;r.push(i>>18|240,i>>12&63|128,i>>6&63|128,63&i|128)}}return r}function q(t){for(var e=[],i=0;i<t.length;++i)e.push(255&t.charCodeAt(i));return e}function H(t,e){for(var i,s,n,r=[],o=0;o<t.length&&!((e-=2)<0);++o)i=t.charCodeAt(o),s=i>>8,n=i%256,r.push(n),r.push(s);return r}function Y(t){return J.toByteArray(X(t))}function z(t,e,i,s){for(var n=0;n<s&&!(n+i>=e.length||n>=t.length);++n)e[n+i]=t[n];return n}function K(t){return t!==t}/*!
<ide> * The buffer module from node.js, for the browser.
<ide> *
<ide> * @author Feross Aboukhadijeh <[email protected]> <http://feross.org>
<ide> * @license MIT
<ide> */
<del>var J=i(63),Q=i(87),Z=i(66);e.Buffer=r,e.SlowBuffer=g,e.INSPECT_MAX_BYTES=50,r.TYPED_ARRAY_SUPPORT=void 0!==t.TYPED_ARRAY_SUPPORT?t.TYPED_ARRAY_SUPPORT:function(){try{var t=new Uint8Array(1);return t.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===t.foo()&&"function"==typeof t.subarray&&0===t.subarray(1,1).byteLength}catch(t){return!1}}(),e.kMaxLength=s(),r.poolSize=8192,r._augment=function(t){return t.__proto__=r.prototype,t},r.from=function(t,e,i){return o(null,t,e,i)},r.TYPED_ARRAY_SUPPORT&&(r.prototype.__proto__=Uint8Array.prototype,r.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&r[Symbol.species]===r&&Object.defineProperty(r,Symbol.species,{value:null,configurable:!0})),r.alloc=function(t,e,i){return h(null,t,e,i)},r.allocUnsafe=function(t){return l(null,t)},r.allocUnsafeSlow=function(t){return l(null,t)},r.isBuffer=function(t){return!(null==t||!t._isBuffer)},r.compare=function(t,e){if(!r.isBuffer(t)||!r.isBuffer(e))throw new TypeError("Arguments must be Buffers");if(t===e)return 0;for(var i=t.length,s=e.length,n=0,o=Math.min(i,s);n<o;++n)if(t[n]!==e[n]){i=t[n],s=e[n];break}return i<s?-1:s<i?1:0},r.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},r.concat=function(t,e){if(!Z(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return r.alloc(0);var i;if(void 0===e)for(e=0,i=0;i<t.length;++i)e+=t[i].length;var s=r.allocUnsafe(e),n=0;for(i=0;i<t.length;++i){var o=t[i];if(!r.isBuffer(o))throw new TypeError('"list" argument must be an Array of Buffers');o.copy(s,n),n+=o.length}return s},r.byteLength=m,r.prototype._isBuffer=!0,r.prototype.swap16=function(){var t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var e=0;e<t;e+=2)v(this,e,e+1);return this},r.prototype.swap32=function(){var t=this.length;if(t%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var e=0;e<t;e+=4)v(this,e,e+3),v(this,e+1,e+2);return this},r.prototype.swap64=function(){var t=this.length;if(t%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var e=0;e<t;e+=8)v(this,e,e+7),v(this,e+1,e+6),v(this,e+2,e+5),v(this,e+3,e+4);return this},r.prototype.toString=function(){var t=0|this.length;return 0===t?"":0===arguments.length?E(this,0,t):y.apply(this,arguments)},r.prototype.equals=function(t){if(!r.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===r.compare(this,t)},r.prototype.inspect=function(){var t="",i=e.INSPECT_MAX_BYTES;return this.length>0&&(t=this.toString("hex",0,i).match(/.{2}/g).join(" "),this.length>i&&(t+=" ... ")),"<Buffer "+t+">"},r.prototype.compare=function(t,e,i,s,n){if(!r.isBuffer(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===i&&(i=t?t.length:0),void 0===s&&(s=0),void 0===n&&(n=this.length),e<0||i>t.length||s<0||n>this.length)throw new RangeError("out of range index");if(s>=n&&e>=i)return 0;if(s>=n)return-1;if(e>=i)return 1;if(e>>>=0,i>>>=0,s>>>=0,n>>>=0,this===t)return 0;for(var o=n-s,a=i-e,h=Math.min(o,a),l=this.slice(s,n),c=t.slice(e,i),u=0;u<h;++u)if(l[u]!==c[u]){o=l[u],a=c[u];break}return o<a?-1:a<o?1:0},r.prototype.includes=function(t,e,i){return-1!==this.indexOf(t,e,i)},r.prototype.indexOf=function(t,e,i){return b(this,t,e,i,!0)},r.prototype.lastIndexOf=function(t,e,i){return b(this,t,e,i,!1)},r.prototype.write=function(t,e,i,s){if(void 0===e)s="utf8",i=this.length,e=0;else if(void 0===i&&"string"==typeof e)s=e,i=this.length,e=0;else{if(!isFinite(e))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");e|=0,isFinite(i)?(i|=0,void 0===s&&(s="utf8")):(s=i,i=void 0)}var n=this.length-e;if((void 0===i||i>n)&&(i=n),t.length>0&&(i<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");s||(s="utf8");for(var r=!1;;)switch(s){case"hex":return w(this,t,e,i);case"utf8":case"utf-8":return _(this,t,e,i);case"ascii":return P(this,t,e,i);case"latin1":case"binary":return T(this,t,e,i);case"base64":return C(this,t,e,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,t,e,i);default:if(r)throw new TypeError("Unknown encoding: "+s);s=(""+s).toLowerCase(),r=!0}},r.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var $=4096;r.prototype.slice=function(t,e){var i=this.length;t=~~t,e=void 0===e?i:~~e,t<0?(t+=i)<0&&(t=0):t>i&&(t=i),e<0?(e+=i)<0&&(e=0):e>i&&(e=i),e<t&&(e=t);var s;if(r.TYPED_ARRAY_SUPPORT)s=this.subarray(t,e),s.__proto__=r.prototype;else{var n=e-t;s=new r(n,void 0);for(var o=0;o<n;++o)s[o]=this[o+t]}return s},r.prototype.readUIntLE=function(t,e,i){t|=0,e|=0,i||O(t,e,this.length);for(var s=this[t],n=1,r=0;++r<e&&(n*=256);)s+=this[t+r]*n;return s},r.prototype.readUIntBE=function(t,e,i){t|=0,e|=0,i||O(t,e,this.length);for(var s=this[t+--e],n=1;e>0&&(n*=256);)s+=this[t+--e]*n;return s},r.prototype.readUInt8=function(t,e){return e||O(t,1,this.length),this[t]},r.prototype.readUInt16LE=function(t,e){return e||O(t,2,this.length),this[t]|this[t+1]<<8},r.prototype.readUInt16BE=function(t,e){return e||O(t,2,this.length),this[t]<<8|this[t+1]},r.prototype.readUInt32LE=function(t,e){return e||O(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},r.prototype.readUInt32BE=function(t,e){return e||O(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},r.prototype.readIntLE=function(t,e,i){t|=0,e|=0,i||O(t,e,this.length);for(var s=this[t],n=1,r=0;++r<e&&(n*=256);)s+=this[t+r]*n;return n*=128,s>=n&&(s-=Math.pow(2,8*e)),s},r.prototype.readIntBE=function(t,e,i){t|=0,e|=0,i||O(t,e,this.length);for(var s=e,n=1,r=this[t+--s];s>0&&(n*=256);)r+=this[t+--s]*n;return n*=128,r>=n&&(r-=Math.pow(2,8*e)),r},r.prototype.readInt8=function(t,e){return e||O(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},r.prototype.readInt16LE=function(t,e){e||O(t,2,this.length);var i=this[t]|this[t+1]<<8;return 32768&i?4294901760|i:i},r.prototype.readInt16BE=function(t,e){e||O(t,2,this.length);var i=this[t+1]|this[t]<<8;return 32768&i?4294901760|i:i},r.prototype.readInt32LE=function(t,e){return e||O(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},r.prototype.readInt32BE=function(t,e){return e||O(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},r.prototype.readFloatLE=function(t,e){return e||O(t,4,this.length),Q.read(this,t,!0,23,4)},r.prototype.readFloatBE=function(t,e){return e||O(t,4,this.length),Q.read(this,t,!1,23,4)},r.prototype.readDoubleLE=function(t,e){return e||O(t,8,this.length),Q.read(this,t,!0,52,8)},r.prototype.readDoubleBE=function(t,e){return e||O(t,8,this.length),Q.read(this,t,!1,52,8)},r.prototype.writeUIntLE=function(t,e,i,s){if(t=+t,e|=0,i|=0,!s){k(this,t,e,i,Math.pow(2,8*i)-1,0)}var n=1,r=0;for(this[e]=255&t;++r<i&&(n*=256);)this[e+r]=t/n&255;return e+i},r.prototype.writeUIntBE=function(t,e,i,s){if(t=+t,e|=0,i|=0,!s){k(this,t,e,i,Math.pow(2,8*i)-1,0)}var n=i-1,r=1;for(this[e+n]=255&t;--n>=0&&(r*=256);)this[e+n]=t/r&255;return e+i},r.prototype.writeUInt8=function(t,e,i){return t=+t,e|=0,i||k(this,t,e,1,255,0),r.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},r.prototype.writeUInt16LE=function(t,e,i){return t=+t,e|=0,i||k(this,t,e,2,65535,0),r.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):F(this,t,e,!0),e+2},r.prototype.writeUInt16BE=function(t,e,i){return t=+t,e|=0,i||k(this,t,e,2,65535,0),r.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):F(this,t,e,!1),e+2},r.prototype.writeUInt32LE=function(t,e,i){return t=+t,e|=0,i||k(this,t,e,4,4294967295,0),r.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):D(this,t,e,!0),e+4},r.prototype.writeUInt32BE=function(t,e,i){return t=+t,e|=0,i||k(this,t,e,4,4294967295,0),r.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):D(this,t,e,!1),e+4},r.prototype.writeIntLE=function(t,e,i,s){if(t=+t,e|=0,!s){var n=Math.pow(2,8*i-1);k(this,t,e,i,n-1,-n)}var r=0,o=1,a=0;for(this[e]=255&t;++r<i&&(o*=256);)t<0&&0===a&&0!==this[e+r-1]&&(a=1),this[e+r]=(t/o>>0)-a&255;return e+i},r.prototype.writeIntBE=function(t,e,i,s){if(t=+t,e|=0,!s){var n=Math.pow(2,8*i-1);k(this,t,e,i,n-1,-n)}var r=i-1,o=1,a=0;for(this[e+r]=255&t;--r>=0&&(o*=256);)t<0&&0===a&&0!==this[e+r+1]&&(a=1),this[e+r]=(t/o>>0)-a&255;return e+i},r.prototype.writeInt8=function(t,e,i){return t=+t,e|=0,i||k(this,t,e,1,127,-128),r.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[e]=255&t,e+1},r.prototype.writeInt16LE=function(t,e,i){return t=+t,e|=0,i||k(this,t,e,2,32767,-32768),r.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):F(this,t,e,!0),e+2},r.prototype.writeInt16BE=function(t,e,i){return t=+t,e|=0,i||k(this,t,e,2,32767,-32768),r.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):F(this,t,e,!1),e+2},r.prototype.writeInt32LE=function(t,e,i){return t=+t,e|=0,i||k(this,t,e,4,2147483647,-2147483648),r.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):D(this,t,e,!0),e+4},r.prototype.writeInt32BE=function(t,e,i){return t=+t,e|=0,i||k(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),r.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):D(this,t,e,!1),e+4},r.prototype.writeFloatLE=function(t,e,i){return G(this,t,e,!0,i)},r.prototype.writeFloatBE=function(t,e,i){return G(this,t,e,!1,i)},r.prototype.writeDoubleLE=function(t,e,i){return N(this,t,e,!0,i)},r.prototype.writeDoubleBE=function(t,e,i){return N(this,t,e,!1,i)},r.prototype.copy=function(t,e,i,s){if(i||(i=0),s||0===s||(s=this.length),e>=t.length&&(e=t.length),e||(e=0),s>0&&s<i&&(s=i),s===i)return 0;if(0===t.length||0===this.length)return 0;if(e<0)throw new RangeError("targetStart out of bounds");if(i<0||i>=this.length)throw new RangeError("sourceStart out of bounds");if(s<0)throw new RangeError("sourceEnd out of bounds");s>this.length&&(s=this.length),t.length-e<s-i&&(s=t.length-e+i);var n,o=s-i;if(this===t&&i<e&&e<s)for(n=o-1;n>=0;--n)t[n+e]=this[n+i];else if(o<1e3||!r.TYPED_ARRAY_SUPPORT)for(n=0;n<o;++n)t[n+e]=this[n+i];else Uint8Array.prototype.set.call(t,this.subarray(i,i+o),e);return o},r.prototype.fill=function(t,e,i,s){if("string"==typeof t){if("string"==typeof e?(s=e,e=0,i=this.length):"string"==typeof i&&(s=i,i=this.length),1===t.length){var n=t.charCodeAt(0);n<256&&(t=n)}if(void 0!==s&&"string"!=typeof s)throw new TypeError("encoding must be a string");if("string"==typeof s&&!r.isEncoding(s))throw new TypeError("Unknown encoding: "+s)}else"number"==typeof t&&(t&=255);if(e<0||this.length<e||this.length<i)throw new RangeError("Out of range index");if(i<=e)return this;e>>>=0,i=void 0===i?this.length:i>>>0,t||(t=0);var o;if("number"==typeof t)for(o=e;o<i;++o)this[o]=t;else{var a=r.isBuffer(t)?t:V(new r(t,s).toString()),h=a.length;for(o=0;o<i-e;++o)this[o+e]=a[o%h]}return this};var tt=/[^+\/0-9A-Za-z-_]/g}).call(e,i(0))},function(t,e){var i={}.toString;t.exports=Array.isArray||function(t){return"[object Array]"==i.call(t)}},,,,,,,,,,,,,function(t,e,i){(function(e){t.exports=e.PIXI=i(92)}).call(e,i(0))},function(t,e,i){(function(e){t.exports=e.Phaser=i(91)}).call(e,i(0))},function(t,e,i){(function(e){t.exports=e.p2=i(90)}).call(e,i(0))},function(t,e,i){t.exports=i.p+"js/game/src/assets/sounds/brick_destroy.wav"},function(t,e,i){t.exports=i.p+"js/game/src/assets/sounds/game_music.wav"},function(t,e,i){t.exports=i.p+"js/game/src/assets/sprites/bricksScaled720X240.png"},function(t,e,i){t.exports=i.p+"js/game/src/assets/sprites/settings-50.png"},,function(t,e){e.read=function(t,e,i,s,n){var r,o,a=8*n-s-1,h=(1<<a)-1,l=h>>1,c=-7,u=i?n-1:0,d=i?-1:1,p=t[e+u];for(u+=d,r=p&(1<<-c)-1,p>>=-c,c+=a;c>0;r=256*r+t[e+u],u+=d,c-=8);for(o=r&(1<<-c)-1,r>>=-c,c+=s;c>0;o=256*o+t[e+u],u+=d,c-=8);if(0===r)r=1-l;else{if(r===h)return o?NaN:1/0*(p?-1:1);o+=Math.pow(2,s),r-=l}return(p?-1:1)*o*Math.pow(2,r-s)},e.write=function(t,e,i,s,n,r){var o,a,h,l=8*r-n-1,c=(1<<l)-1,u=c>>1,d=23===n?Math.pow(2,-24)-Math.pow(2,-77):0,p=s?0:r-1,f=s?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=c):(o=Math.floor(Math.log(e)/Math.LN2),e*(h=Math.pow(2,-o))<1&&(o--,h*=2),e+=o+u>=1?d/h:d*Math.pow(2,1-u),e*h>=2&&(o++,h/=2),o+u>=c?(a=0,o=c):o+u>=1?(a=(e*h-1)*Math.pow(2,n),o+=u):(a=e*Math.pow(2,u-1)*Math.pow(2,n),o=0));n>=8;t[i+p]=255&a,p+=f,a/=256,n-=8);for(o=o<<n|a,l+=n;l>0;t[i+p]=255&o,p+=f,o/=256,l-=8);t[i+p-f]|=128*g}},,,function(t,e,i){var s,s;!function(e){t.exports=e()}(function(){return function t(e,i,n){function r(a,h){if(!i[a]){if(!e[a]){var l="function"==typeof s&&s;if(!h&&l)return s(a,!0);if(o)return s(a,!0);throw new Error("Cannot find module '"+a+"'")}var c=i[a]={exports:{}};e[a][0].call(c.exports,function(t){var i=e[a][1][t];return r(i||t)},c,c.exports,t,e,i,n)}return i[a].exports}for(var o="function"==typeof s&&s,a=0;a<n.length;a++)r(n[a]);return r}({1:[function(t,e,i){function s(){}var n=t("./Scalar");e.exports=s,s.lineInt=function(t,e,i){i=i||0;var s,r,o,a,h,l,c,u=[0,0];return s=t[1][1]-t[0][1],r=t[0][0]-t[1][0],o=s*t[0][0]+r*t[0][1],a=e[1][1]-e[0][1],h=e[0][0]-e[1][0],l=a*e[0][0]+h*e[0][1],c=s*h-a*r,n.eq(c,0,i)||(u[0]=(h*o-r*l)/c,u[1]=(s*l-a*o)/c),u},s.segmentsIntersect=function(t,e,i,s){var n=e[0]-t[0],r=e[1]-t[1],o=s[0]-i[0],a=s[1]-i[1];if(o*r-a*n==0)return!1;var h=(n*(i[1]-t[1])+r*(t[0]-i[0]))/(o*r-a*n),l=(o*(t[1]-i[1])+a*(i[0]-t[0]))/(a*n-o*r);return h>=0&&h<=1&&l>=0&&l<=1}},{"./Scalar":4}],2:[function(t,e,i){function s(){}e.exports=s,s.area=function(t,e,i){return(e[0]-t[0])*(i[1]-t[1])-(i[0]-t[0])*(e[1]-t[1])},s.left=function(t,e,i){return s.area(t,e,i)>0},s.leftOn=function(t,e,i){return s.area(t,e,i)>=0},s.right=function(t,e,i){return s.area(t,e,i)<0},s.rightOn=function(t,e,i){return s.area(t,e,i)<=0};var n=[],r=[];s.collinear=function(t,e,i,o){if(o){var a=n,h=r;a[0]=e[0]-t[0],a[1]=e[1]-t[1],h[0]=i[0]-e[0],h[1]=i[1]-e[1];var l=a[0]*h[0]+a[1]*h[1],c=Math.sqrt(a[0]*a[0]+a[1]*a[1]),u=Math.sqrt(h[0]*h[0]+h[1]*h[1]);return Math.acos(l/(c*u))<o}return 0==s.area(t,e,i)},s.sqdist=function(t,e){var i=e[0]-t[0],s=e[1]-t[1];return i*i+s*s}},{}],3:[function(t,e,i){function s(){this.vertices=[]}function n(t,e,i,s,n){n=n||0;var r=e[1]-t[1],o=t[0]-e[0],h=r*t[0]+o*t[1],l=s[1]-i[1],c=i[0]-s[0],u=l*i[0]+c*i[1],d=r*c-l*o;return a.eq(d,0,n)?[0,0]:[(c*h-o*u)/d,(r*u-l*h)/d]}var r=t("./Line"),o=t("./Point"),a=t("./Scalar");e.exports=s,s.prototype.at=function(t){var e=this.vertices,i=e.length;return e[t<0?t%i+i:t%i]},s.prototype.first=function(){return this.vertices[0]},s.prototype.last=function(){return this.vertices[this.vertices.length-1]},s.prototype.clear=function(){this.vertices.length=0},s.prototype.append=function(t,e,i){if(void 0===e)throw new Error("From is not given!");if(void 0===i)throw new Error("To is not given!");if(i-1<e)throw new Error("lol1");if(i>t.vertices.length)throw new Error("lol2");if(e<0)throw new Error("lol3");for(var s=e;s<i;s++)this.vertices.push(t.vertices[s])},s.prototype.makeCCW=function(){for(var t=0,e=this.vertices,i=1;i<this.vertices.length;++i)(e[i][1]<e[t][1]||e[i][1]==e[t][1]&&e[i][0]>e[t][0])&&(t=i);o.left(this.at(t-1),this.at(t),this.at(t+1))||this.reverse()},s.prototype.reverse=function(){for(var t=[],e=0,i=this.vertices.length;e!==i;e++)t.push(this.vertices.pop());this.vertices=t},s.prototype.isReflex=function(t){return o.right(this.at(t-1),this.at(t),this.at(t+1))};var h=[],l=[];s.prototype.canSee=function(t,e){var i,s,n=h,a=l;if(o.leftOn(this.at(t+1),this.at(t),this.at(e))&&o.rightOn(this.at(t-1),this.at(t),this.at(e)))return!1;s=o.sqdist(this.at(t),this.at(e));for(var c=0;c!==this.vertices.length;++c)if((c+1)%this.vertices.length!==t&&c!==t&&o.leftOn(this.at(t),this.at(e),this.at(c+1))&&o.rightOn(this.at(t),this.at(e),this.at(c))&&(n[0]=this.at(t),n[1]=this.at(e),a[0]=this.at(c),a[1]=this.at(c+1),i=r.lineInt(n,a),o.sqdist(this.at(t),i)<s))return!1;return!0},s.prototype.copy=function(t,e,i){var n=i||new s;if(n.clear(),t<e)for(var r=t;r<=e;r++)n.vertices.push(this.vertices[r]);else{for(var r=0;r<=e;r++)n.vertices.push(this.vertices[r]);for(var r=t;r<this.vertices.length;r++)n.vertices.push(this.vertices[r])}return n},s.prototype.getCutEdges=function(){for(var t=[],e=[],i=[],n=new s,r=Number.MAX_VALUE,o=0;o<this.vertices.length;++o)if(this.isReflex(o))for(var a=0;a<this.vertices.length;++a)if(this.canSee(o,a)){e=this.copy(o,a,n).getCutEdges(),i=this.copy(a,o,n).getCutEdges();for(var h=0;h<i.length;h++)e.push(i[h]);e.length<r&&(t=e,r=e.length,t.push([this.at(o),this.at(a)]))}return t},s.prototype.decomp=function(){var t=this.getCutEdges();return t.length>0?this.slice(t):[this]},s.prototype.slice=function(t){if(0==t.length)return[this];if(t instanceof Array&&t.length&&t[0]instanceof Array&&2==t[0].length&&t[0][0]instanceof Array){for(var e=[this],i=0;i<t.length;i++)for(var s=t[i],n=0;n<e.length;n++){var r=e[n],o=r.slice(s);if(o){e.splice(n,1),e.push(o[0],o[1]);break}}return e}var s=t,i=this.vertices.indexOf(s[0]),n=this.vertices.indexOf(s[1]);return-1!=i&&-1!=n&&[this.copy(i,n),this.copy(n,i)]},s.prototype.isSimple=function(){for(var t=this.vertices,e=0;e<t.length-1;e++)for(var i=0;i<e-1;i++)if(r.segmentsIntersect(t[e],t[e+1],t[i],t[i+1]))return!1;for(var e=1;e<t.length-2;e++)if(r.segmentsIntersect(t[0],t[t.length-1],t[e],t[e+1]))return!1;return!0},s.prototype.quickDecomp=function(t,e,i,r,a,h){a=a||100,h=h||0,r=r||25,t=void 0!==t?t:[],e=e||[],i=i||[];var l=[0,0],c=[0,0],u=[0,0],d=0,p=0,f=0,g=0,m=0,y=0,v=0,b=new s,x=new s,w=this,_=this.vertices;if(_.length<3)return t;if(++h>a)return console.warn("quickDecomp: max level ("+a+") reached."),t;for(var P=0;P<this.vertices.length;++P)if(w.isReflex(P)){e.push(w.vertices[P]),d=p=Number.MAX_VALUE;for(var T=0;T<this.vertices.length;++T)o.left(w.at(P-1),w.at(P),w.at(T))&&o.rightOn(w.at(P-1),w.at(P),w.at(T-1))&&(u=n(w.at(P-1),w.at(P),w.at(T),w.at(T-1)),o.right(w.at(P+1),w.at(P),u)&&(f=o.sqdist(w.vertices[P],u))<p&&(p=f,c=u,y=T)),o.left(w.at(P+1),w.at(P),w.at(T+1))&&o.rightOn(w.at(P+1),w.at(P),w.at(T))&&(u=n(w.at(P+1),w.at(P),w.at(T),w.at(T+1)),o.left(w.at(P-1),w.at(P),u)&&(f=o.sqdist(w.vertices[P],u))<d&&(d=f,l=u,m=T));if(y==(m+1)%this.vertices.length)u[0]=(c[0]+l[0])/2,u[1]=(c[1]+l[1])/2,i.push(u),P<m?(b.append(w,P,m+1),b.vertices.push(u),x.vertices.push(u),0!=y&&x.append(w,y,w.vertices.length),x.append(w,0,P+1)):(0!=P&&b.append(w,P,w.vertices.length),b.append(w,0,m+1),b.vertices.push(u),x.vertices.push(u),x.append(w,y,P+1));else{if(y>m&&(m+=this.vertices.length),g=Number.MAX_VALUE,m<y)return t;for(var T=y;T<=m;++T)o.leftOn(w.at(P-1),w.at(P),w.at(T))&&o.rightOn(w.at(P+1),w.at(P),w.at(T))&&(f=o.sqdist(w.at(P),w.at(T)))<g&&(g=f,v=T%this.vertices.length);P<v?(b.append(w,P,v+1),0!=v&&x.append(w,v,_.length),x.append(w,0,P+1)):(0!=P&&b.append(w,P,_.length),b.append(w,0,v+1),x.append(w,v,P+1))}return b.vertices.length<x.vertices.length?(b.quickDecomp(t,e,i,r,a,h),x.quickDecomp(t,e,i,r,a,h)):(x.quickDecomp(t,e,i,r,a,h),b.quickDecomp(t,e,i,r,a,h)),t}return t.push(this),t},s.prototype.removeCollinearPoints=function(t){for(var e=0,i=this.vertices.length-1;this.vertices.length>3&&i>=0;--i)o.collinear(this.at(i-1),this.at(i),this.at(i+1),t)&&(this.vertices.splice(i%this.vertices.length,1),i--,e++);return e}},{"./Line":1,"./Point":2,"./Scalar":4}],4:[function(t,e,i){function s(){}e.exports=s,s.eq=function(t,e,i){return i=i||0,Math.abs(t-e)<i}},{}],5:[function(t,e,i){e.exports={Polygon:t("./Polygon"),Point:t("./Point")}},{"./Point":2,"./Polygon":3}],6:[function(t,e,i){e.exports={name:"p2",version:"0.7.0",description:"A JavaScript 2D physics engine.",author:"Stefan Hedman <[email protected]> (http://steffe.se)",keywords:["p2.js","p2","physics","engine","2d"],main:"./src/p2.js",engines:{node:"*"},repository:{type:"git",url:"https://github.com/schteppe/p2.js.git"},bugs:{url:"https://github.com/schteppe/p2.js/issues"},licenses:[{type:"MIT"}],devDependencies:{grunt:"^0.4.5","grunt-contrib-jshint":"^0.11.2","grunt-contrib-nodeunit":"^0.4.1","grunt-contrib-uglify":"~0.4.0","grunt-contrib-watch":"~0.5.0","grunt-browserify":"~2.0.1","grunt-contrib-concat":"^0.4.0"},dependencies:{"poly-decomp":"0.1.0"}}},{}],7:[function(t,e,i){function s(t){this.lowerBound=n.create(),t&&t.lowerBound&&n.copy(this.lowerBound,t.lowerBound),this.upperBound=n.create(),t&&t.upperBound&&n.copy(this.upperBound,t.upperBound)}var n=t("../math/vec2");t("../utils/Utils");e.exports=s;var r=n.create();s.prototype.setFromPoints=function(t,e,i,s){var o=this.lowerBound,a=this.upperBound;"number"!=typeof i&&(i=0),0!==i?n.rotate(o,t[0],i):n.copy(o,t[0]),n.copy(a,o);for(var h=Math.cos(i),l=Math.sin(i),c=1;c<t.length;c++){var u=t[c];if(0!==i){var d=u[0],p=u[1];r[0]=h*d-l*p,r[1]=l*d+h*p,u=r}for(var f=0;f<2;f++)u[f]>a[f]&&(a[f]=u[f]),u[f]<o[f]&&(o[f]=u[f])}e&&(n.add(this.lowerBound,this.lowerBound,e),n.add(this.upperBound,this.upperBound,e)),s&&(this.lowerBound[0]-=s,this.lowerBound[1]-=s,this.upperBound[0]+=s,this.upperBound[1]+=s)},s.prototype.copy=function(t){n.copy(this.lowerBound,t.lowerBound),n.copy(this.upperBound,t.upperBound)},s.prototype.extend=function(t){for(var e=2;e--;){var i=t.lowerBound[e];this.lowerBound[e]>i&&(this.lowerBound[e]=i);var s=t.upperBound[e];this.upperBound[e]<s&&(this.upperBound[e]=s)}},s.prototype.overlaps=function(t){var e=this.lowerBound,i=this.upperBound,s=t.lowerBound,n=t.upperBound;return(s[0]<=i[0]&&i[0]<=n[0]||e[0]<=n[0]&&n[0]<=i[0])&&(s[1]<=i[1]&&i[1]<=n[1]||e[1]<=n[1]&&n[1]<=i[1])},s.prototype.containsPoint=function(t){var e=this.lowerBound,i=this.upperBound;return e[0]<=t[0]&&t[0]<=i[0]&&e[1]<=t[1]&&t[1]<=i[1]},s.prototype.overlapsRay=function(t){var e=1/t.direction[0],i=1/t.direction[1],s=(this.lowerBound[0]-t.from[0])*e,n=(this.upperBound[0]-t.from[0])*e,r=(this.lowerBound[1]-t.from[1])*i,o=(this.upperBound[1]-t.from[1])*i,a=Math.max(Math.max(Math.min(s,n),Math.min(r,o))),h=Math.min(Math.min(Math.max(s,n),Math.max(r,o)));return h<0?-1:a>h?-1:a}},{"../math/vec2":30,"../utils/Utils":57}],8:[function(t,e,i){function s(t){this.type=t,this.result=[],this.world=null,this.boundingVolumeType=s.AABB}var n=t("../math/vec2"),r=t("../objects/Body");e.exports=s,s.AABB=1,s.BOUNDING_CIRCLE=2,s.prototype.setWorld=function(t){this.world=t},s.prototype.getCollisionPairs=function(t){};var o=n.create();s.boundingRadiusCheck=function(t,e){n.sub(o,t.position,e.position);var i=n.squaredLength(o),s=t.boundingRadius+e.boundingRadius;return i<=s*s},s.aabbCheck=function(t,e){return t.getAABB().overlaps(e.getAABB())},s.prototype.boundingVolumeCheck=function(t,e){var i;switch(this.boundingVolumeType){case s.BOUNDING_CIRCLE:i=s.boundingRadiusCheck(t,e);break;case s.AABB:i=s.aabbCheck(t,e);break;default:throw new Error("Bounding volume type not recognized: "+this.boundingVolumeType)}return i},s.canCollide=function(t,e){var i=r.KINEMATIC,s=r.STATIC;return(t.type!==s||e.type!==s)&&(!(t.type===i&&e.type===s||t.type===s&&e.type===i)&&((t.type!==i||e.type!==i)&&((t.sleepState!==r.SLEEPING||e.sleepState!==r.SLEEPING)&&!(t.sleepState===r.SLEEPING&&e.type===s||e.sleepState===r.SLEEPING&&t.type===s))))},s.NAIVE=1,s.SAP=2},{"../math/vec2":30,"../objects/Body":31}],9:[function(t,e,i){function s(){n.call(this,n.NAIVE)}var n=(t("../shapes/Circle"),t("../shapes/Plane"),t("../shapes/Shape"),t("../shapes/Particle"),t("../collision/Broadphase"));t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.getCollisionPairs=function(t){var e=t.bodies,i=this.result;i.length=0;for(var s=0,r=e.length;s!==r;s++)for(var o=e[s],a=0;a<s;a++){var h=e[a];n.canCollide(o,h)&&this.boundingVolumeCheck(o,h)&&i.push(o,h)}return i},s.prototype.aabbQuery=function(t,e,i){i=i||[];for(var s=t.bodies,n=0;n<s.length;n++){var r=s[n];r.aabbNeedsUpdate&&r.updateAABB(),r.aabb.overlaps(e)&&i.push(r)}return i}},{"../collision/Broadphase":8,"../math/vec2":30,"../shapes/Circle":39,"../shapes/Particle":43,"../shapes/Plane":44,"../shapes/Shape":45}],10:[function(t,e,i){function s(){this.contactEquations=[],this.frictionEquations=[],this.enableFriction=!0,this.enabledEquations=!0,this.slipForce=10,this.frictionCoefficient=.3,this.surfaceVelocity=0,this.contactEquationPool=new c({size:32}),this.frictionEquationPool=new u({size:64}),this.restitution=0,this.stiffness=p.DEFAULT_STIFFNESS,this.relaxation=p.DEFAULT_RELAXATION,this.frictionStiffness=p.DEFAULT_STIFFNESS,this.frictionRelaxation=p.DEFAULT_RELAXATION,this.enableFrictionReduction=!0,this.collidingBodiesLastStep=new d,this.contactSkinSize=.01}function n(t,e){o.set(t.vertices[0],.5*-e.length,-e.radius),o.set(t.vertices[1],.5*e.length,-e.radius),o.set(t.vertices[2],.5*e.length,e.radius),o.set(t.vertices[3],.5*-e.length,e.radius)}function r(t,e,i,s){for(var n=q,r=H,l=Y,c=z,u=t,d=e.vertices,p=null,f=0;f!==d.length+1;f++){var g=d[f%d.length],m=d[(f+1)%d.length];o.rotate(n,g,s),o.rotate(r,m,s),h(n,n,i),h(r,r,i),a(l,n,u),a(c,r,u);var y=o.crossLength(l,c);if(null===p&&(p=y),y*p<=0)return!1;p=y}return!0}var o=t("../math/vec2"),a=o.sub,h=o.add,l=o.dot,c=(t("../utils/Utils"),t("../utils/ContactEquationPool")),u=t("../utils/FrictionEquationPool"),d=t("../utils/TupleDictionary"),p=t("../equations/Equation"),f=(t("../equations/ContactEquation"),t("../equations/FrictionEquation"),t("../shapes/Circle")),g=t("../shapes/Convex"),m=t("../shapes/Shape"),y=(t("../objects/Body"),t("../shapes/Box"));e.exports=s;var v=o.fromValues(0,1),b=o.fromValues(0,0),x=o.fromValues(0,0),w=o.fromValues(0,0),_=o.fromValues(0,0),P=o.fromValues(0,0),T=o.fromValues(0,0),C=o.fromValues(0,0),S=o.fromValues(0,0),A=o.fromValues(0,0),E=o.fromValues(0,0),I=o.fromValues(0,0),M=o.fromValues(0,0),R=o.fromValues(0,0),B=o.fromValues(0,0),L=o.fromValues(0,0),O=o.fromValues(0,0),k=o.fromValues(0,0),F=o.fromValues(0,0),D=[],U=o.create(),G=o.create();s.prototype.bodiesOverlap=function(t,e){for(var i=U,s=G,n=0,r=t.shapes.length;n!==r;n++){var o=t.shapes[n];t.toWorldFrame(i,o.position);for(var a=0,h=e.shapes.length;a!==h;a++){var l=e.shapes[a];if(e.toWorldFrame(s,l.position),this[o.type|l.type](t,o,i,o.angle+t.angle,e,l,s,l.angle+e.angle,!0))return!0}}return!1},s.prototype.collidedLastStep=function(t,e){var i=0|t.id,s=0|e.id;return!!this.collidingBodiesLastStep.get(i,s)},s.prototype.reset=function(){this.collidingBodiesLastStep.reset();for(var t=this.contactEquations,e=t.length;e--;){var i=t[e],s=i.bodyA.id,n=i.bodyB.id;this.collidingBodiesLastStep.set(s,n,!0)}for(var r=this.contactEquations,o=this.frictionEquations,a=0;a<r.length;a++)this.contactEquationPool.release(r[a]);for(var a=0;a<o.length;a++)this.frictionEquationPool.release(o[a]);this.contactEquations.length=this.frictionEquations.length=0},s.prototype.createContactEquation=function(t,e,i,s){var n=this.contactEquationPool.get();return n.bodyA=t,n.bodyB=e,n.shapeA=i,n.shapeB=s,n.restitution=this.restitution,n.firstImpact=!this.collidedLastStep(t,e),n.stiffness=this.stiffness,n.relaxation=this.relaxation,n.needsUpdate=!0,n.enabled=this.enabledEquations,n.offset=this.contactSkinSize,n},s.prototype.createFrictionEquation=function(t,e,i,s){var n=this.frictionEquationPool.get();return n.bodyA=t,n.bodyB=e,n.shapeA=i,n.shapeB=s,n.setSlipForce(this.slipForce),n.frictionCoefficient=this.frictionCoefficient,n.relativeVelocity=this.surfaceVelocity,n.enabled=this.enabledEquations,n.needsUpdate=!0,n.stiffness=this.frictionStiffness,n.relaxation=this.frictionRelaxation,n.contactEquations.length=0,n},s.prototype.createFrictionFromContact=function(t){var e=this.createFrictionEquation(t.bodyA,t.bodyB,t.shapeA,t.shapeB);return o.copy(e.contactPointA,t.contactPointA),o.copy(e.contactPointB,t.contactPointB),o.rotate90cw(e.t,t.normalA),e.contactEquations.push(t),e},s.prototype.createFrictionFromAverage=function(t){var e=this.contactEquations[this.contactEquations.length-1],i=this.createFrictionEquation(e.bodyA,e.bodyB,e.shapeA,e.shapeB),s=e.bodyA;e.bodyB;o.set(i.contactPointA,0,0),o.set(i.contactPointB,0,0),o.set(i.t,0,0);for(var n=0;n!==t;n++)e=this.contactEquations[this.contactEquations.length-1-n],e.bodyA===s?(o.add(i.t,i.t,e.normalA),o.add(i.contactPointA,i.contactPointA,e.contactPointA),o.add(i.contactPointB,i.contactPointB,e.contactPointB)):(o.sub(i.t,i.t,e.normalA),o.add(i.contactPointA,i.contactPointA,e.contactPointB),o.add(i.contactPointB,i.contactPointB,e.contactPointA)),i.contactEquations.push(e);var r=1/t;return o.scale(i.contactPointA,i.contactPointA,r),o.scale(i.contactPointB,i.contactPointB,r),o.normalize(i.t,i.t),o.rotate90cw(i.t,i.t),i},s.prototype[m.LINE|m.CONVEX]=s.prototype.convexLine=function(t,e,i,s,n,r,o,a,h){return!h&&0},s.prototype[m.LINE|m.BOX]=s.prototype.lineBox=function(t,e,i,s,n,r,o,a,h){return!h&&0};var N=new y({width:1,height:1}),X=o.create();s.prototype[m.CAPSULE|m.CONVEX]=s.prototype[m.CAPSULE|m.BOX]=s.prototype.convexCapsule=function(t,e,i,s,r,a,h,l,c){var u=X;o.set(u,a.length/2,0),o.rotate(u,u,l),o.add(u,u,h);var d=this.circleConvex(r,a,u,l,t,e,i,s,c,a.radius);o.set(u,-a.length/2,0),o.rotate(u,u,l),o.add(u,u,h);var p=this.circleConvex(r,a,u,l,t,e,i,s,c,a.radius);if(c&&(d||p))return!0;var f=N;return n(f,a),this.convexConvex(t,e,i,s,r,f,h,l,c)+d+p},s.prototype[m.CAPSULE|m.LINE]=s.prototype.lineCapsule=function(t,e,i,s,n,r,o,a,h){return!h&&0};var W=o.create(),j=o.create(),V=new y({width:1,height:1});s.prototype[m.CAPSULE|m.CAPSULE]=s.prototype.capsuleCapsule=function(t,e,i,s,r,a,h,l,c){for(var u,d=W,p=j,f=0,g=0;g<2;g++){o.set(d,(0===g?-1:1)*e.length/2,0),o.rotate(d,d,s),o.add(d,d,i);for(var m=0;m<2;m++){o.set(p,(0===m?-1:1)*a.length/2,0),o.rotate(p,p,l),o.add(p,p,h),this.enableFrictionReduction&&(u=this.enableFriction,this.enableFriction=!1);var y=this.circleCircle(t,e,d,s,r,a,p,l,c,e.radius,a.radius);if(this.enableFrictionReduction&&(this.enableFriction=u),c&&y)return!0;f+=y}}this.enableFrictionReduction&&(u=this.enableFriction,this.enableFriction=!1);var v=V;n(v,e);var b=this.convexCapsule(t,v,i,s,r,a,h,l,c);if(this.enableFrictionReduction&&(this.enableFriction=u),c&&b)return!0;if(f+=b,this.enableFrictionReduction){var u=this.enableFriction;this.enableFriction=!1}n(v,a);var x=this.convexCapsule(r,v,h,l,t,e,i,s,c);return this.enableFrictionReduction&&(this.enableFriction=u),!(!c||!x)||(f+=x,this.enableFrictionReduction&&f&&this.enableFriction&&this.frictionEquations.push(this.createFrictionFromAverage(f)),f)},s.prototype[m.LINE|m.LINE]=s.prototype.lineLine=function(t,e,i,s,n,r,o,a,h){return!h&&0},s.prototype[m.PLANE|m.LINE]=s.prototype.planeLine=function(t,e,i,s,n,r,c,u,d){var p=b,f=x,g=w,m=_,y=P,E=T,I=C,M=S,R=A,B=D,L=0;o.set(p,-r.length/2,0),o.set(f,r.length/2,0),o.rotate(g,p,u),o.rotate(m,f,u),h(g,g,c),h(m,m,c),o.copy(p,g),o.copy(f,m),a(y,f,p),o.normalize(E,y),o.rotate90cw(R,E),o.rotate(M,v,s),B[0]=p,B[1]=f;for(var O=0;O<B.length;O++){var k=B[O];a(I,k,i);var F=l(I,M);if(F<0){if(d)return!0;var U=this.createContactEquation(t,n,e,r);L++,o.copy(U.normalA,M),o.normalize(U.normalA,U.normalA),o.scale(I,M,F),a(U.contactPointA,k,I),a(U.contactPointA,U.contactPointA,t.position),a(U.contactPointB,k,c),h(U.contactPointB,U.contactPointB,c),a(U.contactPointB,U.contactPointB,n.position),this.contactEquations.push(U),this.enableFrictionReduction||this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(U))}}return!d&&(this.enableFrictionReduction||L&&this.enableFriction&&this.frictionEquations.push(this.createFrictionFromAverage(L)),L)},s.prototype[m.PARTICLE|m.CAPSULE]=s.prototype.particleCapsule=function(t,e,i,s,n,r,o,a,h){return this.circleLine(t,e,i,s,n,r,o,a,h,r.radius,0)},s.prototype[m.CIRCLE|m.LINE]=s.prototype.circleLine=function(t,e,i,s,n,r,c,u,d,p,f){var p=p||0,f=void 0!==f?f:e.radius,g=b,m=x,y=w,v=_,L=P,O=T,k=C,F=S,U=A,G=E,N=I,X=M,W=R,j=B,V=D;o.set(F,-r.length/2,0),o.set(U,r.length/2,0),o.rotate(G,F,u),o.rotate(N,U,u),h(G,G,c),h(N,N,c),o.copy(F,G),o.copy(U,N),a(O,U,F),o.normalize(k,O),o.rotate90cw(L,k),a(X,i,F);var q=l(X,L);a(v,F,c),a(W,i,c);var H=f+p;if(Math.abs(q)<H){o.scale(g,L,q),a(y,i,g),o.scale(m,L,l(L,W)),o.normalize(m,m),o.scale(m,m,p),h(y,y,m);var Y=l(k,y),z=l(k,F),K=l(k,U);if(Y>z&&Y<K){if(d)return!0;var J=this.createContactEquation(t,n,e,r);return o.scale(J.normalA,g,-1),o.normalize(J.normalA,J.normalA),o.scale(J.contactPointA,J.normalA,f),h(J.contactPointA,J.contactPointA,i),a(J.contactPointA,J.contactPointA,t.position),a(J.contactPointB,y,c),h(J.contactPointB,J.contactPointB,c),a(J.contactPointB,J.contactPointB,n.position),this.contactEquations.push(J),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(J)),1}}V[0]=F,V[1]=U;for(var Q=0;Q<V.length;Q++){var Z=V[Q];if(a(X,Z,i),o.squaredLength(X)<Math.pow(H,2)){if(d)return!0;var J=this.createContactEquation(t,n,e,r);return o.copy(J.normalA,X),o.normalize(J.normalA,J.normalA),o.scale(J.contactPointA,J.normalA,f),h(J.contactPointA,J.contactPointA,i),a(J.contactPointA,J.contactPointA,t.position),a(J.contactPointB,Z,c),o.scale(j,J.normalA,-p),h(J.contactPointB,J.contactPointB,j),h(J.contactPointB,J.contactPointB,c),a(J.contactPointB,J.contactPointB,n.position),this.contactEquations.push(J),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(J)),1}}return 0},s.prototype[m.CIRCLE|m.CAPSULE]=s.prototype.circleCapsule=function(t,e,i,s,n,r,o,a,h){return this.circleLine(t,e,i,s,n,r,o,a,h,r.radius)},s.prototype[m.CIRCLE|m.CONVEX]=s.prototype[m.CIRCLE|m.BOX]=s.prototype.circleConvex=function(t,e,i,s,n,l,c,u,d,p){for(var p="number"==typeof p?p:e.radius,f=b,g=x,m=w,y=_,v=P,T=E,C=I,S=R,A=B,M=L,k=O,F=!1,D=Number.MAX_VALUE,U=l.vertices,G=0;G!==U.length+1;G++){var N=U[G%U.length],X=U[(G+1)%U.length];if(o.rotate(f,N,u),o.rotate(g,X,u),h(f,f,c),h(g,g,c),a(m,g,f),o.normalize(y,m),o.rotate90cw(v,y),o.scale(A,v,-e.radius),h(A,A,i),r(A,l,c,u)){o.sub(M,f,A);var W=Math.abs(o.dot(M,v));W<D&&(o.copy(k,A),D=W,o.scale(S,v,W),o.add(S,S,A),F=!0)}}if(F){if(d)return!0;var j=this.createContactEquation(t,n,e,l);return o.sub(j.normalA,k,i),o.normalize(j.normalA,j.normalA),o.scale(j.contactPointA,j.normalA,p),h(j.contactPointA,j.contactPointA,i),a(j.contactPointA,j.contactPointA,t.position),a(j.contactPointB,S,c),h(j.contactPointB,j.contactPointB,c),a(j.contactPointB,j.contactPointB,n.position),this.contactEquations.push(j),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(j)),1}if(p>0)for(var G=0;G<U.length;G++){var V=U[G];if(o.rotate(C,V,u),h(C,C,c),a(T,C,i),o.squaredLength(T)<Math.pow(p,2)){if(d)return!0;var j=this.createContactEquation(t,n,e,l);return o.copy(j.normalA,T),o.normalize(j.normalA,j.normalA),o.scale(j.contactPointA,j.normalA,p),h(j.contactPointA,j.contactPointA,i),a(j.contactPointA,j.contactPointA,t.position),a(j.contactPointB,C,c),h(j.contactPointB,j.contactPointB,c),a(j.contactPointB,j.contactPointB,n.position),this.contactEquations.push(j),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(j)),1}}return 0};var q=o.create(),H=o.create(),Y=o.create(),z=o.create();s.prototype[m.PARTICLE|m.CONVEX]=s.prototype[m.PARTICLE|m.BOX]=s.prototype.particleConvex=function(t,e,i,s,n,c,u,d,p){var f=b,g=x,m=w,y=_,v=P,S=T,A=C,I=E,M=R,B=k,L=F,O=Number.MAX_VALUE,D=!1,U=c.vertices;if(!r(i,c,u,d))return 0;if(p)return!0;for(var G=0;G!==U.length+1;G++){var N=U[G%U.length],X=U[(G+1)%U.length];o.rotate(f,N,d),o.rotate(g,X,d),h(f,f,u),h(g,g,u),a(m,g,f),o.normalize(y,m),o.rotate90cw(v,y),a(I,i,f);l(I,v);a(S,f,u),a(A,i,u),o.sub(B,f,i);var W=Math.abs(o.dot(B,v));W<O&&(O=W,o.scale(M,v,W),o.add(M,M,i),o.copy(L,v),D=!0)}if(D){var j=this.createContactEquation(t,n,e,c);return o.scale(j.normalA,L,-1),o.normalize(j.normalA,j.normalA),o.set(j.contactPointA,0,0),h(j.contactPointA,j.contactPointA,i),a(j.contactPointA,j.contactPointA,t.position),a(j.contactPointB,M,u),h(j.contactPointB,j.contactPointB,u),a(j.contactPointB,j.contactPointB,n.position),this.contactEquations.push(j),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(j)),1}return 0},s.prototype[m.CIRCLE]=s.prototype.circleCircle=function(t,e,i,s,n,r,l,c,u,d,p){var f=b,d=d||e.radius,p=p||r.radius;a(f,i,l);var g=d+p;if(o.squaredLength(f)>Math.pow(g,2))return 0;if(u)return!0;var m=this.createContactEquation(t,n,e,r);return a(m.normalA,l,i),o.normalize(m.normalA,m.normalA),o.scale(m.contactPointA,m.normalA,d),o.scale(m.contactPointB,m.normalA,-p),h(m.contactPointA,m.contactPointA,i),a(m.contactPointA,m.contactPointA,t.position),h(m.contactPointB,m.contactPointB,l),a(m.contactPointB,m.contactPointB,n.position),this.contactEquations.push(m),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(m)),1},s.prototype[m.PLANE|m.CONVEX]=s.prototype[m.PLANE|m.BOX]=s.prototype.planeConvex=function(t,e,i,s,n,r,c,u,d){var p=b,f=x,g=w,m=0;o.rotate(f,v,s);for(var y=0;y!==r.vertices.length;y++){var _=r.vertices[y];if(o.rotate(p,_,u),h(p,p,c),a(g,p,i),l(g,f)<=0){if(d)return!0;m++;var P=this.createContactEquation(t,n,e,r);a(g,p,i),o.copy(P.normalA,f);var T=l(g,P.normalA);o.scale(g,P.normalA,T),a(P.contactPointB,p,n.position),a(P.contactPointA,p,g),a(P.contactPointA,P.contactPointA,t.position),this.contactEquations.push(P),this.enableFrictionReduction||this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(P))}}return this.enableFrictionReduction&&this.enableFriction&&m&&this.frictionEquations.push(this.createFrictionFromAverage(m)),m},s.prototype[m.PARTICLE|m.PLANE]=s.prototype.particlePlane=function(t,e,i,s,n,r,h,c,u){var d=b,p=x;c=c||0,a(d,i,h),o.rotate(p,v,c);var f=l(d,p);if(f>0)return 0;if(u)return!0;var g=this.createContactEquation(n,t,r,e);return o.copy(g.normalA,p),o.scale(d,g.normalA,f),a(g.contactPointA,i,d),a(g.contactPointA,g.contactPointA,n.position),a(g.contactPointB,i,t.position),this.contactEquations.push(g),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(g)),1},s.prototype[m.CIRCLE|m.PARTICLE]=s.prototype.circleParticle=function(t,e,i,s,n,r,l,c,u){var d=b;if(a(d,l,i),o.squaredLength(d)>Math.pow(e.radius,2))return 0;if(u)return!0;var p=this.createContactEquation(t,n,e,r);return o.copy(p.normalA,d),o.normalize(p.normalA,p.normalA),o.scale(p.contactPointA,p.normalA,e.radius),h(p.contactPointA,p.contactPointA,i),a(p.contactPointA,p.contactPointA,t.position),a(p.contactPointB,l,n.position),this.contactEquations.push(p),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(p)),1};var K=new f({radius:1}),J=o.create(),Q=o.create();o.create();s.prototype[m.PLANE|m.CAPSULE]=s.prototype.planeCapsule=function(t,e,i,s,n,r,a,l,c){var u=J,d=Q,p=K;o.set(u,-r.length/2,0),o.rotate(u,u,l),h(u,u,a),o.set(d,r.length/2,0),o.rotate(d,d,l),h(d,d,a),p.radius=r.radius;var f;this.enableFrictionReduction&&(f=this.enableFriction,this.enableFriction=!1);var g=this.circlePlane(n,p,u,0,t,e,i,s,c),m=this.circlePlane(n,p,d,0,t,e,i,s,c);if(this.enableFrictionReduction&&(this.enableFriction=f),c)return g||m;var y=g+m;return this.enableFrictionReduction&&y&&this.frictionEquations.push(this.createFrictionFromAverage(y)),y},s.prototype[m.CIRCLE|m.PLANE]=s.prototype.circlePlane=function(t,e,i,s,n,r,c,u,d){var p=t,f=e,g=i,m=n,y=c,_=u;_=_||0;var P=b,T=x,C=w;a(P,g,y),o.rotate(T,v,_);var S=l(T,P);if(S>f.radius)return 0;if(d)return!0;var A=this.createContactEquation(m,p,r,e);return o.copy(A.normalA,T),o.scale(A.contactPointB,A.normalA,-f.radius),h(A.contactPointB,A.contactPointB,g),a(A.contactPointB,A.contactPointB,p.position),o.scale(C,A.normalA,S),a(A.contactPointA,P,C),h(A.contactPointA,A.contactPointA,y),a(A.contactPointA,A.contactPointA,m.position),this.contactEquations.push(A),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(A)),1},s.prototype[m.CONVEX]=s.prototype[m.CONVEX|m.BOX]=s.prototype[m.BOX]=s.prototype.convexConvex=function(t,e,i,n,r,c,u,d,p,f){var g=b,m=x,y=w,v=_,T=P,E=C,I=S,M=A,R=0,f="number"==typeof f?f:0;if(!s.findSeparatingAxis(e,i,n,c,u,d,g))return 0;a(I,u,i),l(g,I)>0&&o.scale(g,g,-1);var B=s.getClosestEdge(e,n,g,!0),L=s.getClosestEdge(c,d,g);if(-1===B||-1===L)return 0;for(var O=0;O<2;O++){var k=B,F=L,D=e,U=c,G=i,N=u,X=n,W=d,j=t,V=r;if(0===O){var q;q=k,k=F,F=q,q=D,D=U,U=q,q=G,G=N,N=q,q=X,X=W,W=q,q=j,j=V,V=q}for(var H=F;H<F+2;H++){var Y=U.vertices[(H+U.vertices.length)%U.vertices.length];o.rotate(m,Y,W),h(m,m,N);for(var z=0,K=k-1;K<k+2;K++){var J=D.vertices[(K+D.vertices.length)%D.vertices.length],Q=D.vertices[(K+1+D.vertices.length)%D.vertices.length];o.rotate(y,J,X),o.rotate(v,Q,X),h(y,y,G),h(v,v,G),a(T,v,y),o.rotate90cw(M,T),o.normalize(M,M),a(I,m,y);var Z=l(M,I);(K===k&&Z<=f||K!==k&&Z<=0)&&z++}if(z>=3){if(p)return!0;var $=this.createContactEquation(j,V,D,U);R++;var J=D.vertices[k%D.vertices.length],Q=D.vertices[(k+1)%D.vertices.length];o.rotate(y,J,X),o.rotate(v,Q,X),h(y,y,G),h(v,v,G),a(T,v,y),o.rotate90cw($.normalA,T),o.normalize($.normalA,$.normalA),a(I,m,y);var Z=l($.normalA,I);o.scale(E,$.normalA,Z),a($.contactPointA,m,G),a($.contactPointA,$.contactPointA,E),h($.contactPointA,$.contactPointA,G),a($.contactPointA,$.contactPointA,j.position),a($.contactPointB,m,N),h($.contactPointB,$.contactPointB,N),a($.contactPointB,$.contactPointB,V.position),this.contactEquations.push($),this.enableFrictionReduction||this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact($))}}}return this.enableFrictionReduction&&this.enableFriction&&R&&this.frictionEquations.push(this.createFrictionFromAverage(R)),R};var Z=o.fromValues(0,0);s.projectConvexOntoAxis=function(t,e,i,s,n){var r,a,h=null,c=null,u=Z;o.rotate(u,s,-i);for(var d=0;d<t.vertices.length;d++)r=t.vertices[d],a=l(r,u),(null===h||a>h)&&(h=a),(null===c||a<c)&&(c=a);if(c>h){var p=c;c=h,h=p}var f=l(e,s);o.set(n,c+f,h+f)};var $=o.fromValues(0,0),tt=o.fromValues(0,0),et=o.fromValues(0,0),it=o.fromValues(0,0),st=o.fromValues(0,0),nt=o.fromValues(0,0);s.findSeparatingAxis=function(t,e,i,n,r,h,l){var c=null,u=!1,d=!1,p=$,f=tt,g=et,m=it,v=st,b=nt;if(t instanceof y&&n instanceof y)for(var x=0;2!==x;x++){var w=t,_=i;1===x&&(w=n,_=h);for(var P=0;2!==P;P++){0===P?o.set(m,0,1):1===P&&o.set(m,1,0),0!==_&&o.rotate(m,m,_),s.projectConvexOntoAxis(t,e,i,m,v),s.projectConvexOntoAxis(n,r,h,m,b);var T=v,C=b;v[0]>b[0]&&(C=v,T=b,!0);var S=C[0]-T[1];u=S<=0,(null===c||S>c)&&(o.copy(l,m),c=S,d=u)}}else for(var x=0;2!==x;x++){var w=t,_=i;1===x&&(w=n,_=h);for(var P=0;P!==w.vertices.length;P++){o.rotate(f,w.vertices[P],_),o.rotate(g,w.vertices[(P+1)%w.vertices.length],_),a(p,g,f),o.rotate90cw(m,p),o.normalize(m,m),s.projectConvexOntoAxis(t,e,i,m,v),s.projectConvexOntoAxis(n,r,h,m,b);var T=v,C=b;v[0]>b[0]&&(C=v,T=b,!0);var S=C[0]-T[1];u=S<=0,(null===c||S>c)&&(o.copy(l,m),c=S,d=u)}}return d};var rt=o.fromValues(0,0),ot=o.fromValues(0,0),at=o.fromValues(0,0);s.getClosestEdge=function(t,e,i,s){var n=rt,r=ot,h=at;o.rotate(n,i,-e),s&&o.scale(n,n,-1);for(var c=-1,u=t.vertices.length,d=-1,p=0;p!==u;p++){a(r,t.vertices[(p+1)%u],t.vertices[p%u]),o.rotate90cw(h,r),o.normalize(h,h);var f=l(h,n);(-1===c||f>d)&&(c=p%u,d=f)}return c};var ht=o.create(),lt=o.create(),ct=o.create(),ut=o.create(),dt=o.create(),pt=o.create(),ft=o.create();s.prototype[m.CIRCLE|m.HEIGHTFIELD]=s.prototype.circleHeightfield=function(t,e,i,s,n,r,l,c,u,d){var p=r.heights,d=d||e.radius,f=r.elementWidth,g=lt,m=ht,y=dt,v=ft,b=pt,x=ct,w=ut,_=Math.floor((i[0]-d-l[0])/f),P=Math.ceil((i[0]+d-l[0])/f);_<0&&(_=0),P>=p.length&&(P=p.length-1);for(var T=p[_],C=p[P],S=_;S<P;S++)p[S]<C&&(C=p[S]),p[S]>T&&(T=p[S]);if(i[1]-d>T)return!u&&0;for(var A=!1,S=_;S<P;S++){o.set(x,S*f,p[S]),o.set(w,(S+1)*f,p[S+1]),o.add(x,x,l),o.add(w,w,l),o.sub(b,w,x),o.rotate(b,b,Math.PI/2),o.normalize(b,b),o.scale(m,b,-d),o.add(m,m,i),o.sub(g,m,x);var E=o.dot(g,b);if(m[0]>=x[0]&&m[0]<w[0]&&E<=0){if(u)return!0;A=!0,o.scale(g,b,-E),o.add(y,m,g),o.copy(v,b);var I=this.createContactEquation(n,t,r,e);o.copy(I.normalA,v),o.scale(I.contactPointB,I.normalA,-d),h(I.contactPointB,I.contactPointB,i),a(I.contactPointB,I.contactPointB,t.position),o.copy(I.contactPointA,y),o.sub(I.contactPointA,I.contactPointA,n.position),this.contactEquations.push(I),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(I))}}if(A=!1,d>0)for(var S=_;S<=P;S++)if(o.set(x,S*f,p[S]),o.add(x,x,l),o.sub(g,i,x),o.squaredLength(g)<Math.pow(d,2)){if(u)return!0;A=!0;var I=this.createContactEquation(n,t,r,e);o.copy(I.normalA,g),o.normalize(I.normalA,I.normalA),o.scale(I.contactPointB,I.normalA,-d),h(I.contactPointB,I.contactPointB,i),a(I.contactPointB,I.contactPointB,t.position),a(I.contactPointA,x,l),h(I.contactPointA,I.contactPointA,l),a(I.contactPointA,I.contactPointA,n.position),this.contactEquations.push(I),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(I))}return A?1:0};var gt=o.create(),mt=o.create(),yt=o.create(),vt=new g({vertices:[o.create(),o.create(),o.create(),o.create()]});s.prototype[m.BOX|m.HEIGHTFIELD]=s.prototype[m.CONVEX|m.HEIGHTFIELD]=s.prototype.convexHeightfield=function(t,e,i,s,n,r,a,h,l){var c=r.heights,u=r.elementWidth,d=gt,p=mt,f=yt,g=vt,m=Math.floor((t.aabb.lowerBound[0]-a[0])/u),y=Math.ceil((t.aabb.upperBound[0]-a[0])/u);m<0&&(m=0),y>=c.length&&(y=c.length-1);for(var v=c[m],b=c[y],x=m;x<y;x++)c[x]<b&&(b=c[x]),c[x]>v&&(v=c[x]);if(t.aabb.lowerBound[1]>v)return!l&&0;for(var w=0,x=m;x<y;x++){o.set(d,x*u,c[x]),o.set(p,(x+1)*u,c[x+1]),o.add(d,d,a),o.add(p,p,a);o.set(f,.5*(p[0]+d[0]),.5*(p[1]+d[1]-100)),o.sub(g.vertices[0],p,f),o.sub(g.vertices[1],d,f),o.copy(g.vertices[2],g.vertices[1]),o.copy(g.vertices[3],g.vertices[0]),g.vertices[2][1]-=100,g.vertices[3][1]-=100,w+=this.convexConvex(t,e,i,s,n,g,f,0,l)}return w}},{"../equations/ContactEquation":21,"../equations/Equation":22,"../equations/FrictionEquation":23,"../math/vec2":30,"../objects/Body":31,"../shapes/Box":37,"../shapes/Circle":39,"../shapes/Convex":40,"../shapes/Shape":45,"../utils/ContactEquationPool":48,"../utils/FrictionEquationPool":49,"../utils/TupleDictionary":56,"../utils/Utils":57}],11:[function(t,e,i){function s(t){t=t||{},this.from=t.from?r.fromValues(t.from[0],t.from[1]):r.create(),this.to=t.to?r.fromValues(t.to[0],t.to[1]):r.create(),this.checkCollisionResponse=void 0===t.checkCollisionResponse||t.checkCollisionResponse,this.skipBackfaces=!!t.skipBackfaces,this.collisionMask=void 0!==t.collisionMask?t.collisionMask:-1,this.collisionGroup=void 0!==t.collisionGroup?t.collisionGroup:-1,this.mode=void 0!==t.mode?t.mode:s.ANY,this.callback=t.callback||function(t){},this.direction=r.create(),this.length=1,this.update()}function n(t,e,i){r.sub(a,i,t);var s=r.dot(a,e);return r.scale(h,e,s),r.add(h,h,t),r.squaredDistance(i,h)}e.exports=s;var r=t("../math/vec2");t("../collision/RaycastResult"),t("../shapes/Shape"),t("../collision/AABB");s.prototype.constructor=s,s.CLOSEST=1,s.ANY=2,s.ALL=4,s.prototype.update=function(){var t=this.direction;r.sub(t,this.to,this.from),this.length=r.length(t),r.normalize(t,t)},s.prototype.intersectBodies=function(t,e){for(var i=0,s=e.length;!t.shouldStop(this)&&i<s;i++){var n=e[i],r=n.getAABB();(r.overlapsRay(this)>=0||r.containsPoint(this.from))&&this.intersectBody(t,n)}};var o=r.create();s.prototype.intersectBody=function(t,e){var i=this.checkCollisionResponse;if(!i||e.collisionResponse)for(var s=o,n=0,a=e.shapes.length;n<a;n++){var h=e.shapes[n];if((!i||h.collisionResponse)&&(0!=(this.collisionGroup&h.collisionMask)&&0!=(h.collisionGroup&this.collisionMask))){r.rotate(s,h.position,e.angle),r.add(s,s,e.position);var l=h.angle+e.angle;if(this.intersectShape(t,h,l,s,e),t.shouldStop(this))break}}},s.prototype.intersectShape=function(t,e,i,s,r){n(this.from,this.direction,s)>e.boundingRadius*e.boundingRadius||(this._currentBody=r,this._currentShape=e,e.raycast(t,this,s,i),this._currentBody=this._currentShape=null)},s.prototype.getAABB=function(t){var e=this.to,i=this.from;r.set(t.lowerBound,Math.min(e[0],i[0]),Math.min(e[1],i[1])),r.set(t.upperBound,Math.max(e[0],i[0]),Math.max(e[1],i[1]))};r.create();s.prototype.reportIntersection=function(t,e,i,n){var o=(this.from,this.to,this._currentShape),a=this._currentBody;if(!(this.skipBackfaces&&r.dot(i,this.direction)>0))switch(this.mode){case s.ALL:t.set(i,o,a,e,n),this.callback(t);break;case s.CLOSEST:(e<t.fraction||!t.hasHit())&&t.set(i,o,a,e,n);break;case s.ANY:t.set(i,o,a,e,n)}};var a=r.create(),h=r.create()},{"../collision/AABB":7,"../collision/RaycastResult":12,"../math/vec2":30,"../shapes/Shape":45}],12:[function(t,e,i){function s(){this.normal=n.create(),this.shape=null,this.body=null,this.faceIndex=-1,this.fraction=-1,this.isStopped=!1}var n=t("../math/vec2"),r=t("../collision/Ray");e.exports=s,s.prototype.reset=function(){n.set(this.normal,0,0),this.shape=null,this.body=null,this.faceIndex=-1,this.fraction=-1,this.isStopped=!1},s.prototype.getHitDistance=function(t){return n.distance(t.from,t.to)*this.fraction},s.prototype.hasHit=function(){return-1!==this.fraction},s.prototype.getHitPoint=function(t,e){n.lerp(t,e.from,e.to,this.fraction)},s.prototype.stop=function(){this.isStopped=!0},s.prototype.shouldStop=function(t){return this.isStopped||-1!==this.fraction&&t.mode===r.ANY},s.prototype.set=function(t,e,i,s,r){n.copy(this.normal,t),this.shape=e,this.body=i,this.fraction=s,this.faceIndex=r}},{"../collision/Ray":11,"../math/vec2":30}],13:[function(t,e,i){function s(){r.call(this,r.SAP),this.axisList=[],this.axisIndex=0;var t=this;this._addBodyHandler=function(e){t.axisList.push(e.body)},this._removeBodyHandler=function(e){var i=t.axisList.indexOf(e.body);-1!==i&&t.axisList.splice(i,1)}}var n=t("../utils/Utils"),r=t("../collision/Broadphase");e.exports=s,s.prototype=new r,s.prototype.constructor=s,s.prototype.setWorld=function(t){this.axisList.length=0,n.appendArray(this.axisList,t.bodies),t.off("addBody",this._addBodyHandler).off("removeBody",this._removeBodyHandler),t.on("addBody",this._addBodyHandler).on("removeBody",this._removeBodyHandler),this.world=t},s.sortAxisList=function(t,e){e|=0;for(var i=1,s=t.length;i<s;i++){for(var n=t[i],r=i-1;r>=0&&!(t[r].aabb.lowerBound[e]<=n.aabb.lowerBound[e]);r--)t[r+1]=t[r];t[r+1]=n}return t},s.prototype.sortList=function(){var t=this.axisList,e=this.axisIndex;s.sortAxisList(t,e)},s.prototype.getCollisionPairs=function(t){var e=this.axisList,i=this.result,s=this.axisIndex;i.length=0;for(var n=e.length;n--;){var o=e[n];o.aabbNeedsUpdate&&o.updateAABB()}this.sortList();for(var a=0,h=0|e.length;a!==h;a++)for(var l=e[a],c=a+1;c<h;c++){var u=e[c],d=u.aabb.lowerBound[s]<=l.aabb.upperBound[s];if(!d)break;r.canCollide(l,u)&&this.boundingVolumeCheck(l,u)&&i.push(l,u)}return i},s.prototype.aabbQuery=function(t,e,i){i=i||[],this.sortList();var s=this.axisIndex,n="x";1===s&&(n="y"),2===s&&(n="z");for(var r=this.axisList,o=(e.lowerBound[n],e.upperBound[n],0);o<r.length;o++){var a=r[o];a.aabbNeedsUpdate&&a.updateAABB(),a.aabb.overlaps(e)&&i.push(a)}return i}},{"../collision/Broadphase":8,"../utils/Utils":57}],14:[function(t,e,i){function s(t,e,i,s){this.type=i,s=n.defaults(s,{collideConnected:!0,wakeUpBodies:!0}),this.equations=[],this.bodyA=t,this.bodyB=e,this.collideConnected=s.collideConnected,s.wakeUpBodies&&(t&&t.wakeUp(),e&&e.wakeUp())}e.exports=s;var n=t("../utils/Utils");s.prototype.update=function(){throw new Error("method update() not implmemented in this Constraint subclass!")},s.DISTANCE=1,s.GEAR=2,s.LOCK=3,s.PRISMATIC=4,s.REVOLUTE=5,s.prototype.setStiffness=function(t){for(var e=this.equations,i=0;i!==e.length;i++){var s=e[i];s.stiffness=t,s.needsUpdate=!0}},s.prototype.setRelaxation=function(t){for(var e=this.equations,i=0;i!==e.length;i++){var s=e[i];s.relaxation=t,s.needsUpdate=!0}}},{"../utils/Utils":57}],15:[function(t,e,i){function s(t,e,i){i=a.defaults(i,{localAnchorA:[0,0],localAnchorB:[0,0]}),n.call(this,t,e,n.DISTANCE,i),this.localAnchorA=o.fromValues(i.localAnchorA[0],i.localAnchorA[1]),this.localAnchorB=o.fromValues(i.localAnchorB[0],i.localAnchorB[1]);var s=this.localAnchorA,h=this.localAnchorB;if(this.distance=0,"number"==typeof i.distance)this.distance=i.distance;else{var l=o.create(),c=o.create(),u=o.create();o.rotate(l,s,t.angle),o.rotate(c,h,e.angle),o.add(u,e.position,c),o.sub(u,u,l),o.sub(u,u,t.position),this.distance=o.length(u)}var d;d=void 0===i.maxForce?Number.MAX_VALUE:i.maxForce;var p=new r(t,e,-d,d);this.equations=[p],this.maxForce=d;var u=o.create(),f=o.create(),g=o.create(),m=this;p.computeGq=function(){var t=this.bodyA,e=this.bodyB,i=t.position,n=e.position;return o.rotate(f,s,t.angle),o.rotate(g,h,e.angle),o.add(u,n,g),o.sub(u,u,f),o.sub(u,u,i),o.length(u)-m.distance},this.setMaxForce(d),this.upperLimitEnabled=!1,this.upperLimit=1,this.lowerLimitEnabled=!1,this.lowerLimit=0,this.position=0}var n=t("./Constraint"),r=t("../equations/Equation"),o=t("../math/vec2"),a=t("../utils/Utils");e.exports=s,s.prototype=new n,s.prototype.constructor=s;var h=o.create(),l=o.create(),c=o.create();s.prototype.update=function(){var t=this.equations[0],e=this.bodyA,i=this.bodyB,s=(this.distance,e.position),n=i.position,r=this.equations[0],a=t.G;o.rotate(l,this.localAnchorA,e.angle),o.rotate(c,this.localAnchorB,i.angle),o.add(h,n,c),o.sub(h,h,l),o.sub(h,h,s),this.position=o.length(h);var u=!1;if(this.upperLimitEnabled&&this.position>this.upperLimit&&(r.maxForce=0,r.minForce=-this.maxForce,this.distance=this.upperLimit,u=!0),this.lowerLimitEnabled&&this.position<this.lowerLimit&&(r.maxForce=this.maxForce,r.minForce=0,this.distance=this.lowerLimit,u=!0),(this.lowerLimitEnabled||this.upperLimitEnabled)&&!u)return void(r.enabled=!1);r.enabled=!0,o.normalize(h,h);var d=o.crossLength(l,h),p=o.crossLength(c,h);a[0]=-h[0],a[1]=-h[1],a[2]=-d,a[3]=h[0],a[4]=h[1],a[5]=p},s.prototype.setMaxForce=function(t){var e=this.equations[0];e.minForce=-t,e.maxForce=t},s.prototype.getMaxForce=function(){return this.equations[0].maxForce}},{"../equations/Equation":22,"../math/vec2":30,"../utils/Utils":57,"./Constraint":14}],16:[function(t,e,i){function s(t,e,i){i=i||{},n.call(this,t,e,n.GEAR,i),this.ratio=void 0!==i.ratio?i.ratio:1,this.angle=void 0!==i.angle?i.angle:e.angle-this.ratio*t.angle,i.angle=this.angle,i.ratio=this.ratio,this.equations=[new r(t,e,i)],void 0!==i.maxTorque&&this.setMaxTorque(i.maxTorque)}var n=t("./Constraint"),r=(t("../equations/Equation"),t("../equations/AngleLockEquation"));t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.update=function(){var t=this.equations[0];t.ratio!==this.ratio&&t.setRatio(this.ratio),t.angle=this.angle},s.prototype.setMaxTorque=function(t){this.equations[0].setMaxTorque(t)},s.prototype.getMaxTorque=function(t){return this.equations[0].maxForce}},{"../equations/AngleLockEquation":20,"../equations/Equation":22,"../math/vec2":30,"./Constraint":14}],17:[function(t,e,i){function s(t,e,i){i=i||{},n.call(this,t,e,n.LOCK,i);var s=void 0===i.maxForce?Number.MAX_VALUE:i.maxForce,a=(i.localAngleB,new o(t,e,-s,s)),h=new o(t,e,-s,s),l=new o(t,e,-s,s),c=r.create(),u=r.create(),d=this;a.computeGq=function(){return r.rotate(c,d.localOffsetB,t.angle),r.sub(u,e.position,t.position),r.sub(u,u,c),u[0]},h.computeGq=function(){return r.rotate(c,d.localOffsetB,t.angle),r.sub(u,e.position,t.position),r.sub(u,u,c),u[1]};var p=r.create(),f=r.create();l.computeGq=function(){return r.rotate(p,d.localOffsetB,e.angle-d.localAngleB),r.scale(p,p,-1),r.sub(u,t.position,e.position),r.add(u,u,p),r.rotate(f,p,-Math.PI/2),r.normalize(f,f),r.dot(u,f)},this.localOffsetB=r.create(),i.localOffsetB?r.copy(this.localOffsetB,i.localOffsetB):(r.sub(this.localOffsetB,e.position,t.position),r.rotate(this.localOffsetB,this.localOffsetB,-t.angle)),this.localAngleB=0,"number"==typeof i.localAngleB?this.localAngleB=i.localAngleB:this.localAngleB=e.angle-t.angle,this.equations.push(a,h,l),this.setMaxForce(s)}var n=t("./Constraint"),r=t("../math/vec2"),o=t("../equations/Equation");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.setMaxForce=function(t){for(var e=this.equations,i=0;i<this.equations.length;i++)e[i].maxForce=t,e[i].minForce=-t},s.prototype.getMaxForce=function(){return this.equations[0].maxForce};var a=r.create(),h=r.create(),l=r.create(),c=r.fromValues(1,0),u=r.fromValues(0,1);s.prototype.update=function(){var t=this.equations[0],e=this.equations[1],i=this.equations[2],s=this.bodyA,n=this.bodyB;r.rotate(a,this.localOffsetB,s.angle),r.rotate(h,this.localOffsetB,n.angle-this.localAngleB),r.scale(h,h,-1),r.rotate(l,h,Math.PI/2),r.normalize(l,l),t.G[0]=-1,t.G[1]=0,t.G[2]=-r.crossLength(a,c),t.G[3]=1,e.G[0]=0,e.G[1]=-1,e.G[2]=-r.crossLength(a,u),e.G[4]=1,i.G[0]=-l[0],i.G[1]=-l[1],i.G[3]=l[0],i.G[4]=l[1],i.G[5]=r.crossLength(h,l)}},{"../equations/Equation":22,"../math/vec2":30,"./Constraint":14}],18:[function(t,e,i){function s(t,e,i){i=i||{},n.call(this,t,e,n.PRISMATIC,i);var s=a.fromValues(0,0),l=a.fromValues(1,0),c=a.fromValues(0,0);i.localAnchorA&&a.copy(s,i.localAnchorA),i.localAxisA&&a.copy(l,i.localAxisA),i.localAnchorB&&a.copy(c,i.localAnchorB),this.localAnchorA=s,this.localAnchorB=c,this.localAxisA=l;var u=this.maxForce=void 0!==i.maxForce?i.maxForce:Number.MAX_VALUE,d=new o(t,e,-u,u),p=new a.create,f=new a.create,g=new a.create,m=new a.create;if(d.computeGq=function(){return a.dot(g,m)},d.updateJacobian=function(){var i=this.G,n=t.position,r=e.position;a.rotate(p,s,t.angle),a.rotate(f,c,e.angle),a.add(g,r,f),a.sub(g,g,n),a.sub(g,g,p),a.rotate(m,l,t.angle+Math.PI/2),i[0]=-m[0],i[1]=-m[1],i[2]=-a.crossLength(p,m)+a.crossLength(m,g),i[3]=m[0],i[4]=m[1],i[5]=a.crossLength(f,m)},this.equations.push(d),!i.disableRotationalLock){var y=new h(t,e,-u,u);this.equations.push(y)}this.position=0,this.velocity=0,this.lowerLimitEnabled=void 0!==i.lowerLimit,this.upperLimitEnabled=void 0!==i.upperLimit,this.lowerLimit=void 0!==i.lowerLimit?i.lowerLimit:0,this.upperLimit=void 0!==i.upperLimit?i.upperLimit:1,this.upperLimitEquation=new r(t,e),this.lowerLimitEquation=new r(t,e),this.upperLimitEquation.minForce=this.lowerLimitEquation.minForce=0,this.upperLimitEquation.maxForce=this.lowerLimitEquation.maxForce=u,this.motorEquation=new o(t,e),this.motorEnabled=!1,this.motorSpeed=0;var v=this,b=this.motorEquation;b.computeGW;b.computeGq=function(){return 0},b.computeGW=function(){var t=this.G,e=this.bodyA,i=this.bodyB,s=e.velocity,n=i.velocity,r=e.angularVelocity,o=i.angularVelocity;return this.gmult(t,s,r,n,o)+v.motorSpeed}}var n=t("./Constraint"),r=t("../equations/ContactEquation"),o=t("../equations/Equation"),a=t("../math/vec2"),h=t("../equations/RotationalLockEquation");e.exports=s,s.prototype=new n,s.prototype.constructor=s;var l=a.create(),c=a.create(),u=a.create(),d=a.create(),p=a.create(),f=a.create();s.prototype.update=function(){var t=this.equations,e=t[0],i=this.upperLimit,s=this.lowerLimit,n=this.upperLimitEquation,r=this.lowerLimitEquation,o=this.bodyA,h=this.bodyB,g=this.localAxisA,m=this.localAnchorA,y=this.localAnchorB;e.updateJacobian(),a.rotate(l,g,o.angle),a.rotate(d,m,o.angle),a.add(c,d,o.position),a.rotate(p,y,h.angle),a.add(u,p,h.position);var v=this.position=a.dot(u,l)-a.dot(c,l);if(this.motorEnabled){var b=this.motorEquation.G;b[0]=l[0],b[1]=l[1],b[2]=a.crossLength(l,p),b[3]=-l[0],b[4]=-l[1],b[5]=-a.crossLength(l,d)}if(this.upperLimitEnabled&&v>i)a.scale(n.normalA,l,-1),a.sub(n.contactPointA,c,o.position),a.sub(n.contactPointB,u,h.position),a.scale(f,l,i),a.add(n.contactPointA,n.contactPointA,f),-1===t.indexOf(n)&&t.push(n);else{var x=t.indexOf(n);-1!==x&&t.splice(x,1)}if(this.lowerLimitEnabled&&v<s)a.scale(r.normalA,l,1),a.sub(r.contactPointA,c,o.position),a.sub(r.contactPointB,u,h.position),a.scale(f,l,s),a.sub(r.contactPointB,r.contactPointB,f),-1===t.indexOf(r)&&t.push(r);else{var x=t.indexOf(r);-1!==x&&t.splice(x,1)}},s.prototype.enableMotor=function(){this.motorEnabled||(this.equations.push(this.motorEquation),this.motorEnabled=!0)},s.prototype.disableMotor=function(){if(this.motorEnabled){var t=this.equations.indexOf(this.motorEquation);this.equations.splice(t,1),this.motorEnabled=!1}},s.prototype.setLimits=function(t,e){"number"==typeof t?(this.lowerLimit=t,this.lowerLimitEnabled=!0):(this.lowerLimit=t,this.lowerLimitEnabled=!1),"number"==typeof e?(this.upperLimit=e,this.upperLimitEnabled=!0):(this.upperLimit=e,this.upperLimitEnabled=!1)}},{"../equations/ContactEquation":21,"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../math/vec2":30,"./Constraint":14}],19:[function(t,e,i){function s(t,e,i){i=i||{},n.call(this,t,e,n.REVOLUTE,i);var s=this.maxForce=void 0!==i.maxForce?i.maxForce:Number.MAX_VALUE;this.pivotA=h.create(),this.pivotB=h.create(),i.worldPivot?(h.sub(this.pivotA,i.worldPivot,t.position),h.sub(this.pivotB,i.worldPivot,e.position),h.rotate(this.pivotA,this.pivotA,-t.angle),h.rotate(this.pivotB,this.pivotB,-e.angle)):(h.copy(this.pivotA,i.localPivotA),h.copy(this.pivotB,i.localPivotB));var f=this.equations=[new r(t,e,-s,s),new r(t,e,-s,s)],g=f[0],m=f[1],y=this;g.computeGq=function(){return h.rotate(l,y.pivotA,t.angle),h.rotate(c,y.pivotB,e.angle),h.add(p,e.position,c),h.sub(p,p,t.position),h.sub(p,p,l),h.dot(p,u)},m.computeGq=function(){return h.rotate(l,y.pivotA,t.angle),h.rotate(c,y.pivotB,e.angle),h.add(p,e.position,c),h.sub(p,p,t.position),h.sub(p,p,l),h.dot(p,d)},m.minForce=g.minForce=-s,m.maxForce=g.maxForce=s,this.motorEquation=new o(t,e),this.motorEnabled=!1,this.angle=0,this.lowerLimitEnabled=!1,this.upperLimitEnabled=!1,this.lowerLimit=0,this.upperLimit=0,this.upperLimitEquation=new a(t,e),this.lowerLimitEquation=new a(t,e),this.upperLimitEquation.minForce=0,this.lowerLimitEquation.maxForce=0}var n=t("./Constraint"),r=t("../equations/Equation"),o=t("../equations/RotationalVelocityEquation"),a=t("../equations/RotationalLockEquation"),h=t("../math/vec2");e.exports=s;var l=h.create(),c=h.create(),u=h.fromValues(1,0),d=h.fromValues(0,1),p=h.create();s.prototype=new n,s.prototype.constructor=s,s.prototype.setLimits=function(t,e){"number"==typeof t?(this.lowerLimit=t,this.lowerLimitEnabled=!0):(this.lowerLimit=t,this.lowerLimitEnabled=!1),"number"==typeof e?(this.upperLimit=e,this.upperLimitEnabled=!0):(this.upperLimit=e,this.upperLimitEnabled=!1)},s.prototype.update=function(){var t=this.bodyA,e=this.bodyB,i=this.pivotA,s=this.pivotB,n=this.equations,r=(n[0],n[1],n[0]),o=n[1],a=this.upperLimit,p=this.lowerLimit,f=this.upperLimitEquation,g=this.lowerLimitEquation,m=this.angle=e.angle-t.angle;if(this.upperLimitEnabled&&m>a)f.angle=a,-1===n.indexOf(f)&&n.push(f);else{var y=n.indexOf(f);-1!==y&&n.splice(y,1)}if(this.lowerLimitEnabled&&m<p)g.angle=p,-1===n.indexOf(g)&&n.push(g);else{var y=n.indexOf(g);-1!==y&&n.splice(y,1)}h.rotate(l,i,t.angle),h.rotate(c,s,e.angle),r.G[0]=-1,r.G[1]=0,r.G[2]=-h.crossLength(l,u),r.G[3]=1,r.G[4]=0,r.G[5]=h.crossLength(c,u),o.G[0]=0,o.G[1]=-1,o.G[2]=-h.crossLength(l,d),o.G[3]=0,o.G[4]=1,o.G[5]=h.crossLength(c,d)},s.prototype.enableMotor=function(){this.motorEnabled||(this.equations.push(this.motorEquation),this.motorEnabled=!0)},s.prototype.disableMotor=function(){if(this.motorEnabled){var t=this.equations.indexOf(this.motorEquation);this.equations.splice(t,1),this.motorEnabled=!1}},s.prototype.motorIsEnabled=function(){return!!this.motorEnabled},s.prototype.setMotorSpeed=function(t){if(this.motorEnabled){var e=this.equations.indexOf(this.motorEquation);this.equations[e].relativeVelocity=t}},s.prototype.getMotorSpeed=function(){return!!this.motorEnabled&&this.motorEquation.relativeVelocity}},{"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../equations/RotationalVelocityEquation":25,"../math/vec2":30,"./Constraint":14}],20:[function(t,e,i){function s(t,e,i){i=i||{},n.call(this,t,e,-Number.MAX_VALUE,Number.MAX_VALUE),this.angle=i.angle||0,this.ratio="number"==typeof i.ratio?i.ratio:1,this.setRatio(this.ratio)}var n=t("./Equation");t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.computeGq=function(){return this.ratio*this.bodyA.angle-this.bodyB.angle+this.angle},s.prototype.setRatio=function(t){var e=this.G;e[2]=t,e[5]=-1,this.ratio=t},s.prototype.setMaxTorque=function(t){this.maxForce=t,this.minForce=-t}},{"../math/vec2":30,"./Equation":22}],21:[function(t,e,i){function s(t,e){n.call(this,t,e,0,Number.MAX_VALUE),this.contactPointA=r.create(),this.penetrationVec=r.create(),this.contactPointB=r.create(),this.normalA=r.create(),this.restitution=0,this.firstImpact=!1,this.shapeA=null,this.shapeB=null}var n=t("./Equation"),r=t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.computeB=function(t,e,i){var s=this.bodyA,n=this.bodyB,o=this.contactPointA,a=this.contactPointB,h=s.position,l=n.position,c=this.penetrationVec,u=this.normalA,d=this.G,p=r.crossLength(o,u),f=r.crossLength(a,u);d[0]=-u[0],d[1]=-u[1],d[2]=-p,d[3]=u[0],d[4]=u[1],d[5]=f,r.add(c,l,a),r.sub(c,c,h),r.sub(c,c,o);var g,m;return this.firstImpact&&0!==this.restitution?(m=0,g=1/e*(1+this.restitution)*this.computeGW()):(m=r.dot(u,c)+this.offset,g=this.computeGW()),-m*t-g*e-i*this.computeGiMf()}},{"../math/vec2":30,"./Equation":22}],22:[function(t,e,i){function s(t,e,i,n){this.minForce=void 0===i?-Number.MAX_VALUE:i,this.maxForce=void 0===n?Number.MAX_VALUE:n,this.bodyA=t,this.bodyB=e,this.stiffness=s.DEFAULT_STIFFNESS,this.relaxation=s.DEFAULT_RELAXATION,this.G=new r.ARRAY_TYPE(6);for(var o=0;o<6;o++)this.G[o]=0;this.offset=0,this.a=0,this.b=0,this.epsilon=0,this.timeStep=1/60,this.needsUpdate=!0,this.multiplier=0,this.relativeVelocity=0,this.enabled=!0}e.exports=s;var n=t("../math/vec2"),r=t("../utils/Utils");t("../objects/Body");s.prototype.constructor=s,s.DEFAULT_STIFFNESS=1e6,s.DEFAULT_RELAXATION=4,s.prototype.update=function(){var t=this.stiffness,e=this.relaxation,i=this.timeStep;this.a=4/(i*(1+4*e)),this.b=4*e/(1+4*e),this.epsilon=4/(i*i*t*(1+4*e)),this.needsUpdate=!1},s.prototype.gmult=function(t,e,i,s,n){return t[0]*e[0]+t[1]*e[1]+t[2]*i+t[3]*s[0]+t[4]*s[1]+t[5]*n},s.prototype.computeB=function(t,e,i){var s=this.computeGW();return-this.computeGq()*t-s*e-this.computeGiMf()*i};var o=n.create(),a=n.create();s.prototype.computeGq=function(){var t=this.G,e=this.bodyA,i=this.bodyB,s=(e.position,i.position,e.angle),n=i.angle;return this.gmult(t,o,s,a,n)+this.offset},s.prototype.computeGW=function(){var t=this.G,e=this.bodyA,i=this.bodyB,s=e.velocity,n=i.velocity,r=e.angularVelocity,o=i.angularVelocity;return this.gmult(t,s,r,n,o)+this.relativeVelocity},s.prototype.computeGWlambda=function(){var t=this.G,e=this.bodyA,i=this.bodyB,s=e.vlambda,n=i.vlambda,r=e.wlambda,o=i.wlambda;return this.gmult(t,s,r,n,o)};var h=n.create(),l=n.create();s.prototype.computeGiMf=function(){var t=this.bodyA,e=this.bodyB,i=t.force,s=t.angularForce,r=e.force,o=e.angularForce,a=t.invMassSolve,c=e.invMassSolve,u=t.invInertiaSolve,d=e.invInertiaSolve,p=this.G;return n.scale(h,i,a),n.multiply(h,t.massMultiplier,h),n.scale(l,r,c),n.multiply(l,e.massMultiplier,l),this.gmult(p,h,s*u,l,o*d)},s.prototype.computeGiMGt=function(){var t=this.bodyA,e=this.bodyB,i=t.invMassSolve,s=e.invMassSolve,n=t.invInertiaSolve,r=e.invInertiaSolve,o=this.G;return o[0]*o[0]*i*t.massMultiplier[0]+o[1]*o[1]*i*t.massMultiplier[1]+o[2]*o[2]*n+o[3]*o[3]*s*e.massMultiplier[0]+o[4]*o[4]*s*e.massMultiplier[1]+o[5]*o[5]*r};var c=n.create(),u=n.create(),d=n.create();n.create(),n.create(),n.create();s.prototype.addToWlambda=function(t){var e=this.bodyA,i=this.bodyB,s=c,r=u,o=d,a=e.invMassSolve,h=i.invMassSolve,l=e.invInertiaSolve,p=i.invInertiaSolve,f=this.G;r[0]=f[0],r[1]=f[1],o[0]=f[3],o[1]=f[4],n.scale(s,r,a*t),n.multiply(s,s,e.massMultiplier),n.add(e.vlambda,e.vlambda,s),e.wlambda+=l*f[2]*t,n.scale(s,o,h*t),n.multiply(s,s,i.massMultiplier),n.add(i.vlambda,i.vlambda,s),i.wlambda+=p*f[5]*t},s.prototype.computeInvC=function(t){return 1/(this.computeGiMGt()+t)}},{"../math/vec2":30,"../objects/Body":31,"../utils/Utils":57}],23:[function(t,e,i){function s(t,e,i){r.call(this,t,e,-i,i),this.contactPointA=n.create(),this.contactPointB=n.create(),this.t=n.create(),this.contactEquations=[],this.shapeA=null,this.shapeB=null,this.frictionCoefficient=.3}var n=t("../math/vec2"),r=t("./Equation");t("../utils/Utils");e.exports=s,s.prototype=new r,s.prototype.constructor=s,s.prototype.setSlipForce=function(t){this.maxForce=t,this.minForce=-t},s.prototype.getSlipForce=function(){return this.maxForce},s.prototype.computeB=function(t,e,i){var s=(this.bodyA,this.bodyB,this.contactPointA),r=this.contactPointB,o=this.t,a=this.G;return a[0]=-o[0],a[1]=-o[1],a[2]=-n.crossLength(s,o),a[3]=o[0],a[4]=o[1],a[5]=n.crossLength(r,o),-this.computeGW()*e-i*this.computeGiMf()}},{"../math/vec2":30,"../utils/Utils":57,"./Equation":22}],24:[function(t,e,i){function s(t,e,i){i=i||{},n.call(this,t,e,-Number.MAX_VALUE,Number.MAX_VALUE),this.angle=i.angle||0;var s=this.G;s[2]=1,s[5]=-1}var n=t("./Equation"),r=t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s;var o=r.create(),a=r.create(),h=r.fromValues(1,0),l=r.fromValues(0,1);s.prototype.computeGq=function(){return r.rotate(o,h,this.bodyA.angle+this.angle),r.rotate(a,l,this.bodyB.angle),r.dot(o,a)}},{"../math/vec2":30,"./Equation":22}],25:[function(t,e,i){function s(t,e){n.call(this,t,e,-Number.MAX_VALUE,Number.MAX_VALUE),this.relativeVelocity=1,this.ratio=1}var n=t("./Equation");t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.computeB=function(t,e,i){var s=this.G;s[2]=-1,s[5]=this.ratio;var n=this.computeGiMf();return-this.computeGW()*e-i*n}},{"../math/vec2":30,"./Equation":22}],26:[function(t,e,i){var s=function(){};e.exports=s,s.prototype={constructor:s,on:function(t,e,i){e.context=i||this,void 0===this._listeners&&(this._listeners={});var s=this._listeners;return void 0===s[t]&&(s[t]=[]),-1===s[t].indexOf(e)&&s[t].push(e),this},has:function(t,e){if(void 0===this._listeners)return!1;var i=this._listeners;if(e){if(void 0!==i[t]&&-1!==i[t].indexOf(e))return!0}else if(void 0!==i[t])return!0;return!1},off:function(t,e){if(void 0===this._listeners)return this;var i=this._listeners,s=i[t].indexOf(e);return-1!==s&&i[t].splice(s,1),this},emit:function(t){if(void 0===this._listeners)return this;var e=this._listeners,i=e[t.type];if(void 0!==i){t.target=this;for(var s=0,n=i.length;s<n;s++){var r=i[s];r.call(r.context,t)}}return this}}},{}],27:[function(t,e,i){function s(t,e,i){if(i=i||{},!(t instanceof n&&e instanceof n))throw new Error("First two arguments must be Material instances.");this.id=s.idCounter++,this.materialA=t,this.materialB=e,this.friction=void 0!==i.friction?Number(i.friction):.3,this.restitution=void 0!==i.restitution?Number(i.restitution):0,this.stiffness=void 0!==i.stiffness?Number(i.stiffness):r.DEFAULT_STIFFNESS,this.relaxation=void 0!==i.relaxation?Number(i.relaxation):r.DEFAULT_RELAXATION,this.frictionStiffness=void 0!==i.frictionStiffness?Number(i.frictionStiffness):r.DEFAULT_STIFFNESS,this.frictionRelaxation=void 0!==i.frictionRelaxation?Number(i.frictionRelaxation):r.DEFAULT_RELAXATION,this.surfaceVelocity=void 0!==i.surfaceVelocity?Number(i.surfaceVelocity):0,this.contactSkinSize=.005}var n=t("./Material"),r=t("../equations/Equation");e.exports=s,s.idCounter=0},{"../equations/Equation":22,"./Material":28}],28:[function(t,e,i){function s(t){this.id=t||s.idCounter++}e.exports=s,s.idCounter=0},{}],29:[function(t,e,i){var s={};s.GetArea=function(t){if(t.length<6)return 0;for(var e=t.length-2,i=0,s=0;s<e;s+=2)i+=(t[s+2]-t[s])*(t[s+1]+t[s+3]);return.5*-(i+=(t[0]-t[e])*(t[e+1]+t[1]))},s.Triangulate=function(t){var e=t.length>>1;if(e<3)return[];for(var i=[],n=[],r=0;r<e;r++)n.push(r);for(var r=0,o=e;o>3;){var a=n[(r+0)%o],h=n[(r+1)%o],l=n[(r+2)%o],c=t[2*a],u=t[2*a+1],d=t[2*h],p=t[2*h+1],f=t[2*l],g=t[2*l+1],m=!1;if(s._convex(c,u,d,p,f,g)){m=!0;for(var y=0;y<o;y++){var v=n[y];if(v!=a&&v!=h&&v!=l&&s._PointInTriangle(t[2*v],t[2*v+1],c,u,d,p,f,g)){m=!1;break}}}if(m)i.push(a,h,l),n.splice((r+1)%o,1),o--,r=0;else if(r++>3*o)break}return i.push(n[0],n[1],n[2]),i},s._PointInTriangle=function(t,e,i,s,n,r,o,a){var h=o-i,l=a-s,c=n-i,u=r-s,d=t-i,p=e-s,f=h*h+l*l,g=h*c+l*u,m=h*d+l*p,y=c*c+u*u,v=c*d+u*p,b=1/(f*y-g*g),x=(y*m-g*v)*b,w=(f*v-g*m)*b;return x>=0&&w>=0&&x+w<1},s._convex=function(t,e,i,s,n,r){return(e-s)*(n-i)+(i-t)*(r-s)>=0},e.exports=s},{}],30:[function(t,e,i){var s=e.exports={},n=t("../utils/Utils");s.crossLength=function(t,e){return t[0]*e[1]-t[1]*e[0]},s.crossVZ=function(t,e,i){return s.rotate(t,e,-Math.PI/2),s.scale(t,t,i),t},s.crossZV=function(t,e,i){return s.rotate(t,i,Math.PI/2),s.scale(t,t,e),t},s.rotate=function(t,e,i){if(0!==i){var s=Math.cos(i),n=Math.sin(i),r=e[0],o=e[1];t[0]=s*r-n*o,t[1]=n*r+s*o}else t[0]=e[0],t[1]=e[1]},s.rotate90cw=function(t,e){var i=e[0],s=e[1];t[0]=s,t[1]=-i},s.toLocalFrame=function(t,e,i,n){s.copy(t,e),s.sub(t,t,i),s.rotate(t,t,-n)},s.toGlobalFrame=function(t,e,i,n){s.copy(t,e),s.rotate(t,t,n),s.add(t,t,i)},s.vectorToLocalFrame=function(t,e,i){s.rotate(t,e,-i)},s.vectorToGlobalFrame=function(t,e,i){s.rotate(t,e,i)},s.centroid=function(t,e,i,n){return s.add(t,e,i),s.add(t,t,n),s.scale(t,t,1/3),t},s.create=function(){var t=new n.ARRAY_TYPE(2);return t[0]=0,t[1]=0,t},s.clone=function(t){var e=new n.ARRAY_TYPE(2);return e[0]=t[0],e[1]=t[1],e},s.fromValues=function(t,e){var i=new n.ARRAY_TYPE(2);return i[0]=t,i[1]=e,i},s.copy=function(t,e){return t[0]=e[0],t[1]=e[1],t},s.set=function(t,e,i){return t[0]=e,t[1]=i,t},s.add=function(t,e,i){return t[0]=e[0]+i[0],t[1]=e[1]+i[1],t},s.subtract=function(t,e,i){return t[0]=e[0]-i[0],t[1]=e[1]-i[1],t},s.sub=s.subtract,s.multiply=function(t,e,i){return t[0]=e[0]*i[0],t[1]=e[1]*i[1],t},s.mul=s.multiply,s.divide=function(t,e,i){return t[0]=e[0]/i[0],t[1]=e[1]/i[1],t},s.div=s.divide,s.scale=function(t,e,i){return t[0]=e[0]*i,t[1]=e[1]*i,t},s.distance=function(t,e){var i=e[0]-t[0],s=e[1]-t[1];return Math.sqrt(i*i+s*s)},s.dist=s.distance,s.squaredDistance=function(t,e){var i=e[0]-t[0],s=e[1]-t[1];return i*i+s*s},s.sqrDist=s.squaredDistance,s.length=function(t){var e=t[0],i=t[1];return Math.sqrt(e*e+i*i)},s.len=s.length,s.squaredLength=function(t){var e=t[0],i=t[1];return e*e+i*i},s.sqrLen=s.squaredLength,s.negate=function(t,e){return t[0]=-e[0],t[1]=-e[1],t},s.normalize=function(t,e){var i=e[0],s=e[1],n=i*i+s*s;return n>0&&(n=1/Math.sqrt(n),t[0]=e[0]*n,t[1]=e[1]*n),t},s.dot=function(t,e){return t[0]*e[0]+t[1]*e[1]},s.str=function(t){return"vec2("+t[0]+", "+t[1]+")"},s.lerp=function(t,e,i,s){var n=e[0],r=e[1];return t[0]=n+s*(i[0]-n),t[1]=r+s*(i[1]-r),t},s.reflect=function(t,e,i){var s=e[0]*i[0]+e[1]*i[1];t[0]=e[0]-2*i[0]*s,t[1]=e[1]-2*i[1]*s},s.getLineSegmentsIntersection=function(t,e,i,n,r){var o=s.getLineSegmentsIntersectionFraction(e,i,n,r);return!(o<0)&&(t[0]=e[0]+o*(i[0]-e[0]),t[1]=e[1]+o*(i[1]-e[1]),!0)},s.getLineSegmentsIntersectionFraction=function(t,e,i,s){var n,r,o=e[0]-t[0],a=e[1]-t[1],h=s[0]-i[0],l=s[1]-i[1];return n=(-a*(t[0]-i[0])+o*(t[1]-i[1]))/(-h*a+o*l),r=(h*(t[1]-i[1])-l*(t[0]-i[0]))/(-h*a+o*l),n>=0&&n<=1&&r>=0&&r<=1?r:-1}},{"../utils/Utils":57}],31:[function(t,e,i){function s(t){t=t||{},c.call(this),this.id=t.id||++s._idCounter,this.world=null,this.shapes=[],this.mass=t.mass||0,this.invMass=0,this.inertia=0,this.invInertia=0,this.invMassSolve=0,this.invInertiaSolve=0,this.fixedRotation=!!t.fixedRotation,this.fixedX=!!t.fixedX,this.fixedY=!!t.fixedY,this.massMultiplier=n.create(),this.position=n.fromValues(0,0),t.position&&n.copy(this.position,t.position),this.interpolatedPosition=n.fromValues(0,0),this.interpolatedAngle=0,this.previousPosition=n.fromValues(0,0),this.previousAngle=0,this.velocity=n.fromValues(0,0),t.velocity&&n.copy(this.velocity,t.velocity),this.vlambda=n.fromValues(0,0),this.wlambda=0,this.angle=t.angle||0,this.angularVelocity=t.angularVelocity||0,this.force=n.create(),t.force&&n.copy(this.force,t.force),this.angularForce=t.angularForce||0,this.damping="number"==typeof t.damping?t.damping:.1,this.angularDamping="number"==typeof t.angularDamping?t.angularDamping:.1,this.type=s.STATIC,void 0!==t.type?this.type=t.type:t.mass?this.type=s.DYNAMIC:this.type=s.STATIC,this.boundingRadius=0,this.aabb=new l,this.aabbNeedsUpdate=!0,this.allowSleep=void 0===t.allowSleep||t.allowSleep,this.wantsToSleep=!1,this.sleepState=s.AWAKE,this.sleepSpeedLimit=void 0!==t.sleepSpeedLimit?t.sleepSpeedLimit:.2,this.sleepTimeLimit=void 0!==t.sleepTimeLimit?t.sleepTimeLimit:1,this.gravityScale=void 0!==t.gravityScale?t.gravityScale:1,this.collisionResponse=void 0===t.collisionResponse||t.collisionResponse,this.idleTime=0,this.timeLastSleepy=0,this.ccdSpeedThreshold=void 0!==t.ccdSpeedThreshold?t.ccdSpeedThreshold:-1,this.ccdIterations=void 0!==t.ccdIterations?t.ccdIterations:10,this.concavePath=null,this._wakeUpAfterNarrowphase=!1,this.updateMassProperties()}var n=t("../math/vec2"),r=t("poly-decomp"),o=t("../shapes/Convex"),a=t("../collision/RaycastResult"),h=t("../collision/Ray"),l=t("../collision/AABB"),c=t("../events/EventEmitter");e.exports=s,s.prototype=new c,s.prototype.constructor=s,s._idCounter=0,s.prototype.updateSolveMassProperties=function(){this.sleepState===s.SLEEPING||this.type===s.KINEMATIC?(this.invMassSolve=0,this.invInertiaSolve=0):(this.invMassSolve=this.invMass,this.invInertiaSolve=this.invInertia)},s.prototype.setDensity=function(t){var e=this.getArea();this.mass=e*t,this.updateMassProperties()},s.prototype.getArea=function(){for(var t=0,e=0;e<this.shapes.length;e++)t+=this.shapes[e].area;return t},s.prototype.getAABB=function(){return this.aabbNeedsUpdate&&this.updateAABB(),this.aabb};var u=new l,d=n.create();s.prototype.updateAABB=function(){for(var t=this.shapes,e=t.length,i=d,s=this.angle,r=0;r!==e;r++){var o=t[r],a=o.angle+s;n.rotate(i,o.position,s),n.add(i,i,this.position),o.computeAABB(u,i,a),0===r?this.aabb.copy(u):this.aabb.extend(u)}this.aabbNeedsUpdate=!1},s.prototype.updateBoundingRadius=function(){for(var t=this.shapes,e=t.length,i=0,s=0;s!==e;s++){var r=t[s],o=n.length(r.position),a=r.boundingRadius;o+a>i&&(i=o+a)}this.boundingRadius=i},s.prototype.addShape=function(t,e,i){if(t.body)throw new Error("A shape can only be added to one body.");t.body=this,e?n.copy(t.position,e):n.set(t.position,0,0),t.angle=i||0,this.shapes.push(t),this.updateMassProperties(),this.updateBoundingRadius(),this.aabbNeedsUpdate=!0},s.prototype.removeShape=function(t){var e=this.shapes.indexOf(t);return-1!==e&&(this.shapes.splice(e,1),this.aabbNeedsUpdate=!0,t.body=null,!0)},s.prototype.updateMassProperties=function(){if(this.type===s.STATIC||this.type===s.KINEMATIC)this.mass=Number.MAX_VALUE,this.invMass=0,this.inertia=Number.MAX_VALUE,this.invInertia=0;else{var t=this.shapes,e=t.length,i=this.mass/e,r=0;if(this.fixedRotation)this.inertia=Number.MAX_VALUE,this.invInertia=0;else{for(var o=0;o<e;o++){var a=t[o],h=n.squaredLength(a.position);r+=a.computeMomentOfInertia(i)+i*h}this.inertia=r,this.invInertia=r>0?1/r:0}this.invMass=1/this.mass,n.set(this.massMultiplier,this.fixedX?0:1,this.fixedY?0:1)}};n.create();s.prototype.applyForce=function(t,e){if(n.add(this.force,this.force,t),e){var i=n.crossLength(e,t);this.angularForce+=i}};var p=n.create(),f=n.create(),g=n.create();s.prototype.applyForceLocal=function(t,e){e=e||g;var i=p,s=f;this.vectorToWorldFrame(i,t),this.vectorToWorldFrame(s,e),this.applyForce(i,s)};var m=n.create();s.prototype.applyImpulse=function(t,e){if(this.type===s.DYNAMIC){var i=m;if(n.scale(i,t,this.invMass),n.multiply(i,this.massMultiplier,i),n.add(this.velocity,i,this.velocity),e){var r=n.crossLength(e,t);r*=this.invInertia,this.angularVelocity+=r}}};var y=n.create(),v=n.create(),b=n.create();s.prototype.applyImpulseLocal=function(t,e){e=e||b;var i=y,s=v;this.vectorToWorldFrame(i,t),this.vectorToWorldFrame(s,e),this.applyImpulse(i,s)},s.prototype.toLocalFrame=function(t,e){n.toLocalFrame(t,e,this.position,this.angle)},s.prototype.toWorldFrame=function(t,e){n.toGlobalFrame(t,e,this.position,this.angle)},s.prototype.vectorToLocalFrame=function(t,e){n.vectorToLocalFrame(t,e,this.angle)},s.prototype.vectorToWorldFrame=function(t,e){n.vectorToGlobalFrame(t,e,this.angle)},s.prototype.fromPolygon=function(t,e){e=e||{};for(var i=this.shapes.length;i>=0;--i)this.removeShape(this.shapes[i]);var s=new r.Polygon;if(s.vertices=t,s.makeCCW(),"number"==typeof e.removeCollinearPoints&&s.removeCollinearPoints(e.removeCollinearPoints),void 0===e.skipSimpleCheck&&!s.isSimple())return!1;this.concavePath=s.vertices.slice(0);for(var i=0;i<this.concavePath.length;i++){var a=[0,0];n.copy(a,this.concavePath[i]),this.concavePath[i]=a}var h;h=e.optimalDecomp?s.decomp():s.quickDecomp();for(var l=n.create(),i=0;i!==h.length;i++){for(var c=new o({vertices:h[i].vertices}),u=0;u!==c.vertices.length;u++){var a=c.vertices[u];n.sub(a,a,c.centerOfMass)}n.scale(l,c.centerOfMass,1),c.updateTriangles(),c.updateCenterOfMass(),c.updateBoundingRadius(),this.addShape(c,l)}return this.adjustCenterOfMass(),this.aabbNeedsUpdate=!0,!0};var x=(n.fromValues(0,0),n.fromValues(0,0)),w=n.fromValues(0,0),_=n.fromValues(0,0);s.prototype.adjustCenterOfMass=function(){var t=x,e=w,i=_,s=0;n.set(e,0,0);for(var r=0;r!==this.shapes.length;r++){var o=this.shapes[r];n.scale(t,o.position,o.area),n.add(e,e,t),s+=o.area}n.scale(i,e,1/s);for(var r=0;r!==this.shapes.length;r++){var o=this.shapes[r];n.sub(o.position,o.position,i)}n.add(this.position,this.position,i);for(var r=0;this.concavePath&&r<this.concavePath.length;r++)n.sub(this.concavePath[r],this.concavePath[r],i);this.updateMassProperties(),this.updateBoundingRadius()},s.prototype.setZeroForce=function(){n.set(this.force,0,0),this.angularForce=0},s.prototype.resetConstraintVelocity=function(){var t=this,e=t.vlambda;n.set(e,0,0),t.wlambda=0},s.prototype.addConstraintVelocity=function(){var t=this,e=t.velocity;n.add(e,e,t.vlambda),t.angularVelocity+=t.wlambda},s.prototype.applyDamping=function(t){if(this.type===s.DYNAMIC){var e=this.velocity;n.scale(e,e,Math.pow(1-this.damping,t)),this.angularVelocity*=Math.pow(1-this.angularDamping,t)}},s.prototype.wakeUp=function(){var t=this.sleepState;this.sleepState=s.AWAKE,this.idleTime=0,t!==s.AWAKE&&this.emit(s.wakeUpEvent)},s.prototype.sleep=function(){this.sleepState=s.SLEEPING,this.angularVelocity=0,this.angularForce=0,n.set(this.velocity,0,0),n.set(this.force,0,0),this.emit(s.sleepEvent)},s.prototype.sleepTick=function(t,e,i){if(this.allowSleep&&this.type!==s.SLEEPING){this.wantsToSleep=!1;this.sleepState;n.squaredLength(this.velocity)+Math.pow(this.angularVelocity,2)>=Math.pow(this.sleepSpeedLimit,2)?(this.idleTime=0,this.sleepState=s.AWAKE):(this.idleTime+=i,this.sleepState=s.SLEEPY),this.idleTime>this.sleepTimeLimit&&(e?this.wantsToSleep=!0:this.sleep())}},s.prototype.overlaps=function(t){return this.world.overlapKeeper.bodiesAreOverlapping(this,t)};var P=n.create(),T=n.create();s.prototype.integrate=function(t){var e=this.invMass,i=this.force,s=this.position,r=this.velocity;n.copy(this.previousPosition,this.position),this.previousAngle=this.angle,this.fixedRotation||(this.angularVelocity+=this.angularForce*this.invInertia*t),n.scale(P,i,t*e),n.multiply(P,this.massMultiplier,P),n.add(r,P,r),this.integrateToTimeOfImpact(t)||(n.scale(T,r,t),n.add(s,s,T),this.fixedRotation||(this.angle+=this.angularVelocity*t)),this.aabbNeedsUpdate=!0};var C=new a,S=new h({mode:h.ALL}),A=n.create(),E=n.create(),I=n.create(),M=n.create();s.prototype.integrateToTimeOfImpact=function(t){if(this.ccdSpeedThreshold<0||n.squaredLength(this.velocity)<Math.pow(this.ccdSpeedThreshold,2))return!1;n.normalize(A,this.velocity),n.scale(E,this.velocity,t),n.add(E,E,this.position),n.sub(I,E,this.position);var e,i=this.angularVelocity*t,s=n.length(I),r=1,o=this;if(C.reset(),S.callback=function(t){t.body!==o&&(e=t.body,t.getHitPoint(E,S),n.sub(I,E,o.position),r=n.length(I)/s,t.stop())},n.copy(S.from,this.position),n.copy(S.to,E),S.update(),this.world.raycast(C,S),!e)return!1;var a=this.angle;n.copy(M,this.position);for(var h=0,l=0,c=0,u=r;u>=l&&h<this.ccdIterations;){h++,c=(u-l)/2,n.scale(T,I,r),n.add(this.position,M,T),this.angle=a+i*r,this.updateAABB();this.aabb.overlaps(e.aabb)&&this.world.narrowphase.bodiesOverlap(this,e)?l=c:u=c}return r=c,n.copy(this.position,M),this.angle=a,n.scale(T,I,r),n.add(this.position,this.position,T),this.fixedRotation||(this.angle+=i*r),!0},s.prototype.getVelocityAtPoint=function(t,e){return n.crossVZ(t,e,this.angularVelocity),n.subtract(t,this.velocity,t),t},s.sleepyEvent={type:"sleepy"},s.sleepEvent={type:"sleep"},s.wakeUpEvent={type:"wakeup"},s.DYNAMIC=1,s.STATIC=2,s.KINEMATIC=4,s.AWAKE=0,s.SLEEPY=1,s.SLEEPING=2},{"../collision/AABB":7,"../collision/Ray":11,"../collision/RaycastResult":12,"../events/EventEmitter":26,"../math/vec2":30,"../shapes/Convex":40,"poly-decomp":5}],32:[function(t,e,i){function s(t,e,i){i=i||{},r.call(this,t,e,i),this.localAnchorA=n.fromValues(0,0),this.localAnchorB=n.fromValues(0,0),i.localAnchorA&&n.copy(this.localAnchorA,i.localAnchorA),i.localAnchorB&&n.copy(this.localAnchorB,i.localAnchorB),i.worldAnchorA&&this.setWorldAnchorA(i.worldAnchorA),i.worldAnchorB&&this.setWorldAnchorB(i.worldAnchorB);var s=n.create(),o=n.create();this.getWorldAnchorA(s),this.getWorldAnchorB(o);var a=n.distance(s,o);this.restLength="number"==typeof i.restLength?i.restLength:a}var n=t("../math/vec2"),r=t("./Spring");t("../utils/Utils");e.exports=s,s.prototype=new r,s.prototype.constructor=s,s.prototype.setWorldAnchorA=function(t){this.bodyA.toLocalFrame(this.localAnchorA,t)},s.prototype.setWorldAnchorB=function(t){this.bodyB.toLocalFrame(this.localAnchorB,t)},s.prototype.getWorldAnchorA=function(t){this.bodyA.toWorldFrame(t,this.localAnchorA)},s.prototype.getWorldAnchorB=function(t){this.bodyB.toWorldFrame(t,this.localAnchorB)};var o=n.create(),a=n.create(),h=n.create(),l=n.create(),c=n.create(),u=n.create(),d=n.create(),p=n.create(),f=n.create();s.prototype.applyForce=function(){var t=this.stiffness,e=this.damping,i=this.restLength,s=this.bodyA,r=this.bodyB,g=o,m=a,y=h,v=l,b=f,x=c,w=u,_=d,P=p;this.getWorldAnchorA(x),this.getWorldAnchorB(w),n.sub(_,x,s.position),n.sub(P,w,r.position),n.sub(g,w,x);var T=n.len(g);n.normalize(m,g),n.sub(y,r.velocity,s.velocity),n.crossZV(b,r.angularVelocity,P),n.add(y,y,b),n.crossZV(b,s.angularVelocity,_),n.sub(y,y,b),n.scale(v,m,-t*(T-i)-e*n.dot(y,m)),n.sub(s.force,s.force,v),n.add(r.force,r.force,v);var C=n.crossLength(_,v),S=n.crossLength(P,v);s.angularForce-=C,r.angularForce+=S}},{"../math/vec2":30,"../utils/Utils":57,"./Spring":34}],33:[function(t,e,i){function s(t,e,i){i=i||{},n.call(this,t,e,i),this.restAngle="number"==typeof i.restAngle?i.restAngle:e.angle-t.angle}var n=(t("../math/vec2"),t("./Spring"));e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.applyForce=function(){var t=this.stiffness,e=this.damping,i=this.restAngle,s=this.bodyA,n=this.bodyB,r=n.angle-s.angle,o=n.angularVelocity-s.angularVelocity,a=-t*(r-i)-e*o*0;s.angularForce-=a,n.angularForce+=a}},{"../math/vec2":30,"./Spring":34}],34:[function(t,e,i){function s(t,e,i){i=n.defaults(i,{stiffness:100,damping:1}),this.stiffness=i.stiffness,this.damping=i.damping,this.bodyA=t,this.bodyB=e}var n=(t("../math/vec2"),t("../utils/Utils"));e.exports=s,s.prototype.applyForce=function(){}},{"../math/vec2":30,"../utils/Utils":57}],35:[function(t,e,i){function s(t,e){e=e||{},this.chassisBody=t,this.wheels=[],this.groundBody=new h({mass:0}),this.world=null;var i=this;this.preStepCallback=function(){i.update()}}function n(t,e){e=e||{},this.vehicle=t,this.forwardEquation=new a(t.chassisBody,t.groundBody),this.sideEquation=new a(t.chassisBody,t.groundBody),this.steerValue=0,this.engineForce=0,this.setSideFriction(void 0!==e.sideFriction?e.sideFriction:5),this.localForwardVector=r.fromValues(0,1),e.localForwardVector&&r.copy(this.localForwardVector,e.localForwardVector),this.localPosition=r.fromValues(0,0),e.localPosition&&r.copy(this.localPosition,e.localPosition),o.apply(this,t.chassisBody,t.groundBody),this.equations.push(this.forwardEquation,this.sideEquation),this.setBrakeForce(0)}var r=t("../math/vec2"),o=(t("../utils/Utils"),t("../constraints/Constraint")),a=t("../equations/FrictionEquation"),h=t("../objects/Body");e.exports=s,s.prototype.addToWorld=function(t){this.world=t,t.addBody(this.groundBody),t.on("preStep",this.preStepCallback);for(var e=0;e<this.wheels.length;e++){var i=this.wheels[e];t.addConstraint(i)}},s.prototype.removeFromWorld=function(){var t=this.world;t.removeBody(this.groundBody),t.off("preStep",this.preStepCallback);for(var e=0;e<this.wheels.length;e++){var i=this.wheels[e];t.removeConstraint(i)}this.world=null},s.prototype.addWheel=function(t){var e=new n(this,t);return this.wheels.push(e),e},s.prototype.update=function(){for(var t=0;t<this.wheels.length;t++)this.wheels[t].update()},n.prototype=new o,n.prototype.setBrakeForce=function(t){this.forwardEquation.setSlipForce(t)},n.prototype.setSideFriction=function(t){this.sideEquation.setSlipForce(t)};var l=r.create(),c=r.create();n.prototype.getSpeed=function(){return this.vehicle.chassisBody.vectorToWorldFrame(c,this.localForwardVector),this.vehicle.chassisBody.getVelocityAtPoint(l,c),r.dot(l,c)};var u=r.create();n.prototype.update=function(){this.vehicle.chassisBody.vectorToWorldFrame(this.forwardEquation.t,this.localForwardVector),r.rotate(this.sideEquation.t,this.localForwardVector,Math.PI/2),this.vehicle.chassisBody.vectorToWorldFrame(this.sideEquation.t,this.sideEquation.t),r.rotate(this.forwardEquation.t,this.forwardEquation.t,this.steerValue),r.rotate(this.sideEquation.t,this.sideEquation.t,this.steerValue),this.vehicle.chassisBody.toWorldFrame(this.forwardEquation.contactPointB,this.localPosition),r.copy(this.sideEquation.contactPointB,this.forwardEquation.contactPointB),this.vehicle.chassisBody.vectorToWorldFrame(this.forwardEquation.contactPointA,this.localPosition),r.copy(this.sideEquation.contactPointA,this.forwardEquation.contactPointA),r.normalize(u,this.forwardEquation.t),r.scale(u,u,this.engineForce),this.vehicle.chassisBody.applyForce(u,this.forwardEquation.contactPointA)}},{"../constraints/Constraint":14,"../equations/FrictionEquation":23,"../math/vec2":30,"../objects/Body":31,"../utils/Utils":57}],36:[function(t,e,i){var s=e.exports={AABB:t("./collision/AABB"),AngleLockEquation:t("./equations/AngleLockEquation"),Body:t("./objects/Body"),Broadphase:t("./collision/Broadphase"),Capsule:t("./shapes/Capsule"),Circle:t("./shapes/Circle"),Constraint:t("./constraints/Constraint"),ContactEquation:t("./equations/ContactEquation"),ContactEquationPool:t("./utils/ContactEquationPool"),ContactMaterial:t("./material/ContactMaterial"),Convex:t("./shapes/Convex"),DistanceConstraint:t("./constraints/DistanceConstraint"),Equation:t("./equations/Equation"),EventEmitter:t("./events/EventEmitter"),FrictionEquation:t("./equations/FrictionEquation"),FrictionEquationPool:t("./utils/FrictionEquationPool"),GearConstraint:t("./constraints/GearConstraint"),GSSolver:t("./solver/GSSolver"),Heightfield:t("./shapes/Heightfield"),Line:t("./shapes/Line"),LockConstraint:t("./constraints/LockConstraint"),Material:t("./material/Material"),Narrowphase:t("./collision/Narrowphase"),NaiveBroadphase:t("./collision/NaiveBroadphase"),Particle:t("./shapes/Particle"),Plane:t("./shapes/Plane"),Pool:t("./utils/Pool"),RevoluteConstraint:t("./constraints/RevoluteConstraint"),PrismaticConstraint:t("./constraints/PrismaticConstraint"),Ray:t("./collision/Ray"),RaycastResult:t("./collision/RaycastResult"),Box:t("./shapes/Box"),RotationalVelocityEquation:t("./equations/RotationalVelocityEquation"),SAPBroadphase:t("./collision/SAPBroadphase"),Shape:t("./shapes/Shape"),Solver:t("./solver/Solver"),Spring:t("./objects/Spring"),TopDownVehicle:t("./objects/TopDownVehicle"),LinearSpring:t("./objects/LinearSpring"),RotationalSpring:t("./objects/RotationalSpring"),Utils:t("./utils/Utils"),World:t("./world/World"),vec2:t("./math/vec2"),version:t("../package.json").version};Object.defineProperty(s,"Rectangle",{get:function(){return console.warn("The Rectangle class has been renamed to Box."),this.Box}})},{"../package.json":6,"./collision/AABB":7,"./collision/Broadphase":8,"./collision/NaiveBroadphase":9,"./collision/Narrowphase":10,"./collision/Ray":11,"./collision/RaycastResult":12,"./collision/SAPBroadphase":13,"./constraints/Constraint":14,"./constraints/DistanceConstraint":15,"./constraints/GearConstraint":16,"./constraints/LockConstraint":17,"./constraints/PrismaticConstraint":18,"./constraints/RevoluteConstraint":19,"./equations/AngleLockEquation":20,"./equations/ContactEquation":21,"./equations/Equation":22,"./equations/FrictionEquation":23,"./equations/RotationalVelocityEquation":25,"./events/EventEmitter":26,"./material/ContactMaterial":27,"./material/Material":28,"./math/vec2":30,"./objects/Body":31,"./objects/LinearSpring":32,"./objects/RotationalSpring":33,"./objects/Spring":34,"./objects/TopDownVehicle":35,"./shapes/Box":37,"./shapes/Capsule":38,"./shapes/Circle":39,"./shapes/Convex":40,"./shapes/Heightfield":41,"./shapes/Line":42,"./shapes/Particle":43,"./shapes/Plane":44,"./shapes/Shape":45,"./solver/GSSolver":46,"./solver/Solver":47,"./utils/ContactEquationPool":48,"./utils/FrictionEquationPool":49,"./utils/Pool":55,"./utils/Utils":57,"./world/World":61}],37:[function(t,e,i){function s(t){"number"==typeof arguments[0]&&"number"==typeof arguments[1]&&(t={width:arguments[0],height:arguments[1]},console.warn("The Rectangle has been renamed to Box and its constructor signature has changed. Please use the following format: new Box({ width: 1, height: 1, ... })")),t=t||{};var e=this.width=t.width||1,i=this.height=t.height||1,s=[n.fromValues(-e/2,-i/2),n.fromValues(e/2,-i/2),n.fromValues(e/2,i/2),n.fromValues(-e/2,i/2)],a=[n.fromValues(1,0),n.fromValues(0,1)];t.vertices=s,t.axes=a,t.type=r.BOX,o.call(this,t)}var n=t("../math/vec2"),r=t("./Shape"),o=t("./Convex");e.exports=s,s.prototype=new o,s.prototype.constructor=s,s.prototype.computeMomentOfInertia=function(t){var e=this.width,i=this.height;return t*(i*i+e*e)/12},s.prototype.updateBoundingRadius=function(){var t=this.width,e=this.height;this.boundingRadius=Math.sqrt(t*t+e*e)/2};n.create(),n.create(),n.create(),n.create();s.prototype.computeAABB=function(t,e,i){t.setFromPoints(this.vertices,e,i,0)},s.prototype.updateArea=function(){this.area=this.width*this.height}},{"../math/vec2":30,"./Convex":40,"./Shape":45}],38:[function(t,e,i){function s(t){"number"==typeof arguments[0]&&"number"==typeof arguments[1]&&(t={length:arguments[0],radius:arguments[1]},console.warn("The Capsule constructor signature has changed. Please use the following format: new Capsule({ radius: 1, length: 1 })")),t=t||{},this.length=t.length||1,this.radius=t.radius||1,t.type=n.CAPSULE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.computeMomentOfInertia=function(t){var e=this.radius,i=this.length+e,s=2*e;return t*(s*s+i*i)/12},s.prototype.updateBoundingRadius=function(){this.boundingRadius=this.radius+this.length/2},s.prototype.updateArea=function(){this.area=Math.PI*this.radius*this.radius+2*this.radius*this.length};var o=r.create();s.prototype.computeAABB=function(t,e,i){var s=this.radius;r.set(o,this.length/2,0),0!==i&&r.rotate(o,o,i),r.set(t.upperBound,Math.max(o[0]+s,-o[0]+s),Math.max(o[1]+s,-o[1]+s)),r.set(t.lowerBound,Math.min(o[0]-s,-o[0]-s),Math.min(o[1]-s,-o[1]-s)),r.add(t.lowerBound,t.lowerBound,e),r.add(t.upperBound,t.upperBound,e)};var a=r.create(),h=r.create(),l=r.create(),c=r.create(),u=r.fromValues(0,1);s.prototype.raycast=function(t,e,i,s){for(var n=e.from,o=e.to,d=(e.direction,a),p=h,f=l,g=c,m=this.length/2,y=0;y<2;y++){var v=this.radius*(2*y-1);r.set(f,-m,v),r.set(g,m,v),r.toGlobalFrame(f,f,i,s),r.toGlobalFrame(g,g,i,s);var b=r.getLineSegmentsIntersectionFraction(n,o,f,g);if(b>=0&&(r.rotate(p,u,s),r.scale(p,p,2*y-1),e.reportIntersection(t,b,p,-1),t.shouldStop(e)))return}for(var x=Math.pow(this.radius,2)+Math.pow(m,2),y=0;y<2;y++){r.set(f,m*(2*y-1),0),r.toGlobalFrame(f,f,i,s);var w=Math.pow(o[0]-n[0],2)+Math.pow(o[1]-n[1],2),_=2*((o[0]-n[0])*(n[0]-f[0])+(o[1]-n[1])*(n[1]-f[1])),P=Math.pow(n[0]-f[0],2)+Math.pow(n[1]-f[1],2)-Math.pow(this.radius,2),b=Math.pow(_,2)-4*w*P;if(!(b<0))if(0===b){if(r.lerp(d,n,o,b),r.squaredDistance(d,i)>x&&(r.sub(p,d,f),r.normalize(p,p),e.reportIntersection(t,b,p,-1),t.shouldStop(e)))return}else{var T=Math.sqrt(b),C=1/(2*w),S=(-_-T)*C,A=(-_+T)*C;if(S>=0&&S<=1&&(r.lerp(d,n,o,S),r.squaredDistance(d,i)>x&&(r.sub(p,d,f),r.normalize(p,p),e.reportIntersection(t,S,p,-1),t.shouldStop(e))))return;if(A>=0&&A<=1&&(r.lerp(d,n,o,A),r.squaredDistance(d,i)>x&&(r.sub(p,d,f),r.normalize(p,p),e.reportIntersection(t,A,p,-1),t.shouldStop(e))))return}}}},{"../math/vec2":30,"./Shape":45}],39:[function(t,e,i){function s(t){"number"==typeof arguments[0]&&(t={radius:arguments[0]},console.warn("The Circle constructor signature has changed. Please use the following format: new Circle({ radius: 1 })")),t=t||{},this.radius=t.radius||1,t.type=n.CIRCLE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.computeMomentOfInertia=function(t){var e=this.radius;return t*e*e/2},s.prototype.updateBoundingRadius=function(){this.boundingRadius=this.radius},s.prototype.updateArea=function(){this.area=Math.PI*this.radius*this.radius},s.prototype.computeAABB=function(t,e,i){var s=this.radius;r.set(t.upperBound,s,s),r.set(t.lowerBound,-s,-s),e&&(r.add(t.lowerBound,t.lowerBound,e),r.add(t.upperBound,t.upperBound,e))};var o=r.create(),a=r.create();s.prototype.raycast=function(t,e,i,s){var n=e.from,h=e.to,l=this.radius,c=Math.pow(h[0]-n[0],2)+Math.pow(h[1]-n[1],2),u=2*((h[0]-n[0])*(n[0]-i[0])+(h[1]-n[1])*(n[1]-i[1])),d=Math.pow(n[0]-i[0],2)+Math.pow(n[1]-i[1],2)-Math.pow(l,2),p=Math.pow(u,2)-4*c*d,f=o,g=a;if(!(p<0))if(0===p)r.lerp(f,n,h,p),r.sub(g,f,i),r.normalize(g,g),e.reportIntersection(t,p,g,-1);else{var m=Math.sqrt(p),y=1/(2*c),v=(-u-m)*y,b=(-u+m)*y;if(v>=0&&v<=1&&(r.lerp(f,n,h,v),r.sub(g,f,i),r.normalize(g,g),e.reportIntersection(t,v,g,-1),t.shouldStop(e)))return;b>=0&&b<=1&&(r.lerp(f,n,h,b),r.sub(g,f,i),r.normalize(g,g),e.reportIntersection(t,b,g,-1))}}},{"../math/vec2":30,"./Shape":45}],40:[function(t,e,i){function s(t){Array.isArray(arguments[0])&&(t={vertices:arguments[0],axes:arguments[1]},console.warn("The Convex constructor signature has changed. Please use the following format: new Convex({ vertices: [...], ... })")),t=t||{},this.vertices=[];for(var e=void 0!==t.vertices?t.vertices:[],i=0;i<e.length;i++){var s=r.create();r.copy(s,e[i]),this.vertices.push(s)}if(this.axes=[],t.axes)for(var i=0;i<t.axes.length;i++){var o=r.create();r.copy(o,t.axes[i]),this.axes.push(o)}else for(var i=0;i<this.vertices.length;i++){var a=this.vertices[i],h=this.vertices[(i+1)%this.vertices.length],l=r.create();r.sub(l,h,a),r.rotate90cw(l,l),r.normalize(l,l),this.axes.push(l)}if(this.centerOfMass=r.fromValues(0,0),this.triangles=[],this.vertices.length&&(this.updateTriangles(),this.updateCenterOfMass()),this.boundingRadius=0,t.type=n.CONVEX,n.call(this,t),this.updateBoundingRadius(),this.updateArea(),this.area<0)throw new Error("Convex vertices must be given in conter-clockwise winding.")}var n=t("./Shape"),r=t("../math/vec2"),o=t("../math/polyk");t("poly-decomp");e.exports=s,s.prototype=new n,s.prototype.constructor=s;var a=r.create(),h=r.create();s.prototype.projectOntoLocalAxis=function(t,e){for(var i,s,n=null,o=null,t=a,h=0;h<this.vertices.length;h++)i=this.vertices[h],s=r.dot(i,t),(null===n||s>n)&&(n=s),(null===o||s<o)&&(o=s);if(o>n){var l=o;o=n,n=l}r.set(e,o,n)},s.prototype.projectOntoWorldAxis=function(t,e,i,s){var n=h;this.projectOntoLocalAxis(t,s),0!==i?r.rotate(n,t,i):n=t;var o=r.dot(e,n);r.set(s,s[0]+o,s[1]+o)},s.prototype.updateTriangles=function(){this.triangles.length=0;for(var t=[],e=0;e<this.vertices.length;e++){var i=this.vertices[e];t.push(i[0],i[1])}for(var s=o.Triangulate(t),e=0;e<s.length;e+=3){var n=s[e],r=s[e+1],a=s[e+2];this.triangles.push([n,r,a])}};var l=r.create(),c=r.create(),u=r.create(),d=r.create(),p=r.create();r.create(),r.create(),r.create(),r.create();s.prototype.updateCenterOfMass=function(){var t=this.triangles,e=this.vertices,i=this.centerOfMass,n=l,o=u,a=d,h=p,f=c;r.set(i,0,0);for(var g=0,m=0;m!==t.length;m++){var y=t[m],o=e[y[0]],a=e[y[1]],h=e[y[2]];r.centroid(n,o,a,h);var v=s.triangleArea(o,a,h);g+=v,r.scale(f,n,v),r.add(i,i,f)}r.scale(i,i,1/g)},s.prototype.computeMomentOfInertia=function(t){for(var e=0,i=0,s=this.vertices.length,n=s-1,o=0;o<s;n=o,o++){var a=this.vertices[n],h=this.vertices[o],l=Math.abs(r.crossLength(a,h));e+=l*(r.dot(h,h)+r.dot(h,a)+r.dot(a,a)),i+=l}return t/6*(e/i)},s.prototype.updateBoundingRadius=function(){for(var t=this.vertices,e=0,i=0;i!==t.length;i++){var s=r.squaredLength(t[i]);s>e&&(e=s)}this.boundingRadius=Math.sqrt(e)},s.triangleArea=function(t,e,i){return.5*((e[0]-t[0])*(i[1]-t[1])-(i[0]-t[0])*(e[1]-t[1]))},s.prototype.updateArea=function(){this.updateTriangles(),this.area=0;for(var t=this.triangles,e=this.vertices,i=0;i!==t.length;i++){var n=t[i],r=e[n[0]],o=e[n[1]],a=e[n[2]],h=s.triangleArea(r,o,a);this.area+=h}},s.prototype.computeAABB=function(t,e,i){t.setFromPoints(this.vertices,e,i,0)};var f=r.create(),g=r.create(),m=r.create();s.prototype.raycast=function(t,e,i,s){var n=f,o=g,a=m,h=this.vertices;r.toLocalFrame(n,e.from,i,s),r.toLocalFrame(o,e.to,i,s);for(var l=h.length,c=0;c<l&&!t.shouldStop(e);c++){var u=h[c],d=h[(c+1)%l],p=r.getLineSegmentsIntersectionFraction(n,o,u,d);p>=0&&(r.sub(a,d,u),r.rotate(a,a,-Math.PI/2+s),r.normalize(a,a),e.reportIntersection(t,p,a,c))}}},{"../math/polyk":29,"../math/vec2":30,"./Shape":45,"poly-decomp":5}],41:[function(t,e,i){function s(t){if(Array.isArray(arguments[0])){if(t={heights:arguments[0]},"object"==typeof arguments[1])for(var e in arguments[1])t[e]=arguments[1][e];console.warn("The Heightfield constructor signature has changed. Please use the following format: new Heightfield({ heights: [...], ... })")}t=t||{},this.heights=t.heights?t.heights.slice(0):[],this.maxValue=t.maxValue||null,this.minValue=t.minValue||null,this.elementWidth=t.elementWidth||.1,void 0!==t.maxValue&&void 0!==t.minValue||this.updateMaxMinValues(),t.type=n.HEIGHTFIELD,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");t("../utils/Utils");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.updateMaxMinValues=function(){for(var t=this.heights,e=t[0],i=t[0],s=0;s!==t.length;s++){var n=t[s];n>e&&(e=n),n<i&&(i=n)}this.maxValue=e,this.minValue=i},s.prototype.computeMomentOfInertia=function(t){return Number.MAX_VALUE},s.prototype.updateBoundingRadius=function(){this.boundingRadius=Number.MAX_VALUE},s.prototype.updateArea=function(){for(var t=this.heights,e=0,i=0;i<t.length-1;i++)e+=(t[i]+t[i+1])/2*this.elementWidth;this.area=e};var o=[r.create(),r.create(),r.create(),r.create()];s.prototype.computeAABB=function(t,e,i){r.set(o[0],0,this.maxValue),r.set(o[1],this.elementWidth*this.heights.length,this.maxValue),r.set(o[2],this.elementWidth*this.heights.length,this.minValue),r.set(o[3],0,this.minValue),t.setFromPoints(o,e,i)},s.prototype.getLineSegment=function(t,e,i){var s=this.heights,n=this.elementWidth;r.set(t,i*n,s[i]),r.set(e,(i+1)*n,s[i+1])},s.prototype.getSegmentIndex=function(t){return Math.floor(t[0]/this.elementWidth)},s.prototype.getClampedSegmentIndex=function(t){var e=this.getSegmentIndex(t);return e=Math.min(this.heights.length,Math.max(e,0))};var a=(r.create(),r.create()),h=r.create(),l=r.create(),c=r.create(),u=r.create();r.fromValues(0,1);s.prototype.raycast=function(t,e,i,s){var n=e.from,o=e.to,d=(e.direction,a),p=h,f=l,g=c,m=u;r.toLocalFrame(g,n,i,s),r.toLocalFrame(m,o,i,s);var y=this.getClampedSegmentIndex(g),v=this.getClampedSegmentIndex(m);if(y>v){var b=y;y=v,v=b}for(var x=0;x<this.heights.length-1;x++){this.getLineSegment(p,f,x);var w=r.getLineSegmentsIntersectionFraction(g,m,p,f);if(w>=0&&(r.sub(d,f,p),r.rotate(d,d,s+Math.PI/2),r.normalize(d,d),e.reportIntersection(t,w,d,-1),t.shouldStop(e)))return}}},{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],42:[function(t,e,i){function s(t){"number"==typeof arguments[0]&&(t={length:arguments[0]},console.warn("The Line constructor signature has changed. Please use the following format: new Line({ length: 1, ... })")),t=t||{},this.length=t.length||1,t.type=n.LINE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.computeMomentOfInertia=function(t){return t*Math.pow(this.length,2)/12},s.prototype.updateBoundingRadius=function(){this.boundingRadius=this.length/2};var o=[r.create(),r.create()];s.prototype.computeAABB=function(t,e,i){var s=this.length/2;r.set(o[0],-s,0),r.set(o[1],s,0),t.setFromPoints(o,e,i,0)};var a=(r.create(),r.create()),h=r.create(),l=r.create(),c=r.fromValues(0,1);s.prototype.raycast=function(t,e,i,s){var n=e.from,o=e.to,u=h,d=l,p=this.length/2;r.set(u,-p,0),r.set(d,p,0),r.toGlobalFrame(u,u,i,s),r.toGlobalFrame(d,d,i,s);var f=r.getLineSegmentsIntersectionFraction(u,d,n,o);if(f>=0){var g=a;r.rotate(g,c,s),e.reportIntersection(t,f,g,-1)}}},{"../math/vec2":30,"./Shape":45}],43:[function(t,e,i){function s(t){t=t||{},t.type=n.PARTICLE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.computeMomentOfInertia=function(t){return 0},s.prototype.updateBoundingRadius=function(){this.boundingRadius=0},s.prototype.computeAABB=function(t,e,i){r.copy(t.lowerBound,e),r.copy(t.upperBound,e)}},{"../math/vec2":30,"./Shape":45}],44:[function(t,e,i){function s(t){t=t||{},t.type=n.PLANE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");t("../utils/Utils");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.computeMomentOfInertia=function(t){return 0},s.prototype.updateBoundingRadius=function(){this.boundingRadius=Number.MAX_VALUE},s.prototype.computeAABB=function(t,e,i){var s=i%(2*Math.PI),n=r.set,o=Number.MAX_VALUE,a=t.lowerBound,h=t.upperBound;0===s?(n(a,-o,-o),n(h,o,0)):s===Math.PI/2?(n(a,0,-o),n(h,o,o)):s===Math.PI?(n(a,-o,0),n(h,o,o)):s===3*Math.PI/2?(n(a,-o,-o),n(h,0,o)):(n(a,-o,-o),n(h,o,o)),r.add(a,a,e),r.add(h,h,e)},s.prototype.updateArea=function(){this.area=Number.MAX_VALUE};var o=r.create(),a=(r.create(),r.create(),r.create()),h=r.create();s.prototype.raycast=function(t,e,i,s){var n=e.from,l=e.to,c=e.direction,u=o,d=a,p=h;r.set(d,0,1),r.rotate(d,d,s),r.sub(p,n,i);var f=r.dot(p,d);if(r.sub(p,l,i),!(f*r.dot(p,d)>0||r.squaredDistance(n,l)<f*f)){var g=r.dot(d,c);r.sub(u,n,i);var m=-r.dot(d,u)/g/e.length;e.reportIntersection(t,m,d,-1)}}},{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],45:[function(t,e,i){function s(t){t=t||{},this.body=null,this.position=n.fromValues(0,0),t.position&&n.copy(this.position,t.position),this.angle=t.angle||0,this.type=t.type||0,this.id=s.idCounter++,this.boundingRadius=0,this.collisionGroup=void 0!==t.collisionGroup?t.collisionGroup:1,this.collisionResponse=void 0===t.collisionResponse||t.collisionResponse,this.collisionMask=void 0!==t.collisionMask?t.collisionMask:1,this.material=t.material||null,this.area=0,this.sensor=void 0!==t.sensor&&t.sensor,this.type&&this.updateBoundingRadius(),this.updateArea()}e.exports=s;var n=t("../math/vec2");s.idCounter=0,s.CIRCLE=1,s.PARTICLE=2,s.PLANE=4,s.CONVEX=8,s.LINE=16,s.BOX=32,Object.defineProperty(s,"RECTANGLE",{get:function(){return console.warn("Shape.RECTANGLE is deprecated, use Shape.BOX instead."),s.BOX}}),s.CAPSULE=64,s.HEIGHTFIELD=128,s.prototype.computeMomentOfInertia=function(t){},s.prototype.updateBoundingRadius=function(){},s.prototype.updateArea=function(){},s.prototype.computeAABB=function(t,e,i){},s.prototype.raycast=function(t,e,i,s){}},{"../math/vec2":30}],46:[function(t,e,i){function s(t){o.call(this,t,o.GS),t=t||{},this.iterations=t.iterations||10,this.tolerance=t.tolerance||1e-7,this.arrayStep=30,this.lambda=new a.ARRAY_TYPE(this.arrayStep),this.Bs=new a.ARRAY_TYPE(this.arrayStep),this.invCs=new a.ARRAY_TYPE(this.arrayStep),this.useZeroRHS=!1,this.frictionIterations=0,this.usedIterations=0}function n(t){for(var e=t.length;e--;)t[e]=0}var r=t("../math/vec2"),o=t("./Solver"),a=t("../utils/Utils"),h=t("../equations/FrictionEquation");e.exports=s,s.prototype=new o,s.prototype.constructor=s,s.prototype.solve=function(t,e){this.sortEquations();var i=0,o=this.iterations,l=this.frictionIterations,c=this.equations,u=c.length,d=Math.pow(this.tolerance*u,2),p=e.bodies,f=e.bodies.length,g=(r.add,r.set,this.useZeroRHS),m=this.lambda;if(this.usedIterations=0,u)for(var y=0;y!==f;y++){var v=p[y];v.updateSolveMassProperties()}m.length<u&&(m=this.lambda=new a.ARRAY_TYPE(u+this.arrayStep),this.Bs=new a.ARRAY_TYPE(u+this.arrayStep),this.invCs=new a.ARRAY_TYPE(u+this.arrayStep)),n(m);for(var b=this.invCs,x=this.Bs,m=this.lambda,y=0;y!==c.length;y++){var w=c[y];(w.timeStep!==t||w.needsUpdate)&&(w.timeStep=t,w.update()),x[y]=w.computeB(w.a,w.b,t),b[y]=w.computeInvC(w.epsilon)}var w,_,y,P;if(0!==u){for(y=0;y!==f;y++){var v=p[y];v.resetConstraintVelocity()}if(l){for(i=0;i!==l;i++){for(_=0,P=0;P!==u;P++){w=c[P];var T=s.iterateEquation(P,w,w.epsilon,x,b,m,g,t,i);_+=Math.abs(T)}if(this.usedIterations++,_*_<=d)break}for(s.updateMultipliers(c,m,1/t),P=0;P!==u;P++){var C=c[P];if(C instanceof h){for(var S=0,A=0;A!==C.contactEquations.length;A++)S+=C.contactEquations[A].multiplier;S*=C.frictionCoefficient/C.contactEquations.length,C.maxForce=S,C.minForce=-S}}}for(i=0;i!==o;i++){for(_=0,P=0;P!==u;P++){w=c[P];var T=s.iterateEquation(P,w,w.epsilon,x,b,m,g,t,i);_+=Math.abs(T)}if(this.usedIterations++,_*_<=d)break}for(y=0;y!==f;y++)p[y].addConstraintVelocity();s.updateMultipliers(c,m,1/t)}},s.updateMultipliers=function(t,e,i){for(var s=t.length;s--;)t[s].multiplier=e[s]*i},s.iterateEquation=function(t,e,i,s,n,r,o,a,h){var l=s[t],c=n[t],u=r[t],d=e.computeGWlambda(),p=e.maxForce,f=e.minForce;o&&(l=0);var g=c*(l-d-i*u),m=u+g;return m<f*a?g=f*a-u:m>p*a&&(g=p*a-u),r[t]+=g,e.addToWlambda(g),g}},{"../equations/FrictionEquation":23,"../math/vec2":30,"../utils/Utils":57,"./Solver":47}],47:[function(t,e,i){function s(t,e){t=t||{},n.call(this),this.type=e,this.equations=[],this.equationSortFunction=t.equationSortFunction||!1}var n=(t("../utils/Utils"),t("../events/EventEmitter"));e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.solve=function(t,e){throw new Error("Solver.solve should be implemented by subclasses!")};var r={bodies:[]};s.prototype.solveIsland=function(t,e){this.removeAllEquations(),e.equations.length&&(this.addEquations(e.equations),r.bodies.length=0,e.getBodies(r.bodies),r.bodies.length&&this.solve(t,r))},s.prototype.sortEquations=function(){this.equationSortFunction&&this.equations.sort(this.equationSortFunction)},s.prototype.addEquation=function(t){t.enabled&&this.equations.push(t)},s.prototype.addEquations=function(t){for(var e=0,i=t.length;e!==i;e++){var s=t[e];s.enabled&&this.equations.push(s)}},s.prototype.removeEquation=function(t){var e=this.equations.indexOf(t);-1!==e&&this.equations.splice(e,1)},s.prototype.removeAllEquations=function(){this.equations.length=0},s.GS=1,s.ISLAND=2},{"../events/EventEmitter":26,"../utils/Utils":57}],48:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../equations/ContactEquation"),r=t("./Pool");e.exports=s,s.prototype=new r,s.prototype.constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.bodyA=t.bodyB=null,this}},{"../equations/ContactEquation":21,"./Pool":55}],49:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../equations/FrictionEquation"),r=t("./Pool");e.exports=s,s.prototype=new r,s.prototype.constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.bodyA=t.bodyB=null,this}},{"../equations/FrictionEquation":23,"./Pool":55}],50:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../world/IslandNode"),r=t("./Pool");e.exports=s,s.prototype=new r,s.prototype.constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.reset(),this}},{"../world/IslandNode":60,"./Pool":55}],51:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../world/Island"),r=t("./Pool");e.exports=s,s.prototype=new r,s.prototype.constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.reset(),this}},{"../world/Island":58,"./Pool":55}],52:[function(t,e,i){function s(){this.overlappingShapesLastState=new n,this.overlappingShapesCurrentState=new n,this.recordPool=new r({size:16}),this.tmpDict=new n,this.tmpArray1=[]}var n=t("./TupleDictionary"),r=(t("./OverlapKeeperRecord"),t("./OverlapKeeperRecordPool"));t("./Utils");e.exports=s,s.prototype.tick=function(){for(var t=this.overlappingShapesLastState,e=this.overlappingShapesCurrentState,i=t.keys.length;i--;){var s=t.keys[i],n=t.getByKey(s);e.getByKey(s);n&&this.recordPool.release(n)}t.reset(),t.copy(e),e.reset()},s.prototype.setOverlapping=function(t,e,i,s){var n=(this.overlappingShapesLastState,this.overlappingShapesCurrentState);if(!n.get(e.id,s.id)){var r=this.recordPool.get();r.set(t,e,i,s),n.set(e.id,s.id,r)}},s.prototype.getNewOverlaps=function(t){return this.getDiff(this.overlappingShapesLastState,this.overlappingShapesCurrentState,t)},s.prototype.getEndOverlaps=function(t){return this.getDiff(this.overlappingShapesCurrentState,this.overlappingShapesLastState,t)},s.prototype.bodiesAreOverlapping=function(t,e){for(var i=this.overlappingShapesCurrentState,s=i.keys.length;s--;){var n=i.keys[s],r=i.data[n];if(r.bodyA===t&&r.bodyB===e||r.bodyA===e&&r.bodyB===t)return!0}return!1},s.prototype.getDiff=function(t,e,i){var i=i||[],s=t,n=e;i.length=0;for(var r=n.keys.length;r--;){var o=n.keys[r],a=n.data[o];if(!a)throw new Error("Key "+o+" had no data!");s.data[o]||i.push(a)}return i},s.prototype.isNewOverlap=function(t,e){var i=0|t.id,s=0|e.id,n=this.overlappingShapesLastState,r=this.overlappingShapesCurrentState;return!n.get(i,s)&&!!r.get(i,s)},s.prototype.getNewBodyOverlaps=function(t){this.tmpArray1.length=0;var e=this.getNewOverlaps(this.tmpArray1);return this.getBodyDiff(e,t)},s.prototype.getEndBodyOverlaps=function(t){this.tmpArray1.length=0;var e=this.getEndOverlaps(this.tmpArray1);return this.getBodyDiff(e,t)},s.prototype.getBodyDiff=function(t,e){e=e||[];for(var i=this.tmpDict,s=t.length;s--;){var n=t[s];i.set(0|n.bodyA.id,0|n.bodyB.id,n)}for(s=i.keys.length;s--;){var n=i.getByKey(i.keys[s]);n&&e.push(n.bodyA,n.bodyB)}return i.reset(),e}},{"./OverlapKeeperRecord":53,"./OverlapKeeperRecordPool":54,"./TupleDictionary":56,"./Utils":57}],53:[function(t,e,i){function s(t,e,i,s){this.shapeA=e,this.shapeB=s,this.bodyA=t,this.bodyB=i}e.exports=s,s.prototype.set=function(t,e,i,n){s.call(this,t,e,i,n)}},{}],54:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("./OverlapKeeperRecord"),r=t("./Pool");e.exports=s,s.prototype=new r,s.prototype.constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.bodyA=t.bodyB=t.shapeA=t.shapeB=null,this}},{"./OverlapKeeperRecord":53,"./Pool":55}],55:[function(t,e,i){function s(t){t=t||{},this.objects=[],void 0!==t.size&&this.resize(t.size)}e.exports=s,s.prototype.resize=function(t){for(var e=this.objects;e.length>t;)e.pop();for(;e.length<t;)e.push(this.create());return this},s.prototype.get=function(){var t=this.objects;return t.length?t.pop():this.create()},s.prototype.release=function(t){return this.destroy(t),this.objects.push(t),this}},{}],56:[function(t,e,i){function s(){this.data={},this.keys=[]}var n=t("./Utils");e.exports=s,s.prototype.getKey=function(t,e){return t|=0,e|=0,(0|t)==(0|e)?-1:0|((0|t)>(0|e)?t<<16|65535&e:e<<16|65535&t)},s.prototype.getByKey=function(t){return t|=0,this.data[t]},s.prototype.get=function(t,e){return this.data[this.getKey(t,e)]},s.prototype.set=function(t,e,i){if(!i)throw new Error("No data!");var s=this.getKey(t,e);return this.data[s]||this.keys.push(s),this.data[s]=i,s},s.prototype.reset=function(){for(var t=this.data,e=this.keys,i=e.length;i--;)delete t[e[i]];e.length=0},s.prototype.copy=function(t){this.reset(),n.appendArray(this.keys,t.keys);for(var e=t.keys.length;e--;){var i=t.keys[e];this.data[i]=t.data[i]}}},{"./Utils":57}],57:[function(t,e,i){function s(){}e.exports=s,s.appendArray=function(t,e){if(e.length<15e4)t.push.apply(t,e);else for(var i=0,s=e.length;i!==s;++i)t.push(e[i])},s.splice=function(t,e,i){i=i||1;for(var s=e,n=t.length-i;s<n;s++)t[s]=t[s+i];t.length=n},"undefined"!=typeof P2_ARRAY_TYPE?s.ARRAY_TYPE=P2_ARRAY_TYPE:"undefined"!=typeof Float32Array?s.ARRAY_TYPE=Float32Array:s.ARRAY_TYPE=Array,s.extend=function(t,e){for(var i in e)t[i]=e[i]},s.defaults=function(t,e){t=t||{};for(var i in e)i in t||(t[i]=e[i]);return t}},{}],58:[function(t,e,i){function s(){this.equations=[],this.bodies=[]}var n=t("../objects/Body");e.exports=s,s.prototype.reset=function(){this.equations.length=this.bodies.length=0};var r=[];s.prototype.getBodies=function(t){var e=t||[],i=this.equations;r.length=0;for(var s=0;s!==i.length;s++){var n=i[s];-1===r.indexOf(n.bodyA.id)&&(e.push(n.bodyA),r.push(n.bodyA.id)),-1===r.indexOf(n.bodyB.id)&&(e.push(n.bodyB),r.push(n.bodyB.id))}return e},s.prototype.wantsToSleep=function(){for(var t=0;t<this.bodies.length;t++){var e=this.bodies[t];if(e.type===n.DYNAMIC&&!e.wantsToSleep)return!1}return!0},s.prototype.sleep=function(){for(var t=0;t<this.bodies.length;t++){this.bodies[t].sleep()}return!0}},{"../objects/Body":31}],59:[function(t,e,i){function s(t){this.nodePool=new n({size:16}),this.islandPool=new r({size:8}),this.equations=[],this.islands=[],this.nodes=[],this.queue=[]}var n=(t("../math/vec2"),t("./Island"),t("./IslandNode"),t("./../utils/IslandNodePool")),r=t("./../utils/IslandPool"),o=t("../objects/Body");e.exports=s,s.getUnvisitedNode=function(t){for(var e=t.length,i=0;i!==e;i++){var s=t[i];if(!s.visited&&s.body.type===o.DYNAMIC)return s}return!1},s.prototype.visit=function(t,e,i){e.push(t.body);for(var s=t.equations.length,n=0;n!==s;n++){var r=t.equations[n];-1===i.indexOf(r)&&i.push(r)}},s.prototype.bfs=function(t,e,i){var n=this.queue;for(n.length=0,n.push(t),t.visited=!0,this.visit(t,e,i);n.length;)for(var r,a=n.pop();r=s.getUnvisitedNode(a.neighbors);)r.visited=!0,this.visit(r,e,i),r.body.type===o.DYNAMIC&&n.push(r)},s.prototype.split=function(t){for(var e=t.bodies,i=this.nodes,n=this.equations;i.length;)this.nodePool.release(i.pop());for(var r=0;r!==e.length;r++){var o=this.nodePool.get();o.body=e[r],i.push(o)}for(var a=0;a!==n.length;a++){var h=n[a],r=e.indexOf(h.bodyA),l=e.indexOf(h.bodyB),c=i[r],u=i[l];c.neighbors.push(u),u.neighbors.push(c),c.equations.push(h),u.equations.push(h)}for(var d=this.islands,r=0;r<d.length;r++)this.islandPool.release(d[r]);d.length=0;for(var p;p=s.getUnvisitedNode(i);){var f=this.islandPool.get();this.bfs(p,f.bodies,f.equations),d.push(f)}return d}},{"../math/vec2":30,"../objects/Body":31,"./../utils/IslandNodePool":50,"./../utils/IslandPool":51,"./Island":58,"./IslandNode":60}],60:[function(t,e,i){function s(t){this.body=t,this.neighbors=[],this.equations=[],this.visited=!1}e.exports=s,s.prototype.reset=function(){this.equations.length=0,this.neighbors.length=0,this.visited=!1,this.body=null}},{}],61:[function(t,e,i){function s(t){u.apply(this),t=t||{},this.springs=[],this.bodies=[],this.disabledBodyCollisionPairs=[],this.solver=t.solver||new n,this.narrowphase=new y(this),this.islandManager=new x,this.gravity=r.fromValues(0,-9.78),t.gravity&&r.copy(this.gravity,t.gravity),this.frictionGravity=r.length(this.gravity)||10,this.useWorldGravityAsFrictionGravity=!0,this.useFrictionGravityOnZeroGravity=!0,this.broadphase=t.broadphase||new m,this.broadphase.setWorld(this),this.constraints=[],this.defaultMaterial=new p,this.defaultContactMaterial=new f(this.defaultMaterial,this.defaultMaterial),this.lastTimeStep=1/60,this.applySpringForces=!0,this.applyDamping=!0,this.applyGravity=!0,this.solveConstraints=!0,this.contactMaterials=[],this.time=0,this.accumulator=0,this.stepping=!1,this.bodiesToBeRemoved=[],this.islandSplit=void 0===t.islandSplit||!!t.islandSplit,this.emitImpactEvent=!0,this._constraintIdCounter=0,this._bodyIdCounter=0,this.postStepEvent={type:"postStep"},this.addBodyEvent={type:"addBody",body:null},this.removeBodyEvent={type:"removeBody",body:null},this.addSpringEvent={type:"addSpring",spring:null},this.impactEvent={type:"impact",bodyA:null,bodyB:null,shapeA:null,shapeB:null,contactEquation:null},this.postBroadphaseEvent={type:"postBroadphase",pairs:null},this.sleepMode=s.NO_SLEEPING,this.beginContactEvent={type:"beginContact",shapeA:null,shapeB:null,bodyA:null,bodyB:null,contactEquations:[]},this.endContactEvent={type:"endContact",shapeA:null,shapeB:null,bodyA:null,bodyB:null},this.preSolveEvent={type:"preSolve",contactEquations:null,frictionEquations:null},this.overlappingShapesLastState={keys:[]},this.overlappingShapesCurrentState={keys:[]},this.overlapKeeper=new b}var n=t("../solver/GSSolver"),r=(t("../solver/Solver"),t("../collision/Ray"),t("../math/vec2")),o=t("../shapes/Circle"),a=t("../shapes/Convex"),h=(t("../shapes/Line"),t("../shapes/Plane")),l=t("../shapes/Capsule"),c=t("../shapes/Particle"),u=t("../events/EventEmitter"),d=t("../objects/Body"),p=(t("../shapes/Shape"),t("../objects/LinearSpring"),t("../material/Material")),f=t("../material/ContactMaterial"),g=(t("../constraints/DistanceConstraint"),t("../constraints/Constraint"),t("../constraints/LockConstraint"),t("../constraints/RevoluteConstraint"),t("../constraints/PrismaticConstraint"),t("../constraints/GearConstraint"),t("../../package.json"),t("../collision/Broadphase"),t("../collision/AABB")),m=t("../collision/SAPBroadphase"),y=t("../collision/Narrowphase"),v=t("../utils/Utils"),b=t("../utils/OverlapKeeper"),x=t("./IslandManager");t("../objects/RotationalSpring");e.exports=s,s.prototype=new Object(u.prototype),s.prototype.constructor=s,s.NO_SLEEPING=1,s.BODY_SLEEPING=2,s.ISLAND_SLEEPING=4,s.prototype.addConstraint=function(t){this.constraints.push(t)},s.prototype.addContactMaterial=function(t){this.contactMaterials.push(t)},s.prototype.removeContactMaterial=function(t){var e=this.contactMaterials.indexOf(t);-1!==e&&v.splice(this.contactMaterials,e,1)},s.prototype.getContactMaterial=function(t,e){for(var i=this.contactMaterials,s=0,n=i.length;s!==n;s++){var r=i[s];if(r.materialA.id===t.id&&r.materialB.id===e.id||r.materialA.id===e.id&&r.materialB.id===t.id)return r}return!1},s.prototype.removeConstraint=function(t){var e=this.constraints.indexOf(t);-1!==e&&v.splice(this.constraints,e,1)};var w=(r.create(),r.create(),r.create(),r.create(),r.create(),r.create(),r.create()),_=r.fromValues(0,0),P=r.fromValues(0,0);r.fromValues(0,0),r.fromValues(0,0);s.prototype.step=function(t,e,i){if(i=i||10,0===(e=e||0))this.internalStep(t),this.time+=t;else{this.accumulator+=e;for(var s=0;this.accumulator>=t&&s<i;)this.internalStep(t),this.time+=t,this.accumulator-=t,s++;for(var n=this.accumulator%t/t,o=0;o!==this.bodies.length;o++){var a=this.bodies[o];r.lerp(a.interpolatedPosition,a.previousPosition,a.position,n),a.interpolatedAngle=a.previousAngle+n*(a.angle-a.previousAngle)}}};var T=[];s.prototype.internalStep=function(t){this.stepping=!0;var e=this.springs.length,i=this.springs,n=this.bodies,o=this.gravity,a=this.solver,h=this.bodies.length,l=this.broadphase,c=this.narrowphase,u=this.constraints,p=w,f=(r.scale,r.add),g=(r.rotate,this.islandManager);if(this.overlapKeeper.tick(),this.lastTimeStep=t,this.useWorldGravityAsFrictionGravity){var m=r.length(this.gravity);0===m&&this.useFrictionGravityOnZeroGravity||(this.frictionGravity=m)}if(this.applyGravity)for(var y=0;y!==h;y++){var b=n[y],x=b.force;b.type===d.DYNAMIC&&b.sleepState!==d.SLEEPING&&(r.scale(p,o,b.mass*b.gravityScale),f(x,x,p))}if(this.applySpringForces)for(var y=0;y!==e;y++){var _=i[y];_.applyForce()}if(this.applyDamping)for(var y=0;y!==h;y++){var b=n[y];b.type===d.DYNAMIC&&b.applyDamping(t)}for(var P=l.getCollisionPairs(this),C=this.disabledBodyCollisionPairs,y=C.length-2;y>=0;y-=2)for(var S=P.length-2;S>=0;S-=2)(C[y]===P[S]&&C[y+1]===P[S+1]||C[y+1]===P[S]&&C[y]===P[S+1])&&P.splice(S,2);var A=u.length;for(y=0;y!==A;y++){var E=u[y];if(!E.collideConnected)for(var S=P.length-2;S>=0;S-=2)(E.bodyA===P[S]&&E.bodyB===P[S+1]||E.bodyB===P[S]&&E.bodyA===P[S+1])&&P.splice(S,2)}this.postBroadphaseEvent.pairs=P,this.emit(this.postBroadphaseEvent),this.postBroadphaseEvent.pairs=null,c.reset(this);for(var y=0,I=P.length;y!==I;y+=2)for(var M=P[y],R=P[y+1],B=0,L=M.shapes.length;B!==L;B++)for(var O=M.shapes[B],k=O.position,F=O.angle,D=0,U=R.shapes.length;D!==U;D++){var G=R.shapes[D],N=G.position,X=G.angle,W=this.defaultContactMaterial;if(O.material&&G.material){var j=this.getContactMaterial(O.material,G.material);j&&(W=j)}this.runNarrowphase(c,M,O,k,F,R,G,N,X,W,this.frictionGravity)}for(var y=0;y!==h;y++){var V=n[y];V._wakeUpAfterNarrowphase&&(V.wakeUp(),V._wakeUpAfterNarrowphase=!1)}if(this.has("endContact")){this.overlapKeeper.getEndOverlaps(T);for(var q=this.endContactEvent,D=T.length;D--;){var H=T[D];q.shapeA=H.shapeA,q.shapeB=H.shapeB,q.bodyA=H.bodyA,q.bodyB=H.bodyB,this.emit(q)}T.length=0}var Y=this.preSolveEvent;Y.contactEquations=c.contactEquations,Y.frictionEquations=c.frictionEquations,this.emit(Y),Y.contactEquations=Y.frictionEquations=null;var A=u.length;for(y=0;y!==A;y++)u[y].update();if(c.contactEquations.length||c.frictionEquations.length||A)if(this.islandSplit){for(g.equations.length=0,v.appendArray(g.equations,c.contactEquations),v.appendArray(g.equations,c.frictionEquations),y=0;y!==A;y++)v.appendArray(g.equations,u[y].equations);g.split(this);for(var y=0;y!==g.islands.length;y++){var z=g.islands[y];z.equations.length&&a.solveIsland(t,z)}}else{for(a.addEquations(c.contactEquations),a.addEquations(c.frictionEquations),y=0;y!==A;y++)a.addEquations(u[y].equations);this.solveConstraints&&a.solve(t,this),a.removeAllEquations()}for(var y=0;y!==h;y++){var V=n[y];V.integrate(t)}for(var y=0;y!==h;y++)n[y].setZeroForce();if(this.emitImpactEvent&&this.has("impact"))for(var K=this.impactEvent,y=0;y!==c.contactEquations.length;y++){var J=c.contactEquations[y];J.firstImpact&&(K.bodyA=J.bodyA,K.bodyB=J.bodyB,K.shapeA=J.shapeA,K.shapeB=J.shapeB,K.contactEquation=J,this.emit(K))}if(this.sleepMode===s.BODY_SLEEPING)for(y=0;y!==h;y++)n[y].sleepTick(this.time,!1,t);else if(this.sleepMode===s.ISLAND_SLEEPING&&this.islandSplit){for(y=0;y!==h;y++)n[y].sleepTick(this.time,!0,t);for(var y=0;y<this.islandManager.islands.length;y++){var z=this.islandManager.islands[y];z.wantsToSleep()&&z.sleep()}}this.stepping=!1;for(var Q=this.bodiesToBeRemoved,y=0;y!==Q.length;y++)this.removeBody(Q[y]);Q.length=0,this.emit(this.postStepEvent)},s.prototype.runNarrowphase=function(t,e,i,s,n,o,a,h,l,c,u){if(0!=(i.collisionGroup&a.collisionMask)&&0!=(a.collisionGroup&i.collisionMask)){r.rotate(_,s,e.angle),r.rotate(P,h,o.angle),r.add(_,_,e.position),r.add(P,P,o.position);var p=n+e.angle,f=l+o.angle;t.enableFriction=c.friction>0,t.frictionCoefficient=c.friction;var g;g=e.type===d.STATIC||e.type===d.KINEMATIC?o.mass:o.type===d.STATIC||o.type===d.KINEMATIC?e.mass:e.mass*o.mass/(e.mass+o.mass),t.slipForce=c.friction*u*g,t.restitution=c.restitution,t.surfaceVelocity=c.surfaceVelocity,t.frictionStiffness=c.frictionStiffness,t.frictionRelaxation=c.frictionRelaxation,t.stiffness=c.stiffness,t.relaxation=c.relaxation,t.contactSkinSize=c.contactSkinSize,t.enabledEquations=e.collisionResponse&&o.collisionResponse&&i.collisionResponse&&a.collisionResponse;var m=t[i.type|a.type],y=0;if(m){var v=i.sensor||a.sensor,b=t.frictionEquations.length;y=i.type<a.type?m.call(t,e,i,_,p,o,a,P,f,v):m.call(t,o,a,P,f,e,i,_,p,v);var x=t.frictionEquations.length-b;if(y){if(e.allowSleep&&e.type===d.DYNAMIC&&e.sleepState===d.SLEEPING&&o.sleepState===d.AWAKE&&o.type!==d.STATIC){r.squaredLength(o.velocity)+Math.pow(o.angularVelocity,2)>=2*Math.pow(o.sleepSpeedLimit,2)&&(e._wakeUpAfterNarrowphase=!0)}if(o.allowSleep&&o.type===d.DYNAMIC&&o.sleepState===d.SLEEPING&&e.sleepState===d.AWAKE&&e.type!==d.STATIC){r.squaredLength(e.velocity)+Math.pow(e.angularVelocity,2)>=2*Math.pow(e.sleepSpeedLimit,2)&&(o._wakeUpAfterNarrowphase=!0)}if(this.overlapKeeper.setOverlapping(e,i,o,a),this.has("beginContact")&&this.overlapKeeper.isNewOverlap(i,a)){var w=this.beginContactEvent;if(w.shapeA=i,w.shapeB=a,w.bodyA=e,w.bodyB=o,w.contactEquations.length=0,"number"==typeof y)for(var T=t.contactEquations.length-y;T<t.contactEquations.length;T++)w.contactEquations.push(t.contactEquations[T]);this.emit(w)}if("number"==typeof y&&x>1)for(var T=t.frictionEquations.length-x;T<t.frictionEquations.length;T++){var C=t.frictionEquations[T];C.setSlipForce(C.getSlipForce()/x)}}}}},s.prototype.addSpring=function(t){this.springs.push(t);var e=this.addSpringEvent;e.spring=t,this.emit(e),e.spring=null},s.prototype.removeSpring=function(t){var e=this.springs.indexOf(t);-1!==e&&v.splice(this.springs,e,1)},s.prototype.addBody=function(t){if(-1===this.bodies.indexOf(t)){this.bodies.push(t),t.world=this;var e=this.addBodyEvent;e.body=t,this.emit(e),e.body=null}},s.prototype.removeBody=function(t){if(this.stepping)this.bodiesToBeRemoved.push(t);else{t.world=null;var e=this.bodies.indexOf(t);-1!==e&&(v.splice(this.bodies,e,1),this.removeBodyEvent.body=t,t.resetConstraintVelocity(),this.emit(this.removeBodyEvent),this.removeBodyEvent.body=null)}},s.prototype.getBodyById=function(t){for(var e=this.bodies,i=0;i<e.length;i++){var s=e[i];if(s.id===t)return s}return!1},s.prototype.disableBodyCollision=function(t,e){this.disabledBodyCollisionPairs.push(t,e)},s.prototype.enableBodyCollision=function(t,e){for(var i=this.disabledBodyCollisionPairs,s=0;s<i.length;s+=2)if(i[s]===t&&i[s+1]===e||i[s+1]===t&&i[s]===e)return void i.splice(s,2)},s.prototype.clear=function(){this.time=0,this.solver&&this.solver.equations.length&&this.solver.removeAllEquations();for(var t=this.constraints,e=t.length-1;e>=0;e--)this.removeConstraint(t[e]);for(var i=this.bodies,e=i.length-1;e>=0;e--)this.removeBody(i[e]);for(var n=this.springs,e=n.length-1;e>=0;e--)this.removeSpring(n[e]);for(var r=this.contactMaterials,e=r.length-1;e>=0;e--)this.removeContactMaterial(r[e]);s.apply(this)};var C=r.create(),S=(r.fromValues(0,0),r.fromValues(0,0));s.prototype.hitTest=function(t,e,i){i=i||0;var s=new d({position:t}),n=new c,u=t,p=C,f=S;s.addShape(n);for(var g=this.narrowphase,m=[],y=0,v=e.length;y!==v;y++)for(var b=e[y],x=0,w=b.shapes.length;x!==w;x++){var _=b.shapes[x];r.rotate(p,_.position,b.angle),r.add(p,p,b.position);var P=_.angle+b.angle;(_ instanceof o&&g.circleParticle(b,_,p,P,s,n,u,0,!0)||_ instanceof a&&g.particleConvex(s,n,u,0,b,_,p,P,!0)||_ instanceof h&&g.particlePlane(s,n,u,0,b,_,p,P,!0)||_ instanceof l&&g.particleCapsule(s,n,u,0,b,_,p,P,!0)||_ instanceof c&&r.squaredLength(r.sub(f,p,t))<i*i)&&m.push(b)}return m},s.prototype.setGlobalStiffness=function(t){for(var e=this.constraints,i=0;i!==e.length;i++)for(var s=e[i],n=0;n!==s.equations.length;n++){var r=s.equations[n];r.stiffness=t,r.needsUpdate=!0}for(var o=this.contactMaterials,i=0;i!==o.length;i++){var s=o[i];s.stiffness=s.frictionStiffness=t}var s=this.defaultContactMaterial;s.stiffness=s.frictionStiffness=t},s.prototype.setGlobalRelaxation=function(t){for(var e=0;e!==this.constraints.length;e++)for(var i=this.constraints[e],s=0;s!==i.equations.length;s++){var n=i.equations[s];n.relaxation=t,n.needsUpdate=!0}for(var e=0;e!==this.contactMaterials.length;e++){var i=this.contactMaterials[e];i.relaxation=i.frictionRelaxation=t}var i=this.defaultContactMaterial;i.relaxation=i.frictionRelaxation=t};var A=new g,E=[];s.prototype.raycast=function(t,e){return e.getAABB(A),this.broadphase.aabbQuery(this,A,E),e.intersectBodies(t,E),E.length=0,t.hasHit()}},{"../../package.json":6,"../collision/AABB":7,"../collision/Broadphase":8,"../collision/Narrowphase":10,"../collision/Ray":11,"../collision/SAPBroadphase":13,"../constraints/Constraint":14,"../constraints/DistanceConstraint":15,"../constraints/GearConstraint":16,"../constraints/LockConstraint":17,"../constraints/PrismaticConstraint":18,"../constraints/RevoluteConstraint":19,"../events/EventEmitter":26,"../material/ContactMaterial":27,"../material/Material":28,"../math/vec2":30,"../objects/Body":31,"../objects/LinearSpring":32,"../objects/RotationalSpring":33,"../shapes/Capsule":38,"../shapes/Circle":39,"../shapes/Convex":40,"../shapes/Line":42,"../shapes/Particle":43,"../shapes/Plane":44,"../shapes/Shape":45,"../solver/GSSolver":46,"../solver/Solver":47,"../utils/OverlapKeeper":52,"../utils/Utils":57,"./IslandManager":59}]},{},[36])(36)})},function(t,e,i){(function(i){/**
<add>var J=i(63),Q=i(87),Z=i(66);e.Buffer=r,e.SlowBuffer=g,e.INSPECT_MAX_BYTES=50,r.TYPED_ARRAY_SUPPORT=void 0!==t.TYPED_ARRAY_SUPPORT?t.TYPED_ARRAY_SUPPORT:function(){try{var t=new Uint8Array(1);return t.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===t.foo()&&"function"==typeof t.subarray&&0===t.subarray(1,1).byteLength}catch(t){return!1}}(),e.kMaxLength=s(),r.poolSize=8192,r._augment=function(t){return t.__proto__=r.prototype,t},r.from=function(t,e,i){return o(null,t,e,i)},r.TYPED_ARRAY_SUPPORT&&(r.prototype.__proto__=Uint8Array.prototype,r.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&r[Symbol.species]===r&&Object.defineProperty(r,Symbol.species,{value:null,configurable:!0})),r.alloc=function(t,e,i){return h(null,t,e,i)},r.allocUnsafe=function(t){return l(null,t)},r.allocUnsafeSlow=function(t){return l(null,t)},r.isBuffer=function(t){return!(null==t||!t._isBuffer)},r.compare=function(t,e){if(!r.isBuffer(t)||!r.isBuffer(e))throw new TypeError("Arguments must be Buffers");if(t===e)return 0;for(var i=t.length,s=e.length,n=0,o=Math.min(i,s);n<o;++n)if(t[n]!==e[n]){i=t[n],s=e[n];break}return i<s?-1:s<i?1:0},r.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},r.concat=function(t,e){if(!Z(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return r.alloc(0);var i;if(void 0===e)for(e=0,i=0;i<t.length;++i)e+=t[i].length;var s=r.allocUnsafe(e),n=0;for(i=0;i<t.length;++i){var o=t[i];if(!r.isBuffer(o))throw new TypeError('"list" argument must be an Array of Buffers');o.copy(s,n),n+=o.length}return s},r.byteLength=m,r.prototype._isBuffer=!0,r.prototype.swap16=function(){var t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var e=0;e<t;e+=2)v(this,e,e+1);return this},r.prototype.swap32=function(){var t=this.length;if(t%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var e=0;e<t;e+=4)v(this,e,e+3),v(this,e+1,e+2);return this},r.prototype.swap64=function(){var t=this.length;if(t%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var e=0;e<t;e+=8)v(this,e,e+7),v(this,e+1,e+6),v(this,e+2,e+5),v(this,e+3,e+4);return this},r.prototype.toString=function(){var t=0|this.length;return 0===t?"":0===arguments.length?E(this,0,t):y.apply(this,arguments)},r.prototype.equals=function(t){if(!r.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===r.compare(this,t)},r.prototype.inspect=function(){var t="",i=e.INSPECT_MAX_BYTES;return this.length>0&&(t=this.toString("hex",0,i).match(/.{2}/g).join(" "),this.length>i&&(t+=" ... ")),"<Buffer "+t+">"},r.prototype.compare=function(t,e,i,s,n){if(!r.isBuffer(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===i&&(i=t?t.length:0),void 0===s&&(s=0),void 0===n&&(n=this.length),e<0||i>t.length||s<0||n>this.length)throw new RangeError("out of range index");if(s>=n&&e>=i)return 0;if(s>=n)return-1;if(e>=i)return 1;if(e>>>=0,i>>>=0,s>>>=0,n>>>=0,this===t)return 0;for(var o=n-s,a=i-e,h=Math.min(o,a),l=this.slice(s,n),c=t.slice(e,i),u=0;u<h;++u)if(l[u]!==c[u]){o=l[u],a=c[u];break}return o<a?-1:a<o?1:0},r.prototype.includes=function(t,e,i){return-1!==this.indexOf(t,e,i)},r.prototype.indexOf=function(t,e,i){return b(this,t,e,i,!0)},r.prototype.lastIndexOf=function(t,e,i){return b(this,t,e,i,!1)},r.prototype.write=function(t,e,i,s){if(void 0===e)s="utf8",i=this.length,e=0;else if(void 0===i&&"string"==typeof e)s=e,i=this.length,e=0;else{if(!isFinite(e))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");e|=0,isFinite(i)?(i|=0,void 0===s&&(s="utf8")):(s=i,i=void 0)}var n=this.length-e;if((void 0===i||i>n)&&(i=n),t.length>0&&(i<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");s||(s="utf8");for(var r=!1;;)switch(s){case"hex":return w(this,t,e,i);case"utf8":case"utf-8":return _(this,t,e,i);case"ascii":return P(this,t,e,i);case"latin1":case"binary":return T(this,t,e,i);case"base64":return C(this,t,e,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,t,e,i);default:if(r)throw new TypeError("Unknown encoding: "+s);s=(""+s).toLowerCase(),r=!0}},r.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var $=4096;r.prototype.slice=function(t,e){var i=this.length;t=~~t,e=void 0===e?i:~~e,t<0?(t+=i)<0&&(t=0):t>i&&(t=i),e<0?(e+=i)<0&&(e=0):e>i&&(e=i),e<t&&(e=t);var s;if(r.TYPED_ARRAY_SUPPORT)s=this.subarray(t,e),s.__proto__=r.prototype;else{var n=e-t;s=new r(n,void 0);for(var o=0;o<n;++o)s[o]=this[o+t]}return s},r.prototype.readUIntLE=function(t,e,i){t|=0,e|=0,i||k(t,e,this.length);for(var s=this[t],n=1,r=0;++r<e&&(n*=256);)s+=this[t+r]*n;return s},r.prototype.readUIntBE=function(t,e,i){t|=0,e|=0,i||k(t,e,this.length);for(var s=this[t+--e],n=1;e>0&&(n*=256);)s+=this[t+--e]*n;return s},r.prototype.readUInt8=function(t,e){return e||k(t,1,this.length),this[t]},r.prototype.readUInt16LE=function(t,e){return e||k(t,2,this.length),this[t]|this[t+1]<<8},r.prototype.readUInt16BE=function(t,e){return e||k(t,2,this.length),this[t]<<8|this[t+1]},r.prototype.readUInt32LE=function(t,e){return e||k(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},r.prototype.readUInt32BE=function(t,e){return e||k(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},r.prototype.readIntLE=function(t,e,i){t|=0,e|=0,i||k(t,e,this.length);for(var s=this[t],n=1,r=0;++r<e&&(n*=256);)s+=this[t+r]*n;return n*=128,s>=n&&(s-=Math.pow(2,8*e)),s},r.prototype.readIntBE=function(t,e,i){t|=0,e|=0,i||k(t,e,this.length);for(var s=e,n=1,r=this[t+--s];s>0&&(n*=256);)r+=this[t+--s]*n;return n*=128,r>=n&&(r-=Math.pow(2,8*e)),r},r.prototype.readInt8=function(t,e){return e||k(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},r.prototype.readInt16LE=function(t,e){e||k(t,2,this.length);var i=this[t]|this[t+1]<<8;return 32768&i?4294901760|i:i},r.prototype.readInt16BE=function(t,e){e||k(t,2,this.length);var i=this[t+1]|this[t]<<8;return 32768&i?4294901760|i:i},r.prototype.readInt32LE=function(t,e){return e||k(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},r.prototype.readInt32BE=function(t,e){return e||k(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},r.prototype.readFloatLE=function(t,e){return e||k(t,4,this.length),Q.read(this,t,!0,23,4)},r.prototype.readFloatBE=function(t,e){return e||k(t,4,this.length),Q.read(this,t,!1,23,4)},r.prototype.readDoubleLE=function(t,e){return e||k(t,8,this.length),Q.read(this,t,!0,52,8)},r.prototype.readDoubleBE=function(t,e){return e||k(t,8,this.length),Q.read(this,t,!1,52,8)},r.prototype.writeUIntLE=function(t,e,i,s){if(t=+t,e|=0,i|=0,!s){O(this,t,e,i,Math.pow(2,8*i)-1,0)}var n=1,r=0;for(this[e]=255&t;++r<i&&(n*=256);)this[e+r]=t/n&255;return e+i},r.prototype.writeUIntBE=function(t,e,i,s){if(t=+t,e|=0,i|=0,!s){O(this,t,e,i,Math.pow(2,8*i)-1,0)}var n=i-1,r=1;for(this[e+n]=255&t;--n>=0&&(r*=256);)this[e+n]=t/r&255;return e+i},r.prototype.writeUInt8=function(t,e,i){return t=+t,e|=0,i||O(this,t,e,1,255,0),r.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},r.prototype.writeUInt16LE=function(t,e,i){return t=+t,e|=0,i||O(this,t,e,2,65535,0),r.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):F(this,t,e,!0),e+2},r.prototype.writeUInt16BE=function(t,e,i){return t=+t,e|=0,i||O(this,t,e,2,65535,0),r.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):F(this,t,e,!1),e+2},r.prototype.writeUInt32LE=function(t,e,i){return t=+t,e|=0,i||O(this,t,e,4,4294967295,0),r.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):D(this,t,e,!0),e+4},r.prototype.writeUInt32BE=function(t,e,i){return t=+t,e|=0,i||O(this,t,e,4,4294967295,0),r.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):D(this,t,e,!1),e+4},r.prototype.writeIntLE=function(t,e,i,s){if(t=+t,e|=0,!s){var n=Math.pow(2,8*i-1);O(this,t,e,i,n-1,-n)}var r=0,o=1,a=0;for(this[e]=255&t;++r<i&&(o*=256);)t<0&&0===a&&0!==this[e+r-1]&&(a=1),this[e+r]=(t/o>>0)-a&255;return e+i},r.prototype.writeIntBE=function(t,e,i,s){if(t=+t,e|=0,!s){var n=Math.pow(2,8*i-1);O(this,t,e,i,n-1,-n)}var r=i-1,o=1,a=0;for(this[e+r]=255&t;--r>=0&&(o*=256);)t<0&&0===a&&0!==this[e+r+1]&&(a=1),this[e+r]=(t/o>>0)-a&255;return e+i},r.prototype.writeInt8=function(t,e,i){return t=+t,e|=0,i||O(this,t,e,1,127,-128),r.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[e]=255&t,e+1},r.prototype.writeInt16LE=function(t,e,i){return t=+t,e|=0,i||O(this,t,e,2,32767,-32768),r.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):F(this,t,e,!0),e+2},r.prototype.writeInt16BE=function(t,e,i){return t=+t,e|=0,i||O(this,t,e,2,32767,-32768),r.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):F(this,t,e,!1),e+2},r.prototype.writeInt32LE=function(t,e,i){return t=+t,e|=0,i||O(this,t,e,4,2147483647,-2147483648),r.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):D(this,t,e,!0),e+4},r.prototype.writeInt32BE=function(t,e,i){return t=+t,e|=0,i||O(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),r.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):D(this,t,e,!1),e+4},r.prototype.writeFloatLE=function(t,e,i){return G(this,t,e,!0,i)},r.prototype.writeFloatBE=function(t,e,i){return G(this,t,e,!1,i)},r.prototype.writeDoubleLE=function(t,e,i){return N(this,t,e,!0,i)},r.prototype.writeDoubleBE=function(t,e,i){return N(this,t,e,!1,i)},r.prototype.copy=function(t,e,i,s){if(i||(i=0),s||0===s||(s=this.length),e>=t.length&&(e=t.length),e||(e=0),s>0&&s<i&&(s=i),s===i)return 0;if(0===t.length||0===this.length)return 0;if(e<0)throw new RangeError("targetStart out of bounds");if(i<0||i>=this.length)throw new RangeError("sourceStart out of bounds");if(s<0)throw new RangeError("sourceEnd out of bounds");s>this.length&&(s=this.length),t.length-e<s-i&&(s=t.length-e+i);var n,o=s-i;if(this===t&&i<e&&e<s)for(n=o-1;n>=0;--n)t[n+e]=this[n+i];else if(o<1e3||!r.TYPED_ARRAY_SUPPORT)for(n=0;n<o;++n)t[n+e]=this[n+i];else Uint8Array.prototype.set.call(t,this.subarray(i,i+o),e);return o},r.prototype.fill=function(t,e,i,s){if("string"==typeof t){if("string"==typeof e?(s=e,e=0,i=this.length):"string"==typeof i&&(s=i,i=this.length),1===t.length){var n=t.charCodeAt(0);n<256&&(t=n)}if(void 0!==s&&"string"!=typeof s)throw new TypeError("encoding must be a string");if("string"==typeof s&&!r.isEncoding(s))throw new TypeError("Unknown encoding: "+s)}else"number"==typeof t&&(t&=255);if(e<0||this.length<e||this.length<i)throw new RangeError("Out of range index");if(i<=e)return this;e>>>=0,i=void 0===i?this.length:i>>>0,t||(t=0);var o;if("number"==typeof t)for(o=e;o<i;++o)this[o]=t;else{var a=r.isBuffer(t)?t:V(new r(t,s).toString()),h=a.length;for(o=0;o<i-e;++o)this[o+e]=a[o%h]}return this};var tt=/[^+\/0-9A-Za-z-_]/g}).call(e,i(0))},function(t,e){var i={}.toString;t.exports=Array.isArray||function(t){return"[object Array]"==i.call(t)}},,,,,,,,,,,,,function(t,e,i){(function(e){t.exports=e.PIXI=i(92)}).call(e,i(0))},function(t,e,i){(function(e){t.exports=e.Phaser=i(91)}).call(e,i(0))},function(t,e,i){(function(e){t.exports=e.p2=i(90)}).call(e,i(0))},function(t,e,i){t.exports=i.p+"js/game/src/assets/sounds/brick_destroy.wav"},function(t,e,i){t.exports=i.p+"js/game/src/assets/sounds/game_music.wav"},function(t,e,i){t.exports=i.p+"js/game/src/assets/sprites/bricksScaled720X240.png"},function(t,e,i){t.exports=i.p+"js/game/src/assets/sprites/settings-50.png"},,function(t,e){e.read=function(t,e,i,s,n){var r,o,a=8*n-s-1,h=(1<<a)-1,l=h>>1,c=-7,u=i?n-1:0,d=i?-1:1,p=t[e+u];for(u+=d,r=p&(1<<-c)-1,p>>=-c,c+=a;c>0;r=256*r+t[e+u],u+=d,c-=8);for(o=r&(1<<-c)-1,r>>=-c,c+=s;c>0;o=256*o+t[e+u],u+=d,c-=8);if(0===r)r=1-l;else{if(r===h)return o?NaN:1/0*(p?-1:1);o+=Math.pow(2,s),r-=l}return(p?-1:1)*o*Math.pow(2,r-s)},e.write=function(t,e,i,s,n,r){var o,a,h,l=8*r-n-1,c=(1<<l)-1,u=c>>1,d=23===n?Math.pow(2,-24)-Math.pow(2,-77):0,p=s?0:r-1,f=s?1:-1,g=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=c):(o=Math.floor(Math.log(e)/Math.LN2),e*(h=Math.pow(2,-o))<1&&(o--,h*=2),e+=o+u>=1?d/h:d*Math.pow(2,1-u),e*h>=2&&(o++,h/=2),o+u>=c?(a=0,o=c):o+u>=1?(a=(e*h-1)*Math.pow(2,n),o+=u):(a=e*Math.pow(2,u-1)*Math.pow(2,n),o=0));n>=8;t[i+p]=255&a,p+=f,a/=256,n-=8);for(o=o<<n|a,l+=n;l>0;t[i+p]=255&o,p+=f,o/=256,l-=8);t[i+p-f]|=128*g}},,,function(t,e,i){var s,s;!function(e){t.exports=e()}(function(){return function t(e,i,n){function r(a,h){if(!i[a]){if(!e[a]){var l="function"==typeof s&&s;if(!h&&l)return s(a,!0);if(o)return s(a,!0);throw new Error("Cannot find module '"+a+"'")}var c=i[a]={exports:{}};e[a][0].call(c.exports,function(t){var i=e[a][1][t];return r(i||t)},c,c.exports,t,e,i,n)}return i[a].exports}for(var o="function"==typeof s&&s,a=0;a<n.length;a++)r(n[a]);return r}({1:[function(t,e,i){function s(){}var n=t("./Scalar");e.exports=s,s.lineInt=function(t,e,i){i=i||0;var s,r,o,a,h,l,c,u=[0,0];return s=t[1][1]-t[0][1],r=t[0][0]-t[1][0],o=s*t[0][0]+r*t[0][1],a=e[1][1]-e[0][1],h=e[0][0]-e[1][0],l=a*e[0][0]+h*e[0][1],c=s*h-a*r,n.eq(c,0,i)||(u[0]=(h*o-r*l)/c,u[1]=(s*l-a*o)/c),u},s.segmentsIntersect=function(t,e,i,s){var n=e[0]-t[0],r=e[1]-t[1],o=s[0]-i[0],a=s[1]-i[1];if(o*r-a*n==0)return!1;var h=(n*(i[1]-t[1])+r*(t[0]-i[0]))/(o*r-a*n),l=(o*(t[1]-i[1])+a*(i[0]-t[0]))/(a*n-o*r);return h>=0&&h<=1&&l>=0&&l<=1}},{"./Scalar":4}],2:[function(t,e,i){function s(){}e.exports=s,s.area=function(t,e,i){return(e[0]-t[0])*(i[1]-t[1])-(i[0]-t[0])*(e[1]-t[1])},s.left=function(t,e,i){return s.area(t,e,i)>0},s.leftOn=function(t,e,i){return s.area(t,e,i)>=0},s.right=function(t,e,i){return s.area(t,e,i)<0},s.rightOn=function(t,e,i){return s.area(t,e,i)<=0};var n=[],r=[];s.collinear=function(t,e,i,o){if(o){var a=n,h=r;a[0]=e[0]-t[0],a[1]=e[1]-t[1],h[0]=i[0]-e[0],h[1]=i[1]-e[1];var l=a[0]*h[0]+a[1]*h[1],c=Math.sqrt(a[0]*a[0]+a[1]*a[1]),u=Math.sqrt(h[0]*h[0]+h[1]*h[1]);return Math.acos(l/(c*u))<o}return 0==s.area(t,e,i)},s.sqdist=function(t,e){var i=e[0]-t[0],s=e[1]-t[1];return i*i+s*s}},{}],3:[function(t,e,i){function s(){this.vertices=[]}function n(t,e,i,s,n){n=n||0;var r=e[1]-t[1],o=t[0]-e[0],h=r*t[0]+o*t[1],l=s[1]-i[1],c=i[0]-s[0],u=l*i[0]+c*i[1],d=r*c-l*o;return a.eq(d,0,n)?[0,0]:[(c*h-o*u)/d,(r*u-l*h)/d]}var r=t("./Line"),o=t("./Point"),a=t("./Scalar");e.exports=s,s.prototype.at=function(t){var e=this.vertices,i=e.length;return e[t<0?t%i+i:t%i]},s.prototype.first=function(){return this.vertices[0]},s.prototype.last=function(){return this.vertices[this.vertices.length-1]},s.prototype.clear=function(){this.vertices.length=0},s.prototype.append=function(t,e,i){if(void 0===e)throw new Error("From is not given!");if(void 0===i)throw new Error("To is not given!");if(i-1<e)throw new Error("lol1");if(i>t.vertices.length)throw new Error("lol2");if(e<0)throw new Error("lol3");for(var s=e;s<i;s++)this.vertices.push(t.vertices[s])},s.prototype.makeCCW=function(){for(var t=0,e=this.vertices,i=1;i<this.vertices.length;++i)(e[i][1]<e[t][1]||e[i][1]==e[t][1]&&e[i][0]>e[t][0])&&(t=i);o.left(this.at(t-1),this.at(t),this.at(t+1))||this.reverse()},s.prototype.reverse=function(){for(var t=[],e=0,i=this.vertices.length;e!==i;e++)t.push(this.vertices.pop());this.vertices=t},s.prototype.isReflex=function(t){return o.right(this.at(t-1),this.at(t),this.at(t+1))};var h=[],l=[];s.prototype.canSee=function(t,e){var i,s,n=h,a=l;if(o.leftOn(this.at(t+1),this.at(t),this.at(e))&&o.rightOn(this.at(t-1),this.at(t),this.at(e)))return!1;s=o.sqdist(this.at(t),this.at(e));for(var c=0;c!==this.vertices.length;++c)if((c+1)%this.vertices.length!==t&&c!==t&&o.leftOn(this.at(t),this.at(e),this.at(c+1))&&o.rightOn(this.at(t),this.at(e),this.at(c))&&(n[0]=this.at(t),n[1]=this.at(e),a[0]=this.at(c),a[1]=this.at(c+1),i=r.lineInt(n,a),o.sqdist(this.at(t),i)<s))return!1;return!0},s.prototype.copy=function(t,e,i){var n=i||new s;if(n.clear(),t<e)for(var r=t;r<=e;r++)n.vertices.push(this.vertices[r]);else{for(var r=0;r<=e;r++)n.vertices.push(this.vertices[r]);for(var r=t;r<this.vertices.length;r++)n.vertices.push(this.vertices[r])}return n},s.prototype.getCutEdges=function(){for(var t=[],e=[],i=[],n=new s,r=Number.MAX_VALUE,o=0;o<this.vertices.length;++o)if(this.isReflex(o))for(var a=0;a<this.vertices.length;++a)if(this.canSee(o,a)){e=this.copy(o,a,n).getCutEdges(),i=this.copy(a,o,n).getCutEdges();for(var h=0;h<i.length;h++)e.push(i[h]);e.length<r&&(t=e,r=e.length,t.push([this.at(o),this.at(a)]))}return t},s.prototype.decomp=function(){var t=this.getCutEdges();return t.length>0?this.slice(t):[this]},s.prototype.slice=function(t){if(0==t.length)return[this];if(t instanceof Array&&t.length&&t[0]instanceof Array&&2==t[0].length&&t[0][0]instanceof Array){for(var e=[this],i=0;i<t.length;i++)for(var s=t[i],n=0;n<e.length;n++){var r=e[n],o=r.slice(s);if(o){e.splice(n,1),e.push(o[0],o[1]);break}}return e}var s=t,i=this.vertices.indexOf(s[0]),n=this.vertices.indexOf(s[1]);return-1!=i&&-1!=n&&[this.copy(i,n),this.copy(n,i)]},s.prototype.isSimple=function(){for(var t=this.vertices,e=0;e<t.length-1;e++)for(var i=0;i<e-1;i++)if(r.segmentsIntersect(t[e],t[e+1],t[i],t[i+1]))return!1;for(var e=1;e<t.length-2;e++)if(r.segmentsIntersect(t[0],t[t.length-1],t[e],t[e+1]))return!1;return!0},s.prototype.quickDecomp=function(t,e,i,r,a,h){a=a||100,h=h||0,r=r||25,t=void 0!==t?t:[],e=e||[],i=i||[];var l=[0,0],c=[0,0],u=[0,0],d=0,p=0,f=0,g=0,m=0,y=0,v=0,b=new s,x=new s,w=this,_=this.vertices;if(_.length<3)return t;if(++h>a)return console.warn("quickDecomp: max level ("+a+") reached."),t;for(var P=0;P<this.vertices.length;++P)if(w.isReflex(P)){e.push(w.vertices[P]),d=p=Number.MAX_VALUE;for(var T=0;T<this.vertices.length;++T)o.left(w.at(P-1),w.at(P),w.at(T))&&o.rightOn(w.at(P-1),w.at(P),w.at(T-1))&&(u=n(w.at(P-1),w.at(P),w.at(T),w.at(T-1)),o.right(w.at(P+1),w.at(P),u)&&(f=o.sqdist(w.vertices[P],u))<p&&(p=f,c=u,y=T)),o.left(w.at(P+1),w.at(P),w.at(T+1))&&o.rightOn(w.at(P+1),w.at(P),w.at(T))&&(u=n(w.at(P+1),w.at(P),w.at(T),w.at(T+1)),o.left(w.at(P-1),w.at(P),u)&&(f=o.sqdist(w.vertices[P],u))<d&&(d=f,l=u,m=T));if(y==(m+1)%this.vertices.length)u[0]=(c[0]+l[0])/2,u[1]=(c[1]+l[1])/2,i.push(u),P<m?(b.append(w,P,m+1),b.vertices.push(u),x.vertices.push(u),0!=y&&x.append(w,y,w.vertices.length),x.append(w,0,P+1)):(0!=P&&b.append(w,P,w.vertices.length),b.append(w,0,m+1),b.vertices.push(u),x.vertices.push(u),x.append(w,y,P+1));else{if(y>m&&(m+=this.vertices.length),g=Number.MAX_VALUE,m<y)return t;for(var T=y;T<=m;++T)o.leftOn(w.at(P-1),w.at(P),w.at(T))&&o.rightOn(w.at(P+1),w.at(P),w.at(T))&&(f=o.sqdist(w.at(P),w.at(T)))<g&&(g=f,v=T%this.vertices.length);P<v?(b.append(w,P,v+1),0!=v&&x.append(w,v,_.length),x.append(w,0,P+1)):(0!=P&&b.append(w,P,_.length),b.append(w,0,v+1),x.append(w,v,P+1))}return b.vertices.length<x.vertices.length?(b.quickDecomp(t,e,i,r,a,h),x.quickDecomp(t,e,i,r,a,h)):(x.quickDecomp(t,e,i,r,a,h),b.quickDecomp(t,e,i,r,a,h)),t}return t.push(this),t},s.prototype.removeCollinearPoints=function(t){for(var e=0,i=this.vertices.length-1;this.vertices.length>3&&i>=0;--i)o.collinear(this.at(i-1),this.at(i),this.at(i+1),t)&&(this.vertices.splice(i%this.vertices.length,1),i--,e++);return e}},{"./Line":1,"./Point":2,"./Scalar":4}],4:[function(t,e,i){function s(){}e.exports=s,s.eq=function(t,e,i){return i=i||0,Math.abs(t-e)<i}},{}],5:[function(t,e,i){e.exports={Polygon:t("./Polygon"),Point:t("./Point")}},{"./Point":2,"./Polygon":3}],6:[function(t,e,i){e.exports={name:"p2",version:"0.7.0",description:"A JavaScript 2D physics engine.",author:"Stefan Hedman <[email protected]> (http://steffe.se)",keywords:["p2.js","p2","physics","engine","2d"],main:"./src/p2.js",engines:{node:"*"},repository:{type:"git",url:"https://github.com/schteppe/p2.js.git"},bugs:{url:"https://github.com/schteppe/p2.js/issues"},licenses:[{type:"MIT"}],devDependencies:{grunt:"^0.4.5","grunt-contrib-jshint":"^0.11.2","grunt-contrib-nodeunit":"^0.4.1","grunt-contrib-uglify":"~0.4.0","grunt-contrib-watch":"~0.5.0","grunt-browserify":"~2.0.1","grunt-contrib-concat":"^0.4.0"},dependencies:{"poly-decomp":"0.1.0"}}},{}],7:[function(t,e,i){function s(t){this.lowerBound=n.create(),t&&t.lowerBound&&n.copy(this.lowerBound,t.lowerBound),this.upperBound=n.create(),t&&t.upperBound&&n.copy(this.upperBound,t.upperBound)}var n=t("../math/vec2");t("../utils/Utils");e.exports=s;var r=n.create();s.prototype.setFromPoints=function(t,e,i,s){var o=this.lowerBound,a=this.upperBound;"number"!=typeof i&&(i=0),0!==i?n.rotate(o,t[0],i):n.copy(o,t[0]),n.copy(a,o);for(var h=Math.cos(i),l=Math.sin(i),c=1;c<t.length;c++){var u=t[c];if(0!==i){var d=u[0],p=u[1];r[0]=h*d-l*p,r[1]=l*d+h*p,u=r}for(var f=0;f<2;f++)u[f]>a[f]&&(a[f]=u[f]),u[f]<o[f]&&(o[f]=u[f])}e&&(n.add(this.lowerBound,this.lowerBound,e),n.add(this.upperBound,this.upperBound,e)),s&&(this.lowerBound[0]-=s,this.lowerBound[1]-=s,this.upperBound[0]+=s,this.upperBound[1]+=s)},s.prototype.copy=function(t){n.copy(this.lowerBound,t.lowerBound),n.copy(this.upperBound,t.upperBound)},s.prototype.extend=function(t){for(var e=2;e--;){var i=t.lowerBound[e];this.lowerBound[e]>i&&(this.lowerBound[e]=i);var s=t.upperBound[e];this.upperBound[e]<s&&(this.upperBound[e]=s)}},s.prototype.overlaps=function(t){var e=this.lowerBound,i=this.upperBound,s=t.lowerBound,n=t.upperBound;return(s[0]<=i[0]&&i[0]<=n[0]||e[0]<=n[0]&&n[0]<=i[0])&&(s[1]<=i[1]&&i[1]<=n[1]||e[1]<=n[1]&&n[1]<=i[1])},s.prototype.containsPoint=function(t){var e=this.lowerBound,i=this.upperBound;return e[0]<=t[0]&&t[0]<=i[0]&&e[1]<=t[1]&&t[1]<=i[1]},s.prototype.overlapsRay=function(t){var e=1/t.direction[0],i=1/t.direction[1],s=(this.lowerBound[0]-t.from[0])*e,n=(this.upperBound[0]-t.from[0])*e,r=(this.lowerBound[1]-t.from[1])*i,o=(this.upperBound[1]-t.from[1])*i,a=Math.max(Math.max(Math.min(s,n),Math.min(r,o))),h=Math.min(Math.min(Math.max(s,n),Math.max(r,o)));return h<0?-1:a>h?-1:a}},{"../math/vec2":30,"../utils/Utils":57}],8:[function(t,e,i){function s(t){this.type=t,this.result=[],this.world=null,this.boundingVolumeType=s.AABB}var n=t("../math/vec2"),r=t("../objects/Body");e.exports=s,s.AABB=1,s.BOUNDING_CIRCLE=2,s.prototype.setWorld=function(t){this.world=t},s.prototype.getCollisionPairs=function(t){};var o=n.create();s.boundingRadiusCheck=function(t,e){n.sub(o,t.position,e.position);var i=n.squaredLength(o),s=t.boundingRadius+e.boundingRadius;return i<=s*s},s.aabbCheck=function(t,e){return t.getAABB().overlaps(e.getAABB())},s.prototype.boundingVolumeCheck=function(t,e){var i;switch(this.boundingVolumeType){case s.BOUNDING_CIRCLE:i=s.boundingRadiusCheck(t,e);break;case s.AABB:i=s.aabbCheck(t,e);break;default:throw new Error("Bounding volume type not recognized: "+this.boundingVolumeType)}return i},s.canCollide=function(t,e){var i=r.KINEMATIC,s=r.STATIC;return(t.type!==s||e.type!==s)&&(!(t.type===i&&e.type===s||t.type===s&&e.type===i)&&((t.type!==i||e.type!==i)&&((t.sleepState!==r.SLEEPING||e.sleepState!==r.SLEEPING)&&!(t.sleepState===r.SLEEPING&&e.type===s||e.sleepState===r.SLEEPING&&t.type===s))))},s.NAIVE=1,s.SAP=2},{"../math/vec2":30,"../objects/Body":31}],9:[function(t,e,i){function s(){n.call(this,n.NAIVE)}var n=(t("../shapes/Circle"),t("../shapes/Plane"),t("../shapes/Shape"),t("../shapes/Particle"),t("../collision/Broadphase"));t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.getCollisionPairs=function(t){var e=t.bodies,i=this.result;i.length=0;for(var s=0,r=e.length;s!==r;s++)for(var o=e[s],a=0;a<s;a++){var h=e[a];n.canCollide(o,h)&&this.boundingVolumeCheck(o,h)&&i.push(o,h)}return i},s.prototype.aabbQuery=function(t,e,i){i=i||[];for(var s=t.bodies,n=0;n<s.length;n++){var r=s[n];r.aabbNeedsUpdate&&r.updateAABB(),r.aabb.overlaps(e)&&i.push(r)}return i}},{"../collision/Broadphase":8,"../math/vec2":30,"../shapes/Circle":39,"../shapes/Particle":43,"../shapes/Plane":44,"../shapes/Shape":45}],10:[function(t,e,i){function s(){this.contactEquations=[],this.frictionEquations=[],this.enableFriction=!0,this.enabledEquations=!0,this.slipForce=10,this.frictionCoefficient=.3,this.surfaceVelocity=0,this.contactEquationPool=new c({size:32}),this.frictionEquationPool=new u({size:64}),this.restitution=0,this.stiffness=p.DEFAULT_STIFFNESS,this.relaxation=p.DEFAULT_RELAXATION,this.frictionStiffness=p.DEFAULT_STIFFNESS,this.frictionRelaxation=p.DEFAULT_RELAXATION,this.enableFrictionReduction=!0,this.collidingBodiesLastStep=new d,this.contactSkinSize=.01}function n(t,e){o.set(t.vertices[0],.5*-e.length,-e.radius),o.set(t.vertices[1],.5*e.length,-e.radius),o.set(t.vertices[2],.5*e.length,e.radius),o.set(t.vertices[3],.5*-e.length,e.radius)}function r(t,e,i,s){for(var n=q,r=H,l=Y,c=z,u=t,d=e.vertices,p=null,f=0;f!==d.length+1;f++){var g=d[f%d.length],m=d[(f+1)%d.length];o.rotate(n,g,s),o.rotate(r,m,s),h(n,n,i),h(r,r,i),a(l,n,u),a(c,r,u);var y=o.crossLength(l,c);if(null===p&&(p=y),y*p<=0)return!1;p=y}return!0}var o=t("../math/vec2"),a=o.sub,h=o.add,l=o.dot,c=(t("../utils/Utils"),t("../utils/ContactEquationPool")),u=t("../utils/FrictionEquationPool"),d=t("../utils/TupleDictionary"),p=t("../equations/Equation"),f=(t("../equations/ContactEquation"),t("../equations/FrictionEquation"),t("../shapes/Circle")),g=t("../shapes/Convex"),m=t("../shapes/Shape"),y=(t("../objects/Body"),t("../shapes/Box"));e.exports=s;var v=o.fromValues(0,1),b=o.fromValues(0,0),x=o.fromValues(0,0),w=o.fromValues(0,0),_=o.fromValues(0,0),P=o.fromValues(0,0),T=o.fromValues(0,0),C=o.fromValues(0,0),S=o.fromValues(0,0),A=o.fromValues(0,0),E=o.fromValues(0,0),I=o.fromValues(0,0),M=o.fromValues(0,0),R=o.fromValues(0,0),B=o.fromValues(0,0),L=o.fromValues(0,0),k=o.fromValues(0,0),O=o.fromValues(0,0),F=o.fromValues(0,0),D=[],U=o.create(),G=o.create();s.prototype.bodiesOverlap=function(t,e){for(var i=U,s=G,n=0,r=t.shapes.length;n!==r;n++){var o=t.shapes[n];t.toWorldFrame(i,o.position);for(var a=0,h=e.shapes.length;a!==h;a++){var l=e.shapes[a];if(e.toWorldFrame(s,l.position),this[o.type|l.type](t,o,i,o.angle+t.angle,e,l,s,l.angle+e.angle,!0))return!0}}return!1},s.prototype.collidedLastStep=function(t,e){var i=0|t.id,s=0|e.id;return!!this.collidingBodiesLastStep.get(i,s)},s.prototype.reset=function(){this.collidingBodiesLastStep.reset();for(var t=this.contactEquations,e=t.length;e--;){var i=t[e],s=i.bodyA.id,n=i.bodyB.id;this.collidingBodiesLastStep.set(s,n,!0)}for(var r=this.contactEquations,o=this.frictionEquations,a=0;a<r.length;a++)this.contactEquationPool.release(r[a]);for(var a=0;a<o.length;a++)this.frictionEquationPool.release(o[a]);this.contactEquations.length=this.frictionEquations.length=0},s.prototype.createContactEquation=function(t,e,i,s){var n=this.contactEquationPool.get();return n.bodyA=t,n.bodyB=e,n.shapeA=i,n.shapeB=s,n.restitution=this.restitution,n.firstImpact=!this.collidedLastStep(t,e),n.stiffness=this.stiffness,n.relaxation=this.relaxation,n.needsUpdate=!0,n.enabled=this.enabledEquations,n.offset=this.contactSkinSize,n},s.prototype.createFrictionEquation=function(t,e,i,s){var n=this.frictionEquationPool.get();return n.bodyA=t,n.bodyB=e,n.shapeA=i,n.shapeB=s,n.setSlipForce(this.slipForce),n.frictionCoefficient=this.frictionCoefficient,n.relativeVelocity=this.surfaceVelocity,n.enabled=this.enabledEquations,n.needsUpdate=!0,n.stiffness=this.frictionStiffness,n.relaxation=this.frictionRelaxation,n.contactEquations.length=0,n},s.prototype.createFrictionFromContact=function(t){var e=this.createFrictionEquation(t.bodyA,t.bodyB,t.shapeA,t.shapeB);return o.copy(e.contactPointA,t.contactPointA),o.copy(e.contactPointB,t.contactPointB),o.rotate90cw(e.t,t.normalA),e.contactEquations.push(t),e},s.prototype.createFrictionFromAverage=function(t){var e=this.contactEquations[this.contactEquations.length-1],i=this.createFrictionEquation(e.bodyA,e.bodyB,e.shapeA,e.shapeB),s=e.bodyA;e.bodyB;o.set(i.contactPointA,0,0),o.set(i.contactPointB,0,0),o.set(i.t,0,0);for(var n=0;n!==t;n++)e=this.contactEquations[this.contactEquations.length-1-n],e.bodyA===s?(o.add(i.t,i.t,e.normalA),o.add(i.contactPointA,i.contactPointA,e.contactPointA),o.add(i.contactPointB,i.contactPointB,e.contactPointB)):(o.sub(i.t,i.t,e.normalA),o.add(i.contactPointA,i.contactPointA,e.contactPointB),o.add(i.contactPointB,i.contactPointB,e.contactPointA)),i.contactEquations.push(e);var r=1/t;return o.scale(i.contactPointA,i.contactPointA,r),o.scale(i.contactPointB,i.contactPointB,r),o.normalize(i.t,i.t),o.rotate90cw(i.t,i.t),i},s.prototype[m.LINE|m.CONVEX]=s.prototype.convexLine=function(t,e,i,s,n,r,o,a,h){return!h&&0},s.prototype[m.LINE|m.BOX]=s.prototype.lineBox=function(t,e,i,s,n,r,o,a,h){return!h&&0};var N=new y({width:1,height:1}),X=o.create();s.prototype[m.CAPSULE|m.CONVEX]=s.prototype[m.CAPSULE|m.BOX]=s.prototype.convexCapsule=function(t,e,i,s,r,a,h,l,c){var u=X;o.set(u,a.length/2,0),o.rotate(u,u,l),o.add(u,u,h);var d=this.circleConvex(r,a,u,l,t,e,i,s,c,a.radius);o.set(u,-a.length/2,0),o.rotate(u,u,l),o.add(u,u,h);var p=this.circleConvex(r,a,u,l,t,e,i,s,c,a.radius);if(c&&(d||p))return!0;var f=N;return n(f,a),this.convexConvex(t,e,i,s,r,f,h,l,c)+d+p},s.prototype[m.CAPSULE|m.LINE]=s.prototype.lineCapsule=function(t,e,i,s,n,r,o,a,h){return!h&&0};var W=o.create(),j=o.create(),V=new y({width:1,height:1});s.prototype[m.CAPSULE|m.CAPSULE]=s.prototype.capsuleCapsule=function(t,e,i,s,r,a,h,l,c){for(var u,d=W,p=j,f=0,g=0;g<2;g++){o.set(d,(0===g?-1:1)*e.length/2,0),o.rotate(d,d,s),o.add(d,d,i);for(var m=0;m<2;m++){o.set(p,(0===m?-1:1)*a.length/2,0),o.rotate(p,p,l),o.add(p,p,h),this.enableFrictionReduction&&(u=this.enableFriction,this.enableFriction=!1);var y=this.circleCircle(t,e,d,s,r,a,p,l,c,e.radius,a.radius);if(this.enableFrictionReduction&&(this.enableFriction=u),c&&y)return!0;f+=y}}this.enableFrictionReduction&&(u=this.enableFriction,this.enableFriction=!1);var v=V;n(v,e);var b=this.convexCapsule(t,v,i,s,r,a,h,l,c);if(this.enableFrictionReduction&&(this.enableFriction=u),c&&b)return!0;if(f+=b,this.enableFrictionReduction){var u=this.enableFriction;this.enableFriction=!1}n(v,a);var x=this.convexCapsule(r,v,h,l,t,e,i,s,c);return this.enableFrictionReduction&&(this.enableFriction=u),!(!c||!x)||(f+=x,this.enableFrictionReduction&&f&&this.enableFriction&&this.frictionEquations.push(this.createFrictionFromAverage(f)),f)},s.prototype[m.LINE|m.LINE]=s.prototype.lineLine=function(t,e,i,s,n,r,o,a,h){return!h&&0},s.prototype[m.PLANE|m.LINE]=s.prototype.planeLine=function(t,e,i,s,n,r,c,u,d){var p=b,f=x,g=w,m=_,y=P,E=T,I=C,M=S,R=A,B=D,L=0;o.set(p,-r.length/2,0),o.set(f,r.length/2,0),o.rotate(g,p,u),o.rotate(m,f,u),h(g,g,c),h(m,m,c),o.copy(p,g),o.copy(f,m),a(y,f,p),o.normalize(E,y),o.rotate90cw(R,E),o.rotate(M,v,s),B[0]=p,B[1]=f;for(var k=0;k<B.length;k++){var O=B[k];a(I,O,i);var F=l(I,M);if(F<0){if(d)return!0;var U=this.createContactEquation(t,n,e,r);L++,o.copy(U.normalA,M),o.normalize(U.normalA,U.normalA),o.scale(I,M,F),a(U.contactPointA,O,I),a(U.contactPointA,U.contactPointA,t.position),a(U.contactPointB,O,c),h(U.contactPointB,U.contactPointB,c),a(U.contactPointB,U.contactPointB,n.position),this.contactEquations.push(U),this.enableFrictionReduction||this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(U))}}return!d&&(this.enableFrictionReduction||L&&this.enableFriction&&this.frictionEquations.push(this.createFrictionFromAverage(L)),L)},s.prototype[m.PARTICLE|m.CAPSULE]=s.prototype.particleCapsule=function(t,e,i,s,n,r,o,a,h){return this.circleLine(t,e,i,s,n,r,o,a,h,r.radius,0)},s.prototype[m.CIRCLE|m.LINE]=s.prototype.circleLine=function(t,e,i,s,n,r,c,u,d,p,f){var p=p||0,f=void 0!==f?f:e.radius,g=b,m=x,y=w,v=_,L=P,k=T,O=C,F=S,U=A,G=E,N=I,X=M,W=R,j=B,V=D;o.set(F,-r.length/2,0),o.set(U,r.length/2,0),o.rotate(G,F,u),o.rotate(N,U,u),h(G,G,c),h(N,N,c),o.copy(F,G),o.copy(U,N),a(k,U,F),o.normalize(O,k),o.rotate90cw(L,O),a(X,i,F);var q=l(X,L);a(v,F,c),a(W,i,c);var H=f+p;if(Math.abs(q)<H){o.scale(g,L,q),a(y,i,g),o.scale(m,L,l(L,W)),o.normalize(m,m),o.scale(m,m,p),h(y,y,m);var Y=l(O,y),z=l(O,F),K=l(O,U);if(Y>z&&Y<K){if(d)return!0;var J=this.createContactEquation(t,n,e,r);return o.scale(J.normalA,g,-1),o.normalize(J.normalA,J.normalA),o.scale(J.contactPointA,J.normalA,f),h(J.contactPointA,J.contactPointA,i),a(J.contactPointA,J.contactPointA,t.position),a(J.contactPointB,y,c),h(J.contactPointB,J.contactPointB,c),a(J.contactPointB,J.contactPointB,n.position),this.contactEquations.push(J),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(J)),1}}V[0]=F,V[1]=U;for(var Q=0;Q<V.length;Q++){var Z=V[Q];if(a(X,Z,i),o.squaredLength(X)<Math.pow(H,2)){if(d)return!0;var J=this.createContactEquation(t,n,e,r);return o.copy(J.normalA,X),o.normalize(J.normalA,J.normalA),o.scale(J.contactPointA,J.normalA,f),h(J.contactPointA,J.contactPointA,i),a(J.contactPointA,J.contactPointA,t.position),a(J.contactPointB,Z,c),o.scale(j,J.normalA,-p),h(J.contactPointB,J.contactPointB,j),h(J.contactPointB,J.contactPointB,c),a(J.contactPointB,J.contactPointB,n.position),this.contactEquations.push(J),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(J)),1}}return 0},s.prototype[m.CIRCLE|m.CAPSULE]=s.prototype.circleCapsule=function(t,e,i,s,n,r,o,a,h){return this.circleLine(t,e,i,s,n,r,o,a,h,r.radius)},s.prototype[m.CIRCLE|m.CONVEX]=s.prototype[m.CIRCLE|m.BOX]=s.prototype.circleConvex=function(t,e,i,s,n,l,c,u,d,p){for(var p="number"==typeof p?p:e.radius,f=b,g=x,m=w,y=_,v=P,T=E,C=I,S=R,A=B,M=L,O=k,F=!1,D=Number.MAX_VALUE,U=l.vertices,G=0;G!==U.length+1;G++){var N=U[G%U.length],X=U[(G+1)%U.length];if(o.rotate(f,N,u),o.rotate(g,X,u),h(f,f,c),h(g,g,c),a(m,g,f),o.normalize(y,m),o.rotate90cw(v,y),o.scale(A,v,-e.radius),h(A,A,i),r(A,l,c,u)){o.sub(M,f,A);var W=Math.abs(o.dot(M,v));W<D&&(o.copy(O,A),D=W,o.scale(S,v,W),o.add(S,S,A),F=!0)}}if(F){if(d)return!0;var j=this.createContactEquation(t,n,e,l);return o.sub(j.normalA,O,i),o.normalize(j.normalA,j.normalA),o.scale(j.contactPointA,j.normalA,p),h(j.contactPointA,j.contactPointA,i),a(j.contactPointA,j.contactPointA,t.position),a(j.contactPointB,S,c),h(j.contactPointB,j.contactPointB,c),a(j.contactPointB,j.contactPointB,n.position),this.contactEquations.push(j),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(j)),1}if(p>0)for(var G=0;G<U.length;G++){var V=U[G];if(o.rotate(C,V,u),h(C,C,c),a(T,C,i),o.squaredLength(T)<Math.pow(p,2)){if(d)return!0;var j=this.createContactEquation(t,n,e,l);return o.copy(j.normalA,T),o.normalize(j.normalA,j.normalA),o.scale(j.contactPointA,j.normalA,p),h(j.contactPointA,j.contactPointA,i),a(j.contactPointA,j.contactPointA,t.position),a(j.contactPointB,C,c),h(j.contactPointB,j.contactPointB,c),a(j.contactPointB,j.contactPointB,n.position),this.contactEquations.push(j),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(j)),1}}return 0};var q=o.create(),H=o.create(),Y=o.create(),z=o.create();s.prototype[m.PARTICLE|m.CONVEX]=s.prototype[m.PARTICLE|m.BOX]=s.prototype.particleConvex=function(t,e,i,s,n,c,u,d,p){var f=b,g=x,m=w,y=_,v=P,S=T,A=C,I=E,M=R,B=O,L=F,k=Number.MAX_VALUE,D=!1,U=c.vertices;if(!r(i,c,u,d))return 0;if(p)return!0;for(var G=0;G!==U.length+1;G++){var N=U[G%U.length],X=U[(G+1)%U.length];o.rotate(f,N,d),o.rotate(g,X,d),h(f,f,u),h(g,g,u),a(m,g,f),o.normalize(y,m),o.rotate90cw(v,y),a(I,i,f);l(I,v);a(S,f,u),a(A,i,u),o.sub(B,f,i);var W=Math.abs(o.dot(B,v));W<k&&(k=W,o.scale(M,v,W),o.add(M,M,i),o.copy(L,v),D=!0)}if(D){var j=this.createContactEquation(t,n,e,c);return o.scale(j.normalA,L,-1),o.normalize(j.normalA,j.normalA),o.set(j.contactPointA,0,0),h(j.contactPointA,j.contactPointA,i),a(j.contactPointA,j.contactPointA,t.position),a(j.contactPointB,M,u),h(j.contactPointB,j.contactPointB,u),a(j.contactPointB,j.contactPointB,n.position),this.contactEquations.push(j),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(j)),1}return 0},s.prototype[m.CIRCLE]=s.prototype.circleCircle=function(t,e,i,s,n,r,l,c,u,d,p){var f=b,d=d||e.radius,p=p||r.radius;a(f,i,l);var g=d+p;if(o.squaredLength(f)>Math.pow(g,2))return 0;if(u)return!0;var m=this.createContactEquation(t,n,e,r);return a(m.normalA,l,i),o.normalize(m.normalA,m.normalA),o.scale(m.contactPointA,m.normalA,d),o.scale(m.contactPointB,m.normalA,-p),h(m.contactPointA,m.contactPointA,i),a(m.contactPointA,m.contactPointA,t.position),h(m.contactPointB,m.contactPointB,l),a(m.contactPointB,m.contactPointB,n.position),this.contactEquations.push(m),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(m)),1},s.prototype[m.PLANE|m.CONVEX]=s.prototype[m.PLANE|m.BOX]=s.prototype.planeConvex=function(t,e,i,s,n,r,c,u,d){var p=b,f=x,g=w,m=0;o.rotate(f,v,s);for(var y=0;y!==r.vertices.length;y++){var _=r.vertices[y];if(o.rotate(p,_,u),h(p,p,c),a(g,p,i),l(g,f)<=0){if(d)return!0;m++;var P=this.createContactEquation(t,n,e,r);a(g,p,i),o.copy(P.normalA,f);var T=l(g,P.normalA);o.scale(g,P.normalA,T),a(P.contactPointB,p,n.position),a(P.contactPointA,p,g),a(P.contactPointA,P.contactPointA,t.position),this.contactEquations.push(P),this.enableFrictionReduction||this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(P))}}return this.enableFrictionReduction&&this.enableFriction&&m&&this.frictionEquations.push(this.createFrictionFromAverage(m)),m},s.prototype[m.PARTICLE|m.PLANE]=s.prototype.particlePlane=function(t,e,i,s,n,r,h,c,u){var d=b,p=x;c=c||0,a(d,i,h),o.rotate(p,v,c);var f=l(d,p);if(f>0)return 0;if(u)return!0;var g=this.createContactEquation(n,t,r,e);return o.copy(g.normalA,p),o.scale(d,g.normalA,f),a(g.contactPointA,i,d),a(g.contactPointA,g.contactPointA,n.position),a(g.contactPointB,i,t.position),this.contactEquations.push(g),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(g)),1},s.prototype[m.CIRCLE|m.PARTICLE]=s.prototype.circleParticle=function(t,e,i,s,n,r,l,c,u){var d=b;if(a(d,l,i),o.squaredLength(d)>Math.pow(e.radius,2))return 0;if(u)return!0;var p=this.createContactEquation(t,n,e,r);return o.copy(p.normalA,d),o.normalize(p.normalA,p.normalA),o.scale(p.contactPointA,p.normalA,e.radius),h(p.contactPointA,p.contactPointA,i),a(p.contactPointA,p.contactPointA,t.position),a(p.contactPointB,l,n.position),this.contactEquations.push(p),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(p)),1};var K=new f({radius:1}),J=o.create(),Q=o.create();o.create();s.prototype[m.PLANE|m.CAPSULE]=s.prototype.planeCapsule=function(t,e,i,s,n,r,a,l,c){var u=J,d=Q,p=K;o.set(u,-r.length/2,0),o.rotate(u,u,l),h(u,u,a),o.set(d,r.length/2,0),o.rotate(d,d,l),h(d,d,a),p.radius=r.radius;var f;this.enableFrictionReduction&&(f=this.enableFriction,this.enableFriction=!1);var g=this.circlePlane(n,p,u,0,t,e,i,s,c),m=this.circlePlane(n,p,d,0,t,e,i,s,c);if(this.enableFrictionReduction&&(this.enableFriction=f),c)return g||m;var y=g+m;return this.enableFrictionReduction&&y&&this.frictionEquations.push(this.createFrictionFromAverage(y)),y},s.prototype[m.CIRCLE|m.PLANE]=s.prototype.circlePlane=function(t,e,i,s,n,r,c,u,d){var p=t,f=e,g=i,m=n,y=c,_=u;_=_||0;var P=b,T=x,C=w;a(P,g,y),o.rotate(T,v,_);var S=l(T,P);if(S>f.radius)return 0;if(d)return!0;var A=this.createContactEquation(m,p,r,e);return o.copy(A.normalA,T),o.scale(A.contactPointB,A.normalA,-f.radius),h(A.contactPointB,A.contactPointB,g),a(A.contactPointB,A.contactPointB,p.position),o.scale(C,A.normalA,S),a(A.contactPointA,P,C),h(A.contactPointA,A.contactPointA,y),a(A.contactPointA,A.contactPointA,m.position),this.contactEquations.push(A),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(A)),1},s.prototype[m.CONVEX]=s.prototype[m.CONVEX|m.BOX]=s.prototype[m.BOX]=s.prototype.convexConvex=function(t,e,i,n,r,c,u,d,p,f){var g=b,m=x,y=w,v=_,T=P,E=C,I=S,M=A,R=0,f="number"==typeof f?f:0;if(!s.findSeparatingAxis(e,i,n,c,u,d,g))return 0;a(I,u,i),l(g,I)>0&&o.scale(g,g,-1);var B=s.getClosestEdge(e,n,g,!0),L=s.getClosestEdge(c,d,g);if(-1===B||-1===L)return 0;for(var k=0;k<2;k++){var O=B,F=L,D=e,U=c,G=i,N=u,X=n,W=d,j=t,V=r;if(0===k){var q;q=O,O=F,F=q,q=D,D=U,U=q,q=G,G=N,N=q,q=X,X=W,W=q,q=j,j=V,V=q}for(var H=F;H<F+2;H++){var Y=U.vertices[(H+U.vertices.length)%U.vertices.length];o.rotate(m,Y,W),h(m,m,N);for(var z=0,K=O-1;K<O+2;K++){var J=D.vertices[(K+D.vertices.length)%D.vertices.length],Q=D.vertices[(K+1+D.vertices.length)%D.vertices.length];o.rotate(y,J,X),o.rotate(v,Q,X),h(y,y,G),h(v,v,G),a(T,v,y),o.rotate90cw(M,T),o.normalize(M,M),a(I,m,y);var Z=l(M,I);(K===O&&Z<=f||K!==O&&Z<=0)&&z++}if(z>=3){if(p)return!0;var $=this.createContactEquation(j,V,D,U);R++;var J=D.vertices[O%D.vertices.length],Q=D.vertices[(O+1)%D.vertices.length];o.rotate(y,J,X),o.rotate(v,Q,X),h(y,y,G),h(v,v,G),a(T,v,y),o.rotate90cw($.normalA,T),o.normalize($.normalA,$.normalA),a(I,m,y);var Z=l($.normalA,I);o.scale(E,$.normalA,Z),a($.contactPointA,m,G),a($.contactPointA,$.contactPointA,E),h($.contactPointA,$.contactPointA,G),a($.contactPointA,$.contactPointA,j.position),a($.contactPointB,m,N),h($.contactPointB,$.contactPointB,N),a($.contactPointB,$.contactPointB,V.position),this.contactEquations.push($),this.enableFrictionReduction||this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact($))}}}return this.enableFrictionReduction&&this.enableFriction&&R&&this.frictionEquations.push(this.createFrictionFromAverage(R)),R};var Z=o.fromValues(0,0);s.projectConvexOntoAxis=function(t,e,i,s,n){var r,a,h=null,c=null,u=Z;o.rotate(u,s,-i);for(var d=0;d<t.vertices.length;d++)r=t.vertices[d],a=l(r,u),(null===h||a>h)&&(h=a),(null===c||a<c)&&(c=a);if(c>h){var p=c;c=h,h=p}var f=l(e,s);o.set(n,c+f,h+f)};var $=o.fromValues(0,0),tt=o.fromValues(0,0),et=o.fromValues(0,0),it=o.fromValues(0,0),st=o.fromValues(0,0),nt=o.fromValues(0,0);s.findSeparatingAxis=function(t,e,i,n,r,h,l){var c=null,u=!1,d=!1,p=$,f=tt,g=et,m=it,v=st,b=nt;if(t instanceof y&&n instanceof y)for(var x=0;2!==x;x++){var w=t,_=i;1===x&&(w=n,_=h);for(var P=0;2!==P;P++){0===P?o.set(m,0,1):1===P&&o.set(m,1,0),0!==_&&o.rotate(m,m,_),s.projectConvexOntoAxis(t,e,i,m,v),s.projectConvexOntoAxis(n,r,h,m,b);var T=v,C=b;v[0]>b[0]&&(C=v,T=b,!0);var S=C[0]-T[1];u=S<=0,(null===c||S>c)&&(o.copy(l,m),c=S,d=u)}}else for(var x=0;2!==x;x++){var w=t,_=i;1===x&&(w=n,_=h);for(var P=0;P!==w.vertices.length;P++){o.rotate(f,w.vertices[P],_),o.rotate(g,w.vertices[(P+1)%w.vertices.length],_),a(p,g,f),o.rotate90cw(m,p),o.normalize(m,m),s.projectConvexOntoAxis(t,e,i,m,v),s.projectConvexOntoAxis(n,r,h,m,b);var T=v,C=b;v[0]>b[0]&&(C=v,T=b,!0);var S=C[0]-T[1];u=S<=0,(null===c||S>c)&&(o.copy(l,m),c=S,d=u)}}return d};var rt=o.fromValues(0,0),ot=o.fromValues(0,0),at=o.fromValues(0,0);s.getClosestEdge=function(t,e,i,s){var n=rt,r=ot,h=at;o.rotate(n,i,-e),s&&o.scale(n,n,-1);for(var c=-1,u=t.vertices.length,d=-1,p=0;p!==u;p++){a(r,t.vertices[(p+1)%u],t.vertices[p%u]),o.rotate90cw(h,r),o.normalize(h,h);var f=l(h,n);(-1===c||f>d)&&(c=p%u,d=f)}return c};var ht=o.create(),lt=o.create(),ct=o.create(),ut=o.create(),dt=o.create(),pt=o.create(),ft=o.create();s.prototype[m.CIRCLE|m.HEIGHTFIELD]=s.prototype.circleHeightfield=function(t,e,i,s,n,r,l,c,u,d){var p=r.heights,d=d||e.radius,f=r.elementWidth,g=lt,m=ht,y=dt,v=ft,b=pt,x=ct,w=ut,_=Math.floor((i[0]-d-l[0])/f),P=Math.ceil((i[0]+d-l[0])/f);_<0&&(_=0),P>=p.length&&(P=p.length-1);for(var T=p[_],C=p[P],S=_;S<P;S++)p[S]<C&&(C=p[S]),p[S]>T&&(T=p[S]);if(i[1]-d>T)return!u&&0;for(var A=!1,S=_;S<P;S++){o.set(x,S*f,p[S]),o.set(w,(S+1)*f,p[S+1]),o.add(x,x,l),o.add(w,w,l),o.sub(b,w,x),o.rotate(b,b,Math.PI/2),o.normalize(b,b),o.scale(m,b,-d),o.add(m,m,i),o.sub(g,m,x);var E=o.dot(g,b);if(m[0]>=x[0]&&m[0]<w[0]&&E<=0){if(u)return!0;A=!0,o.scale(g,b,-E),o.add(y,m,g),o.copy(v,b);var I=this.createContactEquation(n,t,r,e);o.copy(I.normalA,v),o.scale(I.contactPointB,I.normalA,-d),h(I.contactPointB,I.contactPointB,i),a(I.contactPointB,I.contactPointB,t.position),o.copy(I.contactPointA,y),o.sub(I.contactPointA,I.contactPointA,n.position),this.contactEquations.push(I),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(I))}}if(A=!1,d>0)for(var S=_;S<=P;S++)if(o.set(x,S*f,p[S]),o.add(x,x,l),o.sub(g,i,x),o.squaredLength(g)<Math.pow(d,2)){if(u)return!0;A=!0;var I=this.createContactEquation(n,t,r,e);o.copy(I.normalA,g),o.normalize(I.normalA,I.normalA),o.scale(I.contactPointB,I.normalA,-d),h(I.contactPointB,I.contactPointB,i),a(I.contactPointB,I.contactPointB,t.position),a(I.contactPointA,x,l),h(I.contactPointA,I.contactPointA,l),a(I.contactPointA,I.contactPointA,n.position),this.contactEquations.push(I),this.enableFriction&&this.frictionEquations.push(this.createFrictionFromContact(I))}return A?1:0};var gt=o.create(),mt=o.create(),yt=o.create(),vt=new g({vertices:[o.create(),o.create(),o.create(),o.create()]});s.prototype[m.BOX|m.HEIGHTFIELD]=s.prototype[m.CONVEX|m.HEIGHTFIELD]=s.prototype.convexHeightfield=function(t,e,i,s,n,r,a,h,l){var c=r.heights,u=r.elementWidth,d=gt,p=mt,f=yt,g=vt,m=Math.floor((t.aabb.lowerBound[0]-a[0])/u),y=Math.ceil((t.aabb.upperBound[0]-a[0])/u);m<0&&(m=0),y>=c.length&&(y=c.length-1);for(var v=c[m],b=c[y],x=m;x<y;x++)c[x]<b&&(b=c[x]),c[x]>v&&(v=c[x]);if(t.aabb.lowerBound[1]>v)return!l&&0;for(var w=0,x=m;x<y;x++){o.set(d,x*u,c[x]),o.set(p,(x+1)*u,c[x+1]),o.add(d,d,a),o.add(p,p,a);o.set(f,.5*(p[0]+d[0]),.5*(p[1]+d[1]-100)),o.sub(g.vertices[0],p,f),o.sub(g.vertices[1],d,f),o.copy(g.vertices[2],g.vertices[1]),o.copy(g.vertices[3],g.vertices[0]),g.vertices[2][1]-=100,g.vertices[3][1]-=100,w+=this.convexConvex(t,e,i,s,n,g,f,0,l)}return w}},{"../equations/ContactEquation":21,"../equations/Equation":22,"../equations/FrictionEquation":23,"../math/vec2":30,"../objects/Body":31,"../shapes/Box":37,"../shapes/Circle":39,"../shapes/Convex":40,"../shapes/Shape":45,"../utils/ContactEquationPool":48,"../utils/FrictionEquationPool":49,"../utils/TupleDictionary":56,"../utils/Utils":57}],11:[function(t,e,i){function s(t){t=t||{},this.from=t.from?r.fromValues(t.from[0],t.from[1]):r.create(),this.to=t.to?r.fromValues(t.to[0],t.to[1]):r.create(),this.checkCollisionResponse=void 0===t.checkCollisionResponse||t.checkCollisionResponse,this.skipBackfaces=!!t.skipBackfaces,this.collisionMask=void 0!==t.collisionMask?t.collisionMask:-1,this.collisionGroup=void 0!==t.collisionGroup?t.collisionGroup:-1,this.mode=void 0!==t.mode?t.mode:s.ANY,this.callback=t.callback||function(t){},this.direction=r.create(),this.length=1,this.update()}function n(t,e,i){r.sub(a,i,t);var s=r.dot(a,e);return r.scale(h,e,s),r.add(h,h,t),r.squaredDistance(i,h)}e.exports=s;var r=t("../math/vec2");t("../collision/RaycastResult"),t("../shapes/Shape"),t("../collision/AABB");s.prototype.constructor=s,s.CLOSEST=1,s.ANY=2,s.ALL=4,s.prototype.update=function(){var t=this.direction;r.sub(t,this.to,this.from),this.length=r.length(t),r.normalize(t,t)},s.prototype.intersectBodies=function(t,e){for(var i=0,s=e.length;!t.shouldStop(this)&&i<s;i++){var n=e[i],r=n.getAABB();(r.overlapsRay(this)>=0||r.containsPoint(this.from))&&this.intersectBody(t,n)}};var o=r.create();s.prototype.intersectBody=function(t,e){var i=this.checkCollisionResponse;if(!i||e.collisionResponse)for(var s=o,n=0,a=e.shapes.length;n<a;n++){var h=e.shapes[n];if((!i||h.collisionResponse)&&(0!=(this.collisionGroup&h.collisionMask)&&0!=(h.collisionGroup&this.collisionMask))){r.rotate(s,h.position,e.angle),r.add(s,s,e.position);var l=h.angle+e.angle;if(this.intersectShape(t,h,l,s,e),t.shouldStop(this))break}}},s.prototype.intersectShape=function(t,e,i,s,r){n(this.from,this.direction,s)>e.boundingRadius*e.boundingRadius||(this._currentBody=r,this._currentShape=e,e.raycast(t,this,s,i),this._currentBody=this._currentShape=null)},s.prototype.getAABB=function(t){var e=this.to,i=this.from;r.set(t.lowerBound,Math.min(e[0],i[0]),Math.min(e[1],i[1])),r.set(t.upperBound,Math.max(e[0],i[0]),Math.max(e[1],i[1]))};r.create();s.prototype.reportIntersection=function(t,e,i,n){var o=(this.from,this.to,this._currentShape),a=this._currentBody;if(!(this.skipBackfaces&&r.dot(i,this.direction)>0))switch(this.mode){case s.ALL:t.set(i,o,a,e,n),this.callback(t);break;case s.CLOSEST:(e<t.fraction||!t.hasHit())&&t.set(i,o,a,e,n);break;case s.ANY:t.set(i,o,a,e,n)}};var a=r.create(),h=r.create()},{"../collision/AABB":7,"../collision/RaycastResult":12,"../math/vec2":30,"../shapes/Shape":45}],12:[function(t,e,i){function s(){this.normal=n.create(),this.shape=null,this.body=null,this.faceIndex=-1,this.fraction=-1,this.isStopped=!1}var n=t("../math/vec2"),r=t("../collision/Ray");e.exports=s,s.prototype.reset=function(){n.set(this.normal,0,0),this.shape=null,this.body=null,this.faceIndex=-1,this.fraction=-1,this.isStopped=!1},s.prototype.getHitDistance=function(t){return n.distance(t.from,t.to)*this.fraction},s.prototype.hasHit=function(){return-1!==this.fraction},s.prototype.getHitPoint=function(t,e){n.lerp(t,e.from,e.to,this.fraction)},s.prototype.stop=function(){this.isStopped=!0},s.prototype.shouldStop=function(t){return this.isStopped||-1!==this.fraction&&t.mode===r.ANY},s.prototype.set=function(t,e,i,s,r){n.copy(this.normal,t),this.shape=e,this.body=i,this.fraction=s,this.faceIndex=r}},{"../collision/Ray":11,"../math/vec2":30}],13:[function(t,e,i){function s(){r.call(this,r.SAP),this.axisList=[],this.axisIndex=0;var t=this;this._addBodyHandler=function(e){t.axisList.push(e.body)},this._removeBodyHandler=function(e){var i=t.axisList.indexOf(e.body);-1!==i&&t.axisList.splice(i,1)}}var n=t("../utils/Utils"),r=t("../collision/Broadphase");e.exports=s,s.prototype=new r,s.prototype.constructor=s,s.prototype.setWorld=function(t){this.axisList.length=0,n.appendArray(this.axisList,t.bodies),t.off("addBody",this._addBodyHandler).off("removeBody",this._removeBodyHandler),t.on("addBody",this._addBodyHandler).on("removeBody",this._removeBodyHandler),this.world=t},s.sortAxisList=function(t,e){e|=0;for(var i=1,s=t.length;i<s;i++){for(var n=t[i],r=i-1;r>=0&&!(t[r].aabb.lowerBound[e]<=n.aabb.lowerBound[e]);r--)t[r+1]=t[r];t[r+1]=n}return t},s.prototype.sortList=function(){var t=this.axisList,e=this.axisIndex;s.sortAxisList(t,e)},s.prototype.getCollisionPairs=function(t){var e=this.axisList,i=this.result,s=this.axisIndex;i.length=0;for(var n=e.length;n--;){var o=e[n];o.aabbNeedsUpdate&&o.updateAABB()}this.sortList();for(var a=0,h=0|e.length;a!==h;a++)for(var l=e[a],c=a+1;c<h;c++){var u=e[c],d=u.aabb.lowerBound[s]<=l.aabb.upperBound[s];if(!d)break;r.canCollide(l,u)&&this.boundingVolumeCheck(l,u)&&i.push(l,u)}return i},s.prototype.aabbQuery=function(t,e,i){i=i||[],this.sortList();var s=this.axisIndex,n="x";1===s&&(n="y"),2===s&&(n="z");for(var r=this.axisList,o=(e.lowerBound[n],e.upperBound[n],0);o<r.length;o++){var a=r[o];a.aabbNeedsUpdate&&a.updateAABB(),a.aabb.overlaps(e)&&i.push(a)}return i}},{"../collision/Broadphase":8,"../utils/Utils":57}],14:[function(t,e,i){function s(t,e,i,s){this.type=i,s=n.defaults(s,{collideConnected:!0,wakeUpBodies:!0}),this.equations=[],this.bodyA=t,this.bodyB=e,this.collideConnected=s.collideConnected,s.wakeUpBodies&&(t&&t.wakeUp(),e&&e.wakeUp())}e.exports=s;var n=t("../utils/Utils");s.prototype.update=function(){throw new Error("method update() not implmemented in this Constraint subclass!")},s.DISTANCE=1,s.GEAR=2,s.LOCK=3,s.PRISMATIC=4,s.REVOLUTE=5,s.prototype.setStiffness=function(t){for(var e=this.equations,i=0;i!==e.length;i++){var s=e[i];s.stiffness=t,s.needsUpdate=!0}},s.prototype.setRelaxation=function(t){for(var e=this.equations,i=0;i!==e.length;i++){var s=e[i];s.relaxation=t,s.needsUpdate=!0}}},{"../utils/Utils":57}],15:[function(t,e,i){function s(t,e,i){i=a.defaults(i,{localAnchorA:[0,0],localAnchorB:[0,0]}),n.call(this,t,e,n.DISTANCE,i),this.localAnchorA=o.fromValues(i.localAnchorA[0],i.localAnchorA[1]),this.localAnchorB=o.fromValues(i.localAnchorB[0],i.localAnchorB[1]);var s=this.localAnchorA,h=this.localAnchorB;if(this.distance=0,"number"==typeof i.distance)this.distance=i.distance;else{var l=o.create(),c=o.create(),u=o.create();o.rotate(l,s,t.angle),o.rotate(c,h,e.angle),o.add(u,e.position,c),o.sub(u,u,l),o.sub(u,u,t.position),this.distance=o.length(u)}var d;d=void 0===i.maxForce?Number.MAX_VALUE:i.maxForce;var p=new r(t,e,-d,d);this.equations=[p],this.maxForce=d;var u=o.create(),f=o.create(),g=o.create(),m=this;p.computeGq=function(){var t=this.bodyA,e=this.bodyB,i=t.position,n=e.position;return o.rotate(f,s,t.angle),o.rotate(g,h,e.angle),o.add(u,n,g),o.sub(u,u,f),o.sub(u,u,i),o.length(u)-m.distance},this.setMaxForce(d),this.upperLimitEnabled=!1,this.upperLimit=1,this.lowerLimitEnabled=!1,this.lowerLimit=0,this.position=0}var n=t("./Constraint"),r=t("../equations/Equation"),o=t("../math/vec2"),a=t("../utils/Utils");e.exports=s,s.prototype=new n,s.prototype.constructor=s;var h=o.create(),l=o.create(),c=o.create();s.prototype.update=function(){var t=this.equations[0],e=this.bodyA,i=this.bodyB,s=(this.distance,e.position),n=i.position,r=this.equations[0],a=t.G;o.rotate(l,this.localAnchorA,e.angle),o.rotate(c,this.localAnchorB,i.angle),o.add(h,n,c),o.sub(h,h,l),o.sub(h,h,s),this.position=o.length(h);var u=!1;if(this.upperLimitEnabled&&this.position>this.upperLimit&&(r.maxForce=0,r.minForce=-this.maxForce,this.distance=this.upperLimit,u=!0),this.lowerLimitEnabled&&this.position<this.lowerLimit&&(r.maxForce=this.maxForce,r.minForce=0,this.distance=this.lowerLimit,u=!0),(this.lowerLimitEnabled||this.upperLimitEnabled)&&!u)return void(r.enabled=!1);r.enabled=!0,o.normalize(h,h);var d=o.crossLength(l,h),p=o.crossLength(c,h);a[0]=-h[0],a[1]=-h[1],a[2]=-d,a[3]=h[0],a[4]=h[1],a[5]=p},s.prototype.setMaxForce=function(t){var e=this.equations[0];e.minForce=-t,e.maxForce=t},s.prototype.getMaxForce=function(){return this.equations[0].maxForce}},{"../equations/Equation":22,"../math/vec2":30,"../utils/Utils":57,"./Constraint":14}],16:[function(t,e,i){function s(t,e,i){i=i||{},n.call(this,t,e,n.GEAR,i),this.ratio=void 0!==i.ratio?i.ratio:1,this.angle=void 0!==i.angle?i.angle:e.angle-this.ratio*t.angle,i.angle=this.angle,i.ratio=this.ratio,this.equations=[new r(t,e,i)],void 0!==i.maxTorque&&this.setMaxTorque(i.maxTorque)}var n=t("./Constraint"),r=(t("../equations/Equation"),t("../equations/AngleLockEquation"));t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.update=function(){var t=this.equations[0];t.ratio!==this.ratio&&t.setRatio(this.ratio),t.angle=this.angle},s.prototype.setMaxTorque=function(t){this.equations[0].setMaxTorque(t)},s.prototype.getMaxTorque=function(t){return this.equations[0].maxForce}},{"../equations/AngleLockEquation":20,"../equations/Equation":22,"../math/vec2":30,"./Constraint":14}],17:[function(t,e,i){function s(t,e,i){i=i||{},n.call(this,t,e,n.LOCK,i);var s=void 0===i.maxForce?Number.MAX_VALUE:i.maxForce,a=(i.localAngleB,new o(t,e,-s,s)),h=new o(t,e,-s,s),l=new o(t,e,-s,s),c=r.create(),u=r.create(),d=this;a.computeGq=function(){return r.rotate(c,d.localOffsetB,t.angle),r.sub(u,e.position,t.position),r.sub(u,u,c),u[0]},h.computeGq=function(){return r.rotate(c,d.localOffsetB,t.angle),r.sub(u,e.position,t.position),r.sub(u,u,c),u[1]};var p=r.create(),f=r.create();l.computeGq=function(){return r.rotate(p,d.localOffsetB,e.angle-d.localAngleB),r.scale(p,p,-1),r.sub(u,t.position,e.position),r.add(u,u,p),r.rotate(f,p,-Math.PI/2),r.normalize(f,f),r.dot(u,f)},this.localOffsetB=r.create(),i.localOffsetB?r.copy(this.localOffsetB,i.localOffsetB):(r.sub(this.localOffsetB,e.position,t.position),r.rotate(this.localOffsetB,this.localOffsetB,-t.angle)),this.localAngleB=0,"number"==typeof i.localAngleB?this.localAngleB=i.localAngleB:this.localAngleB=e.angle-t.angle,this.equations.push(a,h,l),this.setMaxForce(s)}var n=t("./Constraint"),r=t("../math/vec2"),o=t("../equations/Equation");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.setMaxForce=function(t){for(var e=this.equations,i=0;i<this.equations.length;i++)e[i].maxForce=t,e[i].minForce=-t},s.prototype.getMaxForce=function(){return this.equations[0].maxForce};var a=r.create(),h=r.create(),l=r.create(),c=r.fromValues(1,0),u=r.fromValues(0,1);s.prototype.update=function(){var t=this.equations[0],e=this.equations[1],i=this.equations[2],s=this.bodyA,n=this.bodyB;r.rotate(a,this.localOffsetB,s.angle),r.rotate(h,this.localOffsetB,n.angle-this.localAngleB),r.scale(h,h,-1),r.rotate(l,h,Math.PI/2),r.normalize(l,l),t.G[0]=-1,t.G[1]=0,t.G[2]=-r.crossLength(a,c),t.G[3]=1,e.G[0]=0,e.G[1]=-1,e.G[2]=-r.crossLength(a,u),e.G[4]=1,i.G[0]=-l[0],i.G[1]=-l[1],i.G[3]=l[0],i.G[4]=l[1],i.G[5]=r.crossLength(h,l)}},{"../equations/Equation":22,"../math/vec2":30,"./Constraint":14}],18:[function(t,e,i){function s(t,e,i){i=i||{},n.call(this,t,e,n.PRISMATIC,i);var s=a.fromValues(0,0),l=a.fromValues(1,0),c=a.fromValues(0,0);i.localAnchorA&&a.copy(s,i.localAnchorA),i.localAxisA&&a.copy(l,i.localAxisA),i.localAnchorB&&a.copy(c,i.localAnchorB),this.localAnchorA=s,this.localAnchorB=c,this.localAxisA=l;var u=this.maxForce=void 0!==i.maxForce?i.maxForce:Number.MAX_VALUE,d=new o(t,e,-u,u),p=new a.create,f=new a.create,g=new a.create,m=new a.create;if(d.computeGq=function(){return a.dot(g,m)},d.updateJacobian=function(){var i=this.G,n=t.position,r=e.position;a.rotate(p,s,t.angle),a.rotate(f,c,e.angle),a.add(g,r,f),a.sub(g,g,n),a.sub(g,g,p),a.rotate(m,l,t.angle+Math.PI/2),i[0]=-m[0],i[1]=-m[1],i[2]=-a.crossLength(p,m)+a.crossLength(m,g),i[3]=m[0],i[4]=m[1],i[5]=a.crossLength(f,m)},this.equations.push(d),!i.disableRotationalLock){var y=new h(t,e,-u,u);this.equations.push(y)}this.position=0,this.velocity=0,this.lowerLimitEnabled=void 0!==i.lowerLimit,this.upperLimitEnabled=void 0!==i.upperLimit,this.lowerLimit=void 0!==i.lowerLimit?i.lowerLimit:0,this.upperLimit=void 0!==i.upperLimit?i.upperLimit:1,this.upperLimitEquation=new r(t,e),this.lowerLimitEquation=new r(t,e),this.upperLimitEquation.minForce=this.lowerLimitEquation.minForce=0,this.upperLimitEquation.maxForce=this.lowerLimitEquation.maxForce=u,this.motorEquation=new o(t,e),this.motorEnabled=!1,this.motorSpeed=0;var v=this,b=this.motorEquation;b.computeGW;b.computeGq=function(){return 0},b.computeGW=function(){var t=this.G,e=this.bodyA,i=this.bodyB,s=e.velocity,n=i.velocity,r=e.angularVelocity,o=i.angularVelocity;return this.gmult(t,s,r,n,o)+v.motorSpeed}}var n=t("./Constraint"),r=t("../equations/ContactEquation"),o=t("../equations/Equation"),a=t("../math/vec2"),h=t("../equations/RotationalLockEquation");e.exports=s,s.prototype=new n,s.prototype.constructor=s;var l=a.create(),c=a.create(),u=a.create(),d=a.create(),p=a.create(),f=a.create();s.prototype.update=function(){var t=this.equations,e=t[0],i=this.upperLimit,s=this.lowerLimit,n=this.upperLimitEquation,r=this.lowerLimitEquation,o=this.bodyA,h=this.bodyB,g=this.localAxisA,m=this.localAnchorA,y=this.localAnchorB;e.updateJacobian(),a.rotate(l,g,o.angle),a.rotate(d,m,o.angle),a.add(c,d,o.position),a.rotate(p,y,h.angle),a.add(u,p,h.position);var v=this.position=a.dot(u,l)-a.dot(c,l);if(this.motorEnabled){var b=this.motorEquation.G;b[0]=l[0],b[1]=l[1],b[2]=a.crossLength(l,p),b[3]=-l[0],b[4]=-l[1],b[5]=-a.crossLength(l,d)}if(this.upperLimitEnabled&&v>i)a.scale(n.normalA,l,-1),a.sub(n.contactPointA,c,o.position),a.sub(n.contactPointB,u,h.position),a.scale(f,l,i),a.add(n.contactPointA,n.contactPointA,f),-1===t.indexOf(n)&&t.push(n);else{var x=t.indexOf(n);-1!==x&&t.splice(x,1)}if(this.lowerLimitEnabled&&v<s)a.scale(r.normalA,l,1),a.sub(r.contactPointA,c,o.position),a.sub(r.contactPointB,u,h.position),a.scale(f,l,s),a.sub(r.contactPointB,r.contactPointB,f),-1===t.indexOf(r)&&t.push(r);else{var x=t.indexOf(r);-1!==x&&t.splice(x,1)}},s.prototype.enableMotor=function(){this.motorEnabled||(this.equations.push(this.motorEquation),this.motorEnabled=!0)},s.prototype.disableMotor=function(){if(this.motorEnabled){var t=this.equations.indexOf(this.motorEquation);this.equations.splice(t,1),this.motorEnabled=!1}},s.prototype.setLimits=function(t,e){"number"==typeof t?(this.lowerLimit=t,this.lowerLimitEnabled=!0):(this.lowerLimit=t,this.lowerLimitEnabled=!1),"number"==typeof e?(this.upperLimit=e,this.upperLimitEnabled=!0):(this.upperLimit=e,this.upperLimitEnabled=!1)}},{"../equations/ContactEquation":21,"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../math/vec2":30,"./Constraint":14}],19:[function(t,e,i){function s(t,e,i){i=i||{},n.call(this,t,e,n.REVOLUTE,i);var s=this.maxForce=void 0!==i.maxForce?i.maxForce:Number.MAX_VALUE;this.pivotA=h.create(),this.pivotB=h.create(),i.worldPivot?(h.sub(this.pivotA,i.worldPivot,t.position),h.sub(this.pivotB,i.worldPivot,e.position),h.rotate(this.pivotA,this.pivotA,-t.angle),h.rotate(this.pivotB,this.pivotB,-e.angle)):(h.copy(this.pivotA,i.localPivotA),h.copy(this.pivotB,i.localPivotB));var f=this.equations=[new r(t,e,-s,s),new r(t,e,-s,s)],g=f[0],m=f[1],y=this;g.computeGq=function(){return h.rotate(l,y.pivotA,t.angle),h.rotate(c,y.pivotB,e.angle),h.add(p,e.position,c),h.sub(p,p,t.position),h.sub(p,p,l),h.dot(p,u)},m.computeGq=function(){return h.rotate(l,y.pivotA,t.angle),h.rotate(c,y.pivotB,e.angle),h.add(p,e.position,c),h.sub(p,p,t.position),h.sub(p,p,l),h.dot(p,d)},m.minForce=g.minForce=-s,m.maxForce=g.maxForce=s,this.motorEquation=new o(t,e),this.motorEnabled=!1,this.angle=0,this.lowerLimitEnabled=!1,this.upperLimitEnabled=!1,this.lowerLimit=0,this.upperLimit=0,this.upperLimitEquation=new a(t,e),this.lowerLimitEquation=new a(t,e),this.upperLimitEquation.minForce=0,this.lowerLimitEquation.maxForce=0}var n=t("./Constraint"),r=t("../equations/Equation"),o=t("../equations/RotationalVelocityEquation"),a=t("../equations/RotationalLockEquation"),h=t("../math/vec2");e.exports=s;var l=h.create(),c=h.create(),u=h.fromValues(1,0),d=h.fromValues(0,1),p=h.create();s.prototype=new n,s.prototype.constructor=s,s.prototype.setLimits=function(t,e){"number"==typeof t?(this.lowerLimit=t,this.lowerLimitEnabled=!0):(this.lowerLimit=t,this.lowerLimitEnabled=!1),"number"==typeof e?(this.upperLimit=e,this.upperLimitEnabled=!0):(this.upperLimit=e,this.upperLimitEnabled=!1)},s.prototype.update=function(){var t=this.bodyA,e=this.bodyB,i=this.pivotA,s=this.pivotB,n=this.equations,r=(n[0],n[1],n[0]),o=n[1],a=this.upperLimit,p=this.lowerLimit,f=this.upperLimitEquation,g=this.lowerLimitEquation,m=this.angle=e.angle-t.angle;if(this.upperLimitEnabled&&m>a)f.angle=a,-1===n.indexOf(f)&&n.push(f);else{var y=n.indexOf(f);-1!==y&&n.splice(y,1)}if(this.lowerLimitEnabled&&m<p)g.angle=p,-1===n.indexOf(g)&&n.push(g);else{var y=n.indexOf(g);-1!==y&&n.splice(y,1)}h.rotate(l,i,t.angle),h.rotate(c,s,e.angle),r.G[0]=-1,r.G[1]=0,r.G[2]=-h.crossLength(l,u),r.G[3]=1,r.G[4]=0,r.G[5]=h.crossLength(c,u),o.G[0]=0,o.G[1]=-1,o.G[2]=-h.crossLength(l,d),o.G[3]=0,o.G[4]=1,o.G[5]=h.crossLength(c,d)},s.prototype.enableMotor=function(){this.motorEnabled||(this.equations.push(this.motorEquation),this.motorEnabled=!0)},s.prototype.disableMotor=function(){if(this.motorEnabled){var t=this.equations.indexOf(this.motorEquation);this.equations.splice(t,1),this.motorEnabled=!1}},s.prototype.motorIsEnabled=function(){return!!this.motorEnabled},s.prototype.setMotorSpeed=function(t){if(this.motorEnabled){var e=this.equations.indexOf(this.motorEquation);this.equations[e].relativeVelocity=t}},s.prototype.getMotorSpeed=function(){return!!this.motorEnabled&&this.motorEquation.relativeVelocity}},{"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../equations/RotationalVelocityEquation":25,"../math/vec2":30,"./Constraint":14}],20:[function(t,e,i){function s(t,e,i){i=i||{},n.call(this,t,e,-Number.MAX_VALUE,Number.MAX_VALUE),this.angle=i.angle||0,this.ratio="number"==typeof i.ratio?i.ratio:1,this.setRatio(this.ratio)}var n=t("./Equation");t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.computeGq=function(){return this.ratio*this.bodyA.angle-this.bodyB.angle+this.angle},s.prototype.setRatio=function(t){var e=this.G;e[2]=t,e[5]=-1,this.ratio=t},s.prototype.setMaxTorque=function(t){this.maxForce=t,this.minForce=-t}},{"../math/vec2":30,"./Equation":22}],21:[function(t,e,i){function s(t,e){n.call(this,t,e,0,Number.MAX_VALUE),this.contactPointA=r.create(),this.penetrationVec=r.create(),this.contactPointB=r.create(),this.normalA=r.create(),this.restitution=0,this.firstImpact=!1,this.shapeA=null,this.shapeB=null}var n=t("./Equation"),r=t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.computeB=function(t,e,i){var s=this.bodyA,n=this.bodyB,o=this.contactPointA,a=this.contactPointB,h=s.position,l=n.position,c=this.penetrationVec,u=this.normalA,d=this.G,p=r.crossLength(o,u),f=r.crossLength(a,u);d[0]=-u[0],d[1]=-u[1],d[2]=-p,d[3]=u[0],d[4]=u[1],d[5]=f,r.add(c,l,a),r.sub(c,c,h),r.sub(c,c,o);var g,m;return this.firstImpact&&0!==this.restitution?(m=0,g=1/e*(1+this.restitution)*this.computeGW()):(m=r.dot(u,c)+this.offset,g=this.computeGW()),-m*t-g*e-i*this.computeGiMf()}},{"../math/vec2":30,"./Equation":22}],22:[function(t,e,i){function s(t,e,i,n){this.minForce=void 0===i?-Number.MAX_VALUE:i,this.maxForce=void 0===n?Number.MAX_VALUE:n,this.bodyA=t,this.bodyB=e,this.stiffness=s.DEFAULT_STIFFNESS,this.relaxation=s.DEFAULT_RELAXATION,this.G=new r.ARRAY_TYPE(6);for(var o=0;o<6;o++)this.G[o]=0;this.offset=0,this.a=0,this.b=0,this.epsilon=0,this.timeStep=1/60,this.needsUpdate=!0,this.multiplier=0,this.relativeVelocity=0,this.enabled=!0}e.exports=s;var n=t("../math/vec2"),r=t("../utils/Utils");t("../objects/Body");s.prototype.constructor=s,s.DEFAULT_STIFFNESS=1e6,s.DEFAULT_RELAXATION=4,s.prototype.update=function(){var t=this.stiffness,e=this.relaxation,i=this.timeStep;this.a=4/(i*(1+4*e)),this.b=4*e/(1+4*e),this.epsilon=4/(i*i*t*(1+4*e)),this.needsUpdate=!1},s.prototype.gmult=function(t,e,i,s,n){return t[0]*e[0]+t[1]*e[1]+t[2]*i+t[3]*s[0]+t[4]*s[1]+t[5]*n},s.prototype.computeB=function(t,e,i){var s=this.computeGW();return-this.computeGq()*t-s*e-this.computeGiMf()*i};var o=n.create(),a=n.create();s.prototype.computeGq=function(){var t=this.G,e=this.bodyA,i=this.bodyB,s=(e.position,i.position,e.angle),n=i.angle;return this.gmult(t,o,s,a,n)+this.offset},s.prototype.computeGW=function(){var t=this.G,e=this.bodyA,i=this.bodyB,s=e.velocity,n=i.velocity,r=e.angularVelocity,o=i.angularVelocity;return this.gmult(t,s,r,n,o)+this.relativeVelocity},s.prototype.computeGWlambda=function(){var t=this.G,e=this.bodyA,i=this.bodyB,s=e.vlambda,n=i.vlambda,r=e.wlambda,o=i.wlambda;return this.gmult(t,s,r,n,o)};var h=n.create(),l=n.create();s.prototype.computeGiMf=function(){var t=this.bodyA,e=this.bodyB,i=t.force,s=t.angularForce,r=e.force,o=e.angularForce,a=t.invMassSolve,c=e.invMassSolve,u=t.invInertiaSolve,d=e.invInertiaSolve,p=this.G;return n.scale(h,i,a),n.multiply(h,t.massMultiplier,h),n.scale(l,r,c),n.multiply(l,e.massMultiplier,l),this.gmult(p,h,s*u,l,o*d)},s.prototype.computeGiMGt=function(){var t=this.bodyA,e=this.bodyB,i=t.invMassSolve,s=e.invMassSolve,n=t.invInertiaSolve,r=e.invInertiaSolve,o=this.G;return o[0]*o[0]*i*t.massMultiplier[0]+o[1]*o[1]*i*t.massMultiplier[1]+o[2]*o[2]*n+o[3]*o[3]*s*e.massMultiplier[0]+o[4]*o[4]*s*e.massMultiplier[1]+o[5]*o[5]*r};var c=n.create(),u=n.create(),d=n.create();n.create(),n.create(),n.create();s.prototype.addToWlambda=function(t){var e=this.bodyA,i=this.bodyB,s=c,r=u,o=d,a=e.invMassSolve,h=i.invMassSolve,l=e.invInertiaSolve,p=i.invInertiaSolve,f=this.G;r[0]=f[0],r[1]=f[1],o[0]=f[3],o[1]=f[4],n.scale(s,r,a*t),n.multiply(s,s,e.massMultiplier),n.add(e.vlambda,e.vlambda,s),e.wlambda+=l*f[2]*t,n.scale(s,o,h*t),n.multiply(s,s,i.massMultiplier),n.add(i.vlambda,i.vlambda,s),i.wlambda+=p*f[5]*t},s.prototype.computeInvC=function(t){return 1/(this.computeGiMGt()+t)}},{"../math/vec2":30,"../objects/Body":31,"../utils/Utils":57}],23:[function(t,e,i){function s(t,e,i){r.call(this,t,e,-i,i),this.contactPointA=n.create(),this.contactPointB=n.create(),this.t=n.create(),this.contactEquations=[],this.shapeA=null,this.shapeB=null,this.frictionCoefficient=.3}var n=t("../math/vec2"),r=t("./Equation");t("../utils/Utils");e.exports=s,s.prototype=new r,s.prototype.constructor=s,s.prototype.setSlipForce=function(t){this.maxForce=t,this.minForce=-t},s.prototype.getSlipForce=function(){return this.maxForce},s.prototype.computeB=function(t,e,i){var s=(this.bodyA,this.bodyB,this.contactPointA),r=this.contactPointB,o=this.t,a=this.G;return a[0]=-o[0],a[1]=-o[1],a[2]=-n.crossLength(s,o),a[3]=o[0],a[4]=o[1],a[5]=n.crossLength(r,o),-this.computeGW()*e-i*this.computeGiMf()}},{"../math/vec2":30,"../utils/Utils":57,"./Equation":22}],24:[function(t,e,i){function s(t,e,i){i=i||{},n.call(this,t,e,-Number.MAX_VALUE,Number.MAX_VALUE),this.angle=i.angle||0;var s=this.G;s[2]=1,s[5]=-1}var n=t("./Equation"),r=t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s;var o=r.create(),a=r.create(),h=r.fromValues(1,0),l=r.fromValues(0,1);s.prototype.computeGq=function(){return r.rotate(o,h,this.bodyA.angle+this.angle),r.rotate(a,l,this.bodyB.angle),r.dot(o,a)}},{"../math/vec2":30,"./Equation":22}],25:[function(t,e,i){function s(t,e){n.call(this,t,e,-Number.MAX_VALUE,Number.MAX_VALUE),this.relativeVelocity=1,this.ratio=1}var n=t("./Equation");t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.computeB=function(t,e,i){var s=this.G;s[2]=-1,s[5]=this.ratio;var n=this.computeGiMf();return-this.computeGW()*e-i*n}},{"../math/vec2":30,"./Equation":22}],26:[function(t,e,i){var s=function(){};e.exports=s,s.prototype={constructor:s,on:function(t,e,i){e.context=i||this,void 0===this._listeners&&(this._listeners={});var s=this._listeners;return void 0===s[t]&&(s[t]=[]),-1===s[t].indexOf(e)&&s[t].push(e),this},has:function(t,e){if(void 0===this._listeners)return!1;var i=this._listeners;if(e){if(void 0!==i[t]&&-1!==i[t].indexOf(e))return!0}else if(void 0!==i[t])return!0;return!1},off:function(t,e){if(void 0===this._listeners)return this;var i=this._listeners,s=i[t].indexOf(e);return-1!==s&&i[t].splice(s,1),this},emit:function(t){if(void 0===this._listeners)return this;var e=this._listeners,i=e[t.type];if(void 0!==i){t.target=this;for(var s=0,n=i.length;s<n;s++){var r=i[s];r.call(r.context,t)}}return this}}},{}],27:[function(t,e,i){function s(t,e,i){if(i=i||{},!(t instanceof n&&e instanceof n))throw new Error("First two arguments must be Material instances.");this.id=s.idCounter++,this.materialA=t,this.materialB=e,this.friction=void 0!==i.friction?Number(i.friction):.3,this.restitution=void 0!==i.restitution?Number(i.restitution):0,this.stiffness=void 0!==i.stiffness?Number(i.stiffness):r.DEFAULT_STIFFNESS,this.relaxation=void 0!==i.relaxation?Number(i.relaxation):r.DEFAULT_RELAXATION,this.frictionStiffness=void 0!==i.frictionStiffness?Number(i.frictionStiffness):r.DEFAULT_STIFFNESS,this.frictionRelaxation=void 0!==i.frictionRelaxation?Number(i.frictionRelaxation):r.DEFAULT_RELAXATION,this.surfaceVelocity=void 0!==i.surfaceVelocity?Number(i.surfaceVelocity):0,this.contactSkinSize=.005}var n=t("./Material"),r=t("../equations/Equation");e.exports=s,s.idCounter=0},{"../equations/Equation":22,"./Material":28}],28:[function(t,e,i){function s(t){this.id=t||s.idCounter++}e.exports=s,s.idCounter=0},{}],29:[function(t,e,i){var s={};s.GetArea=function(t){if(t.length<6)return 0;for(var e=t.length-2,i=0,s=0;s<e;s+=2)i+=(t[s+2]-t[s])*(t[s+1]+t[s+3]);return.5*-(i+=(t[0]-t[e])*(t[e+1]+t[1]))},s.Triangulate=function(t){var e=t.length>>1;if(e<3)return[];for(var i=[],n=[],r=0;r<e;r++)n.push(r);for(var r=0,o=e;o>3;){var a=n[(r+0)%o],h=n[(r+1)%o],l=n[(r+2)%o],c=t[2*a],u=t[2*a+1],d=t[2*h],p=t[2*h+1],f=t[2*l],g=t[2*l+1],m=!1;if(s._convex(c,u,d,p,f,g)){m=!0;for(var y=0;y<o;y++){var v=n[y];if(v!=a&&v!=h&&v!=l&&s._PointInTriangle(t[2*v],t[2*v+1],c,u,d,p,f,g)){m=!1;break}}}if(m)i.push(a,h,l),n.splice((r+1)%o,1),o--,r=0;else if(r++>3*o)break}return i.push(n[0],n[1],n[2]),i},s._PointInTriangle=function(t,e,i,s,n,r,o,a){var h=o-i,l=a-s,c=n-i,u=r-s,d=t-i,p=e-s,f=h*h+l*l,g=h*c+l*u,m=h*d+l*p,y=c*c+u*u,v=c*d+u*p,b=1/(f*y-g*g),x=(y*m-g*v)*b,w=(f*v-g*m)*b;return x>=0&&w>=0&&x+w<1},s._convex=function(t,e,i,s,n,r){return(e-s)*(n-i)+(i-t)*(r-s)>=0},e.exports=s},{}],30:[function(t,e,i){var s=e.exports={},n=t("../utils/Utils");s.crossLength=function(t,e){return t[0]*e[1]-t[1]*e[0]},s.crossVZ=function(t,e,i){return s.rotate(t,e,-Math.PI/2),s.scale(t,t,i),t},s.crossZV=function(t,e,i){return s.rotate(t,i,Math.PI/2),s.scale(t,t,e),t},s.rotate=function(t,e,i){if(0!==i){var s=Math.cos(i),n=Math.sin(i),r=e[0],o=e[1];t[0]=s*r-n*o,t[1]=n*r+s*o}else t[0]=e[0],t[1]=e[1]},s.rotate90cw=function(t,e){var i=e[0],s=e[1];t[0]=s,t[1]=-i},s.toLocalFrame=function(t,e,i,n){s.copy(t,e),s.sub(t,t,i),s.rotate(t,t,-n)},s.toGlobalFrame=function(t,e,i,n){s.copy(t,e),s.rotate(t,t,n),s.add(t,t,i)},s.vectorToLocalFrame=function(t,e,i){s.rotate(t,e,-i)},s.vectorToGlobalFrame=function(t,e,i){s.rotate(t,e,i)},s.centroid=function(t,e,i,n){return s.add(t,e,i),s.add(t,t,n),s.scale(t,t,1/3),t},s.create=function(){var t=new n.ARRAY_TYPE(2);return t[0]=0,t[1]=0,t},s.clone=function(t){var e=new n.ARRAY_TYPE(2);return e[0]=t[0],e[1]=t[1],e},s.fromValues=function(t,e){var i=new n.ARRAY_TYPE(2);return i[0]=t,i[1]=e,i},s.copy=function(t,e){return t[0]=e[0],t[1]=e[1],t},s.set=function(t,e,i){return t[0]=e,t[1]=i,t},s.add=function(t,e,i){return t[0]=e[0]+i[0],t[1]=e[1]+i[1],t},s.subtract=function(t,e,i){return t[0]=e[0]-i[0],t[1]=e[1]-i[1],t},s.sub=s.subtract,s.multiply=function(t,e,i){return t[0]=e[0]*i[0],t[1]=e[1]*i[1],t},s.mul=s.multiply,s.divide=function(t,e,i){return t[0]=e[0]/i[0],t[1]=e[1]/i[1],t},s.div=s.divide,s.scale=function(t,e,i){return t[0]=e[0]*i,t[1]=e[1]*i,t},s.distance=function(t,e){var i=e[0]-t[0],s=e[1]-t[1];return Math.sqrt(i*i+s*s)},s.dist=s.distance,s.squaredDistance=function(t,e){var i=e[0]-t[0],s=e[1]-t[1];return i*i+s*s},s.sqrDist=s.squaredDistance,s.length=function(t){var e=t[0],i=t[1];return Math.sqrt(e*e+i*i)},s.len=s.length,s.squaredLength=function(t){var e=t[0],i=t[1];return e*e+i*i},s.sqrLen=s.squaredLength,s.negate=function(t,e){return t[0]=-e[0],t[1]=-e[1],t},s.normalize=function(t,e){var i=e[0],s=e[1],n=i*i+s*s;return n>0&&(n=1/Math.sqrt(n),t[0]=e[0]*n,t[1]=e[1]*n),t},s.dot=function(t,e){return t[0]*e[0]+t[1]*e[1]},s.str=function(t){return"vec2("+t[0]+", "+t[1]+")"},s.lerp=function(t,e,i,s){var n=e[0],r=e[1];return t[0]=n+s*(i[0]-n),t[1]=r+s*(i[1]-r),t},s.reflect=function(t,e,i){var s=e[0]*i[0]+e[1]*i[1];t[0]=e[0]-2*i[0]*s,t[1]=e[1]-2*i[1]*s},s.getLineSegmentsIntersection=function(t,e,i,n,r){var o=s.getLineSegmentsIntersectionFraction(e,i,n,r);return!(o<0)&&(t[0]=e[0]+o*(i[0]-e[0]),t[1]=e[1]+o*(i[1]-e[1]),!0)},s.getLineSegmentsIntersectionFraction=function(t,e,i,s){var n,r,o=e[0]-t[0],a=e[1]-t[1],h=s[0]-i[0],l=s[1]-i[1];return n=(-a*(t[0]-i[0])+o*(t[1]-i[1]))/(-h*a+o*l),r=(h*(t[1]-i[1])-l*(t[0]-i[0]))/(-h*a+o*l),n>=0&&n<=1&&r>=0&&r<=1?r:-1}},{"../utils/Utils":57}],31:[function(t,e,i){function s(t){t=t||{},c.call(this),this.id=t.id||++s._idCounter,this.world=null,this.shapes=[],this.mass=t.mass||0,this.invMass=0,this.inertia=0,this.invInertia=0,this.invMassSolve=0,this.invInertiaSolve=0,this.fixedRotation=!!t.fixedRotation,this.fixedX=!!t.fixedX,this.fixedY=!!t.fixedY,this.massMultiplier=n.create(),this.position=n.fromValues(0,0),t.position&&n.copy(this.position,t.position),this.interpolatedPosition=n.fromValues(0,0),this.interpolatedAngle=0,this.previousPosition=n.fromValues(0,0),this.previousAngle=0,this.velocity=n.fromValues(0,0),t.velocity&&n.copy(this.velocity,t.velocity),this.vlambda=n.fromValues(0,0),this.wlambda=0,this.angle=t.angle||0,this.angularVelocity=t.angularVelocity||0,this.force=n.create(),t.force&&n.copy(this.force,t.force),this.angularForce=t.angularForce||0,this.damping="number"==typeof t.damping?t.damping:.1,this.angularDamping="number"==typeof t.angularDamping?t.angularDamping:.1,this.type=s.STATIC,void 0!==t.type?this.type=t.type:t.mass?this.type=s.DYNAMIC:this.type=s.STATIC,this.boundingRadius=0,this.aabb=new l,this.aabbNeedsUpdate=!0,this.allowSleep=void 0===t.allowSleep||t.allowSleep,this.wantsToSleep=!1,this.sleepState=s.AWAKE,this.sleepSpeedLimit=void 0!==t.sleepSpeedLimit?t.sleepSpeedLimit:.2,this.sleepTimeLimit=void 0!==t.sleepTimeLimit?t.sleepTimeLimit:1,this.gravityScale=void 0!==t.gravityScale?t.gravityScale:1,this.collisionResponse=void 0===t.collisionResponse||t.collisionResponse,this.idleTime=0,this.timeLastSleepy=0,this.ccdSpeedThreshold=void 0!==t.ccdSpeedThreshold?t.ccdSpeedThreshold:-1,this.ccdIterations=void 0!==t.ccdIterations?t.ccdIterations:10,this.concavePath=null,this._wakeUpAfterNarrowphase=!1,this.updateMassProperties()}var n=t("../math/vec2"),r=t("poly-decomp"),o=t("../shapes/Convex"),a=t("../collision/RaycastResult"),h=t("../collision/Ray"),l=t("../collision/AABB"),c=t("../events/EventEmitter");e.exports=s,s.prototype=new c,s.prototype.constructor=s,s._idCounter=0,s.prototype.updateSolveMassProperties=function(){this.sleepState===s.SLEEPING||this.type===s.KINEMATIC?(this.invMassSolve=0,this.invInertiaSolve=0):(this.invMassSolve=this.invMass,this.invInertiaSolve=this.invInertia)},s.prototype.setDensity=function(t){var e=this.getArea();this.mass=e*t,this.updateMassProperties()},s.prototype.getArea=function(){for(var t=0,e=0;e<this.shapes.length;e++)t+=this.shapes[e].area;return t},s.prototype.getAABB=function(){return this.aabbNeedsUpdate&&this.updateAABB(),this.aabb};var u=new l,d=n.create();s.prototype.updateAABB=function(){for(var t=this.shapes,e=t.length,i=d,s=this.angle,r=0;r!==e;r++){var o=t[r],a=o.angle+s;n.rotate(i,o.position,s),n.add(i,i,this.position),o.computeAABB(u,i,a),0===r?this.aabb.copy(u):this.aabb.extend(u)}this.aabbNeedsUpdate=!1},s.prototype.updateBoundingRadius=function(){for(var t=this.shapes,e=t.length,i=0,s=0;s!==e;s++){var r=t[s],o=n.length(r.position),a=r.boundingRadius;o+a>i&&(i=o+a)}this.boundingRadius=i},s.prototype.addShape=function(t,e,i){if(t.body)throw new Error("A shape can only be added to one body.");t.body=this,e?n.copy(t.position,e):n.set(t.position,0,0),t.angle=i||0,this.shapes.push(t),this.updateMassProperties(),this.updateBoundingRadius(),this.aabbNeedsUpdate=!0},s.prototype.removeShape=function(t){var e=this.shapes.indexOf(t);return-1!==e&&(this.shapes.splice(e,1),this.aabbNeedsUpdate=!0,t.body=null,!0)},s.prototype.updateMassProperties=function(){if(this.type===s.STATIC||this.type===s.KINEMATIC)this.mass=Number.MAX_VALUE,this.invMass=0,this.inertia=Number.MAX_VALUE,this.invInertia=0;else{var t=this.shapes,e=t.length,i=this.mass/e,r=0;if(this.fixedRotation)this.inertia=Number.MAX_VALUE,this.invInertia=0;else{for(var o=0;o<e;o++){var a=t[o],h=n.squaredLength(a.position);r+=a.computeMomentOfInertia(i)+i*h}this.inertia=r,this.invInertia=r>0?1/r:0}this.invMass=1/this.mass,n.set(this.massMultiplier,this.fixedX?0:1,this.fixedY?0:1)}};n.create();s.prototype.applyForce=function(t,e){if(n.add(this.force,this.force,t),e){var i=n.crossLength(e,t);this.angularForce+=i}};var p=n.create(),f=n.create(),g=n.create();s.prototype.applyForceLocal=function(t,e){e=e||g;var i=p,s=f;this.vectorToWorldFrame(i,t),this.vectorToWorldFrame(s,e),this.applyForce(i,s)};var m=n.create();s.prototype.applyImpulse=function(t,e){if(this.type===s.DYNAMIC){var i=m;if(n.scale(i,t,this.invMass),n.multiply(i,this.massMultiplier,i),n.add(this.velocity,i,this.velocity),e){var r=n.crossLength(e,t);r*=this.invInertia,this.angularVelocity+=r}}};var y=n.create(),v=n.create(),b=n.create();s.prototype.applyImpulseLocal=function(t,e){e=e||b;var i=y,s=v;this.vectorToWorldFrame(i,t),this.vectorToWorldFrame(s,e),this.applyImpulse(i,s)},s.prototype.toLocalFrame=function(t,e){n.toLocalFrame(t,e,this.position,this.angle)},s.prototype.toWorldFrame=function(t,e){n.toGlobalFrame(t,e,this.position,this.angle)},s.prototype.vectorToLocalFrame=function(t,e){n.vectorToLocalFrame(t,e,this.angle)},s.prototype.vectorToWorldFrame=function(t,e){n.vectorToGlobalFrame(t,e,this.angle)},s.prototype.fromPolygon=function(t,e){e=e||{};for(var i=this.shapes.length;i>=0;--i)this.removeShape(this.shapes[i]);var s=new r.Polygon;if(s.vertices=t,s.makeCCW(),"number"==typeof e.removeCollinearPoints&&s.removeCollinearPoints(e.removeCollinearPoints),void 0===e.skipSimpleCheck&&!s.isSimple())return!1;this.concavePath=s.vertices.slice(0);for(var i=0;i<this.concavePath.length;i++){var a=[0,0];n.copy(a,this.concavePath[i]),this.concavePath[i]=a}var h;h=e.optimalDecomp?s.decomp():s.quickDecomp();for(var l=n.create(),i=0;i!==h.length;i++){for(var c=new o({vertices:h[i].vertices}),u=0;u!==c.vertices.length;u++){var a=c.vertices[u];n.sub(a,a,c.centerOfMass)}n.scale(l,c.centerOfMass,1),c.updateTriangles(),c.updateCenterOfMass(),c.updateBoundingRadius(),this.addShape(c,l)}return this.adjustCenterOfMass(),this.aabbNeedsUpdate=!0,!0};var x=(n.fromValues(0,0),n.fromValues(0,0)),w=n.fromValues(0,0),_=n.fromValues(0,0);s.prototype.adjustCenterOfMass=function(){var t=x,e=w,i=_,s=0;n.set(e,0,0);for(var r=0;r!==this.shapes.length;r++){var o=this.shapes[r];n.scale(t,o.position,o.area),n.add(e,e,t),s+=o.area}n.scale(i,e,1/s);for(var r=0;r!==this.shapes.length;r++){var o=this.shapes[r];n.sub(o.position,o.position,i)}n.add(this.position,this.position,i);for(var r=0;this.concavePath&&r<this.concavePath.length;r++)n.sub(this.concavePath[r],this.concavePath[r],i);this.updateMassProperties(),this.updateBoundingRadius()},s.prototype.setZeroForce=function(){n.set(this.force,0,0),this.angularForce=0},s.prototype.resetConstraintVelocity=function(){var t=this,e=t.vlambda;n.set(e,0,0),t.wlambda=0},s.prototype.addConstraintVelocity=function(){var t=this,e=t.velocity;n.add(e,e,t.vlambda),t.angularVelocity+=t.wlambda},s.prototype.applyDamping=function(t){if(this.type===s.DYNAMIC){var e=this.velocity;n.scale(e,e,Math.pow(1-this.damping,t)),this.angularVelocity*=Math.pow(1-this.angularDamping,t)}},s.prototype.wakeUp=function(){var t=this.sleepState;this.sleepState=s.AWAKE,this.idleTime=0,t!==s.AWAKE&&this.emit(s.wakeUpEvent)},s.prototype.sleep=function(){this.sleepState=s.SLEEPING,this.angularVelocity=0,this.angularForce=0,n.set(this.velocity,0,0),n.set(this.force,0,0),this.emit(s.sleepEvent)},s.prototype.sleepTick=function(t,e,i){if(this.allowSleep&&this.type!==s.SLEEPING){this.wantsToSleep=!1;this.sleepState;n.squaredLength(this.velocity)+Math.pow(this.angularVelocity,2)>=Math.pow(this.sleepSpeedLimit,2)?(this.idleTime=0,this.sleepState=s.AWAKE):(this.idleTime+=i,this.sleepState=s.SLEEPY),this.idleTime>this.sleepTimeLimit&&(e?this.wantsToSleep=!0:this.sleep())}},s.prototype.overlaps=function(t){return this.world.overlapKeeper.bodiesAreOverlapping(this,t)};var P=n.create(),T=n.create();s.prototype.integrate=function(t){var e=this.invMass,i=this.force,s=this.position,r=this.velocity;n.copy(this.previousPosition,this.position),this.previousAngle=this.angle,this.fixedRotation||(this.angularVelocity+=this.angularForce*this.invInertia*t),n.scale(P,i,t*e),n.multiply(P,this.massMultiplier,P),n.add(r,P,r),this.integrateToTimeOfImpact(t)||(n.scale(T,r,t),n.add(s,s,T),this.fixedRotation||(this.angle+=this.angularVelocity*t)),this.aabbNeedsUpdate=!0};var C=new a,S=new h({mode:h.ALL}),A=n.create(),E=n.create(),I=n.create(),M=n.create();s.prototype.integrateToTimeOfImpact=function(t){if(this.ccdSpeedThreshold<0||n.squaredLength(this.velocity)<Math.pow(this.ccdSpeedThreshold,2))return!1;n.normalize(A,this.velocity),n.scale(E,this.velocity,t),n.add(E,E,this.position),n.sub(I,E,this.position);var e,i=this.angularVelocity*t,s=n.length(I),r=1,o=this;if(C.reset(),S.callback=function(t){t.body!==o&&(e=t.body,t.getHitPoint(E,S),n.sub(I,E,o.position),r=n.length(I)/s,t.stop())},n.copy(S.from,this.position),n.copy(S.to,E),S.update(),this.world.raycast(C,S),!e)return!1;var a=this.angle;n.copy(M,this.position);for(var h=0,l=0,c=0,u=r;u>=l&&h<this.ccdIterations;){h++,c=(u-l)/2,n.scale(T,I,r),n.add(this.position,M,T),this.angle=a+i*r,this.updateAABB();this.aabb.overlaps(e.aabb)&&this.world.narrowphase.bodiesOverlap(this,e)?l=c:u=c}return r=c,n.copy(this.position,M),this.angle=a,n.scale(T,I,r),n.add(this.position,this.position,T),this.fixedRotation||(this.angle+=i*r),!0},s.prototype.getVelocityAtPoint=function(t,e){return n.crossVZ(t,e,this.angularVelocity),n.subtract(t,this.velocity,t),t},s.sleepyEvent={type:"sleepy"},s.sleepEvent={type:"sleep"},s.wakeUpEvent={type:"wakeup"},s.DYNAMIC=1,s.STATIC=2,s.KINEMATIC=4,s.AWAKE=0,s.SLEEPY=1,s.SLEEPING=2},{"../collision/AABB":7,"../collision/Ray":11,"../collision/RaycastResult":12,"../events/EventEmitter":26,"../math/vec2":30,"../shapes/Convex":40,"poly-decomp":5}],32:[function(t,e,i){function s(t,e,i){i=i||{},r.call(this,t,e,i),this.localAnchorA=n.fromValues(0,0),this.localAnchorB=n.fromValues(0,0),i.localAnchorA&&n.copy(this.localAnchorA,i.localAnchorA),i.localAnchorB&&n.copy(this.localAnchorB,i.localAnchorB),i.worldAnchorA&&this.setWorldAnchorA(i.worldAnchorA),i.worldAnchorB&&this.setWorldAnchorB(i.worldAnchorB);var s=n.create(),o=n.create();this.getWorldAnchorA(s),this.getWorldAnchorB(o);var a=n.distance(s,o);this.restLength="number"==typeof i.restLength?i.restLength:a}var n=t("../math/vec2"),r=t("./Spring");t("../utils/Utils");e.exports=s,s.prototype=new r,s.prototype.constructor=s,s.prototype.setWorldAnchorA=function(t){this.bodyA.toLocalFrame(this.localAnchorA,t)},s.prototype.setWorldAnchorB=function(t){this.bodyB.toLocalFrame(this.localAnchorB,t)},s.prototype.getWorldAnchorA=function(t){this.bodyA.toWorldFrame(t,this.localAnchorA)},s.prototype.getWorldAnchorB=function(t){this.bodyB.toWorldFrame(t,this.localAnchorB)};var o=n.create(),a=n.create(),h=n.create(),l=n.create(),c=n.create(),u=n.create(),d=n.create(),p=n.create(),f=n.create();s.prototype.applyForce=function(){var t=this.stiffness,e=this.damping,i=this.restLength,s=this.bodyA,r=this.bodyB,g=o,m=a,y=h,v=l,b=f,x=c,w=u,_=d,P=p;this.getWorldAnchorA(x),this.getWorldAnchorB(w),n.sub(_,x,s.position),n.sub(P,w,r.position),n.sub(g,w,x);var T=n.len(g);n.normalize(m,g),n.sub(y,r.velocity,s.velocity),n.crossZV(b,r.angularVelocity,P),n.add(y,y,b),n.crossZV(b,s.angularVelocity,_),n.sub(y,y,b),n.scale(v,m,-t*(T-i)-e*n.dot(y,m)),n.sub(s.force,s.force,v),n.add(r.force,r.force,v);var C=n.crossLength(_,v),S=n.crossLength(P,v);s.angularForce-=C,r.angularForce+=S}},{"../math/vec2":30,"../utils/Utils":57,"./Spring":34}],33:[function(t,e,i){function s(t,e,i){i=i||{},n.call(this,t,e,i),this.restAngle="number"==typeof i.restAngle?i.restAngle:e.angle-t.angle}var n=(t("../math/vec2"),t("./Spring"));e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.applyForce=function(){var t=this.stiffness,e=this.damping,i=this.restAngle,s=this.bodyA,n=this.bodyB,r=n.angle-s.angle,o=n.angularVelocity-s.angularVelocity,a=-t*(r-i)-e*o*0;s.angularForce-=a,n.angularForce+=a}},{"../math/vec2":30,"./Spring":34}],34:[function(t,e,i){function s(t,e,i){i=n.defaults(i,{stiffness:100,damping:1}),this.stiffness=i.stiffness,this.damping=i.damping,this.bodyA=t,this.bodyB=e}var n=(t("../math/vec2"),t("../utils/Utils"));e.exports=s,s.prototype.applyForce=function(){}},{"../math/vec2":30,"../utils/Utils":57}],35:[function(t,e,i){function s(t,e){e=e||{},this.chassisBody=t,this.wheels=[],this.groundBody=new h({mass:0}),this.world=null;var i=this;this.preStepCallback=function(){i.update()}}function n(t,e){e=e||{},this.vehicle=t,this.forwardEquation=new a(t.chassisBody,t.groundBody),this.sideEquation=new a(t.chassisBody,t.groundBody),this.steerValue=0,this.engineForce=0,this.setSideFriction(void 0!==e.sideFriction?e.sideFriction:5),this.localForwardVector=r.fromValues(0,1),e.localForwardVector&&r.copy(this.localForwardVector,e.localForwardVector),this.localPosition=r.fromValues(0,0),e.localPosition&&r.copy(this.localPosition,e.localPosition),o.apply(this,t.chassisBody,t.groundBody),this.equations.push(this.forwardEquation,this.sideEquation),this.setBrakeForce(0)}var r=t("../math/vec2"),o=(t("../utils/Utils"),t("../constraints/Constraint")),a=t("../equations/FrictionEquation"),h=t("../objects/Body");e.exports=s,s.prototype.addToWorld=function(t){this.world=t,t.addBody(this.groundBody),t.on("preStep",this.preStepCallback);for(var e=0;e<this.wheels.length;e++){var i=this.wheels[e];t.addConstraint(i)}},s.prototype.removeFromWorld=function(){var t=this.world;t.removeBody(this.groundBody),t.off("preStep",this.preStepCallback);for(var e=0;e<this.wheels.length;e++){var i=this.wheels[e];t.removeConstraint(i)}this.world=null},s.prototype.addWheel=function(t){var e=new n(this,t);return this.wheels.push(e),e},s.prototype.update=function(){for(var t=0;t<this.wheels.length;t++)this.wheels[t].update()},n.prototype=new o,n.prototype.setBrakeForce=function(t){this.forwardEquation.setSlipForce(t)},n.prototype.setSideFriction=function(t){this.sideEquation.setSlipForce(t)};var l=r.create(),c=r.create();n.prototype.getSpeed=function(){return this.vehicle.chassisBody.vectorToWorldFrame(c,this.localForwardVector),this.vehicle.chassisBody.getVelocityAtPoint(l,c),r.dot(l,c)};var u=r.create();n.prototype.update=function(){this.vehicle.chassisBody.vectorToWorldFrame(this.forwardEquation.t,this.localForwardVector),r.rotate(this.sideEquation.t,this.localForwardVector,Math.PI/2),this.vehicle.chassisBody.vectorToWorldFrame(this.sideEquation.t,this.sideEquation.t),r.rotate(this.forwardEquation.t,this.forwardEquation.t,this.steerValue),r.rotate(this.sideEquation.t,this.sideEquation.t,this.steerValue),this.vehicle.chassisBody.toWorldFrame(this.forwardEquation.contactPointB,this.localPosition),r.copy(this.sideEquation.contactPointB,this.forwardEquation.contactPointB),this.vehicle.chassisBody.vectorToWorldFrame(this.forwardEquation.contactPointA,this.localPosition),r.copy(this.sideEquation.contactPointA,this.forwardEquation.contactPointA),r.normalize(u,this.forwardEquation.t),r.scale(u,u,this.engineForce),this.vehicle.chassisBody.applyForce(u,this.forwardEquation.contactPointA)}},{"../constraints/Constraint":14,"../equations/FrictionEquation":23,"../math/vec2":30,"../objects/Body":31,"../utils/Utils":57}],36:[function(t,e,i){var s=e.exports={AABB:t("./collision/AABB"),AngleLockEquation:t("./equations/AngleLockEquation"),Body:t("./objects/Body"),Broadphase:t("./collision/Broadphase"),Capsule:t("./shapes/Capsule"),Circle:t("./shapes/Circle"),Constraint:t("./constraints/Constraint"),ContactEquation:t("./equations/ContactEquation"),ContactEquationPool:t("./utils/ContactEquationPool"),ContactMaterial:t("./material/ContactMaterial"),Convex:t("./shapes/Convex"),DistanceConstraint:t("./constraints/DistanceConstraint"),Equation:t("./equations/Equation"),EventEmitter:t("./events/EventEmitter"),FrictionEquation:t("./equations/FrictionEquation"),FrictionEquationPool:t("./utils/FrictionEquationPool"),GearConstraint:t("./constraints/GearConstraint"),GSSolver:t("./solver/GSSolver"),Heightfield:t("./shapes/Heightfield"),Line:t("./shapes/Line"),LockConstraint:t("./constraints/LockConstraint"),Material:t("./material/Material"),Narrowphase:t("./collision/Narrowphase"),NaiveBroadphase:t("./collision/NaiveBroadphase"),Particle:t("./shapes/Particle"),Plane:t("./shapes/Plane"),Pool:t("./utils/Pool"),RevoluteConstraint:t("./constraints/RevoluteConstraint"),PrismaticConstraint:t("./constraints/PrismaticConstraint"),Ray:t("./collision/Ray"),RaycastResult:t("./collision/RaycastResult"),Box:t("./shapes/Box"),RotationalVelocityEquation:t("./equations/RotationalVelocityEquation"),SAPBroadphase:t("./collision/SAPBroadphase"),Shape:t("./shapes/Shape"),Solver:t("./solver/Solver"),Spring:t("./objects/Spring"),TopDownVehicle:t("./objects/TopDownVehicle"),LinearSpring:t("./objects/LinearSpring"),RotationalSpring:t("./objects/RotationalSpring"),Utils:t("./utils/Utils"),World:t("./world/World"),vec2:t("./math/vec2"),version:t("../package.json").version};Object.defineProperty(s,"Rectangle",{get:function(){return console.warn("The Rectangle class has been renamed to Box."),this.Box}})},{"../package.json":6,"./collision/AABB":7,"./collision/Broadphase":8,"./collision/NaiveBroadphase":9,"./collision/Narrowphase":10,"./collision/Ray":11,"./collision/RaycastResult":12,"./collision/SAPBroadphase":13,"./constraints/Constraint":14,"./constraints/DistanceConstraint":15,"./constraints/GearConstraint":16,"./constraints/LockConstraint":17,"./constraints/PrismaticConstraint":18,"./constraints/RevoluteConstraint":19,"./equations/AngleLockEquation":20,"./equations/ContactEquation":21,"./equations/Equation":22,"./equations/FrictionEquation":23,"./equations/RotationalVelocityEquation":25,"./events/EventEmitter":26,"./material/ContactMaterial":27,"./material/Material":28,"./math/vec2":30,"./objects/Body":31,"./objects/LinearSpring":32,"./objects/RotationalSpring":33,"./objects/Spring":34,"./objects/TopDownVehicle":35,"./shapes/Box":37,"./shapes/Capsule":38,"./shapes/Circle":39,"./shapes/Convex":40,"./shapes/Heightfield":41,"./shapes/Line":42,"./shapes/Particle":43,"./shapes/Plane":44,"./shapes/Shape":45,"./solver/GSSolver":46,"./solver/Solver":47,"./utils/ContactEquationPool":48,"./utils/FrictionEquationPool":49,"./utils/Pool":55,"./utils/Utils":57,"./world/World":61}],37:[function(t,e,i){function s(t){"number"==typeof arguments[0]&&"number"==typeof arguments[1]&&(t={width:arguments[0],height:arguments[1]},console.warn("The Rectangle has been renamed to Box and its constructor signature has changed. Please use the following format: new Box({ width: 1, height: 1, ... })")),t=t||{};var e=this.width=t.width||1,i=this.height=t.height||1,s=[n.fromValues(-e/2,-i/2),n.fromValues(e/2,-i/2),n.fromValues(e/2,i/2),n.fromValues(-e/2,i/2)],a=[n.fromValues(1,0),n.fromValues(0,1)];t.vertices=s,t.axes=a,t.type=r.BOX,o.call(this,t)}var n=t("../math/vec2"),r=t("./Shape"),o=t("./Convex");e.exports=s,s.prototype=new o,s.prototype.constructor=s,s.prototype.computeMomentOfInertia=function(t){var e=this.width,i=this.height;return t*(i*i+e*e)/12},s.prototype.updateBoundingRadius=function(){var t=this.width,e=this.height;this.boundingRadius=Math.sqrt(t*t+e*e)/2};n.create(),n.create(),n.create(),n.create();s.prototype.computeAABB=function(t,e,i){t.setFromPoints(this.vertices,e,i,0)},s.prototype.updateArea=function(){this.area=this.width*this.height}},{"../math/vec2":30,"./Convex":40,"./Shape":45}],38:[function(t,e,i){function s(t){"number"==typeof arguments[0]&&"number"==typeof arguments[1]&&(t={length:arguments[0],radius:arguments[1]},console.warn("The Capsule constructor signature has changed. Please use the following format: new Capsule({ radius: 1, length: 1 })")),t=t||{},this.length=t.length||1,this.radius=t.radius||1,t.type=n.CAPSULE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.computeMomentOfInertia=function(t){var e=this.radius,i=this.length+e,s=2*e;return t*(s*s+i*i)/12},s.prototype.updateBoundingRadius=function(){this.boundingRadius=this.radius+this.length/2},s.prototype.updateArea=function(){this.area=Math.PI*this.radius*this.radius+2*this.radius*this.length};var o=r.create();s.prototype.computeAABB=function(t,e,i){var s=this.radius;r.set(o,this.length/2,0),0!==i&&r.rotate(o,o,i),r.set(t.upperBound,Math.max(o[0]+s,-o[0]+s),Math.max(o[1]+s,-o[1]+s)),r.set(t.lowerBound,Math.min(o[0]-s,-o[0]-s),Math.min(o[1]-s,-o[1]-s)),r.add(t.lowerBound,t.lowerBound,e),r.add(t.upperBound,t.upperBound,e)};var a=r.create(),h=r.create(),l=r.create(),c=r.create(),u=r.fromValues(0,1);s.prototype.raycast=function(t,e,i,s){for(var n=e.from,o=e.to,d=(e.direction,a),p=h,f=l,g=c,m=this.length/2,y=0;y<2;y++){var v=this.radius*(2*y-1);r.set(f,-m,v),r.set(g,m,v),r.toGlobalFrame(f,f,i,s),r.toGlobalFrame(g,g,i,s);var b=r.getLineSegmentsIntersectionFraction(n,o,f,g);if(b>=0&&(r.rotate(p,u,s),r.scale(p,p,2*y-1),e.reportIntersection(t,b,p,-1),t.shouldStop(e)))return}for(var x=Math.pow(this.radius,2)+Math.pow(m,2),y=0;y<2;y++){r.set(f,m*(2*y-1),0),r.toGlobalFrame(f,f,i,s);var w=Math.pow(o[0]-n[0],2)+Math.pow(o[1]-n[1],2),_=2*((o[0]-n[0])*(n[0]-f[0])+(o[1]-n[1])*(n[1]-f[1])),P=Math.pow(n[0]-f[0],2)+Math.pow(n[1]-f[1],2)-Math.pow(this.radius,2),b=Math.pow(_,2)-4*w*P;if(!(b<0))if(0===b){if(r.lerp(d,n,o,b),r.squaredDistance(d,i)>x&&(r.sub(p,d,f),r.normalize(p,p),e.reportIntersection(t,b,p,-1),t.shouldStop(e)))return}else{var T=Math.sqrt(b),C=1/(2*w),S=(-_-T)*C,A=(-_+T)*C;if(S>=0&&S<=1&&(r.lerp(d,n,o,S),r.squaredDistance(d,i)>x&&(r.sub(p,d,f),r.normalize(p,p),e.reportIntersection(t,S,p,-1),t.shouldStop(e))))return;if(A>=0&&A<=1&&(r.lerp(d,n,o,A),r.squaredDistance(d,i)>x&&(r.sub(p,d,f),r.normalize(p,p),e.reportIntersection(t,A,p,-1),t.shouldStop(e))))return}}}},{"../math/vec2":30,"./Shape":45}],39:[function(t,e,i){function s(t){"number"==typeof arguments[0]&&(t={radius:arguments[0]},console.warn("The Circle constructor signature has changed. Please use the following format: new Circle({ radius: 1 })")),t=t||{},this.radius=t.radius||1,t.type=n.CIRCLE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.computeMomentOfInertia=function(t){var e=this.radius;return t*e*e/2},s.prototype.updateBoundingRadius=function(){this.boundingRadius=this.radius},s.prototype.updateArea=function(){this.area=Math.PI*this.radius*this.radius},s.prototype.computeAABB=function(t,e,i){var s=this.radius;r.set(t.upperBound,s,s),r.set(t.lowerBound,-s,-s),e&&(r.add(t.lowerBound,t.lowerBound,e),r.add(t.upperBound,t.upperBound,e))};var o=r.create(),a=r.create();s.prototype.raycast=function(t,e,i,s){var n=e.from,h=e.to,l=this.radius,c=Math.pow(h[0]-n[0],2)+Math.pow(h[1]-n[1],2),u=2*((h[0]-n[0])*(n[0]-i[0])+(h[1]-n[1])*(n[1]-i[1])),d=Math.pow(n[0]-i[0],2)+Math.pow(n[1]-i[1],2)-Math.pow(l,2),p=Math.pow(u,2)-4*c*d,f=o,g=a;if(!(p<0))if(0===p)r.lerp(f,n,h,p),r.sub(g,f,i),r.normalize(g,g),e.reportIntersection(t,p,g,-1);else{var m=Math.sqrt(p),y=1/(2*c),v=(-u-m)*y,b=(-u+m)*y;if(v>=0&&v<=1&&(r.lerp(f,n,h,v),r.sub(g,f,i),r.normalize(g,g),e.reportIntersection(t,v,g,-1),t.shouldStop(e)))return;b>=0&&b<=1&&(r.lerp(f,n,h,b),r.sub(g,f,i),r.normalize(g,g),e.reportIntersection(t,b,g,-1))}}},{"../math/vec2":30,"./Shape":45}],40:[function(t,e,i){function s(t){Array.isArray(arguments[0])&&(t={vertices:arguments[0],axes:arguments[1]},console.warn("The Convex constructor signature has changed. Please use the following format: new Convex({ vertices: [...], ... })")),t=t||{},this.vertices=[];for(var e=void 0!==t.vertices?t.vertices:[],i=0;i<e.length;i++){var s=r.create();r.copy(s,e[i]),this.vertices.push(s)}if(this.axes=[],t.axes)for(var i=0;i<t.axes.length;i++){var o=r.create();r.copy(o,t.axes[i]),this.axes.push(o)}else for(var i=0;i<this.vertices.length;i++){var a=this.vertices[i],h=this.vertices[(i+1)%this.vertices.length],l=r.create();r.sub(l,h,a),r.rotate90cw(l,l),r.normalize(l,l),this.axes.push(l)}if(this.centerOfMass=r.fromValues(0,0),this.triangles=[],this.vertices.length&&(this.updateTriangles(),this.updateCenterOfMass()),this.boundingRadius=0,t.type=n.CONVEX,n.call(this,t),this.updateBoundingRadius(),this.updateArea(),this.area<0)throw new Error("Convex vertices must be given in conter-clockwise winding.")}var n=t("./Shape"),r=t("../math/vec2"),o=t("../math/polyk");t("poly-decomp");e.exports=s,s.prototype=new n,s.prototype.constructor=s;var a=r.create(),h=r.create();s.prototype.projectOntoLocalAxis=function(t,e){for(var i,s,n=null,o=null,t=a,h=0;h<this.vertices.length;h++)i=this.vertices[h],s=r.dot(i,t),(null===n||s>n)&&(n=s),(null===o||s<o)&&(o=s);if(o>n){var l=o;o=n,n=l}r.set(e,o,n)},s.prototype.projectOntoWorldAxis=function(t,e,i,s){var n=h;this.projectOntoLocalAxis(t,s),0!==i?r.rotate(n,t,i):n=t;var o=r.dot(e,n);r.set(s,s[0]+o,s[1]+o)},s.prototype.updateTriangles=function(){this.triangles.length=0;for(var t=[],e=0;e<this.vertices.length;e++){var i=this.vertices[e];t.push(i[0],i[1])}for(var s=o.Triangulate(t),e=0;e<s.length;e+=3){var n=s[e],r=s[e+1],a=s[e+2];this.triangles.push([n,r,a])}};var l=r.create(),c=r.create(),u=r.create(),d=r.create(),p=r.create();r.create(),r.create(),r.create(),r.create();s.prototype.updateCenterOfMass=function(){var t=this.triangles,e=this.vertices,i=this.centerOfMass,n=l,o=u,a=d,h=p,f=c;r.set(i,0,0);for(var g=0,m=0;m!==t.length;m++){var y=t[m],o=e[y[0]],a=e[y[1]],h=e[y[2]];r.centroid(n,o,a,h);var v=s.triangleArea(o,a,h);g+=v,r.scale(f,n,v),r.add(i,i,f)}r.scale(i,i,1/g)},s.prototype.computeMomentOfInertia=function(t){for(var e=0,i=0,s=this.vertices.length,n=s-1,o=0;o<s;n=o,o++){var a=this.vertices[n],h=this.vertices[o],l=Math.abs(r.crossLength(a,h));e+=l*(r.dot(h,h)+r.dot(h,a)+r.dot(a,a)),i+=l}return t/6*(e/i)},s.prototype.updateBoundingRadius=function(){for(var t=this.vertices,e=0,i=0;i!==t.length;i++){var s=r.squaredLength(t[i]);s>e&&(e=s)}this.boundingRadius=Math.sqrt(e)},s.triangleArea=function(t,e,i){return.5*((e[0]-t[0])*(i[1]-t[1])-(i[0]-t[0])*(e[1]-t[1]))},s.prototype.updateArea=function(){this.updateTriangles(),this.area=0;for(var t=this.triangles,e=this.vertices,i=0;i!==t.length;i++){var n=t[i],r=e[n[0]],o=e[n[1]],a=e[n[2]],h=s.triangleArea(r,o,a);this.area+=h}},s.prototype.computeAABB=function(t,e,i){t.setFromPoints(this.vertices,e,i,0)};var f=r.create(),g=r.create(),m=r.create();s.prototype.raycast=function(t,e,i,s){var n=f,o=g,a=m,h=this.vertices;r.toLocalFrame(n,e.from,i,s),r.toLocalFrame(o,e.to,i,s);for(var l=h.length,c=0;c<l&&!t.shouldStop(e);c++){var u=h[c],d=h[(c+1)%l],p=r.getLineSegmentsIntersectionFraction(n,o,u,d);p>=0&&(r.sub(a,d,u),r.rotate(a,a,-Math.PI/2+s),r.normalize(a,a),e.reportIntersection(t,p,a,c))}}},{"../math/polyk":29,"../math/vec2":30,"./Shape":45,"poly-decomp":5}],41:[function(t,e,i){function s(t){if(Array.isArray(arguments[0])){if(t={heights:arguments[0]},"object"==typeof arguments[1])for(var e in arguments[1])t[e]=arguments[1][e];console.warn("The Heightfield constructor signature has changed. Please use the following format: new Heightfield({ heights: [...], ... })")}t=t||{},this.heights=t.heights?t.heights.slice(0):[],this.maxValue=t.maxValue||null,this.minValue=t.minValue||null,this.elementWidth=t.elementWidth||.1,void 0!==t.maxValue&&void 0!==t.minValue||this.updateMaxMinValues(),t.type=n.HEIGHTFIELD,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");t("../utils/Utils");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.updateMaxMinValues=function(){for(var t=this.heights,e=t[0],i=t[0],s=0;s!==t.length;s++){var n=t[s];n>e&&(e=n),n<i&&(i=n)}this.maxValue=e,this.minValue=i},s.prototype.computeMomentOfInertia=function(t){return Number.MAX_VALUE},s.prototype.updateBoundingRadius=function(){this.boundingRadius=Number.MAX_VALUE},s.prototype.updateArea=function(){for(var t=this.heights,e=0,i=0;i<t.length-1;i++)e+=(t[i]+t[i+1])/2*this.elementWidth;this.area=e};var o=[r.create(),r.create(),r.create(),r.create()];s.prototype.computeAABB=function(t,e,i){r.set(o[0],0,this.maxValue),r.set(o[1],this.elementWidth*this.heights.length,this.maxValue),r.set(o[2],this.elementWidth*this.heights.length,this.minValue),r.set(o[3],0,this.minValue),t.setFromPoints(o,e,i)},s.prototype.getLineSegment=function(t,e,i){var s=this.heights,n=this.elementWidth;r.set(t,i*n,s[i]),r.set(e,(i+1)*n,s[i+1])},s.prototype.getSegmentIndex=function(t){return Math.floor(t[0]/this.elementWidth)},s.prototype.getClampedSegmentIndex=function(t){var e=this.getSegmentIndex(t);return e=Math.min(this.heights.length,Math.max(e,0))};var a=(r.create(),r.create()),h=r.create(),l=r.create(),c=r.create(),u=r.create();r.fromValues(0,1);s.prototype.raycast=function(t,e,i,s){var n=e.from,o=e.to,d=(e.direction,a),p=h,f=l,g=c,m=u;r.toLocalFrame(g,n,i,s),r.toLocalFrame(m,o,i,s);var y=this.getClampedSegmentIndex(g),v=this.getClampedSegmentIndex(m);if(y>v){var b=y;y=v,v=b}for(var x=0;x<this.heights.length-1;x++){this.getLineSegment(p,f,x);var w=r.getLineSegmentsIntersectionFraction(g,m,p,f);if(w>=0&&(r.sub(d,f,p),r.rotate(d,d,s+Math.PI/2),r.normalize(d,d),e.reportIntersection(t,w,d,-1),t.shouldStop(e)))return}}},{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],42:[function(t,e,i){function s(t){"number"==typeof arguments[0]&&(t={length:arguments[0]},console.warn("The Line constructor signature has changed. Please use the following format: new Line({ length: 1, ... })")),t=t||{},this.length=t.length||1,t.type=n.LINE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.computeMomentOfInertia=function(t){return t*Math.pow(this.length,2)/12},s.prototype.updateBoundingRadius=function(){this.boundingRadius=this.length/2};var o=[r.create(),r.create()];s.prototype.computeAABB=function(t,e,i){var s=this.length/2;r.set(o[0],-s,0),r.set(o[1],s,0),t.setFromPoints(o,e,i,0)};var a=(r.create(),r.create()),h=r.create(),l=r.create(),c=r.fromValues(0,1);s.prototype.raycast=function(t,e,i,s){var n=e.from,o=e.to,u=h,d=l,p=this.length/2;r.set(u,-p,0),r.set(d,p,0),r.toGlobalFrame(u,u,i,s),r.toGlobalFrame(d,d,i,s);var f=r.getLineSegmentsIntersectionFraction(u,d,n,o);if(f>=0){var g=a;r.rotate(g,c,s),e.reportIntersection(t,f,g,-1)}}},{"../math/vec2":30,"./Shape":45}],43:[function(t,e,i){function s(t){t=t||{},t.type=n.PARTICLE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.computeMomentOfInertia=function(t){return 0},s.prototype.updateBoundingRadius=function(){this.boundingRadius=0},s.prototype.computeAABB=function(t,e,i){r.copy(t.lowerBound,e),r.copy(t.upperBound,e)}},{"../math/vec2":30,"./Shape":45}],44:[function(t,e,i){function s(t){t=t||{},t.type=n.PLANE,n.call(this,t)}var n=t("./Shape"),r=t("../math/vec2");t("../utils/Utils");e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.computeMomentOfInertia=function(t){return 0},s.prototype.updateBoundingRadius=function(){this.boundingRadius=Number.MAX_VALUE},s.prototype.computeAABB=function(t,e,i){var s=i%(2*Math.PI),n=r.set,o=Number.MAX_VALUE,a=t.lowerBound,h=t.upperBound;0===s?(n(a,-o,-o),n(h,o,0)):s===Math.PI/2?(n(a,0,-o),n(h,o,o)):s===Math.PI?(n(a,-o,0),n(h,o,o)):s===3*Math.PI/2?(n(a,-o,-o),n(h,0,o)):(n(a,-o,-o),n(h,o,o)),r.add(a,a,e),r.add(h,h,e)},s.prototype.updateArea=function(){this.area=Number.MAX_VALUE};var o=r.create(),a=(r.create(),r.create(),r.create()),h=r.create();s.prototype.raycast=function(t,e,i,s){var n=e.from,l=e.to,c=e.direction,u=o,d=a,p=h;r.set(d,0,1),r.rotate(d,d,s),r.sub(p,n,i);var f=r.dot(p,d);if(r.sub(p,l,i),!(f*r.dot(p,d)>0||r.squaredDistance(n,l)<f*f)){var g=r.dot(d,c);r.sub(u,n,i);var m=-r.dot(d,u)/g/e.length;e.reportIntersection(t,m,d,-1)}}},{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],45:[function(t,e,i){function s(t){t=t||{},this.body=null,this.position=n.fromValues(0,0),t.position&&n.copy(this.position,t.position),this.angle=t.angle||0,this.type=t.type||0,this.id=s.idCounter++,this.boundingRadius=0,this.collisionGroup=void 0!==t.collisionGroup?t.collisionGroup:1,this.collisionResponse=void 0===t.collisionResponse||t.collisionResponse,this.collisionMask=void 0!==t.collisionMask?t.collisionMask:1,this.material=t.material||null,this.area=0,this.sensor=void 0!==t.sensor&&t.sensor,this.type&&this.updateBoundingRadius(),this.updateArea()}e.exports=s;var n=t("../math/vec2");s.idCounter=0,s.CIRCLE=1,s.PARTICLE=2,s.PLANE=4,s.CONVEX=8,s.LINE=16,s.BOX=32,Object.defineProperty(s,"RECTANGLE",{get:function(){return console.warn("Shape.RECTANGLE is deprecated, use Shape.BOX instead."),s.BOX}}),s.CAPSULE=64,s.HEIGHTFIELD=128,s.prototype.computeMomentOfInertia=function(t){},s.prototype.updateBoundingRadius=function(){},s.prototype.updateArea=function(){},s.prototype.computeAABB=function(t,e,i){},s.prototype.raycast=function(t,e,i,s){}},{"../math/vec2":30}],46:[function(t,e,i){function s(t){o.call(this,t,o.GS),t=t||{},this.iterations=t.iterations||10,this.tolerance=t.tolerance||1e-7,this.arrayStep=30,this.lambda=new a.ARRAY_TYPE(this.arrayStep),this.Bs=new a.ARRAY_TYPE(this.arrayStep),this.invCs=new a.ARRAY_TYPE(this.arrayStep),this.useZeroRHS=!1,this.frictionIterations=0,this.usedIterations=0}function n(t){for(var e=t.length;e--;)t[e]=0}var r=t("../math/vec2"),o=t("./Solver"),a=t("../utils/Utils"),h=t("../equations/FrictionEquation");e.exports=s,s.prototype=new o,s.prototype.constructor=s,s.prototype.solve=function(t,e){this.sortEquations();var i=0,o=this.iterations,l=this.frictionIterations,c=this.equations,u=c.length,d=Math.pow(this.tolerance*u,2),p=e.bodies,f=e.bodies.length,g=(r.add,r.set,this.useZeroRHS),m=this.lambda;if(this.usedIterations=0,u)for(var y=0;y!==f;y++){var v=p[y];v.updateSolveMassProperties()}m.length<u&&(m=this.lambda=new a.ARRAY_TYPE(u+this.arrayStep),this.Bs=new a.ARRAY_TYPE(u+this.arrayStep),this.invCs=new a.ARRAY_TYPE(u+this.arrayStep)),n(m);for(var b=this.invCs,x=this.Bs,m=this.lambda,y=0;y!==c.length;y++){var w=c[y];(w.timeStep!==t||w.needsUpdate)&&(w.timeStep=t,w.update()),x[y]=w.computeB(w.a,w.b,t),b[y]=w.computeInvC(w.epsilon)}var w,_,y,P;if(0!==u){for(y=0;y!==f;y++){var v=p[y];v.resetConstraintVelocity()}if(l){for(i=0;i!==l;i++){for(_=0,P=0;P!==u;P++){w=c[P];var T=s.iterateEquation(P,w,w.epsilon,x,b,m,g,t,i);_+=Math.abs(T)}if(this.usedIterations++,_*_<=d)break}for(s.updateMultipliers(c,m,1/t),P=0;P!==u;P++){var C=c[P];if(C instanceof h){for(var S=0,A=0;A!==C.contactEquations.length;A++)S+=C.contactEquations[A].multiplier;S*=C.frictionCoefficient/C.contactEquations.length,C.maxForce=S,C.minForce=-S}}}for(i=0;i!==o;i++){for(_=0,P=0;P!==u;P++){w=c[P];var T=s.iterateEquation(P,w,w.epsilon,x,b,m,g,t,i);_+=Math.abs(T)}if(this.usedIterations++,_*_<=d)break}for(y=0;y!==f;y++)p[y].addConstraintVelocity();s.updateMultipliers(c,m,1/t)}},s.updateMultipliers=function(t,e,i){for(var s=t.length;s--;)t[s].multiplier=e[s]*i},s.iterateEquation=function(t,e,i,s,n,r,o,a,h){var l=s[t],c=n[t],u=r[t],d=e.computeGWlambda(),p=e.maxForce,f=e.minForce;o&&(l=0);var g=c*(l-d-i*u),m=u+g;return m<f*a?g=f*a-u:m>p*a&&(g=p*a-u),r[t]+=g,e.addToWlambda(g),g}},{"../equations/FrictionEquation":23,"../math/vec2":30,"../utils/Utils":57,"./Solver":47}],47:[function(t,e,i){function s(t,e){t=t||{},n.call(this),this.type=e,this.equations=[],this.equationSortFunction=t.equationSortFunction||!1}var n=(t("../utils/Utils"),t("../events/EventEmitter"));e.exports=s,s.prototype=new n,s.prototype.constructor=s,s.prototype.solve=function(t,e){throw new Error("Solver.solve should be implemented by subclasses!")};var r={bodies:[]};s.prototype.solveIsland=function(t,e){this.removeAllEquations(),e.equations.length&&(this.addEquations(e.equations),r.bodies.length=0,e.getBodies(r.bodies),r.bodies.length&&this.solve(t,r))},s.prototype.sortEquations=function(){this.equationSortFunction&&this.equations.sort(this.equationSortFunction)},s.prototype.addEquation=function(t){t.enabled&&this.equations.push(t)},s.prototype.addEquations=function(t){for(var e=0,i=t.length;e!==i;e++){var s=t[e];s.enabled&&this.equations.push(s)}},s.prototype.removeEquation=function(t){var e=this.equations.indexOf(t);-1!==e&&this.equations.splice(e,1)},s.prototype.removeAllEquations=function(){this.equations.length=0},s.GS=1,s.ISLAND=2},{"../events/EventEmitter":26,"../utils/Utils":57}],48:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../equations/ContactEquation"),r=t("./Pool");e.exports=s,s.prototype=new r,s.prototype.constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.bodyA=t.bodyB=null,this}},{"../equations/ContactEquation":21,"./Pool":55}],49:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../equations/FrictionEquation"),r=t("./Pool");e.exports=s,s.prototype=new r,s.prototype.constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.bodyA=t.bodyB=null,this}},{"../equations/FrictionEquation":23,"./Pool":55}],50:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../world/IslandNode"),r=t("./Pool");e.exports=s,s.prototype=new r,s.prototype.constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.reset(),this}},{"../world/IslandNode":60,"./Pool":55}],51:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("../world/Island"),r=t("./Pool");e.exports=s,s.prototype=new r,s.prototype.constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.reset(),this}},{"../world/Island":58,"./Pool":55}],52:[function(t,e,i){function s(){this.overlappingShapesLastState=new n,this.overlappingShapesCurrentState=new n,this.recordPool=new r({size:16}),this.tmpDict=new n,this.tmpArray1=[]}var n=t("./TupleDictionary"),r=(t("./OverlapKeeperRecord"),t("./OverlapKeeperRecordPool"));t("./Utils");e.exports=s,s.prototype.tick=function(){for(var t=this.overlappingShapesLastState,e=this.overlappingShapesCurrentState,i=t.keys.length;i--;){var s=t.keys[i],n=t.getByKey(s);e.getByKey(s);n&&this.recordPool.release(n)}t.reset(),t.copy(e),e.reset()},s.prototype.setOverlapping=function(t,e,i,s){var n=(this.overlappingShapesLastState,this.overlappingShapesCurrentState);if(!n.get(e.id,s.id)){var r=this.recordPool.get();r.set(t,e,i,s),n.set(e.id,s.id,r)}},s.prototype.getNewOverlaps=function(t){return this.getDiff(this.overlappingShapesLastState,this.overlappingShapesCurrentState,t)},s.prototype.getEndOverlaps=function(t){return this.getDiff(this.overlappingShapesCurrentState,this.overlappingShapesLastState,t)},s.prototype.bodiesAreOverlapping=function(t,e){for(var i=this.overlappingShapesCurrentState,s=i.keys.length;s--;){var n=i.keys[s],r=i.data[n];if(r.bodyA===t&&r.bodyB===e||r.bodyA===e&&r.bodyB===t)return!0}return!1},s.prototype.getDiff=function(t,e,i){var i=i||[],s=t,n=e;i.length=0;for(var r=n.keys.length;r--;){var o=n.keys[r],a=n.data[o];if(!a)throw new Error("Key "+o+" had no data!");s.data[o]||i.push(a)}return i},s.prototype.isNewOverlap=function(t,e){var i=0|t.id,s=0|e.id,n=this.overlappingShapesLastState,r=this.overlappingShapesCurrentState;return!n.get(i,s)&&!!r.get(i,s)},s.prototype.getNewBodyOverlaps=function(t){this.tmpArray1.length=0;var e=this.getNewOverlaps(this.tmpArray1);return this.getBodyDiff(e,t)},s.prototype.getEndBodyOverlaps=function(t){this.tmpArray1.length=0;var e=this.getEndOverlaps(this.tmpArray1);return this.getBodyDiff(e,t)},s.prototype.getBodyDiff=function(t,e){e=e||[];for(var i=this.tmpDict,s=t.length;s--;){var n=t[s];i.set(0|n.bodyA.id,0|n.bodyB.id,n)}for(s=i.keys.length;s--;){var n=i.getByKey(i.keys[s]);n&&e.push(n.bodyA,n.bodyB)}return i.reset(),e}},{"./OverlapKeeperRecord":53,"./OverlapKeeperRecordPool":54,"./TupleDictionary":56,"./Utils":57}],53:[function(t,e,i){function s(t,e,i,s){this.shapeA=e,this.shapeB=s,this.bodyA=t,this.bodyB=i}e.exports=s,s.prototype.set=function(t,e,i,n){s.call(this,t,e,i,n)}},{}],54:[function(t,e,i){function s(){r.apply(this,arguments)}var n=t("./OverlapKeeperRecord"),r=t("./Pool");e.exports=s,s.prototype=new r,s.prototype.constructor=s,s.prototype.create=function(){return new n},s.prototype.destroy=function(t){return t.bodyA=t.bodyB=t.shapeA=t.shapeB=null,this}},{"./OverlapKeeperRecord":53,"./Pool":55}],55:[function(t,e,i){function s(t){t=t||{},this.objects=[],void 0!==t.size&&this.resize(t.size)}e.exports=s,s.prototype.resize=function(t){for(var e=this.objects;e.length>t;)e.pop();for(;e.length<t;)e.push(this.create());return this},s.prototype.get=function(){var t=this.objects;return t.length?t.pop():this.create()},s.prototype.release=function(t){return this.destroy(t),this.objects.push(t),this}},{}],56:[function(t,e,i){function s(){this.data={},this.keys=[]}var n=t("./Utils");e.exports=s,s.prototype.getKey=function(t,e){return t|=0,e|=0,(0|t)==(0|e)?-1:0|((0|t)>(0|e)?t<<16|65535&e:e<<16|65535&t)},s.prototype.getByKey=function(t){return t|=0,this.data[t]},s.prototype.get=function(t,e){return this.data[this.getKey(t,e)]},s.prototype.set=function(t,e,i){if(!i)throw new Error("No data!");var s=this.getKey(t,e);return this.data[s]||this.keys.push(s),this.data[s]=i,s},s.prototype.reset=function(){for(var t=this.data,e=this.keys,i=e.length;i--;)delete t[e[i]];e.length=0},s.prototype.copy=function(t){this.reset(),n.appendArray(this.keys,t.keys);for(var e=t.keys.length;e--;){var i=t.keys[e];this.data[i]=t.data[i]}}},{"./Utils":57}],57:[function(t,e,i){function s(){}e.exports=s,s.appendArray=function(t,e){if(e.length<15e4)t.push.apply(t,e);else for(var i=0,s=e.length;i!==s;++i)t.push(e[i])},s.splice=function(t,e,i){i=i||1;for(var s=e,n=t.length-i;s<n;s++)t[s]=t[s+i];t.length=n},"undefined"!=typeof P2_ARRAY_TYPE?s.ARRAY_TYPE=P2_ARRAY_TYPE:"undefined"!=typeof Float32Array?s.ARRAY_TYPE=Float32Array:s.ARRAY_TYPE=Array,s.extend=function(t,e){for(var i in e)t[i]=e[i]},s.defaults=function(t,e){t=t||{};for(var i in e)i in t||(t[i]=e[i]);return t}},{}],58:[function(t,e,i){function s(){this.equations=[],this.bodies=[]}var n=t("../objects/Body");e.exports=s,s.prototype.reset=function(){this.equations.length=this.bodies.length=0};var r=[];s.prototype.getBodies=function(t){var e=t||[],i=this.equations;r.length=0;for(var s=0;s!==i.length;s++){var n=i[s];-1===r.indexOf(n.bodyA.id)&&(e.push(n.bodyA),r.push(n.bodyA.id)),-1===r.indexOf(n.bodyB.id)&&(e.push(n.bodyB),r.push(n.bodyB.id))}return e},s.prototype.wantsToSleep=function(){for(var t=0;t<this.bodies.length;t++){var e=this.bodies[t];if(e.type===n.DYNAMIC&&!e.wantsToSleep)return!1}return!0},s.prototype.sleep=function(){for(var t=0;t<this.bodies.length;t++){this.bodies[t].sleep()}return!0}},{"../objects/Body":31}],59:[function(t,e,i){function s(t){this.nodePool=new n({size:16}),this.islandPool=new r({size:8}),this.equations=[],this.islands=[],this.nodes=[],this.queue=[]}var n=(t("../math/vec2"),t("./Island"),t("./IslandNode"),t("./../utils/IslandNodePool")),r=t("./../utils/IslandPool"),o=t("../objects/Body");e.exports=s,s.getUnvisitedNode=function(t){for(var e=t.length,i=0;i!==e;i++){var s=t[i];if(!s.visited&&s.body.type===o.DYNAMIC)return s}return!1},s.prototype.visit=function(t,e,i){e.push(t.body);for(var s=t.equations.length,n=0;n!==s;n++){var r=t.equations[n];-1===i.indexOf(r)&&i.push(r)}},s.prototype.bfs=function(t,e,i){var n=this.queue;for(n.length=0,n.push(t),t.visited=!0,this.visit(t,e,i);n.length;)for(var r,a=n.pop();r=s.getUnvisitedNode(a.neighbors);)r.visited=!0,this.visit(r,e,i),r.body.type===o.DYNAMIC&&n.push(r)},s.prototype.split=function(t){for(var e=t.bodies,i=this.nodes,n=this.equations;i.length;)this.nodePool.release(i.pop());for(var r=0;r!==e.length;r++){var o=this.nodePool.get();o.body=e[r],i.push(o)}for(var a=0;a!==n.length;a++){var h=n[a],r=e.indexOf(h.bodyA),l=e.indexOf(h.bodyB),c=i[r],u=i[l];c.neighbors.push(u),u.neighbors.push(c),c.equations.push(h),u.equations.push(h)}for(var d=this.islands,r=0;r<d.length;r++)this.islandPool.release(d[r]);d.length=0;for(var p;p=s.getUnvisitedNode(i);){var f=this.islandPool.get();this.bfs(p,f.bodies,f.equations),d.push(f)}return d}},{"../math/vec2":30,"../objects/Body":31,"./../utils/IslandNodePool":50,"./../utils/IslandPool":51,"./Island":58,"./IslandNode":60}],60:[function(t,e,i){function s(t){this.body=t,this.neighbors=[],this.equations=[],this.visited=!1}e.exports=s,s.prototype.reset=function(){this.equations.length=0,this.neighbors.length=0,this.visited=!1,this.body=null}},{}],61:[function(t,e,i){function s(t){u.apply(this),t=t||{},this.springs=[],this.bodies=[],this.disabledBodyCollisionPairs=[],this.solver=t.solver||new n,this.narrowphase=new y(this),this.islandManager=new x,this.gravity=r.fromValues(0,-9.78),t.gravity&&r.copy(this.gravity,t.gravity),this.frictionGravity=r.length(this.gravity)||10,this.useWorldGravityAsFrictionGravity=!0,this.useFrictionGravityOnZeroGravity=!0,this.broadphase=t.broadphase||new m,this.broadphase.setWorld(this),this.constraints=[],this.defaultMaterial=new p,this.defaultContactMaterial=new f(this.defaultMaterial,this.defaultMaterial),this.lastTimeStep=1/60,this.applySpringForces=!0,this.applyDamping=!0,this.applyGravity=!0,this.solveConstraints=!0,this.contactMaterials=[],this.time=0,this.accumulator=0,this.stepping=!1,this.bodiesToBeRemoved=[],this.islandSplit=void 0===t.islandSplit||!!t.islandSplit,this.emitImpactEvent=!0,this._constraintIdCounter=0,this._bodyIdCounter=0,this.postStepEvent={type:"postStep"},this.addBodyEvent={type:"addBody",body:null},this.removeBodyEvent={type:"removeBody",body:null},this.addSpringEvent={type:"addSpring",spring:null},this.impactEvent={type:"impact",bodyA:null,bodyB:null,shapeA:null,shapeB:null,contactEquation:null},this.postBroadphaseEvent={type:"postBroadphase",pairs:null},this.sleepMode=s.NO_SLEEPING,this.beginContactEvent={type:"beginContact",shapeA:null,shapeB:null,bodyA:null,bodyB:null,contactEquations:[]},this.endContactEvent={type:"endContact",shapeA:null,shapeB:null,bodyA:null,bodyB:null},this.preSolveEvent={type:"preSolve",contactEquations:null,frictionEquations:null},this.overlappingShapesLastState={keys:[]},this.overlappingShapesCurrentState={keys:[]},this.overlapKeeper=new b}var n=t("../solver/GSSolver"),r=(t("../solver/Solver"),t("../collision/Ray"),t("../math/vec2")),o=t("../shapes/Circle"),a=t("../shapes/Convex"),h=(t("../shapes/Line"),t("../shapes/Plane")),l=t("../shapes/Capsule"),c=t("../shapes/Particle"),u=t("../events/EventEmitter"),d=t("../objects/Body"),p=(t("../shapes/Shape"),t("../objects/LinearSpring"),t("../material/Material")),f=t("../material/ContactMaterial"),g=(t("../constraints/DistanceConstraint"),t("../constraints/Constraint"),t("../constraints/LockConstraint"),t("../constraints/RevoluteConstraint"),t("../constraints/PrismaticConstraint"),t("../constraints/GearConstraint"),t("../../package.json"),t("../collision/Broadphase"),t("../collision/AABB")),m=t("../collision/SAPBroadphase"),y=t("../collision/Narrowphase"),v=t("../utils/Utils"),b=t("../utils/OverlapKeeper"),x=t("./IslandManager");t("../objects/RotationalSpring");e.exports=s,s.prototype=new Object(u.prototype),s.prototype.constructor=s,s.NO_SLEEPING=1,s.BODY_SLEEPING=2,s.ISLAND_SLEEPING=4,s.prototype.addConstraint=function(t){this.constraints.push(t)},s.prototype.addContactMaterial=function(t){this.contactMaterials.push(t)},s.prototype.removeContactMaterial=function(t){var e=this.contactMaterials.indexOf(t);-1!==e&&v.splice(this.contactMaterials,e,1)},s.prototype.getContactMaterial=function(t,e){for(var i=this.contactMaterials,s=0,n=i.length;s!==n;s++){var r=i[s];if(r.materialA.id===t.id&&r.materialB.id===e.id||r.materialA.id===e.id&&r.materialB.id===t.id)return r}return!1},s.prototype.removeConstraint=function(t){var e=this.constraints.indexOf(t);-1!==e&&v.splice(this.constraints,e,1)};var w=(r.create(),r.create(),r.create(),r.create(),r.create(),r.create(),r.create()),_=r.fromValues(0,0),P=r.fromValues(0,0);r.fromValues(0,0),r.fromValues(0,0);s.prototype.step=function(t,e,i){if(i=i||10,0===(e=e||0))this.internalStep(t),this.time+=t;else{this.accumulator+=e;for(var s=0;this.accumulator>=t&&s<i;)this.internalStep(t),this.time+=t,this.accumulator-=t,s++;for(var n=this.accumulator%t/t,o=0;o!==this.bodies.length;o++){var a=this.bodies[o];r.lerp(a.interpolatedPosition,a.previousPosition,a.position,n),a.interpolatedAngle=a.previousAngle+n*(a.angle-a.previousAngle)}}};var T=[];s.prototype.internalStep=function(t){this.stepping=!0;var e=this.springs.length,i=this.springs,n=this.bodies,o=this.gravity,a=this.solver,h=this.bodies.length,l=this.broadphase,c=this.narrowphase,u=this.constraints,p=w,f=(r.scale,r.add),g=(r.rotate,this.islandManager);if(this.overlapKeeper.tick(),this.lastTimeStep=t,this.useWorldGravityAsFrictionGravity){var m=r.length(this.gravity);0===m&&this.useFrictionGravityOnZeroGravity||(this.frictionGravity=m)}if(this.applyGravity)for(var y=0;y!==h;y++){var b=n[y],x=b.force;b.type===d.DYNAMIC&&b.sleepState!==d.SLEEPING&&(r.scale(p,o,b.mass*b.gravityScale),f(x,x,p))}if(this.applySpringForces)for(var y=0;y!==e;y++){var _=i[y];_.applyForce()}if(this.applyDamping)for(var y=0;y!==h;y++){var b=n[y];b.type===d.DYNAMIC&&b.applyDamping(t)}for(var P=l.getCollisionPairs(this),C=this.disabledBodyCollisionPairs,y=C.length-2;y>=0;y-=2)for(var S=P.length-2;S>=0;S-=2)(C[y]===P[S]&&C[y+1]===P[S+1]||C[y+1]===P[S]&&C[y]===P[S+1])&&P.splice(S,2);var A=u.length;for(y=0;y!==A;y++){var E=u[y];if(!E.collideConnected)for(var S=P.length-2;S>=0;S-=2)(E.bodyA===P[S]&&E.bodyB===P[S+1]||E.bodyB===P[S]&&E.bodyA===P[S+1])&&P.splice(S,2)}this.postBroadphaseEvent.pairs=P,this.emit(this.postBroadphaseEvent),this.postBroadphaseEvent.pairs=null,c.reset(this);for(var y=0,I=P.length;y!==I;y+=2)for(var M=P[y],R=P[y+1],B=0,L=M.shapes.length;B!==L;B++)for(var k=M.shapes[B],O=k.position,F=k.angle,D=0,U=R.shapes.length;D!==U;D++){var G=R.shapes[D],N=G.position,X=G.angle,W=this.defaultContactMaterial;if(k.material&&G.material){var j=this.getContactMaterial(k.material,G.material);j&&(W=j)}this.runNarrowphase(c,M,k,O,F,R,G,N,X,W,this.frictionGravity)}for(var y=0;y!==h;y++){var V=n[y];V._wakeUpAfterNarrowphase&&(V.wakeUp(),V._wakeUpAfterNarrowphase=!1)}if(this.has("endContact")){this.overlapKeeper.getEndOverlaps(T);for(var q=this.endContactEvent,D=T.length;D--;){var H=T[D];q.shapeA=H.shapeA,q.shapeB=H.shapeB,q.bodyA=H.bodyA,q.bodyB=H.bodyB,this.emit(q)}T.length=0}var Y=this.preSolveEvent;Y.contactEquations=c.contactEquations,Y.frictionEquations=c.frictionEquations,this.emit(Y),Y.contactEquations=Y.frictionEquations=null;var A=u.length;for(y=0;y!==A;y++)u[y].update();if(c.contactEquations.length||c.frictionEquations.length||A)if(this.islandSplit){for(g.equations.length=0,v.appendArray(g.equations,c.contactEquations),v.appendArray(g.equations,c.frictionEquations),y=0;y!==A;y++)v.appendArray(g.equations,u[y].equations);g.split(this);for(var y=0;y!==g.islands.length;y++){var z=g.islands[y];z.equations.length&&a.solveIsland(t,z)}}else{for(a.addEquations(c.contactEquations),a.addEquations(c.frictionEquations),y=0;y!==A;y++)a.addEquations(u[y].equations);this.solveConstraints&&a.solve(t,this),a.removeAllEquations()}for(var y=0;y!==h;y++){var V=n[y];V.integrate(t)}for(var y=0;y!==h;y++)n[y].setZeroForce();if(this.emitImpactEvent&&this.has("impact"))for(var K=this.impactEvent,y=0;y!==c.contactEquations.length;y++){var J=c.contactEquations[y];J.firstImpact&&(K.bodyA=J.bodyA,K.bodyB=J.bodyB,K.shapeA=J.shapeA,K.shapeB=J.shapeB,K.contactEquation=J,this.emit(K))}if(this.sleepMode===s.BODY_SLEEPING)for(y=0;y!==h;y++)n[y].sleepTick(this.time,!1,t);else if(this.sleepMode===s.ISLAND_SLEEPING&&this.islandSplit){for(y=0;y!==h;y++)n[y].sleepTick(this.time,!0,t);for(var y=0;y<this.islandManager.islands.length;y++){var z=this.islandManager.islands[y];z.wantsToSleep()&&z.sleep()}}this.stepping=!1;for(var Q=this.bodiesToBeRemoved,y=0;y!==Q.length;y++)this.removeBody(Q[y]);Q.length=0,this.emit(this.postStepEvent)},s.prototype.runNarrowphase=function(t,e,i,s,n,o,a,h,l,c,u){if(0!=(i.collisionGroup&a.collisionMask)&&0!=(a.collisionGroup&i.collisionMask)){r.rotate(_,s,e.angle),r.rotate(P,h,o.angle),r.add(_,_,e.position),r.add(P,P,o.position);var p=n+e.angle,f=l+o.angle;t.enableFriction=c.friction>0,t.frictionCoefficient=c.friction;var g;g=e.type===d.STATIC||e.type===d.KINEMATIC?o.mass:o.type===d.STATIC||o.type===d.KINEMATIC?e.mass:e.mass*o.mass/(e.mass+o.mass),t.slipForce=c.friction*u*g,t.restitution=c.restitution,t.surfaceVelocity=c.surfaceVelocity,t.frictionStiffness=c.frictionStiffness,t.frictionRelaxation=c.frictionRelaxation,t.stiffness=c.stiffness,t.relaxation=c.relaxation,t.contactSkinSize=c.contactSkinSize,t.enabledEquations=e.collisionResponse&&o.collisionResponse&&i.collisionResponse&&a.collisionResponse;var m=t[i.type|a.type],y=0;if(m){var v=i.sensor||a.sensor,b=t.frictionEquations.length;y=i.type<a.type?m.call(t,e,i,_,p,o,a,P,f,v):m.call(t,o,a,P,f,e,i,_,p,v);var x=t.frictionEquations.length-b;if(y){if(e.allowSleep&&e.type===d.DYNAMIC&&e.sleepState===d.SLEEPING&&o.sleepState===d.AWAKE&&o.type!==d.STATIC){r.squaredLength(o.velocity)+Math.pow(o.angularVelocity,2)>=2*Math.pow(o.sleepSpeedLimit,2)&&(e._wakeUpAfterNarrowphase=!0)}if(o.allowSleep&&o.type===d.DYNAMIC&&o.sleepState===d.SLEEPING&&e.sleepState===d.AWAKE&&e.type!==d.STATIC){r.squaredLength(e.velocity)+Math.pow(e.angularVelocity,2)>=2*Math.pow(e.sleepSpeedLimit,2)&&(o._wakeUpAfterNarrowphase=!0)}if(this.overlapKeeper.setOverlapping(e,i,o,a),this.has("beginContact")&&this.overlapKeeper.isNewOverlap(i,a)){var w=this.beginContactEvent;if(w.shapeA=i,w.shapeB=a,w.bodyA=e,w.bodyB=o,w.contactEquations.length=0,"number"==typeof y)for(var T=t.contactEquations.length-y;T<t.contactEquations.length;T++)w.contactEquations.push(t.contactEquations[T]);this.emit(w)}if("number"==typeof y&&x>1)for(var T=t.frictionEquations.length-x;T<t.frictionEquations.length;T++){var C=t.frictionEquations[T];C.setSlipForce(C.getSlipForce()/x)}}}}},s.prototype.addSpring=function(t){this.springs.push(t);var e=this.addSpringEvent;e.spring=t,this.emit(e),e.spring=null},s.prototype.removeSpring=function(t){var e=this.springs.indexOf(t);-1!==e&&v.splice(this.springs,e,1)},s.prototype.addBody=function(t){if(-1===this.bodies.indexOf(t)){this.bodies.push(t),t.world=this;var e=this.addBodyEvent;e.body=t,this.emit(e),e.body=null}},s.prototype.removeBody=function(t){if(this.stepping)this.bodiesToBeRemoved.push(t);else{t.world=null;var e=this.bodies.indexOf(t);-1!==e&&(v.splice(this.bodies,e,1),this.removeBodyEvent.body=t,t.resetConstraintVelocity(),this.emit(this.removeBodyEvent),this.removeBodyEvent.body=null)}},s.prototype.getBodyById=function(t){for(var e=this.bodies,i=0;i<e.length;i++){var s=e[i];if(s.id===t)return s}return!1},s.prototype.disableBodyCollision=function(t,e){this.disabledBodyCollisionPairs.push(t,e)},s.prototype.enableBodyCollision=function(t,e){for(var i=this.disabledBodyCollisionPairs,s=0;s<i.length;s+=2)if(i[s]===t&&i[s+1]===e||i[s+1]===t&&i[s]===e)return void i.splice(s,2)},s.prototype.clear=function(){this.time=0,this.solver&&this.solver.equations.length&&this.solver.removeAllEquations();for(var t=this.constraints,e=t.length-1;e>=0;e--)this.removeConstraint(t[e]);for(var i=this.bodies,e=i.length-1;e>=0;e--)this.removeBody(i[e]);for(var n=this.springs,e=n.length-1;e>=0;e--)this.removeSpring(n[e]);for(var r=this.contactMaterials,e=r.length-1;e>=0;e--)this.removeContactMaterial(r[e]);s.apply(this)};var C=r.create(),S=(r.fromValues(0,0),r.fromValues(0,0));s.prototype.hitTest=function(t,e,i){i=i||0;var s=new d({position:t}),n=new c,u=t,p=C,f=S;s.addShape(n);for(var g=this.narrowphase,m=[],y=0,v=e.length;y!==v;y++)for(var b=e[y],x=0,w=b.shapes.length;x!==w;x++){var _=b.shapes[x];r.rotate(p,_.position,b.angle),r.add(p,p,b.position);var P=_.angle+b.angle;(_ instanceof o&&g.circleParticle(b,_,p,P,s,n,u,0,!0)||_ instanceof a&&g.particleConvex(s,n,u,0,b,_,p,P,!0)||_ instanceof h&&g.particlePlane(s,n,u,0,b,_,p,P,!0)||_ instanceof l&&g.particleCapsule(s,n,u,0,b,_,p,P,!0)||_ instanceof c&&r.squaredLength(r.sub(f,p,t))<i*i)&&m.push(b)}return m},s.prototype.setGlobalStiffness=function(t){for(var e=this.constraints,i=0;i!==e.length;i++)for(var s=e[i],n=0;n!==s.equations.length;n++){var r=s.equations[n];r.stiffness=t,r.needsUpdate=!0}for(var o=this.contactMaterials,i=0;i!==o.length;i++){var s=o[i];s.stiffness=s.frictionStiffness=t}var s=this.defaultContactMaterial;s.stiffness=s.frictionStiffness=t},s.prototype.setGlobalRelaxation=function(t){for(var e=0;e!==this.constraints.length;e++)for(var i=this.constraints[e],s=0;s!==i.equations.length;s++){var n=i.equations[s];n.relaxation=t,n.needsUpdate=!0}for(var e=0;e!==this.contactMaterials.length;e++){var i=this.contactMaterials[e];i.relaxation=i.frictionRelaxation=t}var i=this.defaultContactMaterial;i.relaxation=i.frictionRelaxation=t};var A=new g,E=[];s.prototype.raycast=function(t,e){return e.getAABB(A),this.broadphase.aabbQuery(this,A,E),e.intersectBodies(t,E),E.length=0,t.hasHit()}},{"../../package.json":6,"../collision/AABB":7,"../collision/Broadphase":8,"../collision/Narrowphase":10,"../collision/Ray":11,"../collision/SAPBroadphase":13,"../constraints/Constraint":14,"../constraints/DistanceConstraint":15,"../constraints/GearConstraint":16,"../constraints/LockConstraint":17,"../constraints/PrismaticConstraint":18,"../constraints/RevoluteConstraint":19,"../events/EventEmitter":26,"../material/ContactMaterial":27,"../material/Material":28,"../math/vec2":30,"../objects/Body":31,"../objects/LinearSpring":32,"../objects/RotationalSpring":33,"../shapes/Capsule":38,"../shapes/Circle":39,"../shapes/Convex":40,"../shapes/Line":42,"../shapes/Particle":43,"../shapes/Plane":44,"../shapes/Shape":45,"../solver/GSSolver":46,"../solver/Solver":47,"../utils/OverlapKeeper":52,"../utils/Utils":57,"./IslandManager":59}]},{},[36])(36)})},function(t,e,i){(function(i){/**
<ide> * @author Richard Davey <[email protected]>
<ide> * @copyright 2016 Photon Storm Ltd.
<ide> * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
<ide> * @copyright 2016 Photon Storm Ltd.
<ide> * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
<ide> */
<del>n.BitmapData=function(t,e,i,s,r){void 0!==i&&0!==i||(i=256),void 0!==s&&0!==s||(s=256),void 0===r&&(r=!1),this.game=t,this.key=e,this.width=i,this.height=s,this.canvas=n.Canvas.create(this,i,s,null,r),this.context=this.canvas.getContext("2d",{alpha:!0}),this.ctx=this.context,this.smoothProperty=t.renderType===n.CANVAS?t.renderer.renderSession.smoothProperty:n.Canvas.getSmoothingPrefix(this.context),this.imageData=this.context.getImageData(0,0,i,s),this.data=null,this.imageData&&(this.data=this.imageData.data),this.pixels=null,this.data&&(this.imageData.data.buffer?(this.buffer=this.imageData.data.buffer,this.pixels=new Uint32Array(this.buffer)):window.ArrayBuffer?(this.buffer=new ArrayBuffer(this.imageData.data.length),this.pixels=new Uint32Array(this.buffer)):this.pixels=this.imageData.data),this.baseTexture=new PIXI.BaseTexture(this.canvas),this.texture=new PIXI.Texture(this.baseTexture),this.frameData=new n.FrameData,this.textureFrame=this.frameData.addFrame(new n.Frame(0,0,0,i,s,"bitmapData")),this.texture.frame=this.textureFrame,this.type=n.BITMAPDATA,this.disableTextureUpload=!1,this.dirty=!1,this.cls=this.clear,this._image=null,this._pos=new n.Point,this._size=new n.Point,this._scale=new n.Point,this._rotate=0,this._alpha={prev:1,current:1},this._anchor=new n.Point,this._tempR=0,this._tempG=0,this._tempB=0,this._circle=new n.Circle,this._swapCanvas=void 0},n.BitmapData.prototype={move:function(t,e,i){return 0!==t&&this.moveH(t,i),0!==e&&this.moveV(e,i),this},moveH:function(t,e){void 0===e&&(e=!0),void 0===this._swapCanvas&&(this._swapCanvas=PIXI.CanvasPool.create(this,this.width,this.height));var i=this._swapCanvas,s=i.getContext("2d"),n=this.height,r=this.canvas;if(s.clearRect(0,0,this.width,this.height),t<0){t=Math.abs(t);var o=this.width-t;e&&s.drawImage(r,0,0,t,n,o,0,t,n),s.drawImage(r,t,0,o,n,0,0,o,n)}else{var o=this.width-t;e&&s.drawImage(r,o,0,t,n,0,0,t,n),s.drawImage(r,0,0,o,n,t,0,o,n)}return this.clear(),this.copy(this._swapCanvas)},moveV:function(t,e){void 0===e&&(e=!0),void 0===this._swapCanvas&&(this._swapCanvas=PIXI.CanvasPool.create(this,this.width,this.height));var i=this._swapCanvas,s=i.getContext("2d"),n=this.width,r=this.canvas;if(s.clearRect(0,0,this.width,this.height),t<0){t=Math.abs(t);var o=this.height-t;e&&s.drawImage(r,0,0,n,t,0,o,n,t),s.drawImage(r,0,t,n,o,0,0,n,o)}else{var o=this.height-t;e&&s.drawImage(r,0,o,n,t,0,0,n,t),s.drawImage(r,0,0,n,o,0,t,n,o)}return this.clear(),this.copy(this._swapCanvas)},add:function(t){if(Array.isArray(t))for(var e=0;e<t.length;e++)t[e].loadTexture&&t[e].loadTexture(this);else t.loadTexture(this);return this},load:function(t){if("string"==typeof t&&(t=this.game.cache.getImage(t)),t)return this.resize(t.width,t.height),this.cls(),this.draw(t),this.update(),this},clear:function(t,e,i,s){return void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=this.width),void 0===s&&(s=this.height),this.context.clearRect(t,e,i,s),this.dirty=!0,this},fill:function(t,e,i,s){return void 0===s&&(s=1),this.context.fillStyle="rgba("+t+","+e+","+i+","+s+")",this.context.fillRect(0,0,this.width,this.height),this.dirty=!0,this},generateTexture:function(t){var e=new Image;e.src=this.canvas.toDataURL("image/png");var i=this.game.cache.addImage(t,"",e);return new PIXI.Texture(i.base)},resize:function(t,e){return t===this.width&&e===this.height||(this.width=t,this.height=e,this.canvas.width=t,this.canvas.height=e,void 0!==this._swapCanvas&&(this._swapCanvas.width=t,this._swapCanvas.height=e),this.baseTexture.width=t,this.baseTexture.height=e,this.textureFrame.width=t,this.textureFrame.height=e,this.texture.width=t,this.texture.height=e,this.texture.crop.width=t,this.texture.crop.height=e,this.update(),this.dirty=!0),this},update:function(t,e,i,s){return void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=Math.max(1,this.width)),void 0===s&&(s=Math.max(1,this.height)),this.imageData=this.context.getImageData(t,e,i,s),this.data=this.imageData.data,this.imageData.data.buffer?(this.buffer=this.imageData.data.buffer,this.pixels=new Uint32Array(this.buffer)):window.ArrayBuffer?(this.buffer=new ArrayBuffer(this.imageData.data.length),this.pixels=new Uint32Array(this.buffer)):this.pixels=this.imageData.data,this},processPixelRGB:function(t,e,i,s,r,o){void 0===i&&(i=0),void 0===s&&(s=0),void 0===r&&(r=this.width),void 0===o&&(o=this.height);for(var a=i+r,h=s+o,l=n.Color.createColor(),c={r:0,g:0,b:0,a:0},u=!1,d=s;d<h;d++)for(var p=i;p<a;p++)n.Color.unpackPixel(this.getPixel32(p,d),l),!1!==(c=t.call(e,l,p,d))&&null!==c&&void 0!==c&&(this.setPixel32(p,d,c.r,c.g,c.b,c.a,!1),u=!0);return u&&(this.context.putImageData(this.imageData,0,0),this.dirty=!0),this},processPixel:function(t,e,i,s,n,r){void 0===i&&(i=0),void 0===s&&(s=0),void 0===n&&(n=this.width),void 0===r&&(r=this.height);for(var o=i+n,a=s+r,h=0,l=0,c=!1,u=s;u<a;u++)for(var d=i;d<o;d++)h=this.getPixel32(d,u),(l=t.call(e,h,d,u))!==h&&(this.pixels[u*this.width+d]=l,c=!0);return c&&(this.context.putImageData(this.imageData,0,0),this.dirty=!0),this},replaceRGB:function(t,e,i,s,r,o,a,h,l){var c=0,u=0,d=this.width,p=this.height,f=n.Color.packPixel(t,e,i,s);void 0!==l&&l instanceof n.Rectangle&&(c=l.x,u=l.y,d=l.width,p=l.height);for(var g=0;g<p;g++)for(var m=0;m<d;m++)this.getPixel32(c+m,u+g)===f&&this.setPixel32(c+m,u+g,r,o,a,h,!1);return this.context.putImageData(this.imageData,0,0),this.dirty=!0,this},setHSL:function(t,e,i,s){var r=t||0===t,o=e||0===e,a=i||0===i;if(r||o||a){void 0===s&&(s=new n.Rectangle(0,0,this.width,this.height));for(var h=n.Color.createColor(),l=s.y;l<s.bottom;l++)for(var c=s.x;c<s.right;c++)n.Color.unpackPixel(this.getPixel32(c,l),h,!0),r&&(h.h=t),o&&(h.s=e),a&&(h.l=i),n.Color.HSLtoRGB(h.h,h.s,h.l,h),this.setPixel32(c,l,h.r,h.g,h.b,h.a,!1);return this.context.putImageData(this.imageData,0,0),this.dirty=!0,this}},shiftHSL:function(t,e,i,s){if(void 0!==t&&null!==t||(t=!1),void 0!==e&&null!==e||(e=!1),void 0!==i&&null!==i||(i=!1),t||e||i){void 0===s&&(s=new n.Rectangle(0,0,this.width,this.height));for(var r=n.Color.createColor(),o=s.y;o<s.bottom;o++)for(var a=s.x;a<s.right;a++)n.Color.unpackPixel(this.getPixel32(a,o),r,!0),t&&(r.h=this.game.math.wrap(r.h+t,0,1)),e&&(r.s=this.game.math.clamp(r.s+e,0,1)),i&&(r.l=this.game.math.clamp(r.l+i,0,1)),n.Color.HSLtoRGB(r.h,r.s,r.l,r),this.setPixel32(a,o,r.r,r.g,r.b,r.a,!1);return this.context.putImageData(this.imageData,0,0),this.dirty=!0,this}},setPixel32:function(t,e,i,s,r,o,a){return void 0===a&&(a=!0),t>=0&&t<=this.width&&e>=0&&e<=this.height&&(n.Device.LITTLE_ENDIAN?this.pixels[e*this.width+t]=o<<24|r<<16|s<<8|i:this.pixels[e*this.width+t]=i<<24|s<<16|r<<8|o,a&&(this.context.putImageData(this.imageData,0,0),this.dirty=!0)),this},setPixel:function(t,e,i,s,n,r){return this.setPixel32(t,e,i,s,n,255,r)},getPixel:function(t,e,i){i||(i=n.Color.createColor());var s=~~(t+e*this.width);return s*=4,i.r=this.data[s],i.g=this.data[++s],i.b=this.data[++s],i.a=this.data[++s],i},getPixel32:function(t,e){if(t>=0&&t<=this.width&&e>=0&&e<=this.height)return this.pixels[e*this.width+t]},getPixelRGB:function(t,e,i,s,r){return n.Color.unpackPixel(this.getPixel32(t,e),i,s,r)},getPixels:function(t){return this.context.getImageData(t.x,t.y,t.width,t.height)},getFirstPixel:function(t){void 0===t&&(t=0);var e=n.Color.createColor(),i=0,s=0,r=1,o=!1;1===t?(r=-1,s=this.height):3===t&&(r=-1,i=this.width);do{n.Color.unpackPixel(this.getPixel32(i,s),e),0===t||1===t?++i===this.width&&(i=0,((s+=r)>=this.height||s<=0)&&(o=!0)):2!==t&&3!==t||++s===this.height&&(s=0,((i+=r)>=this.width||i<=0)&&(o=!0))}while(0===e.a&&!o);return e.x=i,e.y=s,e},getBounds:function(t){return void 0===t&&(t=new n.Rectangle),t.x=this.getFirstPixel(2).x,t.x===this.width?t.setTo(0,0,0,0):(t.y=this.getFirstPixel(0).y,t.width=this.getFirstPixel(3).x-t.x+1,t.height=this.getFirstPixel(1).y-t.y+1,t)},addToWorld:function(t,e,i,s,n,r){n=n||1,r=r||1;var o=this.game.add.image(t,e,this);return o.anchor.set(i,s),o.scale.set(n,r),o},copy:function(t,e,i,s,r,o,a,h,l,c,u,d,p,f,g,m,y){if(void 0!==t&&null!==t||(t=this),(t instanceof n.RenderTexture||t instanceof PIXI.RenderTexture)&&(t=t.getCanvas()),this._image=t,t instanceof n.Sprite||t instanceof n.Image||t instanceof n.Text||t instanceof PIXI.Sprite)this._pos.set(t.texture.crop.x,t.texture.crop.y),this._size.set(t.texture.crop.width,t.texture.crop.height),this._scale.set(t.scale.x,t.scale.y),this._anchor.set(t.anchor.x,t.anchor.y),this._rotate=t.rotation,this._alpha.current=t.alpha,t.texture instanceof n.RenderTexture||t.texture instanceof PIXI.RenderTexture?this._image=t.texture.getCanvas():this._image=t.texture.baseTexture.source,void 0!==o&&null!==o||(o=t.x),void 0!==a&&null!==a||(a=t.y),t.texture.trim&&(o+=t.texture.trim.x-t.anchor.x*t.texture.trim.width,a+=t.texture.trim.y-t.anchor.y*t.texture.trim.height),16777215!==t.tint&&(t.cachedTint!==t.tint&&(t.cachedTint=t.tint,t.tintedTexture=PIXI.CanvasTinter.getTintedTexture(t,t.tint)),this._image=t.tintedTexture,this._pos.set(0));else{if(this._pos.set(0),this._scale.set(1),this._anchor.set(0),this._rotate=0,this._alpha.current=1,t instanceof n.BitmapData)this._image=t.canvas;else if("string"==typeof t){if(null===(t=this.game.cache.getImage(t)))return;this._image=t}this._size.set(this._image.width,this._image.height)}if(void 0!==e&&null!==e||(e=0),void 0!==i&&null!==i||(i=0),s&&(this._size.x=s),r&&(this._size.y=r),void 0!==o&&null!==o||(o=e),void 0!==a&&null!==a||(a=i),void 0!==h&&null!==h||(h=this._size.x),void 0!==l&&null!==l||(l=this._size.y),"number"==typeof c&&(this._rotate=c),"number"==typeof u&&(this._anchor.x=u),"number"==typeof d&&(this._anchor.y=d),"number"==typeof p&&(this._scale.x=p),"number"==typeof f&&(this._scale.y=f),"number"==typeof g&&(this._alpha.current=g),void 0===m&&(m=null),void 0===y&&(y=!1),!(this._alpha.current<=0||0===this._scale.x||0===this._scale.y||0===this._size.x||0===this._size.y)){var v=this.context;return this._alpha.prev=v.globalAlpha,v.save(),v.globalAlpha=this._alpha.current,m&&(this.op=m),y&&(o|=0,a|=0),v.translate(o,a),v.scale(this._scale.x,this._scale.y),v.rotate(this._rotate),v.drawImage(this._image,this._pos.x+e,this._pos.y+i,this._size.x,this._size.y,-h*this._anchor.x,-l*this._anchor.y,h,l),v.restore(),v.globalAlpha=this._alpha.prev,this.dirty=!0,this}},copyTransform:function(t,e,i){if(void 0===e&&(e=null),void 0===i&&(i=!1),!t.hasOwnProperty("worldTransform")||!t.worldVisible||0===t.worldAlpha)return this;var s=t.worldTransform;if(this._pos.set(t.texture.crop.x,t.texture.crop.y),this._size.set(t.texture.crop.width,t.texture.crop.height),0===s.a||0===s.d||0===this._size.x||0===this._size.y)return this;t.texture instanceof n.RenderTexture||t.texture instanceof PIXI.RenderTexture?this._image=t.texture.getCanvas():this._image=t.texture.baseTexture.source;var r=s.tx,o=s.ty;t.texture.trim&&(r+=t.texture.trim.x-t.anchor.x*t.texture.trim.width,o+=t.texture.trim.y-t.anchor.y*t.texture.trim.height),16777215!==t.tint&&(t.cachedTint!==t.tint&&(t.cachedTint=t.tint,t.tintedTexture=PIXI.CanvasTinter.getTintedTexture(t,t.tint)),this._image=t.tintedTexture,this._pos.set(0)),i&&(r|=0,o|=0);var a=this.context;return this._alpha.prev=a.globalAlpha,a.save(),a.globalAlpha=this._alpha.current,e&&(this.op=e),a[this.smoothProperty]=t.texture.baseTexture.scaleMode===PIXI.scaleModes.LINEAR,a.setTransform(s.a,s.b,s.c,s.d,r,o),a.drawImage(this._image,this._pos.x,this._pos.y,this._size.x,this._size.y,-this._size.x*t.anchor.x,-this._size.y*t.anchor.y,this._size.x,this._size.y),a.restore(),a.globalAlpha=this._alpha.prev,this.dirty=!0,this},copyRect:function(t,e,i,s,n,r,o){return this.copy(t,e.x,e.y,e.width,e.height,i,s,e.width,e.height,0,0,0,1,1,n,r,o)},draw:function(t,e,i,s,n,r,o){return this.copy(t,null,null,null,null,e,i,s,n,null,null,null,null,null,null,r,o)},drawGroup:function(t,e,i){return t.total>0&&t.forEachExists(this.drawGroupProxy,this,e,i),this},drawGroupProxy:function(t,e,i){if(t.hasOwnProperty("texture")&&this.copyTransform(t,e,i),t.type===n.GROUP&&t.exists)this.drawGroup(t,e,i);else if(t.hasOwnProperty("children")&&t.children.length>0)for(var s=0;s<t.children.length;s++)t.children[s].exists&&this.copyTransform(t.children[s],e,i)},drawFull:function(t,e,i){if(!1===t.worldVisible||0===t.worldAlpha||t.hasOwnProperty("exists")&&!1===t.exists)return this;if(t.type!==n.GROUP&&t.type!==n.EMITTER&&t.type!==n.BITMAPTEXT)if(t.type===n.GRAPHICS){var s=t.getBounds();this.ctx.save(),this.ctx.translate(s.x,s.y),PIXI.CanvasGraphics.renderGraphics(t,this.ctx),this.ctx.restore()}else this.copy(t,null,null,null,null,t.worldPosition.x,t.worldPosition.y,null,null,t.worldRotation,null,null,t.worldScale.x,t.worldScale.y,t.worldAlpha,e,i);if(t.children)for(var r=0;r<t.children.length;r++)this.drawFull(t.children[r],e,i);return this},shadow:function(t,e,i,s){var n=this.context;return void 0===t||null===t?n.shadowColor="rgba(0,0,0,0)":(n.shadowColor=t,n.shadowBlur=e||5,n.shadowOffsetX=i||10,n.shadowOffsetY=s||10),this},alphaMask:function(t,e,i,s){return void 0===s||null===s?this.draw(e).blendSourceAtop():this.draw(e,s.x,s.y,s.width,s.height).blendSourceAtop(),void 0===i||null===i?this.draw(t).blendReset():this.draw(t,i.x,i.y,i.width,i.height).blendReset(),this},extract:function(t,e,i,s,n,r,o,a,h){return void 0===n&&(n=255),void 0===r&&(r=!1),void 0===o&&(o=e),void 0===a&&(a=i),void 0===h&&(h=s),r&&t.resize(this.width,this.height),this.processPixelRGB(function(r,l,c){return r.r===e&&r.g===i&&r.b===s&&t.setPixel32(l,c,o,a,h,n,!1),!1},this),t.context.putImageData(t.imageData,0,0),t.dirty=!0,t},rect:function(t,e,i,s,n){return void 0!==n&&(this.context.fillStyle=n),this.context.fillRect(t,e,i,s),this},text:function(t,e,i,s,n,r){void 0===e&&(e=0),void 0===i&&(i=0),void 0===s&&(s="14px Courier"),void 0===n&&(n="rgb(255,255,255)"),void 0===r&&(r=!0);var o=this.context,a=o.font;return o.font=s,r&&(o.fillStyle="rgb(0,0,0)",o.fillText(t,e+1,i+1)),o.fillStyle=n,o.fillText(t,e,i),o.font=a,this},circle:function(t,e,i,s){var n=this.context;return void 0!==s&&(n.fillStyle=s),n.beginPath(),n.arc(t,e,i,0,2*Math.PI,!1),n.closePath(),n.fill(),this},line:function(t,e,i,s,n,r){void 0===n&&(n="#fff"),void 0===r&&(r=1);var o=this.context;return o.beginPath(),o.moveTo(t,e),o.lineTo(i,s),o.lineWidth=r,o.strokeStyle=n,o.stroke(),o.closePath(),this},textureLine:function(t,e,i){if(void 0===i&&(i="repeat-x"),"string"!=typeof e||(e=this.game.cache.getImage(e))){var s=t.length;"no-repeat"===i&&s>e.width&&(s=e.width);var r=this.context;return r.fillStyle=r.createPattern(e,i),this._circle=new n.Circle(t.start.x,t.start.y,e.height),this._circle.circumferencePoint(t.angle-1.5707963267948966,!1,this._pos),r.save(),r.translate(this._pos.x,this._pos.y),r.rotate(t.angle),r.fillRect(0,0,s,e.height),r.restore(),this.dirty=!0,this}},render:function(){return!this.disableTextureUpload&&this.dirty&&(this.baseTexture.dirty(),this.dirty=!1),this},destroy:function(){this.frameData.destroy(),this.texture.destroy(!0),PIXI.CanvasPool.remove(this)},blendReset:function(){return this.op="source-over",this},blendSourceOver:function(){return this.op="source-over",this},blendSourceIn:function(){return this.op="source-in",this},blendSourceOut:function(){return this.op="source-out",this},blendSourceAtop:function(){return this.op="source-atop",this},blendDestinationOver:function(){return this.op="destination-over",this},blendDestinationIn:function(){return this.op="destination-in",this},blendDestinationOut:function(){return this.op="destination-out",this},blendDestinationAtop:function(){return this.op="destination-atop",this},blendXor:function(){return this.op="xor",this},blendAdd:function(){return this.op="lighter",this},blendMultiply:function(){return this.op="multiply",this},blendScreen:function(){return this.op="screen",this},blendOverlay:function(){return this.op="overlay",this},blendDarken:function(){return this.op="darken",this},blendLighten:function(){return this.op="lighten",this},blendColorDodge:function(){return this.op="color-dodge",this},blendColorBurn:function(){return this.op="color-burn",this},blendHardLight:function(){return this.op="hard-light",this},blendSoftLight:function(){return this.op="soft-light",this},blendDifference:function(){return this.op="difference",this},blendExclusion:function(){return this.op="exclusion",this},blendHue:function(){return this.op="hue",this},blendSaturation:function(){return this.op="saturation",this},blendColor:function(){return this.op="color",this},blendLuminosity:function(){return this.op="luminosity",this}},Object.defineProperty(n.BitmapData.prototype,"smoothed",{get:function(){n.Canvas.getSmoothingEnabled(this.context)},set:function(t){n.Canvas.setSmoothingEnabled(this.context,t)}}),Object.defineProperty(n.BitmapData.prototype,"op",{get:function(){return this.context.globalCompositeOperation},set:function(t){this.context.globalCompositeOperation=t}}),n.BitmapData.getTransform=function(t,e,i,s,n,r){return"number"!=typeof t&&(t=0),"number"!=typeof e&&(e=0),"number"!=typeof i&&(i=1),"number"!=typeof s&&(s=1),"number"!=typeof n&&(n=0),"number"!=typeof r&&(r=0),{sx:i,sy:s,scaleX:i,scaleY:s,skewX:n,skewY:r,translateX:t,translateY:e,tx:t,ty:e}},n.BitmapData.prototype.constructor=n.BitmapData,PIXI.Graphics=function(){PIXI.DisplayObjectContainer.call(this),this.renderable=!0,this.fillAlpha=1,this.lineWidth=0,this.lineColor=0,this.graphicsData=[],this.tint=16777215,this.blendMode=PIXI.blendModes.NORMAL,this.currentPath=null,this._webGL=[],this.isMask=!1,this.boundsPadding=0,this._localBounds=new PIXI.Rectangle(0,0,1,1),this.dirty=!0,this._boundsDirty=!1,this.webGLDirty=!1,this.cachedSpriteDirty=!1},PIXI.Graphics.prototype=Object.create(PIXI.DisplayObjectContainer.prototype),PIXI.Graphics.prototype.constructor=PIXI.Graphics,PIXI.Graphics.prototype.lineStyle=function(t,e,i){return this.lineWidth=t||0,this.lineColor=e||0,this.lineAlpha=void 0===i?1:i,this.currentPath&&(this.currentPath.shape.points.length?this.drawShape(new PIXI.Polygon(this.currentPath.shape.points.slice(-2))):(this.currentPath.lineWidth=this.lineWidth,this.currentPath.lineColor=this.lineColor,this.currentPath.lineAlpha=this.lineAlpha)),this},PIXI.Graphics.prototype.moveTo=function(t,e){return this.drawShape(new PIXI.Polygon([t,e])),this},PIXI.Graphics.prototype.lineTo=function(t,e){return this.currentPath||this.moveTo(0,0),this.currentPath.shape.points.push(t,e),this.dirty=!0,this._boundsDirty=!0,this},PIXI.Graphics.prototype.quadraticCurveTo=function(t,e,i,s){this.currentPath?0===this.currentPath.shape.points.length&&(this.currentPath.shape.points=[0,0]):this.moveTo(0,0);var n,r,o=this.currentPath.shape.points;0===o.length&&this.moveTo(0,0);for(var a=o[o.length-2],h=o[o.length-1],l=0,c=1;c<=20;++c)l=c/20,n=a+(t-a)*l,r=h+(e-h)*l,o.push(n+(t+(i-t)*l-n)*l,r+(e+(s-e)*l-r)*l);return this.dirty=!0,this._boundsDirty=!0,this},PIXI.Graphics.prototype.bezierCurveTo=function(t,e,i,s,n,r){this.currentPath?0===this.currentPath.shape.points.length&&(this.currentPath.shape.points=[0,0]):this.moveTo(0,0);for(var o,a,h,l,c,u=this.currentPath.shape.points,d=u[u.length-2],p=u[u.length-1],f=0,g=1;g<=20;++g)f=g/20,o=1-f,a=o*o,h=a*o,l=f*f,c=l*f,u.push(h*d+3*a*f*t+3*o*l*i+c*n,h*p+3*a*f*e+3*o*l*s+c*r);return this.dirty=!0,this._boundsDirty=!0,this},PIXI.Graphics.prototype.arcTo=function(t,e,i,s,n){this.currentPath?0===this.currentPath.shape.points.length&&this.currentPath.shape.points.push(t,e):this.moveTo(t,e);var r=this.currentPath.shape.points,o=r[r.length-2],a=r[r.length-1],h=a-e,l=o-t,c=s-e,u=i-t,d=Math.abs(h*u-l*c);if(d<1e-8||0===n)r[r.length-2]===t&&r[r.length-1]===e||r.push(t,e);else{var p=h*h+l*l,f=c*c+u*u,g=h*c+l*u,m=n*Math.sqrt(p)/d,y=n*Math.sqrt(f)/d,v=m*g/p,b=y*g/f,x=m*u+y*l,w=m*c+y*h,_=l*(y+v),P=h*(y+v),T=u*(m+b),C=c*(m+b),S=Math.atan2(P-w,_-x),A=Math.atan2(C-w,T-x);this.arc(x+t,w+e,n,S,A,l*c>u*h)}return this.dirty=!0,this._boundsDirty=!0,this},PIXI.Graphics.prototype.arc=function(t,e,i,s,n,r,o){if(s===n)return this;void 0===r&&(r=!1),void 0===o&&(o=40),!r&&n<=s?n+=2*Math.PI:r&&s<=n&&(s+=2*Math.PI);var a=r?-1*(s-n):n-s,h=Math.ceil(Math.abs(a)/(2*Math.PI))*o;if(0===a)return this;var l=t+Math.cos(s)*i,c=e+Math.sin(s)*i;r&&this.filling?this.moveTo(t,e):this.moveTo(l,c);for(var u=this.currentPath.shape.points,d=a/(2*h),p=2*d,f=Math.cos(d),g=Math.sin(d),m=h-1,y=m%1/m,v=0;v<=m;v++){var b=v+y*v,x=d+s+p*b,w=Math.cos(x),_=-Math.sin(x);u.push((f*w+g*_)*i+t,(f*-_+g*w)*i+e)}return this.dirty=!0,this._boundsDirty=!0,this},PIXI.Graphics.prototype.beginFill=function(t,e){return this.filling=!0,this.fillColor=t||0,this.fillAlpha=void 0===e?1:e,this.currentPath&&this.currentPath.shape.points.length<=2&&(this.currentPath.fill=this.filling,this.currentPath.fillColor=this.fillColor,this.currentPath.fillAlpha=this.fillAlpha),this},PIXI.Graphics.prototype.endFill=function(){return this.filling=!1,this.fillColor=null,this.fillAlpha=1,this},PIXI.Graphics.prototype.drawRect=function(t,e,i,s){return this.drawShape(new PIXI.Rectangle(t,e,i,s)),this},PIXI.Graphics.prototype.drawRoundedRect=function(t,e,i,s,n){return this.drawShape(new PIXI.RoundedRectangle(t,e,i,s,n)),this},PIXI.Graphics.prototype.drawCircle=function(t,e,i){return this.drawShape(new PIXI.Circle(t,e,i)),this},PIXI.Graphics.prototype.drawEllipse=function(t,e,i,s){return this.drawShape(new PIXI.Ellipse(t,e,i,s)),this},PIXI.Graphics.prototype.drawPolygon=function(t){(t instanceof n.Polygon||t instanceof PIXI.Polygon)&&(t=t.points);var e=t;if(!Array.isArray(e)){e=new Array(arguments.length);for(var i=0;i<e.length;++i)e[i]=arguments[i]}return this.drawShape(new n.Polygon(e)),this},PIXI.Graphics.prototype.clear=function(){return this.lineWidth=0,this.filling=!1,this.dirty=!0,this._boundsDirty=!0,this.clearDirty=!0,this.graphicsData=[],this.updateLocalBounds(),this},PIXI.Graphics.prototype.generateTexture=function(t,e,i){void 0===t&&(t=1),void 0===e&&(e=PIXI.scaleModes.DEFAULT),void 0===i&&(i=0);var s=this.getBounds();s.width+=i,s.height+=i;var n=new PIXI.CanvasBuffer(s.width*t,s.height*t),r=PIXI.Texture.fromCanvas(n.canvas,e);return r.baseTexture.resolution=t,n.context.scale(t,t),n.context.translate(-s.x,-s.y),PIXI.CanvasGraphics.renderGraphics(this,n.context),r},PIXI.Graphics.prototype._renderWebGL=function(t){if(!1!==this.visible&&0!==this.alpha&&!0!==this.isMask){if(this._cacheAsBitmap)return(this.dirty||this.cachedSpriteDirty)&&(this._generateCachedSprite(),this.updateCachedSpriteTexture(),this.cachedSpriteDirty=!1,this.dirty=!1),this._cachedSprite.worldAlpha=this.worldAlpha,void PIXI.Sprite.prototype._renderWebGL.call(this._cachedSprite,t);if(t.spriteBatch.stop(),t.blendModeManager.setBlendMode(this.blendMode),this._mask&&t.maskManager.pushMask(this._mask,t),this._filters&&t.filterManager.pushFilter(this._filterBlock),this.blendMode!==t.spriteBatch.currentBlendMode){t.spriteBatch.currentBlendMode=this.blendMode;var e=PIXI.blendModesWebGL[t.spriteBatch.currentBlendMode];t.spriteBatch.gl.blendFunc(e[0],e[1])}if(this.webGLDirty&&(this.dirty=!0,this.webGLDirty=!1),PIXI.WebGLGraphics.renderGraphics(this,t),this.children.length){t.spriteBatch.start();for(var i=0;i<this.children.length;i++)this.children[i]._renderWebGL(t);t.spriteBatch.stop()}this._filters&&t.filterManager.popFilter(),this._mask&&t.maskManager.popMask(this.mask,t),t.drawCount++,t.spriteBatch.start()}},PIXI.Graphics.prototype._renderCanvas=function(t){if(!1!==this.visible&&0!==this.alpha&&!0!==this.isMask){if(this._prevTint!==this.tint&&(this.dirty=!0,this._prevTint=this.tint),this._cacheAsBitmap)return(this.dirty||this.cachedSpriteDirty)&&(this._generateCachedSprite(),this.updateCachedSpriteTexture(),this.cachedSpriteDirty=!1,this.dirty=!1),this._cachedSprite.alpha=this.alpha,void PIXI.Sprite.prototype._renderCanvas.call(this._cachedSprite,t);var e=t.context,i=this.worldTransform;this.blendMode!==t.currentBlendMode&&(t.currentBlendMode=this.blendMode,e.globalCompositeOperation=PIXI.blendModesCanvas[t.currentBlendMode]),this._mask&&t.maskManager.pushMask(this._mask,t);var s=t.resolution,n=i.tx*t.resolution+t.shakeX,r=i.ty*t.resolution+t.shakeY;e.setTransform(i.a*s,i.b*s,i.c*s,i.d*s,n,r),PIXI.CanvasGraphics.renderGraphics(this,e);for(var o=0;o<this.children.length;o++)this.children[o]._renderCanvas(t);this._mask&&t.maskManager.popMask(t)}},PIXI.Graphics.prototype.getBounds=function(t){if(!this._currentBounds){if(!this.renderable)return PIXI.EmptyRectangle;this.dirty&&(this.updateLocalBounds(),this.webGLDirty=!0,this.cachedSpriteDirty=!0,this.dirty=!1);var e=this._localBounds,i=e.x,s=e.width+e.x,n=e.y,r=e.height+e.y,o=t||this.worldTransform,a=o.a,h=o.b,l=o.c,c=o.d,u=o.tx,d=o.ty,p=a*s+l*r+u,f=c*r+h*s+d,g=a*i+l*r+u,m=c*r+h*i+d,y=a*i+l*n+u,v=c*n+h*i+d,b=a*s+l*n+u,x=c*n+h*s+d,w=p,_=f,P=p,T=f;P=g<P?g:P,P=y<P?y:P,P=b<P?b:P,T=m<T?m:T,T=v<T?v:T,T=x<T?x:T,w=g>w?g:w,w=y>w?y:w,w=b>w?b:w,_=m>_?m:_,_=v>_?v:_,_=x>_?x:_,this._bounds.x=P,this._bounds.width=w-P,this._bounds.y=T,this._bounds.height=_-T,this._currentBounds=this._bounds}return this._currentBounds},PIXI.Graphics.prototype.getLocalBounds=function(){var t=this.worldTransform;this.worldTransform=PIXI.identityMatrix;for(var e=0;e<this.children.length;e++)this.children[e].updateTransform();var i=this.getBounds();for(this.worldTransform=t,e=0;e<this.children.length;e++)this.children[e].updateTransform();return i},PIXI.Graphics.prototype.containsPoint=function(t){this.worldTransform.applyInverse(t,tempPoint);for(var e=this.graphicsData,i=0;i<e.length;i++){var s=e[i];if(s.fill&&(s.shape&&s.shape.contains(tempPoint.x,tempPoint.y)))return!0}return!1},PIXI.Graphics.prototype.updateLocalBounds=function(){var t=1/0,e=-1/0,i=1/0,s=-1/0;if(this.graphicsData.length)for(var r,o,a,h,l,c,u=0;u<this.graphicsData.length;u++){var d=this.graphicsData[u],p=d.type,f=d.lineWidth;if(r=d.shape,p===PIXI.Graphics.RECT||p===PIXI.Graphics.RREC)a=r.x-f/2,h=r.y-f/2,l=r.width+f,c=r.height+f,t=a<t?a:t,e=a+l>e?a+l:e,i=h<i?h:i,s=h+c>s?h+c:s;else if(p===PIXI.Graphics.CIRC)a=r.x,h=r.y,l=r.radius+f/2,c=r.radius+f/2,t=a-l<t?a-l:t,e=a+l>e?a+l:e,i=h-c<i?h-c:i,s=h+c>s?h+c:s;else if(p===PIXI.Graphics.ELIP)a=r.x,h=r.y,l=r.width+f/2,c=r.height+f/2,t=a-l<t?a-l:t,e=a+l>e?a+l:e,i=h-c<i?h-c:i,s=h+c>s?h+c:s;else{o=r.points;for(var g=0;g<o.length;g++)o[g]instanceof n.Point?(a=o[g].x,h=o[g].y):(a=o[g],h=o[g+1],g<o.length-1&&g++),t=a-f<t?a-f:t,e=a+f>e?a+f:e,i=h-f<i?h-f:i,s=h+f>s?h+f:s}}else t=0,e=0,i=0,s=0;var m=this.boundsPadding;this._localBounds.x=t-m,this._localBounds.width=e-t+2*m,this._localBounds.y=i-m,this._localBounds.height=s-i+2*m},PIXI.Graphics.prototype._generateCachedSprite=function(){var t=this.getLocalBounds();if(this._cachedSprite)this._cachedSprite.buffer.resize(t.width,t.height);else{var e=new PIXI.CanvasBuffer(t.width,t.height),i=PIXI.Texture.fromCanvas(e.canvas);this._cachedSprite=new PIXI.Sprite(i),this._cachedSprite.buffer=e,this._cachedSprite.worldTransform=this.worldTransform}this._cachedSprite.anchor.x=-t.x/t.width,this._cachedSprite.anchor.y=-t.y/t.height,this._cachedSprite.buffer.context.translate(-t.x,-t.y),this.worldAlpha=1,PIXI.CanvasGraphics.renderGraphics(this,this._cachedSprite.buffer.context),this._cachedSprite.alpha=this.alpha},PIXI.Graphics.prototype.updateCachedSpriteTexture=function(){var t=this._cachedSprite,e=t.texture,i=t.buffer.canvas;e.baseTexture.width=i.width,e.baseTexture.height=i.height,e.crop.width=e.frame.width=i.width,e.crop.height=e.frame.height=i.height,t._width=i.width,t._height=i.height,e.baseTexture.dirty()},PIXI.Graphics.prototype.destroyCachedSprite=function(){this._cachedSprite.texture.destroy(!0),this._cachedSprite=null},PIXI.Graphics.prototype.drawShape=function(t){this.currentPath&&this.currentPath.shape.points.length<=2&&this.graphicsData.pop(),this.currentPath=null,t instanceof n.Polygon&&(t=t.clone(),t.flatten());var e=new PIXI.GraphicsData(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.filling,t);return this.graphicsData.push(e),e.type===PIXI.Graphics.POLY&&(e.shape.closed=this.filling,this.currentPath=e),this.dirty=!0,this._boundsDirty=!0,e},Object.defineProperty(PIXI.Graphics.prototype,"cacheAsBitmap",{get:function(){return this._cacheAsBitmap},set:function(t){this._cacheAsBitmap=t,this._cacheAsBitmap?this._generateCachedSprite():this.destroyCachedSprite(),this.dirty=!0,this.webGLDirty=!0}}),PIXI.GraphicsData=function(t,e,i,s,n,r,o){this.lineWidth=t,this.lineColor=e,this.lineAlpha=i,this._lineTint=e,this.fillColor=s,this.fillAlpha=n,this._fillTint=s,this.fill=r,this.shape=o,this.type=o.type},PIXI.GraphicsData.prototype.constructor=PIXI.GraphicsData,PIXI.GraphicsData.prototype.clone=function(){return new GraphicsData(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.fill,this.shape)},PIXI.EarCut={},PIXI.EarCut.Triangulate=function(t,e,i){i=i||2;var s=e&&e.length,n=s?e[0]*i:t.length,r=PIXI.EarCut.linkedList(t,0,n,i,!0),o=[];if(!r)return o;var a,h,l,c,u,d,p;if(s&&(r=PIXI.EarCut.eliminateHoles(t,e,r,i)),t.length>80*i){a=l=t[0],h=c=t[1];for(var f=i;f<n;f+=i)u=t[f],d=t[f+1],u<a&&(a=u),d<h&&(h=d),u>l&&(l=u),d>c&&(c=d);p=Math.max(l-a,c-h)}return PIXI.EarCut.earcutLinked(r,o,i,a,h,p),o},PIXI.EarCut.linkedList=function(t,e,i,s,n){var r,o,a,h=0;for(r=e,o=i-s;r<i;r+=s)h+=(t[o]-t[r])*(t[r+1]+t[o+1]),o=r;if(n===h>0)for(r=e;r<i;r+=s)a=PIXI.EarCut.insertNode(r,t[r],t[r+1],a);else for(r=i-s;r>=e;r-=s)a=PIXI.EarCut.insertNode(r,t[r],t[r+1],a);return a},PIXI.EarCut.filterPoints=function(t,e){if(!t)return t;e||(e=t);var i,s=t;do{if(i=!1,s.steiner||!PIXI.EarCut.equals(s,s.next)&&0!==PIXI.EarCut.area(s.prev,s,s.next))s=s.next;else{if(PIXI.EarCut.removeNode(s),(s=e=s.prev)===s.next)return null;i=!0}}while(i||s!==e);return e},PIXI.EarCut.earcutLinked=function(t,e,i,s,n,r,o){if(t){!o&&r&&PIXI.EarCut.indexCurve(t,s,n,r);for(var a,h,l=t;t.prev!==t.next;)if(a=t.prev,h=t.next,r?PIXI.EarCut.isEarHashed(t,s,n,r):PIXI.EarCut.isEar(t))e.push(a.i/i),e.push(t.i/i),e.push(h.i/i),PIXI.EarCut.removeNode(t),t=h.next,l=h.next;else if((t=h)===l){o?1===o?(t=PIXI.EarCut.cureLocalIntersections(t,e,i),PIXI.EarCut.earcutLinked(t,e,i,s,n,r,2)):2===o&&PIXI.EarCut.splitEarcut(t,e,i,s,n,r):PIXI.EarCut.earcutLinked(PIXI.EarCut.filterPoints(t),e,i,s,n,r,1);break}}},PIXI.EarCut.isEar=function(t){var e=t.prev,i=t,s=t.next;if(PIXI.EarCut.area(e,i,s)>=0)return!1;for(var n=t.next.next;n!==t.prev;){if(PIXI.EarCut.pointInTriangle(e.x,e.y,i.x,i.y,s.x,s.y,n.x,n.y)&&PIXI.EarCut.area(n.prev,n,n.next)>=0)return!1;n=n.next}return!0},PIXI.EarCut.isEarHashed=function(t,e,i,s){var n=t.prev,r=t,o=t.next;if(PIXI.EarCut.area(n,r,o)>=0)return!1;for(var a=n.x<r.x?n.x<o.x?n.x:o.x:r.x<o.x?r.x:o.x,h=n.y<r.y?n.y<o.y?n.y:o.y:r.y<o.y?r.y:o.y,l=n.x>r.x?n.x>o.x?n.x:o.x:r.x>o.x?r.x:o.x,c=n.y>r.y?n.y>o.y?n.y:o.y:r.y>o.y?r.y:o.y,u=PIXI.EarCut.zOrder(a,h,e,i,s),d=PIXI.EarCut.zOrder(l,c,e,i,s),p=t.nextZ;p&&p.z<=d;){if(p!==t.prev&&p!==t.next&&PIXI.EarCut.pointInTriangle(n.x,n.y,r.x,r.y,o.x,o.y,p.x,p.y)&&PIXI.EarCut.area(p.prev,p,p.next)>=0)return!1;p=p.nextZ}for(p=t.prevZ;p&&p.z>=u;){if(p!==t.prev&&p!==t.next&&PIXI.EarCut.pointInTriangle(n.x,n.y,r.x,r.y,o.x,o.y,p.x,p.y)&&PIXI.EarCut.area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}return!0},PIXI.EarCut.cureLocalIntersections=function(t,e,i){var s=t;do{var n=s.prev,r=s.next.next;PIXI.EarCut.intersects(n,s,s.next,r)&&PIXI.EarCut.locallyInside(n,r)&&PIXI.EarCut.locallyInside(r,n)&&(e.push(n.i/i),e.push(s.i/i),e.push(r.i/i),PIXI.EarCut.removeNode(s),PIXI.EarCut.removeNode(s.next),s=t=r),s=s.next}while(s!==t);return s},PIXI.EarCut.splitEarcut=function(t,e,i,s,n,r){var o=t;do{for(var a=o.next.next;a!==o.prev;){if(o.i!==a.i&&PIXI.EarCut.isValidDiagonal(o,a)){var h=PIXI.EarCut.splitPolygon(o,a);return o=PIXI.EarCut.filterPoints(o,o.next),h=PIXI.EarCut.filterPoints(h,h.next),PIXI.EarCut.earcutLinked(o,e,i,s,n,r),void PIXI.EarCut.earcutLinked(h,e,i,s,n,r)}a=a.next}o=o.next}while(o!==t)},PIXI.EarCut.eliminateHoles=function(t,e,i,s){var n,r,o,a,h,l=[];for(n=0,r=e.length;n<r;n++)o=e[n]*s,a=n<r-1?e[n+1]*s:t.length,h=PIXI.EarCut.linkedList(t,o,a,s,!1),h===h.next&&(h.steiner=!0),l.push(PIXI.EarCut.getLeftmost(h));for(l.sort(compareX),n=0;n<l.length;n++)PIXI.EarCut.eliminateHole(l[n],i),i=PIXI.EarCut.filterPoints(i,i.next);return i},PIXI.EarCut.compareX=function(t,e){return t.x-e.x},PIXI.EarCut.eliminateHole=function(t,e){if(e=PIXI.EarCut.findHoleBridge(t,e)){var i=PIXI.EarCut.splitPolygon(e,t);PIXI.EarCut.filterPoints(i,i.next)}},PIXI.EarCut.findHoleBridge=function(t,e){var i,s=e,n=t.x,r=t.y,o=-1/0;do{if(r<=s.y&&r>=s.next.y){var a=s.x+(r-s.y)*(s.next.x-s.x)/(s.next.y-s.y);a<=n&&a>o&&(o=a,i=s.x<s.next.x?s:s.next)}s=s.next}while(s!==e);if(!i)return null;if(t.x===i.x)return i.prev;var h,l=i,c=1/0;for(s=i.next;s!==l;)n>=s.x&&s.x>=i.x&&PIXI.EarCut.pointInTriangle(r<i.y?n:o,r,i.x,i.y,r<i.y?o:n,r,s.x,s.y)&&((h=Math.abs(r-s.y)/(n-s.x))<c||h===c&&s.x>i.x)&&PIXI.EarCut.locallyInside(s,t)&&(i=s,c=h),s=s.next;return i},PIXI.EarCut.indexCurve=function(t,e,i,s){var n=t;do{null===n.z&&(n.z=PIXI.EarCut.zOrder(n.x,n.y,e,i,s)),n.prevZ=n.prev,n.nextZ=n.next,n=n.next}while(n!==t);n.prevZ.nextZ=null,n.prevZ=null,PIXI.EarCut.sortLinked(n)},PIXI.EarCut.sortLinked=function(t){var e,i,s,n,r,o,a,h,l=1;do{for(i=t,t=null,r=null,o=0;i;){for(o++,s=i,a=0,e=0;e<l&&(a++,s=s.nextZ);e++);for(h=l;a>0||h>0&&s;)0===a?(n=s,s=s.nextZ,h--):0!==h&&s?i.z<=s.z?(n=i,i=i.nextZ,a--):(n=s,s=s.nextZ,h--):(n=i,i=i.nextZ,a--),r?r.nextZ=n:t=n,n.prevZ=r,r=n;i=s}r.nextZ=null,l*=2}while(o>1);return t},PIXI.EarCut.zOrder=function(t,e,i,s,n){return t=32767*(t-i)/n,e=32767*(e-s)/n,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1},PIXI.EarCut.getLeftmost=function(t){var e=t,i=t;do{e.x<i.x&&(i=e),e=e.next}while(e!==t);return i},PIXI.EarCut.pointInTriangle=function(t,e,i,s,n,r,o,a){return(n-o)*(e-a)-(t-o)*(r-a)>=0&&(t-o)*(s-a)-(i-o)*(e-a)>=0&&(i-o)*(r-a)-(n-o)*(s-a)>=0},PIXI.EarCut.isValidDiagonal=function(t,e){return PIXI.EarCut.equals(t,e)||t.next.i!==e.i&&t.prev.i!==e.i&&!PIXI.EarCut.intersectsPolygon(t,e)&&PIXI.EarCut.locallyInside(t,e)&&PIXI.EarCut.locallyInside(e,t)&&PIXI.EarCut.middleInside(t,e)},PIXI.EarCut.area=function(t,e,i){return(e.y-t.y)*(i.x-e.x)-(e.x-t.x)*(i.y-e.y)},PIXI.EarCut.equals=function(t,e){return t.x===e.x&&t.y===e.y},PIXI.EarCut.intersects=function(t,e,i,s){return PIXI.EarCut.area(t,e,i)>0!=PIXI.EarCut.area(t,e,s)>0&&PIXI.EarCut.area(i,s,t)>0!=PIXI.EarCut.area(i,s,e)>0},PIXI.EarCut.intersectsPolygon=function(t,e){var i=t;do{if(i.i!==t.i&&i.next.i!==t.i&&i.i!==e.i&&i.next.i!==e.i&&PIXI.EarCut.intersects(i,i.next,t,e))return!0;i=i.next}while(i!==t);return!1},PIXI.EarCut.locallyInside=function(t,e){return PIXI.EarCut.area(t.prev,t,t.next)<0?PIXI.EarCut.area(t,e,t.next)>=0&&PIXI.EarCut.area(t,t.prev,e)>=0:PIXI.EarCut.area(t,e,t.prev)<0||PIXI.EarCut.area(t,t.next,e)<0},PIXI.EarCut.middleInside=function(t,e){var i=t,s=!1,n=(t.x+e.x)/2,r=(t.y+e.y)/2;do{i.y>r!=i.next.y>r&&n<(i.next.x-i.x)*(r-i.y)/(i.next.y-i.y)+i.x&&(s=!s),i=i.next}while(i!==t);return s},PIXI.EarCut.splitPolygon=function(t,e){var i=new PIXI.EarCut.Node(t.i,t.x,t.y),s=new PIXI.EarCut.Node(e.i,e.x,e.y),n=t.next,r=e.prev;return t.next=e,e.prev=t,i.next=n,n.prev=i,s.next=i,i.prev=s,r.next=s,s.prev=r,s},PIXI.EarCut.insertNode=function(t,e,i,s){var n=new PIXI.EarCut.Node(t,e,i);return s?(n.next=s.next,n.prev=s,s.next.prev=n,s.next=n):(n.prev=n,n.next=n),n},PIXI.EarCut.removeNode=function(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)},PIXI.EarCut.Node=function(t,e,i){this.i=t,this.x=e,this.y=i,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1},PIXI.WebGLGraphics=function(){},PIXI.WebGLGraphics.stencilBufferLimit=6,PIXI.WebGLGraphics.renderGraphics=function(t,e){var i,s=e.gl,n=e.projection,r=e.offset,o=e.shaderManager.primitiveShader;t.dirty&&PIXI.WebGLGraphics.updateGraphics(t,s);for(var a=t._webGL[s.id],h=0;h<a.data.length;h++)1===a.data[h].mode?(i=a.data[h],e.stencilManager.pushStencil(t,i,e),s.drawElements(s.TRIANGLE_FAN,4,s.UNSIGNED_SHORT,2*(i.indices.length-4)),e.stencilManager.popStencil(t,i,e)):(i=a.data[h],e.shaderManager.setShader(o),o=e.shaderManager.primitiveShader,s.uniformMatrix3fv(o.translationMatrix,!1,t.worldTransform.toArray(!0)),s.uniform1f(o.flipY,1),s.uniform2f(o.projectionVector,n.x,-n.y),s.uniform2f(o.offsetVector,-r.x,-r.y),s.uniform3fv(o.tintColor,PIXI.hex2rgb(t.tint)),s.uniform1f(o.alpha,t.worldAlpha),s.bindBuffer(s.ARRAY_BUFFER,i.buffer),s.vertexAttribPointer(o.aVertexPosition,2,s.FLOAT,!1,24,0),s.vertexAttribPointer(o.colorAttribute,4,s.FLOAT,!1,24,8),s.bindBuffer(s.ELEMENT_ARRAY_BUFFER,i.indexBuffer),s.drawElements(s.TRIANGLE_STRIP,i.indices.length,s.UNSIGNED_SHORT,0))},PIXI.WebGLGraphics.updateGraphics=function(t,e){var i=t._webGL[e.id];i||(i=t._webGL[e.id]={lastIndex:0,data:[],gl:e}),t.dirty=!1;var s;if(t.clearDirty){for(t.clearDirty=!1,s=0;s<i.data.length;s++){var n=i.data[s];n.reset(),PIXI.WebGLGraphics.graphicsDataPool.push(n)}i.data=[],i.lastIndex=0}var r;for(s=i.lastIndex;s<t.graphicsData.length;s++){var o=t.graphicsData[s];if(o.type===PIXI.Graphics.POLY){if(o.points=o.shape.points.slice(),o.shape.closed&&(o.points[0]===o.points[o.points.length-2]&&o.points[1]===o.points[o.points.length-1]||o.points.push(o.points[0],o.points[1])),o.fill&&o.points.length>=PIXI.WebGLGraphics.stencilBufferLimit)if(o.points.length<2*PIXI.WebGLGraphics.stencilBufferLimit){r=PIXI.WebGLGraphics.switchMode(i,0);var a=PIXI.WebGLGraphics.buildPoly(o,r);a||(r=PIXI.WebGLGraphics.switchMode(i,1),PIXI.WebGLGraphics.buildComplexPoly(o,r))}else r=PIXI.WebGLGraphics.switchMode(i,1),PIXI.WebGLGraphics.buildComplexPoly(o,r);o.lineWidth>0&&(r=PIXI.WebGLGraphics.switchMode(i,0),PIXI.WebGLGraphics.buildLine(o,r))}else r=PIXI.WebGLGraphics.switchMode(i,0),o.type===PIXI.Graphics.RECT?PIXI.WebGLGraphics.buildRectangle(o,r):o.type===PIXI.Graphics.CIRC||o.type===PIXI.Graphics.ELIP?PIXI.WebGLGraphics.buildCircle(o,r):o.type===PIXI.Graphics.RREC&&PIXI.WebGLGraphics.buildRoundedRectangle(o,r);i.lastIndex++}for(s=0;s<i.data.length;s++)r=i.data[s],r.dirty&&r.upload()},PIXI.WebGLGraphics.switchMode=function(t,e){var i;return t.data.length?(i=t.data[t.data.length-1],i.mode===e&&1!==e||(i=PIXI.WebGLGraphics.graphicsDataPool.pop()||new PIXI.WebGLGraphicsData(t.gl),i.mode=e,t.data.push(i))):(i=PIXI.WebGLGraphics.graphicsDataPool.pop()||new PIXI.WebGLGraphicsData(t.gl),i.mode=e,t.data.push(i)),i.dirty=!0,i},PIXI.WebGLGraphics.buildRectangle=function(t,e){var i=t.shape,s=i.x,n=i.y,r=i.width,o=i.height;if(t.fill){var a=PIXI.hex2rgb(t.fillColor),h=t.fillAlpha,l=a[0]*h,c=a[1]*h,u=a[2]*h,d=e.points,p=e.indices,f=d.length/6;d.push(s,n),d.push(l,c,u,h),d.push(s+r,n),d.push(l,c,u,h),d.push(s,n+o),d.push(l,c,u,h),d.push(s+r,n+o),d.push(l,c,u,h),p.push(f,f,f+1,f+2,f+3,f+3)}if(t.lineWidth){var g=t.points;t.points=[s,n,s+r,n,s+r,n+o,s,n+o,s,n],PIXI.WebGLGraphics.buildLine(t,e),t.points=g}},PIXI.WebGLGraphics.buildRoundedRectangle=function(t,e){var i=t.shape,s=i.x,n=i.y,r=i.width,o=i.height,a=i.radius,h=[];if(h.push(s,n+a),h=h.concat(PIXI.WebGLGraphics.quadraticBezierCurve(s,n+o-a,s,n+o,s+a,n+o)),h=h.concat(PIXI.WebGLGraphics.quadraticBezierCurve(s+r-a,n+o,s+r,n+o,s+r,n+o-a)),h=h.concat(PIXI.WebGLGraphics.quadraticBezierCurve(s+r,n+a,s+r,n,s+r-a,n)),h=h.concat(PIXI.WebGLGraphics.quadraticBezierCurve(s+a,n,s,n,s,n+a)),t.fill){var l=PIXI.hex2rgb(t.fillColor),c=t.fillAlpha,u=l[0]*c,d=l[1]*c,p=l[2]*c,f=e.points,g=e.indices,m=f.length/6,y=PIXI.EarCut.Triangulate(h,null,2),v=0;for(v=0;v<y.length;v+=3)g.push(y[v]+m),g.push(y[v]+m),g.push(y[v+1]+m),g.push(y[v+2]+m),g.push(y[v+2]+m);for(v=0;v<h.length;v++)f.push(h[v],h[++v],u,d,p,c)}if(t.lineWidth){var b=t.points;t.points=h,PIXI.WebGLGraphics.buildLine(t,e),t.points=b}},PIXI.WebGLGraphics.quadraticBezierCurve=function(t,e,i,s,n,r){function o(t,e,i){return t+(e-t)*i}for(var a,h,l,c,u,d,p=[],f=0,g=0;g<=20;g++)f=g/20,a=o(t,i,f),h=o(e,s,f),l=o(i,n,f),c=o(s,r,f),u=o(a,l,f),d=o(h,c,f),p.push(u,d);return p},PIXI.WebGLGraphics.buildCircle=function(t,e){var i,s,n=t.shape,r=n.x,o=n.y;t.type===PIXI.Graphics.CIRC?(i=n.radius,s=n.radius):(i=n.width,s=n.height);var a=2*Math.PI/40,h=0;if(t.fill){var l=PIXI.hex2rgb(t.fillColor),c=t.fillAlpha,u=l[0]*c,d=l[1]*c,p=l[2]*c,f=e.points,g=e.indices,m=f.length/6;for(g.push(m),h=0;h<41;h++)f.push(r,o,u,d,p,c),f.push(r+Math.sin(a*h)*i,o+Math.cos(a*h)*s,u,d,p,c),g.push(m++,m++);g.push(m-1)}if(t.lineWidth){var y=t.points;for(t.points=[],h=0;h<41;h++)t.points.push(r+Math.sin(a*h)*i,o+Math.cos(a*h)*s);PIXI.WebGLGraphics.buildLine(t,e),t.points=y}},PIXI.WebGLGraphics.buildLine=function(t,e){var i=0,s=t.points;if(0!==s.length){if(t.lineWidth%2)for(i=0;i<s.length;i++)s[i]+=.5;var n=new PIXI.Point(s[0],s[1]),r=new PIXI.Point(s[s.length-2],s[s.length-1]);if(n.x===r.x&&n.y===r.y){s=s.slice(),s.pop(),s.pop(),r=new PIXI.Point(s[s.length-2],s[s.length-1]);var o=r.x+.5*(n.x-r.x),a=r.y+.5*(n.y-r.y);s.unshift(o,a),s.push(o,a)}var h,l,c,u,d,p,f,g,m,y,v,b,x,w,_,P,T,C,S,A,E,I,M,R=e.points,B=e.indices,L=s.length/2,O=s.length,k=R.length/6,F=t.lineWidth/2,D=PIXI.hex2rgb(t.lineColor),U=t.lineAlpha,G=D[0]*U,N=D[1]*U,X=D[2]*U;for(c=s[0],u=s[1],d=s[2],p=s[3],m=-(u-p),y=c-d,M=Math.sqrt(m*m+y*y),m/=M,y/=M,m*=F,y*=F,R.push(c-m,u-y,G,N,X,U),R.push(c+m,u+y,G,N,X,U),i=1;i<L-1;i++)c=s[2*(i-1)],u=s[2*(i-1)+1],d=s[2*i],p=s[2*i+1],f=s[2*(i+1)],g=s[2*(i+1)+1],m=-(u-p),y=c-d,M=Math.sqrt(m*m+y*y),m/=M,y/=M,m*=F,y*=F,v=-(p-g),b=d-f,M=Math.sqrt(v*v+b*b),v/=M,b/=M,v*=F,b*=F,_=-y+u-(-y+p),P=-m+d-(-m+c),T=(-m+c)*(-y+p)-(-m+d)*(-y+u),C=-b+g-(-b+p),S=-v+d-(-v+f),A=(-v+f)*(-b+p)-(-v+d)*(-b+g),E=_*S-C*P,Math.abs(E)<.1?(E+=10.1,R.push(d-m,p-y,G,N,X,U),R.push(d+m,p+y,G,N,X,U)):(h=(P*A-S*T)/E,l=(C*T-_*A)/E,I=(h-d)*(h-d)+(l-p)+(l-p),I>19600?(x=m-v,w=y-b,M=Math.sqrt(x*x+w*w),x/=M,w/=M,x*=F,w*=F,R.push(d-x,p-w),R.push(G,N,X,U),R.push(d+x,p+w),R.push(G,N,X,U),R.push(d-x,p-w),R.push(G,N,X,U),O++):(R.push(h,l),R.push(G,N,X,U),R.push(d-(h-d),p-(l-p)),R.push(G,N,X,U)));for(c=s[2*(L-2)],u=s[2*(L-2)+1],d=s[2*(L-1)],p=s[2*(L-1)+1],m=-(u-p),y=c-d,M=Math.sqrt(m*m+y*y),m/=M,y/=M,m*=F,y*=F,R.push(d-m,p-y),R.push(G,N,X,U),R.push(d+m,p+y),R.push(G,N,X,U),B.push(k),i=0;i<O;i++)B.push(k++);B.push(k-1)}},PIXI.WebGLGraphics.buildComplexPoly=function(t,e){var i=t.points.slice();if(!(i.length<6)){var s=e.indices;e.points=i,e.alpha=t.fillAlpha,e.color=PIXI.hex2rgb(t.fillColor);for(var n,r,o=1/0,a=-1/0,h=1/0,l=-1/0,c=0;c<i.length;c+=2)n=i[c],r=i[c+1],o=n<o?n:o,a=n>a?n:a,h=r<h?r:h,l=r>l?r:l;i.push(o,h,a,h,a,l,o,l);var u=i.length/2;for(c=0;c<u;c++)s.push(c)}},PIXI.WebGLGraphics.buildPoly=function(t,e){var i=t.points;if(!(i.length<6)){var s=e.points,n=e.indices,r=i.length/2,o=PIXI.hex2rgb(t.fillColor),a=t.fillAlpha,h=o[0]*a,l=o[1]*a,c=o[2]*a,u=PIXI.EarCut.Triangulate(i,null,2);if(!u)return!1;var d=s.length/6,p=0;for(p=0;p<u.length;p+=3)n.push(u[p]+d),n.push(u[p]+d),n.push(u[p+1]+d),n.push(u[p+2]+d),n.push(u[p+2]+d);for(p=0;p<r;p++)s.push(i[2*p],i[2*p+1],h,l,c,a);return!0}},PIXI.WebGLGraphics.graphicsDataPool=[],PIXI.WebGLGraphicsData=function(t){this.gl=t,this.color=[0,0,0],this.points=[],this.indices=[],this.buffer=t.createBuffer(),this.indexBuffer=t.createBuffer(),this.mode=1,this.alpha=1,this.dirty=!0},PIXI.WebGLGraphicsData.prototype.reset=function(){this.points=[],this.indices=[]},PIXI.WebGLGraphicsData.prototype.upload=function(){var t=this.gl;this.glPoints=new PIXI.Float32Array(this.points),t.bindBuffer(t.ARRAY_BUFFER,this.buffer),t.bufferData(t.ARRAY_BUFFER,this.glPoints,t.STATIC_DRAW),this.glIndicies=new PIXI.Uint16Array(this.indices),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,this.glIndicies,t.STATIC_DRAW),this.dirty=!1},PIXI.CanvasGraphics=function(){},PIXI.CanvasGraphics.renderGraphics=function(t,e){var i=t.worldAlpha;t.dirty&&(this.updateGraphicsTint(t),t.dirty=!1);for(var s=0;s<t.graphicsData.length;s++){var n=t.graphicsData[s],r=n.shape,o=n._fillTint,a=n._lineTint;if(e.lineWidth=n.lineWidth,n.type===PIXI.Graphics.POLY){e.beginPath();var h=r.points;e.moveTo(h[0],h[1]);for(var l=1;l<h.length/2;l++)e.lineTo(h[2*l],h[2*l+1]);r.closed&&e.lineTo(h[0],h[1]),h[0]===h[h.length-2]&&h[1]===h[h.length-1]&&e.closePath(),n.fill&&(e.globalAlpha=n.fillAlpha*i,e.fillStyle="#"+("00000"+(0|o).toString(16)).substr(-6),e.fill()),n.lineWidth&&(e.globalAlpha=n.lineAlpha*i,e.strokeStyle="#"+("00000"+(0|a).toString(16)).substr(-6),e.stroke())}else if(n.type===PIXI.Graphics.RECT)(n.fillColor||0===n.fillColor)&&(e.globalAlpha=n.fillAlpha*i,e.fillStyle="#"+("00000"+(0|o).toString(16)).substr(-6),e.fillRect(r.x,r.y,r.width,r.height)),n.lineWidth&&(e.globalAlpha=n.lineAlpha*i,e.strokeStyle="#"+("00000"+(0|a).toString(16)).substr(-6),e.strokeRect(r.x,r.y,r.width,r.height));else if(n.type===PIXI.Graphics.CIRC)e.beginPath(),e.arc(r.x,r.y,r.radius,0,2*Math.PI),e.closePath(),n.fill&&(e.globalAlpha=n.fillAlpha*i,e.fillStyle="#"+("00000"+(0|o).toString(16)).substr(-6),e.fill()),n.lineWidth&&(e.globalAlpha=n.lineAlpha*i,e.strokeStyle="#"+("00000"+(0|a).toString(16)).substr(-6),e.stroke());else if(n.type===PIXI.Graphics.ELIP){var c=2*r.width,u=2*r.height,d=r.x-c/2,p=r.y-u/2;e.beginPath();var f=c/2*.5522848,g=u/2*.5522848,m=d+c,y=p+u,v=d+c/2,b=p+u/2;e.moveTo(d,b),e.bezierCurveTo(d,b-g,v-f,p,v,p),e.bezierCurveTo(v+f,p,m,b-g,m,b),e.bezierCurveTo(m,b+g,v+f,y,v,y),e.bezierCurveTo(v-f,y,d,b+g,d,b),e.closePath(),n.fill&&(e.globalAlpha=n.fillAlpha*i,e.fillStyle="#"+("00000"+(0|o).toString(16)).substr(-6),e.fill()),n.lineWidth&&(e.globalAlpha=n.lineAlpha*i,e.strokeStyle="#"+("00000"+(0|a).toString(16)).substr(-6),e.stroke())}else if(n.type===PIXI.Graphics.RREC){var x=r.x,w=r.y,_=r.width,P=r.height,T=r.radius,C=Math.min(_,P)/2|0;T=T>C?C:T,e.beginPath(),e.moveTo(x,w+T),e.lineTo(x,w+P-T),e.quadraticCurveTo(x,w+P,x+T,w+P),e.lineTo(x+_-T,w+P),e.quadraticCurveTo(x+_,w+P,x+_,w+P-T),e.lineTo(x+_,w+T),e.quadraticCurveTo(x+_,w,x+_-T,w),e.lineTo(x+T,w),e.quadraticCurveTo(x,w,x,w+T),e.closePath(),(n.fillColor||0===n.fillColor)&&(e.globalAlpha=n.fillAlpha*i,e.fillStyle="#"+("00000"+(0|o).toString(16)).substr(-6),e.fill()),n.lineWidth&&(e.globalAlpha=n.lineAlpha*i,e.strokeStyle="#"+("00000"+(0|a).toString(16)).substr(-6),e.stroke())}}},PIXI.CanvasGraphics.renderGraphicsMask=function(t,e){var i=t.graphicsData.length;if(0!==i){e.beginPath();for(var s=0;s<i;s++){var n=t.graphicsData[s],r=n.shape;if(n.type===PIXI.Graphics.POLY){var o=r.points;e.moveTo(o[0],o[1]);for(var a=1;a<o.length/2;a++)e.lineTo(o[2*a],o[2*a+1]);o[0]===o[o.length-2]&&o[1]===o[o.length-1]&&e.closePath()}else if(n.type===PIXI.Graphics.RECT)e.rect(r.x,r.y,r.width,r.height),e.closePath();else if(n.type===PIXI.Graphics.CIRC)e.arc(r.x,r.y,r.radius,0,2*Math.PI),e.closePath();else if(n.type===PIXI.Graphics.ELIP){var h=2*r.width,l=2*r.height,c=r.x-h/2,u=r.y-l/2,d=h/2*.5522848,p=l/2*.5522848,f=c+h,g=u+l,m=c+h/2,y=u+l/2;e.moveTo(c,y),e.bezierCurveTo(c,y-p,m-d,u,m,u),e.bezierCurveTo(m+d,u,f,y-p,f,y),e.bezierCurveTo(f,y+p,m+d,g,m,g),e.bezierCurveTo(m-d,g,c,y+p,c,y),e.closePath()}else if(n.type===PIXI.Graphics.RREC){var v=r.x,b=r.y,x=r.width,w=r.height,_=r.radius,P=Math.min(x,w)/2|0;_=_>P?P:_,e.moveTo(v,b+_),e.lineTo(v,b+w-_),e.quadraticCurveTo(v,b+w,v+_,b+w),e.lineTo(v+x-_,b+w),e.quadraticCurveTo(v+x,b+w,v+x,b+w-_),e.lineTo(v+x,b+_),e.quadraticCurveTo(v+x,b,v+x-_,b),e.lineTo(v+_,b),e.quadraticCurveTo(v,b,v,b+_),e.closePath()}}}},PIXI.CanvasGraphics.updateGraphicsTint=function(t){if(16777215!==t.tint)for(var e=(t.tint>>16&255)/255,i=(t.tint>>8&255)/255,s=(255&t.tint)/255,n=0;n<t.graphicsData.length;n++){var r=t.graphicsData[n],o=0|r.fillColor,a=0|r.lineColor;r._fillTint=((o>>16&255)/255*e*255<<16)+((o>>8&255)/255*i*255<<8)+(255&o)/255*s*255,r._lineTint=((a>>16&255)/255*e*255<<16)+((a>>8&255)/255*i*255<<8)+(255&a)/255*s*255}},/**
<add>n.BitmapData=function(t,e,i,s,r){void 0!==i&&0!==i||(i=256),void 0!==s&&0!==s||(s=256),void 0===r&&(r=!1),this.game=t,this.key=e,this.width=i,this.height=s,this.canvas=n.Canvas.create(this,i,s,null,r),this.context=this.canvas.getContext("2d",{alpha:!0}),this.ctx=this.context,this.smoothProperty=t.renderType===n.CANVAS?t.renderer.renderSession.smoothProperty:n.Canvas.getSmoothingPrefix(this.context),this.imageData=this.context.getImageData(0,0,i,s),this.data=null,this.imageData&&(this.data=this.imageData.data),this.pixels=null,this.data&&(this.imageData.data.buffer?(this.buffer=this.imageData.data.buffer,this.pixels=new Uint32Array(this.buffer)):window.ArrayBuffer?(this.buffer=new ArrayBuffer(this.imageData.data.length),this.pixels=new Uint32Array(this.buffer)):this.pixels=this.imageData.data),this.baseTexture=new PIXI.BaseTexture(this.canvas),this.texture=new PIXI.Texture(this.baseTexture),this.frameData=new n.FrameData,this.textureFrame=this.frameData.addFrame(new n.Frame(0,0,0,i,s,"bitmapData")),this.texture.frame=this.textureFrame,this.type=n.BITMAPDATA,this.disableTextureUpload=!1,this.dirty=!1,this.cls=this.clear,this._image=null,this._pos=new n.Point,this._size=new n.Point,this._scale=new n.Point,this._rotate=0,this._alpha={prev:1,current:1},this._anchor=new n.Point,this._tempR=0,this._tempG=0,this._tempB=0,this._circle=new n.Circle,this._swapCanvas=void 0},n.BitmapData.prototype={move:function(t,e,i){return 0!==t&&this.moveH(t,i),0!==e&&this.moveV(e,i),this},moveH:function(t,e){void 0===e&&(e=!0),void 0===this._swapCanvas&&(this._swapCanvas=PIXI.CanvasPool.create(this,this.width,this.height));var i=this._swapCanvas,s=i.getContext("2d"),n=this.height,r=this.canvas;if(s.clearRect(0,0,this.width,this.height),t<0){t=Math.abs(t);var o=this.width-t;e&&s.drawImage(r,0,0,t,n,o,0,t,n),s.drawImage(r,t,0,o,n,0,0,o,n)}else{var o=this.width-t;e&&s.drawImage(r,o,0,t,n,0,0,t,n),s.drawImage(r,0,0,o,n,t,0,o,n)}return this.clear(),this.copy(this._swapCanvas)},moveV:function(t,e){void 0===e&&(e=!0),void 0===this._swapCanvas&&(this._swapCanvas=PIXI.CanvasPool.create(this,this.width,this.height));var i=this._swapCanvas,s=i.getContext("2d"),n=this.width,r=this.canvas;if(s.clearRect(0,0,this.width,this.height),t<0){t=Math.abs(t);var o=this.height-t;e&&s.drawImage(r,0,0,n,t,0,o,n,t),s.drawImage(r,0,t,n,o,0,0,n,o)}else{var o=this.height-t;e&&s.drawImage(r,0,o,n,t,0,0,n,t),s.drawImage(r,0,0,n,o,0,t,n,o)}return this.clear(),this.copy(this._swapCanvas)},add:function(t){if(Array.isArray(t))for(var e=0;e<t.length;e++)t[e].loadTexture&&t[e].loadTexture(this);else t.loadTexture(this);return this},load:function(t){if("string"==typeof t&&(t=this.game.cache.getImage(t)),t)return this.resize(t.width,t.height),this.cls(),this.draw(t),this.update(),this},clear:function(t,e,i,s){return void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=this.width),void 0===s&&(s=this.height),this.context.clearRect(t,e,i,s),this.dirty=!0,this},fill:function(t,e,i,s){return void 0===s&&(s=1),this.context.fillStyle="rgba("+t+","+e+","+i+","+s+")",this.context.fillRect(0,0,this.width,this.height),this.dirty=!0,this},generateTexture:function(t){var e=new Image;e.src=this.canvas.toDataURL("image/png");var i=this.game.cache.addImage(t,"",e);return new PIXI.Texture(i.base)},resize:function(t,e){return t===this.width&&e===this.height||(this.width=t,this.height=e,this.canvas.width=t,this.canvas.height=e,void 0!==this._swapCanvas&&(this._swapCanvas.width=t,this._swapCanvas.height=e),this.baseTexture.width=t,this.baseTexture.height=e,this.textureFrame.width=t,this.textureFrame.height=e,this.texture.width=t,this.texture.height=e,this.texture.crop.width=t,this.texture.crop.height=e,this.update(),this.dirty=!0),this},update:function(t,e,i,s){return void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=Math.max(1,this.width)),void 0===s&&(s=Math.max(1,this.height)),this.imageData=this.context.getImageData(t,e,i,s),this.data=this.imageData.data,this.imageData.data.buffer?(this.buffer=this.imageData.data.buffer,this.pixels=new Uint32Array(this.buffer)):window.ArrayBuffer?(this.buffer=new ArrayBuffer(this.imageData.data.length),this.pixels=new Uint32Array(this.buffer)):this.pixels=this.imageData.data,this},processPixelRGB:function(t,e,i,s,r,o){void 0===i&&(i=0),void 0===s&&(s=0),void 0===r&&(r=this.width),void 0===o&&(o=this.height);for(var a=i+r,h=s+o,l=n.Color.createColor(),c={r:0,g:0,b:0,a:0},u=!1,d=s;d<h;d++)for(var p=i;p<a;p++)n.Color.unpackPixel(this.getPixel32(p,d),l),!1!==(c=t.call(e,l,p,d))&&null!==c&&void 0!==c&&(this.setPixel32(p,d,c.r,c.g,c.b,c.a,!1),u=!0);return u&&(this.context.putImageData(this.imageData,0,0),this.dirty=!0),this},processPixel:function(t,e,i,s,n,r){void 0===i&&(i=0),void 0===s&&(s=0),void 0===n&&(n=this.width),void 0===r&&(r=this.height);for(var o=i+n,a=s+r,h=0,l=0,c=!1,u=s;u<a;u++)for(var d=i;d<o;d++)h=this.getPixel32(d,u),(l=t.call(e,h,d,u))!==h&&(this.pixels[u*this.width+d]=l,c=!0);return c&&(this.context.putImageData(this.imageData,0,0),this.dirty=!0),this},replaceRGB:function(t,e,i,s,r,o,a,h,l){var c=0,u=0,d=this.width,p=this.height,f=n.Color.packPixel(t,e,i,s);void 0!==l&&l instanceof n.Rectangle&&(c=l.x,u=l.y,d=l.width,p=l.height);for(var g=0;g<p;g++)for(var m=0;m<d;m++)this.getPixel32(c+m,u+g)===f&&this.setPixel32(c+m,u+g,r,o,a,h,!1);return this.context.putImageData(this.imageData,0,0),this.dirty=!0,this},setHSL:function(t,e,i,s){var r=t||0===t,o=e||0===e,a=i||0===i;if(r||o||a){void 0===s&&(s=new n.Rectangle(0,0,this.width,this.height));for(var h=n.Color.createColor(),l=s.y;l<s.bottom;l++)for(var c=s.x;c<s.right;c++)n.Color.unpackPixel(this.getPixel32(c,l),h,!0),r&&(h.h=t),o&&(h.s=e),a&&(h.l=i),n.Color.HSLtoRGB(h.h,h.s,h.l,h),this.setPixel32(c,l,h.r,h.g,h.b,h.a,!1);return this.context.putImageData(this.imageData,0,0),this.dirty=!0,this}},shiftHSL:function(t,e,i,s){if(void 0!==t&&null!==t||(t=!1),void 0!==e&&null!==e||(e=!1),void 0!==i&&null!==i||(i=!1),t||e||i){void 0===s&&(s=new n.Rectangle(0,0,this.width,this.height));for(var r=n.Color.createColor(),o=s.y;o<s.bottom;o++)for(var a=s.x;a<s.right;a++)n.Color.unpackPixel(this.getPixel32(a,o),r,!0),t&&(r.h=this.game.math.wrap(r.h+t,0,1)),e&&(r.s=this.game.math.clamp(r.s+e,0,1)),i&&(r.l=this.game.math.clamp(r.l+i,0,1)),n.Color.HSLtoRGB(r.h,r.s,r.l,r),this.setPixel32(a,o,r.r,r.g,r.b,r.a,!1);return this.context.putImageData(this.imageData,0,0),this.dirty=!0,this}},setPixel32:function(t,e,i,s,r,o,a){return void 0===a&&(a=!0),t>=0&&t<=this.width&&e>=0&&e<=this.height&&(n.Device.LITTLE_ENDIAN?this.pixels[e*this.width+t]=o<<24|r<<16|s<<8|i:this.pixels[e*this.width+t]=i<<24|s<<16|r<<8|o,a&&(this.context.putImageData(this.imageData,0,0),this.dirty=!0)),this},setPixel:function(t,e,i,s,n,r){return this.setPixel32(t,e,i,s,n,255,r)},getPixel:function(t,e,i){i||(i=n.Color.createColor());var s=~~(t+e*this.width);return s*=4,i.r=this.data[s],i.g=this.data[++s],i.b=this.data[++s],i.a=this.data[++s],i},getPixel32:function(t,e){if(t>=0&&t<=this.width&&e>=0&&e<=this.height)return this.pixels[e*this.width+t]},getPixelRGB:function(t,e,i,s,r){return n.Color.unpackPixel(this.getPixel32(t,e),i,s,r)},getPixels:function(t){return this.context.getImageData(t.x,t.y,t.width,t.height)},getFirstPixel:function(t){void 0===t&&(t=0);var e=n.Color.createColor(),i=0,s=0,r=1,o=!1;1===t?(r=-1,s=this.height):3===t&&(r=-1,i=this.width);do{n.Color.unpackPixel(this.getPixel32(i,s),e),0===t||1===t?++i===this.width&&(i=0,((s+=r)>=this.height||s<=0)&&(o=!0)):2!==t&&3!==t||++s===this.height&&(s=0,((i+=r)>=this.width||i<=0)&&(o=!0))}while(0===e.a&&!o);return e.x=i,e.y=s,e},getBounds:function(t){return void 0===t&&(t=new n.Rectangle),t.x=this.getFirstPixel(2).x,t.x===this.width?t.setTo(0,0,0,0):(t.y=this.getFirstPixel(0).y,t.width=this.getFirstPixel(3).x-t.x+1,t.height=this.getFirstPixel(1).y-t.y+1,t)},addToWorld:function(t,e,i,s,n,r){n=n||1,r=r||1;var o=this.game.add.image(t,e,this);return o.anchor.set(i,s),o.scale.set(n,r),o},copy:function(t,e,i,s,r,o,a,h,l,c,u,d,p,f,g,m,y){if(void 0!==t&&null!==t||(t=this),(t instanceof n.RenderTexture||t instanceof PIXI.RenderTexture)&&(t=t.getCanvas()),this._image=t,t instanceof n.Sprite||t instanceof n.Image||t instanceof n.Text||t instanceof PIXI.Sprite)this._pos.set(t.texture.crop.x,t.texture.crop.y),this._size.set(t.texture.crop.width,t.texture.crop.height),this._scale.set(t.scale.x,t.scale.y),this._anchor.set(t.anchor.x,t.anchor.y),this._rotate=t.rotation,this._alpha.current=t.alpha,t.texture instanceof n.RenderTexture||t.texture instanceof PIXI.RenderTexture?this._image=t.texture.getCanvas():this._image=t.texture.baseTexture.source,void 0!==o&&null!==o||(o=t.x),void 0!==a&&null!==a||(a=t.y),t.texture.trim&&(o+=t.texture.trim.x-t.anchor.x*t.texture.trim.width,a+=t.texture.trim.y-t.anchor.y*t.texture.trim.height),16777215!==t.tint&&(t.cachedTint!==t.tint&&(t.cachedTint=t.tint,t.tintedTexture=PIXI.CanvasTinter.getTintedTexture(t,t.tint)),this._image=t.tintedTexture,this._pos.set(0));else{if(this._pos.set(0),this._scale.set(1),this._anchor.set(0),this._rotate=0,this._alpha.current=1,t instanceof n.BitmapData)this._image=t.canvas;else if("string"==typeof t){if(null===(t=this.game.cache.getImage(t)))return;this._image=t}this._size.set(this._image.width,this._image.height)}if(void 0!==e&&null!==e||(e=0),void 0!==i&&null!==i||(i=0),s&&(this._size.x=s),r&&(this._size.y=r),void 0!==o&&null!==o||(o=e),void 0!==a&&null!==a||(a=i),void 0!==h&&null!==h||(h=this._size.x),void 0!==l&&null!==l||(l=this._size.y),"number"==typeof c&&(this._rotate=c),"number"==typeof u&&(this._anchor.x=u),"number"==typeof d&&(this._anchor.y=d),"number"==typeof p&&(this._scale.x=p),"number"==typeof f&&(this._scale.y=f),"number"==typeof g&&(this._alpha.current=g),void 0===m&&(m=null),void 0===y&&(y=!1),!(this._alpha.current<=0||0===this._scale.x||0===this._scale.y||0===this._size.x||0===this._size.y)){var v=this.context;return this._alpha.prev=v.globalAlpha,v.save(),v.globalAlpha=this._alpha.current,m&&(this.op=m),y&&(o|=0,a|=0),v.translate(o,a),v.scale(this._scale.x,this._scale.y),v.rotate(this._rotate),v.drawImage(this._image,this._pos.x+e,this._pos.y+i,this._size.x,this._size.y,-h*this._anchor.x,-l*this._anchor.y,h,l),v.restore(),v.globalAlpha=this._alpha.prev,this.dirty=!0,this}},copyTransform:function(t,e,i){if(void 0===e&&(e=null),void 0===i&&(i=!1),!t.hasOwnProperty("worldTransform")||!t.worldVisible||0===t.worldAlpha)return this;var s=t.worldTransform;if(this._pos.set(t.texture.crop.x,t.texture.crop.y),this._size.set(t.texture.crop.width,t.texture.crop.height),0===s.a||0===s.d||0===this._size.x||0===this._size.y)return this;t.texture instanceof n.RenderTexture||t.texture instanceof PIXI.RenderTexture?this._image=t.texture.getCanvas():this._image=t.texture.baseTexture.source;var r=s.tx,o=s.ty;t.texture.trim&&(r+=t.texture.trim.x-t.anchor.x*t.texture.trim.width,o+=t.texture.trim.y-t.anchor.y*t.texture.trim.height),16777215!==t.tint&&(t.cachedTint!==t.tint&&(t.cachedTint=t.tint,t.tintedTexture=PIXI.CanvasTinter.getTintedTexture(t,t.tint)),this._image=t.tintedTexture,this._pos.set(0)),i&&(r|=0,o|=0);var a=this.context;return this._alpha.prev=a.globalAlpha,a.save(),a.globalAlpha=this._alpha.current,e&&(this.op=e),a[this.smoothProperty]=t.texture.baseTexture.scaleMode===PIXI.scaleModes.LINEAR,a.setTransform(s.a,s.b,s.c,s.d,r,o),a.drawImage(this._image,this._pos.x,this._pos.y,this._size.x,this._size.y,-this._size.x*t.anchor.x,-this._size.y*t.anchor.y,this._size.x,this._size.y),a.restore(),a.globalAlpha=this._alpha.prev,this.dirty=!0,this},copyRect:function(t,e,i,s,n,r,o){return this.copy(t,e.x,e.y,e.width,e.height,i,s,e.width,e.height,0,0,0,1,1,n,r,o)},draw:function(t,e,i,s,n,r,o){return this.copy(t,null,null,null,null,e,i,s,n,null,null,null,null,null,null,r,o)},drawGroup:function(t,e,i){return t.total>0&&t.forEachExists(this.drawGroupProxy,this,e,i),this},drawGroupProxy:function(t,e,i){if(t.hasOwnProperty("texture")&&this.copyTransform(t,e,i),t.type===n.GROUP&&t.exists)this.drawGroup(t,e,i);else if(t.hasOwnProperty("children")&&t.children.length>0)for(var s=0;s<t.children.length;s++)t.children[s].exists&&this.copyTransform(t.children[s],e,i)},drawFull:function(t,e,i){if(!1===t.worldVisible||0===t.worldAlpha||t.hasOwnProperty("exists")&&!1===t.exists)return this;if(t.type!==n.GROUP&&t.type!==n.EMITTER&&t.type!==n.BITMAPTEXT)if(t.type===n.GRAPHICS){var s=t.getBounds();this.ctx.save(),this.ctx.translate(s.x,s.y),PIXI.CanvasGraphics.renderGraphics(t,this.ctx),this.ctx.restore()}else this.copy(t,null,null,null,null,t.worldPosition.x,t.worldPosition.y,null,null,t.worldRotation,null,null,t.worldScale.x,t.worldScale.y,t.worldAlpha,e,i);if(t.children)for(var r=0;r<t.children.length;r++)this.drawFull(t.children[r],e,i);return this},shadow:function(t,e,i,s){var n=this.context;return void 0===t||null===t?n.shadowColor="rgba(0,0,0,0)":(n.shadowColor=t,n.shadowBlur=e||5,n.shadowOffsetX=i||10,n.shadowOffsetY=s||10),this},alphaMask:function(t,e,i,s){return void 0===s||null===s?this.draw(e).blendSourceAtop():this.draw(e,s.x,s.y,s.width,s.height).blendSourceAtop(),void 0===i||null===i?this.draw(t).blendReset():this.draw(t,i.x,i.y,i.width,i.height).blendReset(),this},extract:function(t,e,i,s,n,r,o,a,h){return void 0===n&&(n=255),void 0===r&&(r=!1),void 0===o&&(o=e),void 0===a&&(a=i),void 0===h&&(h=s),r&&t.resize(this.width,this.height),this.processPixelRGB(function(r,l,c){return r.r===e&&r.g===i&&r.b===s&&t.setPixel32(l,c,o,a,h,n,!1),!1},this),t.context.putImageData(t.imageData,0,0),t.dirty=!0,t},rect:function(t,e,i,s,n){return void 0!==n&&(this.context.fillStyle=n),this.context.fillRect(t,e,i,s),this},text:function(t,e,i,s,n,r){void 0===e&&(e=0),void 0===i&&(i=0),void 0===s&&(s="14px Courier"),void 0===n&&(n="rgb(255,255,255)"),void 0===r&&(r=!0);var o=this.context,a=o.font;return o.font=s,r&&(o.fillStyle="rgb(0,0,0)",o.fillText(t,e+1,i+1)),o.fillStyle=n,o.fillText(t,e,i),o.font=a,this},circle:function(t,e,i,s){var n=this.context;return void 0!==s&&(n.fillStyle=s),n.beginPath(),n.arc(t,e,i,0,2*Math.PI,!1),n.closePath(),n.fill(),this},line:function(t,e,i,s,n,r){void 0===n&&(n="#fff"),void 0===r&&(r=1);var o=this.context;return o.beginPath(),o.moveTo(t,e),o.lineTo(i,s),o.lineWidth=r,o.strokeStyle=n,o.stroke(),o.closePath(),this},textureLine:function(t,e,i){if(void 0===i&&(i="repeat-x"),"string"!=typeof e||(e=this.game.cache.getImage(e))){var s=t.length;"no-repeat"===i&&s>e.width&&(s=e.width);var r=this.context;return r.fillStyle=r.createPattern(e,i),this._circle=new n.Circle(t.start.x,t.start.y,e.height),this._circle.circumferencePoint(t.angle-1.5707963267948966,!1,this._pos),r.save(),r.translate(this._pos.x,this._pos.y),r.rotate(t.angle),r.fillRect(0,0,s,e.height),r.restore(),this.dirty=!0,this}},render:function(){return!this.disableTextureUpload&&this.dirty&&(this.baseTexture.dirty(),this.dirty=!1),this},destroy:function(){this.frameData.destroy(),this.texture.destroy(!0),PIXI.CanvasPool.remove(this)},blendReset:function(){return this.op="source-over",this},blendSourceOver:function(){return this.op="source-over",this},blendSourceIn:function(){return this.op="source-in",this},blendSourceOut:function(){return this.op="source-out",this},blendSourceAtop:function(){return this.op="source-atop",this},blendDestinationOver:function(){return this.op="destination-over",this},blendDestinationIn:function(){return this.op="destination-in",this},blendDestinationOut:function(){return this.op="destination-out",this},blendDestinationAtop:function(){return this.op="destination-atop",this},blendXor:function(){return this.op="xor",this},blendAdd:function(){return this.op="lighter",this},blendMultiply:function(){return this.op="multiply",this},blendScreen:function(){return this.op="screen",this},blendOverlay:function(){return this.op="overlay",this},blendDarken:function(){return this.op="darken",this},blendLighten:function(){return this.op="lighten",this},blendColorDodge:function(){return this.op="color-dodge",this},blendColorBurn:function(){return this.op="color-burn",this},blendHardLight:function(){return this.op="hard-light",this},blendSoftLight:function(){return this.op="soft-light",this},blendDifference:function(){return this.op="difference",this},blendExclusion:function(){return this.op="exclusion",this},blendHue:function(){return this.op="hue",this},blendSaturation:function(){return this.op="saturation",this},blendColor:function(){return this.op="color",this},blendLuminosity:function(){return this.op="luminosity",this}},Object.defineProperty(n.BitmapData.prototype,"smoothed",{get:function(){n.Canvas.getSmoothingEnabled(this.context)},set:function(t){n.Canvas.setSmoothingEnabled(this.context,t)}}),Object.defineProperty(n.BitmapData.prototype,"op",{get:function(){return this.context.globalCompositeOperation},set:function(t){this.context.globalCompositeOperation=t}}),n.BitmapData.getTransform=function(t,e,i,s,n,r){return"number"!=typeof t&&(t=0),"number"!=typeof e&&(e=0),"number"!=typeof i&&(i=1),"number"!=typeof s&&(s=1),"number"!=typeof n&&(n=0),"number"!=typeof r&&(r=0),{sx:i,sy:s,scaleX:i,scaleY:s,skewX:n,skewY:r,translateX:t,translateY:e,tx:t,ty:e}},n.BitmapData.prototype.constructor=n.BitmapData,PIXI.Graphics=function(){PIXI.DisplayObjectContainer.call(this),this.renderable=!0,this.fillAlpha=1,this.lineWidth=0,this.lineColor=0,this.graphicsData=[],this.tint=16777215,this.blendMode=PIXI.blendModes.NORMAL,this.currentPath=null,this._webGL=[],this.isMask=!1,this.boundsPadding=0,this._localBounds=new PIXI.Rectangle(0,0,1,1),this.dirty=!0,this._boundsDirty=!1,this.webGLDirty=!1,this.cachedSpriteDirty=!1},PIXI.Graphics.prototype=Object.create(PIXI.DisplayObjectContainer.prototype),PIXI.Graphics.prototype.constructor=PIXI.Graphics,PIXI.Graphics.prototype.lineStyle=function(t,e,i){return this.lineWidth=t||0,this.lineColor=e||0,this.lineAlpha=void 0===i?1:i,this.currentPath&&(this.currentPath.shape.points.length?this.drawShape(new PIXI.Polygon(this.currentPath.shape.points.slice(-2))):(this.currentPath.lineWidth=this.lineWidth,this.currentPath.lineColor=this.lineColor,this.currentPath.lineAlpha=this.lineAlpha)),this},PIXI.Graphics.prototype.moveTo=function(t,e){return this.drawShape(new PIXI.Polygon([t,e])),this},PIXI.Graphics.prototype.lineTo=function(t,e){return this.currentPath||this.moveTo(0,0),this.currentPath.shape.points.push(t,e),this.dirty=!0,this._boundsDirty=!0,this},PIXI.Graphics.prototype.quadraticCurveTo=function(t,e,i,s){this.currentPath?0===this.currentPath.shape.points.length&&(this.currentPath.shape.points=[0,0]):this.moveTo(0,0);var n,r,o=this.currentPath.shape.points;0===o.length&&this.moveTo(0,0);for(var a=o[o.length-2],h=o[o.length-1],l=0,c=1;c<=20;++c)l=c/20,n=a+(t-a)*l,r=h+(e-h)*l,o.push(n+(t+(i-t)*l-n)*l,r+(e+(s-e)*l-r)*l);return this.dirty=!0,this._boundsDirty=!0,this},PIXI.Graphics.prototype.bezierCurveTo=function(t,e,i,s,n,r){this.currentPath?0===this.currentPath.shape.points.length&&(this.currentPath.shape.points=[0,0]):this.moveTo(0,0);for(var o,a,h,l,c,u=this.currentPath.shape.points,d=u[u.length-2],p=u[u.length-1],f=0,g=1;g<=20;++g)f=g/20,o=1-f,a=o*o,h=a*o,l=f*f,c=l*f,u.push(h*d+3*a*f*t+3*o*l*i+c*n,h*p+3*a*f*e+3*o*l*s+c*r);return this.dirty=!0,this._boundsDirty=!0,this},PIXI.Graphics.prototype.arcTo=function(t,e,i,s,n){this.currentPath?0===this.currentPath.shape.points.length&&this.currentPath.shape.points.push(t,e):this.moveTo(t,e);var r=this.currentPath.shape.points,o=r[r.length-2],a=r[r.length-1],h=a-e,l=o-t,c=s-e,u=i-t,d=Math.abs(h*u-l*c);if(d<1e-8||0===n)r[r.length-2]===t&&r[r.length-1]===e||r.push(t,e);else{var p=h*h+l*l,f=c*c+u*u,g=h*c+l*u,m=n*Math.sqrt(p)/d,y=n*Math.sqrt(f)/d,v=m*g/p,b=y*g/f,x=m*u+y*l,w=m*c+y*h,_=l*(y+v),P=h*(y+v),T=u*(m+b),C=c*(m+b),S=Math.atan2(P-w,_-x),A=Math.atan2(C-w,T-x);this.arc(x+t,w+e,n,S,A,l*c>u*h)}return this.dirty=!0,this._boundsDirty=!0,this},PIXI.Graphics.prototype.arc=function(t,e,i,s,n,r,o){if(s===n)return this;void 0===r&&(r=!1),void 0===o&&(o=40),!r&&n<=s?n+=2*Math.PI:r&&s<=n&&(s+=2*Math.PI);var a=r?-1*(s-n):n-s,h=Math.ceil(Math.abs(a)/(2*Math.PI))*o;if(0===a)return this;var l=t+Math.cos(s)*i,c=e+Math.sin(s)*i;r&&this.filling?this.moveTo(t,e):this.moveTo(l,c);for(var u=this.currentPath.shape.points,d=a/(2*h),p=2*d,f=Math.cos(d),g=Math.sin(d),m=h-1,y=m%1/m,v=0;v<=m;v++){var b=v+y*v,x=d+s+p*b,w=Math.cos(x),_=-Math.sin(x);u.push((f*w+g*_)*i+t,(f*-_+g*w)*i+e)}return this.dirty=!0,this._boundsDirty=!0,this},PIXI.Graphics.prototype.beginFill=function(t,e){return this.filling=!0,this.fillColor=t||0,this.fillAlpha=void 0===e?1:e,this.currentPath&&this.currentPath.shape.points.length<=2&&(this.currentPath.fill=this.filling,this.currentPath.fillColor=this.fillColor,this.currentPath.fillAlpha=this.fillAlpha),this},PIXI.Graphics.prototype.endFill=function(){return this.filling=!1,this.fillColor=null,this.fillAlpha=1,this},PIXI.Graphics.prototype.drawRect=function(t,e,i,s){return this.drawShape(new PIXI.Rectangle(t,e,i,s)),this},PIXI.Graphics.prototype.drawRoundedRect=function(t,e,i,s,n){return this.drawShape(new PIXI.RoundedRectangle(t,e,i,s,n)),this},PIXI.Graphics.prototype.drawCircle=function(t,e,i){return this.drawShape(new PIXI.Circle(t,e,i)),this},PIXI.Graphics.prototype.drawEllipse=function(t,e,i,s){return this.drawShape(new PIXI.Ellipse(t,e,i,s)),this},PIXI.Graphics.prototype.drawPolygon=function(t){(t instanceof n.Polygon||t instanceof PIXI.Polygon)&&(t=t.points);var e=t;if(!Array.isArray(e)){e=new Array(arguments.length);for(var i=0;i<e.length;++i)e[i]=arguments[i]}return this.drawShape(new n.Polygon(e)),this},PIXI.Graphics.prototype.clear=function(){return this.lineWidth=0,this.filling=!1,this.dirty=!0,this._boundsDirty=!0,this.clearDirty=!0,this.graphicsData=[],this.updateLocalBounds(),this},PIXI.Graphics.prototype.generateTexture=function(t,e,i){void 0===t&&(t=1),void 0===e&&(e=PIXI.scaleModes.DEFAULT),void 0===i&&(i=0);var s=this.getBounds();s.width+=i,s.height+=i;var n=new PIXI.CanvasBuffer(s.width*t,s.height*t),r=PIXI.Texture.fromCanvas(n.canvas,e);return r.baseTexture.resolution=t,n.context.scale(t,t),n.context.translate(-s.x,-s.y),PIXI.CanvasGraphics.renderGraphics(this,n.context),r},PIXI.Graphics.prototype._renderWebGL=function(t){if(!1!==this.visible&&0!==this.alpha&&!0!==this.isMask){if(this._cacheAsBitmap)return(this.dirty||this.cachedSpriteDirty)&&(this._generateCachedSprite(),this.updateCachedSpriteTexture(),this.cachedSpriteDirty=!1,this.dirty=!1),this._cachedSprite.worldAlpha=this.worldAlpha,void PIXI.Sprite.prototype._renderWebGL.call(this._cachedSprite,t);if(t.spriteBatch.stop(),t.blendModeManager.setBlendMode(this.blendMode),this._mask&&t.maskManager.pushMask(this._mask,t),this._filters&&t.filterManager.pushFilter(this._filterBlock),this.blendMode!==t.spriteBatch.currentBlendMode){t.spriteBatch.currentBlendMode=this.blendMode;var e=PIXI.blendModesWebGL[t.spriteBatch.currentBlendMode];t.spriteBatch.gl.blendFunc(e[0],e[1])}if(this.webGLDirty&&(this.dirty=!0,this.webGLDirty=!1),PIXI.WebGLGraphics.renderGraphics(this,t),this.children.length){t.spriteBatch.start();for(var i=0;i<this.children.length;i++)this.children[i]._renderWebGL(t);t.spriteBatch.stop()}this._filters&&t.filterManager.popFilter(),this._mask&&t.maskManager.popMask(this.mask,t),t.drawCount++,t.spriteBatch.start()}},PIXI.Graphics.prototype._renderCanvas=function(t){if(!1!==this.visible&&0!==this.alpha&&!0!==this.isMask){if(this._prevTint!==this.tint&&(this.dirty=!0,this._prevTint=this.tint),this._cacheAsBitmap)return(this.dirty||this.cachedSpriteDirty)&&(this._generateCachedSprite(),this.updateCachedSpriteTexture(),this.cachedSpriteDirty=!1,this.dirty=!1),this._cachedSprite.alpha=this.alpha,void PIXI.Sprite.prototype._renderCanvas.call(this._cachedSprite,t);var e=t.context,i=this.worldTransform;this.blendMode!==t.currentBlendMode&&(t.currentBlendMode=this.blendMode,e.globalCompositeOperation=PIXI.blendModesCanvas[t.currentBlendMode]),this._mask&&t.maskManager.pushMask(this._mask,t);var s=t.resolution,n=i.tx*t.resolution+t.shakeX,r=i.ty*t.resolution+t.shakeY;e.setTransform(i.a*s,i.b*s,i.c*s,i.d*s,n,r),PIXI.CanvasGraphics.renderGraphics(this,e);for(var o=0;o<this.children.length;o++)this.children[o]._renderCanvas(t);this._mask&&t.maskManager.popMask(t)}},PIXI.Graphics.prototype.getBounds=function(t){if(!this._currentBounds){if(!this.renderable)return PIXI.EmptyRectangle;this.dirty&&(this.updateLocalBounds(),this.webGLDirty=!0,this.cachedSpriteDirty=!0,this.dirty=!1);var e=this._localBounds,i=e.x,s=e.width+e.x,n=e.y,r=e.height+e.y,o=t||this.worldTransform,a=o.a,h=o.b,l=o.c,c=o.d,u=o.tx,d=o.ty,p=a*s+l*r+u,f=c*r+h*s+d,g=a*i+l*r+u,m=c*r+h*i+d,y=a*i+l*n+u,v=c*n+h*i+d,b=a*s+l*n+u,x=c*n+h*s+d,w=p,_=f,P=p,T=f;P=g<P?g:P,P=y<P?y:P,P=b<P?b:P,T=m<T?m:T,T=v<T?v:T,T=x<T?x:T,w=g>w?g:w,w=y>w?y:w,w=b>w?b:w,_=m>_?m:_,_=v>_?v:_,_=x>_?x:_,this._bounds.x=P,this._bounds.width=w-P,this._bounds.y=T,this._bounds.height=_-T,this._currentBounds=this._bounds}return this._currentBounds},PIXI.Graphics.prototype.getLocalBounds=function(){var t=this.worldTransform;this.worldTransform=PIXI.identityMatrix;for(var e=0;e<this.children.length;e++)this.children[e].updateTransform();var i=this.getBounds();for(this.worldTransform=t,e=0;e<this.children.length;e++)this.children[e].updateTransform();return i},PIXI.Graphics.prototype.containsPoint=function(t){this.worldTransform.applyInverse(t,tempPoint);for(var e=this.graphicsData,i=0;i<e.length;i++){var s=e[i];if(s.fill&&(s.shape&&s.shape.contains(tempPoint.x,tempPoint.y)))return!0}return!1},PIXI.Graphics.prototype.updateLocalBounds=function(){var t=1/0,e=-1/0,i=1/0,s=-1/0;if(this.graphicsData.length)for(var r,o,a,h,l,c,u=0;u<this.graphicsData.length;u++){var d=this.graphicsData[u],p=d.type,f=d.lineWidth;if(r=d.shape,p===PIXI.Graphics.RECT||p===PIXI.Graphics.RREC)a=r.x-f/2,h=r.y-f/2,l=r.width+f,c=r.height+f,t=a<t?a:t,e=a+l>e?a+l:e,i=h<i?h:i,s=h+c>s?h+c:s;else if(p===PIXI.Graphics.CIRC)a=r.x,h=r.y,l=r.radius+f/2,c=r.radius+f/2,t=a-l<t?a-l:t,e=a+l>e?a+l:e,i=h-c<i?h-c:i,s=h+c>s?h+c:s;else if(p===PIXI.Graphics.ELIP)a=r.x,h=r.y,l=r.width+f/2,c=r.height+f/2,t=a-l<t?a-l:t,e=a+l>e?a+l:e,i=h-c<i?h-c:i,s=h+c>s?h+c:s;else{o=r.points;for(var g=0;g<o.length;g++)o[g]instanceof n.Point?(a=o[g].x,h=o[g].y):(a=o[g],h=o[g+1],g<o.length-1&&g++),t=a-f<t?a-f:t,e=a+f>e?a+f:e,i=h-f<i?h-f:i,s=h+f>s?h+f:s}}else t=0,e=0,i=0,s=0;var m=this.boundsPadding;this._localBounds.x=t-m,this._localBounds.width=e-t+2*m,this._localBounds.y=i-m,this._localBounds.height=s-i+2*m},PIXI.Graphics.prototype._generateCachedSprite=function(){var t=this.getLocalBounds();if(this._cachedSprite)this._cachedSprite.buffer.resize(t.width,t.height);else{var e=new PIXI.CanvasBuffer(t.width,t.height),i=PIXI.Texture.fromCanvas(e.canvas);this._cachedSprite=new PIXI.Sprite(i),this._cachedSprite.buffer=e,this._cachedSprite.worldTransform=this.worldTransform}this._cachedSprite.anchor.x=-t.x/t.width,this._cachedSprite.anchor.y=-t.y/t.height,this._cachedSprite.buffer.context.translate(-t.x,-t.y),this.worldAlpha=1,PIXI.CanvasGraphics.renderGraphics(this,this._cachedSprite.buffer.context),this._cachedSprite.alpha=this.alpha},PIXI.Graphics.prototype.updateCachedSpriteTexture=function(){var t=this._cachedSprite,e=t.texture,i=t.buffer.canvas;e.baseTexture.width=i.width,e.baseTexture.height=i.height,e.crop.width=e.frame.width=i.width,e.crop.height=e.frame.height=i.height,t._width=i.width,t._height=i.height,e.baseTexture.dirty()},PIXI.Graphics.prototype.destroyCachedSprite=function(){this._cachedSprite.texture.destroy(!0),this._cachedSprite=null},PIXI.Graphics.prototype.drawShape=function(t){this.currentPath&&this.currentPath.shape.points.length<=2&&this.graphicsData.pop(),this.currentPath=null,t instanceof n.Polygon&&(t=t.clone(),t.flatten());var e=new PIXI.GraphicsData(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.filling,t);return this.graphicsData.push(e),e.type===PIXI.Graphics.POLY&&(e.shape.closed=this.filling,this.currentPath=e),this.dirty=!0,this._boundsDirty=!0,e},Object.defineProperty(PIXI.Graphics.prototype,"cacheAsBitmap",{get:function(){return this._cacheAsBitmap},set:function(t){this._cacheAsBitmap=t,this._cacheAsBitmap?this._generateCachedSprite():this.destroyCachedSprite(),this.dirty=!0,this.webGLDirty=!0}}),PIXI.GraphicsData=function(t,e,i,s,n,r,o){this.lineWidth=t,this.lineColor=e,this.lineAlpha=i,this._lineTint=e,this.fillColor=s,this.fillAlpha=n,this._fillTint=s,this.fill=r,this.shape=o,this.type=o.type},PIXI.GraphicsData.prototype.constructor=PIXI.GraphicsData,PIXI.GraphicsData.prototype.clone=function(){return new GraphicsData(this.lineWidth,this.lineColor,this.lineAlpha,this.fillColor,this.fillAlpha,this.fill,this.shape)},PIXI.EarCut={},PIXI.EarCut.Triangulate=function(t,e,i){i=i||2;var s=e&&e.length,n=s?e[0]*i:t.length,r=PIXI.EarCut.linkedList(t,0,n,i,!0),o=[];if(!r)return o;var a,h,l,c,u,d,p;if(s&&(r=PIXI.EarCut.eliminateHoles(t,e,r,i)),t.length>80*i){a=l=t[0],h=c=t[1];for(var f=i;f<n;f+=i)u=t[f],d=t[f+1],u<a&&(a=u),d<h&&(h=d),u>l&&(l=u),d>c&&(c=d);p=Math.max(l-a,c-h)}return PIXI.EarCut.earcutLinked(r,o,i,a,h,p),o},PIXI.EarCut.linkedList=function(t,e,i,s,n){var r,o,a,h=0;for(r=e,o=i-s;r<i;r+=s)h+=(t[o]-t[r])*(t[r+1]+t[o+1]),o=r;if(n===h>0)for(r=e;r<i;r+=s)a=PIXI.EarCut.insertNode(r,t[r],t[r+1],a);else for(r=i-s;r>=e;r-=s)a=PIXI.EarCut.insertNode(r,t[r],t[r+1],a);return a},PIXI.EarCut.filterPoints=function(t,e){if(!t)return t;e||(e=t);var i,s=t;do{if(i=!1,s.steiner||!PIXI.EarCut.equals(s,s.next)&&0!==PIXI.EarCut.area(s.prev,s,s.next))s=s.next;else{if(PIXI.EarCut.removeNode(s),(s=e=s.prev)===s.next)return null;i=!0}}while(i||s!==e);return e},PIXI.EarCut.earcutLinked=function(t,e,i,s,n,r,o){if(t){!o&&r&&PIXI.EarCut.indexCurve(t,s,n,r);for(var a,h,l=t;t.prev!==t.next;)if(a=t.prev,h=t.next,r?PIXI.EarCut.isEarHashed(t,s,n,r):PIXI.EarCut.isEar(t))e.push(a.i/i),e.push(t.i/i),e.push(h.i/i),PIXI.EarCut.removeNode(t),t=h.next,l=h.next;else if((t=h)===l){o?1===o?(t=PIXI.EarCut.cureLocalIntersections(t,e,i),PIXI.EarCut.earcutLinked(t,e,i,s,n,r,2)):2===o&&PIXI.EarCut.splitEarcut(t,e,i,s,n,r):PIXI.EarCut.earcutLinked(PIXI.EarCut.filterPoints(t),e,i,s,n,r,1);break}}},PIXI.EarCut.isEar=function(t){var e=t.prev,i=t,s=t.next;if(PIXI.EarCut.area(e,i,s)>=0)return!1;for(var n=t.next.next;n!==t.prev;){if(PIXI.EarCut.pointInTriangle(e.x,e.y,i.x,i.y,s.x,s.y,n.x,n.y)&&PIXI.EarCut.area(n.prev,n,n.next)>=0)return!1;n=n.next}return!0},PIXI.EarCut.isEarHashed=function(t,e,i,s){var n=t.prev,r=t,o=t.next;if(PIXI.EarCut.area(n,r,o)>=0)return!1;for(var a=n.x<r.x?n.x<o.x?n.x:o.x:r.x<o.x?r.x:o.x,h=n.y<r.y?n.y<o.y?n.y:o.y:r.y<o.y?r.y:o.y,l=n.x>r.x?n.x>o.x?n.x:o.x:r.x>o.x?r.x:o.x,c=n.y>r.y?n.y>o.y?n.y:o.y:r.y>o.y?r.y:o.y,u=PIXI.EarCut.zOrder(a,h,e,i,s),d=PIXI.EarCut.zOrder(l,c,e,i,s),p=t.nextZ;p&&p.z<=d;){if(p!==t.prev&&p!==t.next&&PIXI.EarCut.pointInTriangle(n.x,n.y,r.x,r.y,o.x,o.y,p.x,p.y)&&PIXI.EarCut.area(p.prev,p,p.next)>=0)return!1;p=p.nextZ}for(p=t.prevZ;p&&p.z>=u;){if(p!==t.prev&&p!==t.next&&PIXI.EarCut.pointInTriangle(n.x,n.y,r.x,r.y,o.x,o.y,p.x,p.y)&&PIXI.EarCut.area(p.prev,p,p.next)>=0)return!1;p=p.prevZ}return!0},PIXI.EarCut.cureLocalIntersections=function(t,e,i){var s=t;do{var n=s.prev,r=s.next.next;PIXI.EarCut.intersects(n,s,s.next,r)&&PIXI.EarCut.locallyInside(n,r)&&PIXI.EarCut.locallyInside(r,n)&&(e.push(n.i/i),e.push(s.i/i),e.push(r.i/i),PIXI.EarCut.removeNode(s),PIXI.EarCut.removeNode(s.next),s=t=r),s=s.next}while(s!==t);return s},PIXI.EarCut.splitEarcut=function(t,e,i,s,n,r){var o=t;do{for(var a=o.next.next;a!==o.prev;){if(o.i!==a.i&&PIXI.EarCut.isValidDiagonal(o,a)){var h=PIXI.EarCut.splitPolygon(o,a);return o=PIXI.EarCut.filterPoints(o,o.next),h=PIXI.EarCut.filterPoints(h,h.next),PIXI.EarCut.earcutLinked(o,e,i,s,n,r),void PIXI.EarCut.earcutLinked(h,e,i,s,n,r)}a=a.next}o=o.next}while(o!==t)},PIXI.EarCut.eliminateHoles=function(t,e,i,s){var n,r,o,a,h,l=[];for(n=0,r=e.length;n<r;n++)o=e[n]*s,a=n<r-1?e[n+1]*s:t.length,h=PIXI.EarCut.linkedList(t,o,a,s,!1),h===h.next&&(h.steiner=!0),l.push(PIXI.EarCut.getLeftmost(h));for(l.sort(compareX),n=0;n<l.length;n++)PIXI.EarCut.eliminateHole(l[n],i),i=PIXI.EarCut.filterPoints(i,i.next);return i},PIXI.EarCut.compareX=function(t,e){return t.x-e.x},PIXI.EarCut.eliminateHole=function(t,e){if(e=PIXI.EarCut.findHoleBridge(t,e)){var i=PIXI.EarCut.splitPolygon(e,t);PIXI.EarCut.filterPoints(i,i.next)}},PIXI.EarCut.findHoleBridge=function(t,e){var i,s=e,n=t.x,r=t.y,o=-1/0;do{if(r<=s.y&&r>=s.next.y){var a=s.x+(r-s.y)*(s.next.x-s.x)/(s.next.y-s.y);a<=n&&a>o&&(o=a,i=s.x<s.next.x?s:s.next)}s=s.next}while(s!==e);if(!i)return null;if(t.x===i.x)return i.prev;var h,l=i,c=1/0;for(s=i.next;s!==l;)n>=s.x&&s.x>=i.x&&PIXI.EarCut.pointInTriangle(r<i.y?n:o,r,i.x,i.y,r<i.y?o:n,r,s.x,s.y)&&((h=Math.abs(r-s.y)/(n-s.x))<c||h===c&&s.x>i.x)&&PIXI.EarCut.locallyInside(s,t)&&(i=s,c=h),s=s.next;return i},PIXI.EarCut.indexCurve=function(t,e,i,s){var n=t;do{null===n.z&&(n.z=PIXI.EarCut.zOrder(n.x,n.y,e,i,s)),n.prevZ=n.prev,n.nextZ=n.next,n=n.next}while(n!==t);n.prevZ.nextZ=null,n.prevZ=null,PIXI.EarCut.sortLinked(n)},PIXI.EarCut.sortLinked=function(t){var e,i,s,n,r,o,a,h,l=1;do{for(i=t,t=null,r=null,o=0;i;){for(o++,s=i,a=0,e=0;e<l&&(a++,s=s.nextZ);e++);for(h=l;a>0||h>0&&s;)0===a?(n=s,s=s.nextZ,h--):0!==h&&s?i.z<=s.z?(n=i,i=i.nextZ,a--):(n=s,s=s.nextZ,h--):(n=i,i=i.nextZ,a--),r?r.nextZ=n:t=n,n.prevZ=r,r=n;i=s}r.nextZ=null,l*=2}while(o>1);return t},PIXI.EarCut.zOrder=function(t,e,i,s,n){return t=32767*(t-i)/n,e=32767*(e-s)/n,t=16711935&(t|t<<8),t=252645135&(t|t<<4),t=858993459&(t|t<<2),t=1431655765&(t|t<<1),e=16711935&(e|e<<8),e=252645135&(e|e<<4),e=858993459&(e|e<<2),e=1431655765&(e|e<<1),t|e<<1},PIXI.EarCut.getLeftmost=function(t){var e=t,i=t;do{e.x<i.x&&(i=e),e=e.next}while(e!==t);return i},PIXI.EarCut.pointInTriangle=function(t,e,i,s,n,r,o,a){return(n-o)*(e-a)-(t-o)*(r-a)>=0&&(t-o)*(s-a)-(i-o)*(e-a)>=0&&(i-o)*(r-a)-(n-o)*(s-a)>=0},PIXI.EarCut.isValidDiagonal=function(t,e){return PIXI.EarCut.equals(t,e)||t.next.i!==e.i&&t.prev.i!==e.i&&!PIXI.EarCut.intersectsPolygon(t,e)&&PIXI.EarCut.locallyInside(t,e)&&PIXI.EarCut.locallyInside(e,t)&&PIXI.EarCut.middleInside(t,e)},PIXI.EarCut.area=function(t,e,i){return(e.y-t.y)*(i.x-e.x)-(e.x-t.x)*(i.y-e.y)},PIXI.EarCut.equals=function(t,e){return t.x===e.x&&t.y===e.y},PIXI.EarCut.intersects=function(t,e,i,s){return PIXI.EarCut.area(t,e,i)>0!=PIXI.EarCut.area(t,e,s)>0&&PIXI.EarCut.area(i,s,t)>0!=PIXI.EarCut.area(i,s,e)>0},PIXI.EarCut.intersectsPolygon=function(t,e){var i=t;do{if(i.i!==t.i&&i.next.i!==t.i&&i.i!==e.i&&i.next.i!==e.i&&PIXI.EarCut.intersects(i,i.next,t,e))return!0;i=i.next}while(i!==t);return!1},PIXI.EarCut.locallyInside=function(t,e){return PIXI.EarCut.area(t.prev,t,t.next)<0?PIXI.EarCut.area(t,e,t.next)>=0&&PIXI.EarCut.area(t,t.prev,e)>=0:PIXI.EarCut.area(t,e,t.prev)<0||PIXI.EarCut.area(t,t.next,e)<0},PIXI.EarCut.middleInside=function(t,e){var i=t,s=!1,n=(t.x+e.x)/2,r=(t.y+e.y)/2;do{i.y>r!=i.next.y>r&&n<(i.next.x-i.x)*(r-i.y)/(i.next.y-i.y)+i.x&&(s=!s),i=i.next}while(i!==t);return s},PIXI.EarCut.splitPolygon=function(t,e){var i=new PIXI.EarCut.Node(t.i,t.x,t.y),s=new PIXI.EarCut.Node(e.i,e.x,e.y),n=t.next,r=e.prev;return t.next=e,e.prev=t,i.next=n,n.prev=i,s.next=i,i.prev=s,r.next=s,s.prev=r,s},PIXI.EarCut.insertNode=function(t,e,i,s){var n=new PIXI.EarCut.Node(t,e,i);return s?(n.next=s.next,n.prev=s,s.next.prev=n,s.next=n):(n.prev=n,n.next=n),n},PIXI.EarCut.removeNode=function(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)},PIXI.EarCut.Node=function(t,e,i){this.i=t,this.x=e,this.y=i,this.prev=null,this.next=null,this.z=null,this.prevZ=null,this.nextZ=null,this.steiner=!1},PIXI.WebGLGraphics=function(){},PIXI.WebGLGraphics.stencilBufferLimit=6,PIXI.WebGLGraphics.renderGraphics=function(t,e){var i,s=e.gl,n=e.projection,r=e.offset,o=e.shaderManager.primitiveShader;t.dirty&&PIXI.WebGLGraphics.updateGraphics(t,s);for(var a=t._webGL[s.id],h=0;h<a.data.length;h++)1===a.data[h].mode?(i=a.data[h],e.stencilManager.pushStencil(t,i,e),s.drawElements(s.TRIANGLE_FAN,4,s.UNSIGNED_SHORT,2*(i.indices.length-4)),e.stencilManager.popStencil(t,i,e)):(i=a.data[h],e.shaderManager.setShader(o),o=e.shaderManager.primitiveShader,s.uniformMatrix3fv(o.translationMatrix,!1,t.worldTransform.toArray(!0)),s.uniform1f(o.flipY,1),s.uniform2f(o.projectionVector,n.x,-n.y),s.uniform2f(o.offsetVector,-r.x,-r.y),s.uniform3fv(o.tintColor,PIXI.hex2rgb(t.tint)),s.uniform1f(o.alpha,t.worldAlpha),s.bindBuffer(s.ARRAY_BUFFER,i.buffer),s.vertexAttribPointer(o.aVertexPosition,2,s.FLOAT,!1,24,0),s.vertexAttribPointer(o.colorAttribute,4,s.FLOAT,!1,24,8),s.bindBuffer(s.ELEMENT_ARRAY_BUFFER,i.indexBuffer),s.drawElements(s.TRIANGLE_STRIP,i.indices.length,s.UNSIGNED_SHORT,0))},PIXI.WebGLGraphics.updateGraphics=function(t,e){var i=t._webGL[e.id];i||(i=t._webGL[e.id]={lastIndex:0,data:[],gl:e}),t.dirty=!1;var s;if(t.clearDirty){for(t.clearDirty=!1,s=0;s<i.data.length;s++){var n=i.data[s];n.reset(),PIXI.WebGLGraphics.graphicsDataPool.push(n)}i.data=[],i.lastIndex=0}var r;for(s=i.lastIndex;s<t.graphicsData.length;s++){var o=t.graphicsData[s];if(o.type===PIXI.Graphics.POLY){if(o.points=o.shape.points.slice(),o.shape.closed&&(o.points[0]===o.points[o.points.length-2]&&o.points[1]===o.points[o.points.length-1]||o.points.push(o.points[0],o.points[1])),o.fill&&o.points.length>=PIXI.WebGLGraphics.stencilBufferLimit)if(o.points.length<2*PIXI.WebGLGraphics.stencilBufferLimit){r=PIXI.WebGLGraphics.switchMode(i,0);var a=PIXI.WebGLGraphics.buildPoly(o,r);a||(r=PIXI.WebGLGraphics.switchMode(i,1),PIXI.WebGLGraphics.buildComplexPoly(o,r))}else r=PIXI.WebGLGraphics.switchMode(i,1),PIXI.WebGLGraphics.buildComplexPoly(o,r);o.lineWidth>0&&(r=PIXI.WebGLGraphics.switchMode(i,0),PIXI.WebGLGraphics.buildLine(o,r))}else r=PIXI.WebGLGraphics.switchMode(i,0),o.type===PIXI.Graphics.RECT?PIXI.WebGLGraphics.buildRectangle(o,r):o.type===PIXI.Graphics.CIRC||o.type===PIXI.Graphics.ELIP?PIXI.WebGLGraphics.buildCircle(o,r):o.type===PIXI.Graphics.RREC&&PIXI.WebGLGraphics.buildRoundedRectangle(o,r);i.lastIndex++}for(s=0;s<i.data.length;s++)r=i.data[s],r.dirty&&r.upload()},PIXI.WebGLGraphics.switchMode=function(t,e){var i;return t.data.length?(i=t.data[t.data.length-1],i.mode===e&&1!==e||(i=PIXI.WebGLGraphics.graphicsDataPool.pop()||new PIXI.WebGLGraphicsData(t.gl),i.mode=e,t.data.push(i))):(i=PIXI.WebGLGraphics.graphicsDataPool.pop()||new PIXI.WebGLGraphicsData(t.gl),i.mode=e,t.data.push(i)),i.dirty=!0,i},PIXI.WebGLGraphics.buildRectangle=function(t,e){var i=t.shape,s=i.x,n=i.y,r=i.width,o=i.height;if(t.fill){var a=PIXI.hex2rgb(t.fillColor),h=t.fillAlpha,l=a[0]*h,c=a[1]*h,u=a[2]*h,d=e.points,p=e.indices,f=d.length/6;d.push(s,n),d.push(l,c,u,h),d.push(s+r,n),d.push(l,c,u,h),d.push(s,n+o),d.push(l,c,u,h),d.push(s+r,n+o),d.push(l,c,u,h),p.push(f,f,f+1,f+2,f+3,f+3)}if(t.lineWidth){var g=t.points;t.points=[s,n,s+r,n,s+r,n+o,s,n+o,s,n],PIXI.WebGLGraphics.buildLine(t,e),t.points=g}},PIXI.WebGLGraphics.buildRoundedRectangle=function(t,e){var i=t.shape,s=i.x,n=i.y,r=i.width,o=i.height,a=i.radius,h=[];if(h.push(s,n+a),h=h.concat(PIXI.WebGLGraphics.quadraticBezierCurve(s,n+o-a,s,n+o,s+a,n+o)),h=h.concat(PIXI.WebGLGraphics.quadraticBezierCurve(s+r-a,n+o,s+r,n+o,s+r,n+o-a)),h=h.concat(PIXI.WebGLGraphics.quadraticBezierCurve(s+r,n+a,s+r,n,s+r-a,n)),h=h.concat(PIXI.WebGLGraphics.quadraticBezierCurve(s+a,n,s,n,s,n+a)),t.fill){var l=PIXI.hex2rgb(t.fillColor),c=t.fillAlpha,u=l[0]*c,d=l[1]*c,p=l[2]*c,f=e.points,g=e.indices,m=f.length/6,y=PIXI.EarCut.Triangulate(h,null,2),v=0;for(v=0;v<y.length;v+=3)g.push(y[v]+m),g.push(y[v]+m),g.push(y[v+1]+m),g.push(y[v+2]+m),g.push(y[v+2]+m);for(v=0;v<h.length;v++)f.push(h[v],h[++v],u,d,p,c)}if(t.lineWidth){var b=t.points;t.points=h,PIXI.WebGLGraphics.buildLine(t,e),t.points=b}},PIXI.WebGLGraphics.quadraticBezierCurve=function(t,e,i,s,n,r){function o(t,e,i){return t+(e-t)*i}for(var a,h,l,c,u,d,p=[],f=0,g=0;g<=20;g++)f=g/20,a=o(t,i,f),h=o(e,s,f),l=o(i,n,f),c=o(s,r,f),u=o(a,l,f),d=o(h,c,f),p.push(u,d);return p},PIXI.WebGLGraphics.buildCircle=function(t,e){var i,s,n=t.shape,r=n.x,o=n.y;t.type===PIXI.Graphics.CIRC?(i=n.radius,s=n.radius):(i=n.width,s=n.height);var a=2*Math.PI/40,h=0;if(t.fill){var l=PIXI.hex2rgb(t.fillColor),c=t.fillAlpha,u=l[0]*c,d=l[1]*c,p=l[2]*c,f=e.points,g=e.indices,m=f.length/6;for(g.push(m),h=0;h<41;h++)f.push(r,o,u,d,p,c),f.push(r+Math.sin(a*h)*i,o+Math.cos(a*h)*s,u,d,p,c),g.push(m++,m++);g.push(m-1)}if(t.lineWidth){var y=t.points;for(t.points=[],h=0;h<41;h++)t.points.push(r+Math.sin(a*h)*i,o+Math.cos(a*h)*s);PIXI.WebGLGraphics.buildLine(t,e),t.points=y}},PIXI.WebGLGraphics.buildLine=function(t,e){var i=0,s=t.points;if(0!==s.length){if(t.lineWidth%2)for(i=0;i<s.length;i++)s[i]+=.5;var n=new PIXI.Point(s[0],s[1]),r=new PIXI.Point(s[s.length-2],s[s.length-1]);if(n.x===r.x&&n.y===r.y){s=s.slice(),s.pop(),s.pop(),r=new PIXI.Point(s[s.length-2],s[s.length-1]);var o=r.x+.5*(n.x-r.x),a=r.y+.5*(n.y-r.y);s.unshift(o,a),s.push(o,a)}var h,l,c,u,d,p,f,g,m,y,v,b,x,w,_,P,T,C,S,A,E,I,M,R=e.points,B=e.indices,L=s.length/2,k=s.length,O=R.length/6,F=t.lineWidth/2,D=PIXI.hex2rgb(t.lineColor),U=t.lineAlpha,G=D[0]*U,N=D[1]*U,X=D[2]*U;for(c=s[0],u=s[1],d=s[2],p=s[3],m=-(u-p),y=c-d,M=Math.sqrt(m*m+y*y),m/=M,y/=M,m*=F,y*=F,R.push(c-m,u-y,G,N,X,U),R.push(c+m,u+y,G,N,X,U),i=1;i<L-1;i++)c=s[2*(i-1)],u=s[2*(i-1)+1],d=s[2*i],p=s[2*i+1],f=s[2*(i+1)],g=s[2*(i+1)+1],m=-(u-p),y=c-d,M=Math.sqrt(m*m+y*y),m/=M,y/=M,m*=F,y*=F,v=-(p-g),b=d-f,M=Math.sqrt(v*v+b*b),v/=M,b/=M,v*=F,b*=F,_=-y+u-(-y+p),P=-m+d-(-m+c),T=(-m+c)*(-y+p)-(-m+d)*(-y+u),C=-b+g-(-b+p),S=-v+d-(-v+f),A=(-v+f)*(-b+p)-(-v+d)*(-b+g),E=_*S-C*P,Math.abs(E)<.1?(E+=10.1,R.push(d-m,p-y,G,N,X,U),R.push(d+m,p+y,G,N,X,U)):(h=(P*A-S*T)/E,l=(C*T-_*A)/E,I=(h-d)*(h-d)+(l-p)+(l-p),I>19600?(x=m-v,w=y-b,M=Math.sqrt(x*x+w*w),x/=M,w/=M,x*=F,w*=F,R.push(d-x,p-w),R.push(G,N,X,U),R.push(d+x,p+w),R.push(G,N,X,U),R.push(d-x,p-w),R.push(G,N,X,U),k++):(R.push(h,l),R.push(G,N,X,U),R.push(d-(h-d),p-(l-p)),R.push(G,N,X,U)));for(c=s[2*(L-2)],u=s[2*(L-2)+1],d=s[2*(L-1)],p=s[2*(L-1)+1],m=-(u-p),y=c-d,M=Math.sqrt(m*m+y*y),m/=M,y/=M,m*=F,y*=F,R.push(d-m,p-y),R.push(G,N,X,U),R.push(d+m,p+y),R.push(G,N,X,U),B.push(O),i=0;i<k;i++)B.push(O++);B.push(O-1)}},PIXI.WebGLGraphics.buildComplexPoly=function(t,e){var i=t.points.slice();if(!(i.length<6)){var s=e.indices;e.points=i,e.alpha=t.fillAlpha,e.color=PIXI.hex2rgb(t.fillColor);for(var n,r,o=1/0,a=-1/0,h=1/0,l=-1/0,c=0;c<i.length;c+=2)n=i[c],r=i[c+1],o=n<o?n:o,a=n>a?n:a,h=r<h?r:h,l=r>l?r:l;i.push(o,h,a,h,a,l,o,l);var u=i.length/2;for(c=0;c<u;c++)s.push(c)}},PIXI.WebGLGraphics.buildPoly=function(t,e){var i=t.points;if(!(i.length<6)){var s=e.points,n=e.indices,r=i.length/2,o=PIXI.hex2rgb(t.fillColor),a=t.fillAlpha,h=o[0]*a,l=o[1]*a,c=o[2]*a,u=PIXI.EarCut.Triangulate(i,null,2);if(!u)return!1;var d=s.length/6,p=0;for(p=0;p<u.length;p+=3)n.push(u[p]+d),n.push(u[p]+d),n.push(u[p+1]+d),n.push(u[p+2]+d),n.push(u[p+2]+d);for(p=0;p<r;p++)s.push(i[2*p],i[2*p+1],h,l,c,a);return!0}},PIXI.WebGLGraphics.graphicsDataPool=[],PIXI.WebGLGraphicsData=function(t){this.gl=t,this.color=[0,0,0],this.points=[],this.indices=[],this.buffer=t.createBuffer(),this.indexBuffer=t.createBuffer(),this.mode=1,this.alpha=1,this.dirty=!0},PIXI.WebGLGraphicsData.prototype.reset=function(){this.points=[],this.indices=[]},PIXI.WebGLGraphicsData.prototype.upload=function(){var t=this.gl;this.glPoints=new PIXI.Float32Array(this.points),t.bindBuffer(t.ARRAY_BUFFER,this.buffer),t.bufferData(t.ARRAY_BUFFER,this.glPoints,t.STATIC_DRAW),this.glIndicies=new PIXI.Uint16Array(this.indices),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,this.glIndicies,t.STATIC_DRAW),this.dirty=!1},PIXI.CanvasGraphics=function(){},PIXI.CanvasGraphics.renderGraphics=function(t,e){var i=t.worldAlpha;t.dirty&&(this.updateGraphicsTint(t),t.dirty=!1);for(var s=0;s<t.graphicsData.length;s++){var n=t.graphicsData[s],r=n.shape,o=n._fillTint,a=n._lineTint;if(e.lineWidth=n.lineWidth,n.type===PIXI.Graphics.POLY){e.beginPath();var h=r.points;e.moveTo(h[0],h[1]);for(var l=1;l<h.length/2;l++)e.lineTo(h[2*l],h[2*l+1]);r.closed&&e.lineTo(h[0],h[1]),h[0]===h[h.length-2]&&h[1]===h[h.length-1]&&e.closePath(),n.fill&&(e.globalAlpha=n.fillAlpha*i,e.fillStyle="#"+("00000"+(0|o).toString(16)).substr(-6),e.fill()),n.lineWidth&&(e.globalAlpha=n.lineAlpha*i,e.strokeStyle="#"+("00000"+(0|a).toString(16)).substr(-6),e.stroke())}else if(n.type===PIXI.Graphics.RECT)(n.fillColor||0===n.fillColor)&&(e.globalAlpha=n.fillAlpha*i,e.fillStyle="#"+("00000"+(0|o).toString(16)).substr(-6),e.fillRect(r.x,r.y,r.width,r.height)),n.lineWidth&&(e.globalAlpha=n.lineAlpha*i,e.strokeStyle="#"+("00000"+(0|a).toString(16)).substr(-6),e.strokeRect(r.x,r.y,r.width,r.height));else if(n.type===PIXI.Graphics.CIRC)e.beginPath(),e.arc(r.x,r.y,r.radius,0,2*Math.PI),e.closePath(),n.fill&&(e.globalAlpha=n.fillAlpha*i,e.fillStyle="#"+("00000"+(0|o).toString(16)).substr(-6),e.fill()),n.lineWidth&&(e.globalAlpha=n.lineAlpha*i,e.strokeStyle="#"+("00000"+(0|a).toString(16)).substr(-6),e.stroke());else if(n.type===PIXI.Graphics.ELIP){var c=2*r.width,u=2*r.height,d=r.x-c/2,p=r.y-u/2;e.beginPath();var f=c/2*.5522848,g=u/2*.5522848,m=d+c,y=p+u,v=d+c/2,b=p+u/2;e.moveTo(d,b),e.bezierCurveTo(d,b-g,v-f,p,v,p),e.bezierCurveTo(v+f,p,m,b-g,m,b),e.bezierCurveTo(m,b+g,v+f,y,v,y),e.bezierCurveTo(v-f,y,d,b+g,d,b),e.closePath(),n.fill&&(e.globalAlpha=n.fillAlpha*i,e.fillStyle="#"+("00000"+(0|o).toString(16)).substr(-6),e.fill()),n.lineWidth&&(e.globalAlpha=n.lineAlpha*i,e.strokeStyle="#"+("00000"+(0|a).toString(16)).substr(-6),e.stroke())}else if(n.type===PIXI.Graphics.RREC){var x=r.x,w=r.y,_=r.width,P=r.height,T=r.radius,C=Math.min(_,P)/2|0;T=T>C?C:T,e.beginPath(),e.moveTo(x,w+T),e.lineTo(x,w+P-T),e.quadraticCurveTo(x,w+P,x+T,w+P),e.lineTo(x+_-T,w+P),e.quadraticCurveTo(x+_,w+P,x+_,w+P-T),e.lineTo(x+_,w+T),e.quadraticCurveTo(x+_,w,x+_-T,w),e.lineTo(x+T,w),e.quadraticCurveTo(x,w,x,w+T),e.closePath(),(n.fillColor||0===n.fillColor)&&(e.globalAlpha=n.fillAlpha*i,e.fillStyle="#"+("00000"+(0|o).toString(16)).substr(-6),e.fill()),n.lineWidth&&(e.globalAlpha=n.lineAlpha*i,e.strokeStyle="#"+("00000"+(0|a).toString(16)).substr(-6),e.stroke())}}},PIXI.CanvasGraphics.renderGraphicsMask=function(t,e){var i=t.graphicsData.length;if(0!==i){e.beginPath();for(var s=0;s<i;s++){var n=t.graphicsData[s],r=n.shape;if(n.type===PIXI.Graphics.POLY){var o=r.points;e.moveTo(o[0],o[1]);for(var a=1;a<o.length/2;a++)e.lineTo(o[2*a],o[2*a+1]);o[0]===o[o.length-2]&&o[1]===o[o.length-1]&&e.closePath()}else if(n.type===PIXI.Graphics.RECT)e.rect(r.x,r.y,r.width,r.height),e.closePath();else if(n.type===PIXI.Graphics.CIRC)e.arc(r.x,r.y,r.radius,0,2*Math.PI),e.closePath();else if(n.type===PIXI.Graphics.ELIP){var h=2*r.width,l=2*r.height,c=r.x-h/2,u=r.y-l/2,d=h/2*.5522848,p=l/2*.5522848,f=c+h,g=u+l,m=c+h/2,y=u+l/2;e.moveTo(c,y),e.bezierCurveTo(c,y-p,m-d,u,m,u),e.bezierCurveTo(m+d,u,f,y-p,f,y),e.bezierCurveTo(f,y+p,m+d,g,m,g),e.bezierCurveTo(m-d,g,c,y+p,c,y),e.closePath()}else if(n.type===PIXI.Graphics.RREC){var v=r.x,b=r.y,x=r.width,w=r.height,_=r.radius,P=Math.min(x,w)/2|0;_=_>P?P:_,e.moveTo(v,b+_),e.lineTo(v,b+w-_),e.quadraticCurveTo(v,b+w,v+_,b+w),e.lineTo(v+x-_,b+w),e.quadraticCurveTo(v+x,b+w,v+x,b+w-_),e.lineTo(v+x,b+_),e.quadraticCurveTo(v+x,b,v+x-_,b),e.lineTo(v+_,b),e.quadraticCurveTo(v,b,v,b+_),e.closePath()}}}},PIXI.CanvasGraphics.updateGraphicsTint=function(t){if(16777215!==t.tint)for(var e=(t.tint>>16&255)/255,i=(t.tint>>8&255)/255,s=(255&t.tint)/255,n=0;n<t.graphicsData.length;n++){var r=t.graphicsData[n],o=0|r.fillColor,a=0|r.lineColor;r._fillTint=((o>>16&255)/255*e*255<<16)+((o>>8&255)/255*i*255<<8)+(255&o)/255*s*255,r._lineTint=((a>>16&255)/255*e*255<<16)+((a>>8&255)/255*i*255<<8)+(255&a)/255*s*255}},/**
<ide> * @author Richard Davey <[email protected]>
<ide> * @copyright 2016 Photon Storm Ltd.
<ide> * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
<ide> * @copyright 2016 Photon Storm Ltd.
<ide> * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
<ide> */
<del>return n.Math.degToRad=function(t){return t*h},n.Math.radToDeg=function(t){return t*l},n.RandomDataGenerator=function(t){void 0===t&&(t=[]),this.c=1,this.s0=0,this.s1=0,this.s2=0,"string"==typeof t?this.state(t):this.sow(t)},n.RandomDataGenerator.prototype={rnd:function(){var t=2091639*this.s0+2.3283064365386963e-10*this.c;return this.c=0|t,this.s0=this.s1,this.s1=this.s2,this.s2=t-this.c,this.s2},sow:function(t){if(this.s0=this.hash(" "),this.s1=this.hash(this.s0),this.s2=this.hash(this.s1),this.c=1,t)for(var e=0;e<t.length&&null!=t[e];e++){var i=t[e];this.s0-=this.hash(i),this.s0+=~~(this.s0<0),this.s1-=this.hash(i),this.s1+=~~(this.s1<0),this.s2-=this.hash(i),this.s2+=~~(this.s2<0)}},hash:function(t){var e,i,s;for(s=4022871197,t=t.toString(),i=0;i<t.length;i++)s+=t.charCodeAt(i),e=.02519603282416938*s,s=e>>>0,e-=s,e*=s,s=e>>>0,e-=s,s+=4294967296*e;return 2.3283064365386963e-10*(s>>>0)},integer:function(){return 4294967296*this.rnd.apply(this)},frac:function(){return this.rnd.apply(this)+1.1102230246251565e-16*(2097152*this.rnd.apply(this)|0)},real:function(){return this.integer()+this.frac()},integerInRange:function(t,e){return Math.floor(this.realInRange(0,e-t+1)+t)},between:function(t,e){return this.integerInRange(t,e)},realInRange:function(t,e){return this.frac()*(e-t)+t},normal:function(){return 1-2*this.frac()},uuid:function(){var t="",e="";for(e=t="";t++<36;e+=~t%5|3*t&4?(15^t?8^this.frac()*(20^t?16:4):4).toString(16):"-");return e},pick:function(t){return t[this.integerInRange(0,t.length-1)]},sign:function(){return this.pick([-1,1])},weightedPick:function(t){return t[~~(Math.pow(this.frac(),2)*(t.length-1)+.5)]},timestamp:function(t,e){return this.realInRange(t||9466848e5,e||1577862e6)},angle:function(){return this.integerInRange(-180,180)},state:function(t){return"string"==typeof t&&t.match(/^!rnd/)&&(t=t.split(","),this.c=parseFloat(t[1]),this.s0=parseFloat(t[2]),this.s1=parseFloat(t[3]),this.s2=parseFloat(t[4])),["!rnd",this.c,this.s0,this.s1,this.s2].join(",")}},n.RandomDataGenerator.prototype.constructor=n.RandomDataGenerator,n.QuadTree=function(t,e,i,s,n,r,o){this.maxObjects=10,this.maxLevels=4,this.level=0,this.bounds={},this.objects=[],this.nodes=[],this._empty=[],this.reset(t,e,i,s,n,r,o)},n.QuadTree.prototype={reset:function(t,e,i,s,n,r,o){this.maxObjects=n||10,this.maxLevels=r||4,this.level=o||0,this.bounds={x:Math.round(t),y:Math.round(e),width:i,height:s,subWidth:Math.floor(i/2),subHeight:Math.floor(s/2),right:Math.round(t)+Math.floor(i/2),bottom:Math.round(e)+Math.floor(s/2)},this.objects.length=0,this.nodes.length=0},populate:function(t){t.forEach(this.populateHandler,this,!0)},populateHandler:function(t){t.body&&t.exists&&this.insert(t.body)},split:function(){this.nodes[0]=new n.QuadTree(this.bounds.right,this.bounds.y,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[1]=new n.QuadTree(this.bounds.x,this.bounds.y,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[2]=new n.QuadTree(this.bounds.x,this.bounds.bottom,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[3]=new n.QuadTree(this.bounds.right,this.bounds.bottom,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1)},insert:function(t){var e,i=0;if(null!=this.nodes[0]&&-1!==(e=this.getIndex(t)))return void this.nodes[e].insert(t);if(this.objects.push(t),this.objects.length>this.maxObjects&&this.level<this.maxLevels)for(null==this.nodes[0]&&this.split();i<this.objects.length;)e=this.getIndex(this.objects[i]),-1!==e?this.nodes[e].insert(this.objects.splice(i,1)[0]):i++},getIndex:function(t){var e=-1;return t.x<this.bounds.right&&t.right<this.bounds.right?t.y<this.bounds.bottom&&t.bottom<this.bounds.bottom?e=1:t.y>this.bounds.bottom&&(e=2):t.x>this.bounds.right&&(t.y<this.bounds.bottom&&t.bottom<this.bounds.bottom?e=0:t.y>this.bounds.bottom&&(e=3)),e},retrieve:function(t){if(t instanceof n.Rectangle)var e=this.objects,i=this.getIndex(t);else{if(!t.body)return this._empty;var e=this.objects,i=this.getIndex(t.body)}return this.nodes[0]&&(-1!==i?e=e.concat(this.nodes[i].retrieve(t)):(e=e.concat(this.nodes[0].retrieve(t)),e=e.concat(this.nodes[1].retrieve(t)),e=e.concat(this.nodes[2].retrieve(t)),e=e.concat(this.nodes[3].retrieve(t)))),e},clear:function(){this.objects.length=0;for(var t=this.nodes.length;t--;)this.nodes[t].clear(),this.nodes.splice(t,1);this.nodes.length=0}},n.QuadTree.prototype.constructor=n.QuadTree,n.Net=function(t){this.game=t},n.Net.prototype={getHostName:function(){return window.location&&window.location.hostname?window.location.hostname:null},checkDomainName:function(t){return-1!==window.location.hostname.indexOf(t)},updateQueryString:function(t,e,i,s){void 0===i&&(i=!1),void 0!==s&&""!==s||(s=window.location.href);var n="",r=new RegExp("([?|&])"+t+"=.*?(&|#|$)(.*)","gi");if(r.test(s))n=void 0!==e&&null!==e?s.replace(r,"$1"+t+"="+e+"$2$3"):s.replace(r,"$1$3").replace(/(&|\?)$/,"");else if(void 0!==e&&null!==e){var o=-1!==s.indexOf("?")?"&":"?",a=s.split("#");s=a[0]+o+t+"="+e,a[1]&&(s+="#"+a[1]),n=s}else n=s;if(!i)return n;window.location.href=n},getQueryString:function(t){void 0===t&&(t="");var e={},i=location.search.substring(1).split("&");for(var s in i){var n=i[s].split("=");if(n.length>1){if(t&&t===this.decodeURI(n[0]))return this.decodeURI(n[1]);e[this.decodeURI(n[0])]=this.decodeURI(n[1])}}return e},decodeURI:function(t){return decodeURIComponent(t.replace(/\+/g," "))}},n.Net.prototype.constructor=n.Net,n.TweenManager=function(t){this.game=t,this.frameBased=!1,this._tweens=[],this._add=[],this.easeMap={Power0:n.Easing.Power0,Power1:n.Easing.Power1,Power2:n.Easing.Power2,Power3:n.Easing.Power3,Power4:n.Easing.Power4,Linear:n.Easing.Linear.None,Quad:n.Easing.Quadratic.Out,Cubic:n.Easing.Cubic.Out,Quart:n.Easing.Quartic.Out,Quint:n.Easing.Quintic.Out,Sine:n.Easing.Sinusoidal.Out,Expo:n.Easing.Exponential.Out,Circ:n.Easing.Circular.Out,Elastic:n.Easing.Elastic.Out,Back:n.Easing.Back.Out,Bounce:n.Easing.Bounce.Out,"Quad.easeIn":n.Easing.Quadratic.In,"Cubic.easeIn":n.Easing.Cubic.In,"Quart.easeIn":n.Easing.Quartic.In,"Quint.easeIn":n.Easing.Quintic.In,"Sine.easeIn":n.Easing.Sinusoidal.In,"Expo.easeIn":n.Easing.Exponential.In,"Circ.easeIn":n.Easing.Circular.In,"Elastic.easeIn":n.Easing.Elastic.In,"Back.easeIn":n.Easing.Back.In,"Bounce.easeIn":n.Easing.Bounce.In,"Quad.easeOut":n.Easing.Quadratic.Out,"Cubic.easeOut":n.Easing.Cubic.Out,"Quart.easeOut":n.Easing.Quartic.Out,"Quint.easeOut":n.Easing.Quintic.Out,"Sine.easeOut":n.Easing.Sinusoidal.Out,"Expo.easeOut":n.Easing.Exponential.Out,"Circ.easeOut":n.Easing.Circular.Out,"Elastic.easeOut":n.Easing.Elastic.Out,"Back.easeOut":n.Easing.Back.Out,"Bounce.easeOut":n.Easing.Bounce.Out,"Quad.easeInOut":n.Easing.Quadratic.InOut,"Cubic.easeInOut":n.Easing.Cubic.InOut,"Quart.easeInOut":n.Easing.Quartic.InOut,"Quint.easeInOut":n.Easing.Quintic.InOut,"Sine.easeInOut":n.Easing.Sinusoidal.InOut,"Expo.easeInOut":n.Easing.Exponential.InOut,"Circ.easeInOut":n.Easing.Circular.InOut,"Elastic.easeInOut":n.Easing.Elastic.InOut,"Back.easeInOut":n.Easing.Back.InOut,"Bounce.easeInOut":n.Easing.Bounce.InOut},this.game.onPause.add(this._pauseAll,this),this.game.onResume.add(this._resumeAll,this)},n.TweenManager.prototype={getAll:function(){return this._tweens},removeAll:function(){for(var t=0;t<this._tweens.length;t++)this._tweens[t].pendingDelete=!0;this._add=[]},removeFrom:function(t,e){void 0===e&&(e=!0);var i,s;if(Array.isArray(t))for(i=0,s=t.length;i<s;i++)this.removeFrom(t[i]);else if(t.type===n.GROUP&&e)for(var i=0,s=t.children.length;i<s;i++)this.removeFrom(t.children[i]);else{for(i=0,s=this._tweens.length;i<s;i++)t===this._tweens[i].target&&this.remove(this._tweens[i]);for(i=0,s=this._add.length;i<s;i++)t===this._add[i].target&&this.remove(this._add[i])}},add:function(t){t._manager=this,this._add.push(t)},create:function(t){return new n.Tween(t,this.game,this)},remove:function(t){var e=this._tweens.indexOf(t);-1!==e?this._tweens[e].pendingDelete=!0:-1!==(e=this._add.indexOf(t))&&(this._add[e].pendingDelete=!0)},update:function(){var t=this._add.length,e=this._tweens.length;if(0===e&&0===t)return!1;for(var i=0;i<e;)this._tweens[i].update(this.game.time.time)?i++:(this._tweens.splice(i,1),e--);return t>0&&(this._tweens=this._tweens.concat(this._add),this._add.length=0),!0},isTweening:function(t){return this._tweens.some(function(e){return e.target===t})},_pauseAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t]._pause()},_resumeAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t]._resume()},pauseAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t].pause()},resumeAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t].resume(!0)}},n.TweenManager.prototype.constructor=n.TweenManager,n.Tween=function(t,e,i){this.game=e,this.target=t,this.manager=i,this.timeline=[],this.reverse=!1,this.timeScale=1,this.repeatCounter=0,this.pendingDelete=!1,this.onStart=new n.Signal,this.onLoop=new n.Signal,this.onRepeat=new n.Signal,this.onChildComplete=new n.Signal,this.onComplete=new n.Signal,this.isRunning=!1,this.current=0,this.properties={},this.chainedTween=null,this.isPaused=!1,this.frameBased=i.frameBased,this._onUpdateCallback=null,this._onUpdateCallbackContext=null,this._pausedTime=0,this._codePaused=!1,this._hasStarted=!1},n.Tween.prototype={to:function(t,e,i,s,r,o,a){return(void 0===e||e<=0)&&(e=1e3),void 0!==i&&null!==i||(i=n.Easing.Default),void 0===s&&(s=!1),void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=!1),"string"==typeof i&&this.manager.easeMap[i]&&(i=this.manager.easeMap[i]),this.isRunning?(console.warn("Phaser.Tween.to cannot be called after Tween.start"),this):(this.timeline.push(new n.TweenData(this).to(t,e,i,r,o,a)),s&&this.start(),this)},from:function(t,e,i,s,r,o,a){return void 0===e&&(e=1e3),void 0!==i&&null!==i||(i=n.Easing.Default),void 0===s&&(s=!1),void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=!1),"string"==typeof i&&this.manager.easeMap[i]&&(i=this.manager.easeMap[i]),this.isRunning?(console.warn("Phaser.Tween.from cannot be called after Tween.start"),this):(this.timeline.push(new n.TweenData(this).from(t,e,i,r,o,a)),s&&this.start(),this)},start:function(t){if(void 0===t&&(t=0),null===this.game||null===this.target||0===this.timeline.length||this.isRunning)return this;for(var e=0;e<this.timeline.length;e++)for(var i in this.timeline[e].vEnd)this.properties[i]=this.target[i]||0,Array.isArray(this.properties[i])||(this.properties[i]*=1);for(var e=0;e<this.timeline.length;e++)this.timeline[e].loadValues();return this.manager.add(this),this.isRunning=!0,(t<0||t>this.timeline.length-1)&&(t=0),this.current=t,this.timeline[this.current].start(),this},stop:function(t){return void 0===t&&(t=!1),this.isRunning=!1,this._onUpdateCallback=null,this._onUpdateCallbackContext=null,t&&(this.onComplete.dispatch(this.target,this),this._hasStarted=!1,this.chainedTween&&this.chainedTween.start()),this.manager.remove(this),this},updateTweenData:function(t,e,i){if(0===this.timeline.length)return this;if(void 0===i&&(i=0),-1===i)for(var s=0;s<this.timeline.length;s++)this.timeline[s][t]=e;else this.timeline[i][t]=e;return this},delay:function(t,e){return this.updateTweenData("delay",t,e)},repeat:function(t,e,i){return void 0===e&&(e=0),this.updateTweenData("repeatCounter",t,i),this.updateTweenData("repeatDelay",e,i)},repeatDelay:function(t,e){return this.updateTweenData("repeatDelay",t,e)},yoyo:function(t,e,i){return void 0===e&&(e=0),this.updateTweenData("yoyo",t,i),this.updateTweenData("yoyoDelay",e,i)},yoyoDelay:function(t,e){return this.updateTweenData("yoyoDelay",t,e)},easing:function(t,e){return"string"==typeof t&&this.manager.easeMap[t]&&(t=this.manager.easeMap[t]),this.updateTweenData("easingFunction",t,e)},interpolation:function(t,e,i){return void 0===e&&(e=n.Math),this.updateTweenData("interpolationFunction",t,i),this.updateTweenData("interpolationContext",e,i)},repeatAll:function(t){return void 0===t&&(t=0),this.repeatCounter=t,this},chain:function(){for(var t=arguments.length;t--;)t>0?arguments[t-1].chainedTween=arguments[t]:this.chainedTween=arguments[t];return this},loop:function(t){return void 0===t&&(t=!0),this.repeatCounter=t?-1:0,this},onUpdateCallback:function(t,e){return this._onUpdateCallback=t,this._onUpdateCallbackContext=e,this},pause:function(){this.isPaused=!0,this._codePaused=!0,this._pausedTime=this.game.time.time},_pause:function(){this._codePaused||(this.isPaused=!0,this._pausedTime=this.game.time.time)},resume:function(){if(this.isPaused){this.isPaused=!1,this._codePaused=!1;for(var t=0;t<this.timeline.length;t++)this.timeline[t].isRunning||(this.timeline[t].startTime+=this.game.time.time-this._pausedTime)}},_resume:function(){this._codePaused||this.resume()},update:function(t){if(this.pendingDelete||!this.target)return!1;if(this.isPaused)return!0;var e=this.timeline[this.current].update(t);if(e===n.TweenData.PENDING)return!0;if(e===n.TweenData.RUNNING)return this._hasStarted||(this.onStart.dispatch(this.target,this),this._hasStarted=!0),null!==this._onUpdateCallback&&this._onUpdateCallback.call(this._onUpdateCallbackContext,this,this.timeline[this.current].value,this.timeline[this.current]),this.isRunning;if(e===n.TweenData.LOOPED)return-1===this.timeline[this.current].repeatCounter?this.onLoop.dispatch(this.target,this):this.onRepeat.dispatch(this.target,this),!0;if(e===n.TweenData.COMPLETE){var i=!1;return this.reverse?--this.current<0&&(this.current=this.timeline.length-1,i=!0):++this.current===this.timeline.length&&(this.current=0,i=!0),i?-1===this.repeatCounter?(this.timeline[this.current].start(),this.onLoop.dispatch(this.target,this),!0):this.repeatCounter>0?(this.repeatCounter--,this.timeline[this.current].start(),this.onRepeat.dispatch(this.target,this),!0):(this.isRunning=!1,this.onComplete.dispatch(this.target,this),this._hasStarted=!1,this.chainedTween&&this.chainedTween.start(),!1):(this.onChildComplete.dispatch(this.target,this),this.timeline[this.current].start(),!0)}},generateData:function(t,e){if(null===this.game||null===this.target)return null;void 0===t&&(t=60),void 0===e&&(e=[]);for(var i=0;i<this.timeline.length;i++)for(var s in this.timeline[i].vEnd)this.properties[s]=this.target[s]||0,Array.isArray(this.properties[s])||(this.properties[s]*=1);for(var i=0;i<this.timeline.length;i++)this.timeline[i].loadValues();for(var i=0;i<this.timeline.length;i++)e=e.concat(this.timeline[i].generateData(t));return e}},Object.defineProperty(n.Tween.prototype,"totalDuration",{get:function(){for(var t=0,e=0;e<this.timeline.length;e++)t+=this.timeline[e].duration;return t}}),n.Tween.prototype.constructor=n.Tween,n.TweenData=function(t){this.parent=t,this.game=t.game,this.vStart={},this.vStartCache={},this.vEnd={},this.vEndCache={},this.duration=1e3,this.percent=0,this.value=0,this.repeatCounter=0,this.repeatDelay=0,this.repeatTotal=0,this.interpolate=!1,this.yoyo=!1,this.yoyoDelay=0,this.inReverse=!1,this.delay=0,this.dt=0,this.startTime=null,this.easingFunction=n.Easing.Default,this.interpolationFunction=n.Math.linearInterpolation,this.interpolationContext=n.Math,this.isRunning=!1,this.isFrom=!1},n.TweenData.PENDING=0,n.TweenData.RUNNING=1,n.TweenData.LOOPED=2,n.TweenData.COMPLETE=3,n.TweenData.prototype={to:function(t,e,i,s,n,r){return this.vEnd=t,this.duration=e,this.easingFunction=i,this.delay=s,this.repeatTotal=n,this.yoyo=r,this.isFrom=!1,this},from:function(t,e,i,s,n,r){return this.vEnd=t,this.duration=e,this.easingFunction=i,this.delay=s,this.repeatTotal=n,this.yoyo=r,this.isFrom=!0,this},start:function(){if(this.startTime=this.game.time.time+this.delay,this.parent.reverse?this.dt=this.duration:this.dt=0,this.delay>0?this.isRunning=!1:this.isRunning=!0,this.isFrom)for(var t in this.vStartCache)this.vStart[t]=this.vEndCache[t],this.vEnd[t]=this.vStartCache[t],this.parent.target[t]=this.vStart[t];return this.value=0,this.yoyoCounter=0,this.repeatCounter=this.repeatTotal,this},loadValues:function(){for(var t in this.parent.properties){if(this.vStart[t]=this.parent.properties[t],Array.isArray(this.vEnd[t])){if(0===this.vEnd[t].length)continue;0===this.percent&&(this.vEnd[t]=[this.vStart[t]].concat(this.vEnd[t]))}void 0!==this.vEnd[t]?("string"==typeof this.vEnd[t]&&(this.vEnd[t]=this.vStart[t]+parseFloat(this.vEnd[t],10)),this.parent.properties[t]=this.vEnd[t]):this.vEnd[t]=this.vStart[t],this.vStartCache[t]=this.vStart[t],this.vEndCache[t]=this.vEnd[t]}return this},update:function(t){if(this.isRunning){if(t<this.startTime)return n.TweenData.RUNNING}else{if(!(t>=this.startTime))return n.TweenData.PENDING;this.isRunning=!0}var e=this.parent.frameBased?this.game.time.physicsElapsedMS:this.game.time.elapsedMS;this.parent.reverse?(this.dt-=e*this.parent.timeScale,this.dt=Math.max(this.dt,0)):(this.dt+=e*this.parent.timeScale,this.dt=Math.min(this.dt,this.duration)),this.percent=this.dt/this.duration,this.value=this.easingFunction(this.percent);for(var i in this.vEnd){var s=this.vStart[i],r=this.vEnd[i];Array.isArray(r)?this.parent.target[i]=this.interpolationFunction.call(this.interpolationContext,r,this.value):this.parent.target[i]=s+(r-s)*this.value}return!this.parent.reverse&&1===this.percent||this.parent.reverse&&0===this.percent?this.repeat():n.TweenData.RUNNING},generateData:function(t){this.parent.reverse?this.dt=this.duration:this.dt=0;var e=[],i=!1,s=1/t*1e3;do{this.parent.reverse?(this.dt-=s,this.dt=Math.max(this.dt,0)):(this.dt+=s,this.dt=Math.min(this.dt,this.duration)),this.percent=this.dt/this.duration,this.value=this.easingFunction(this.percent);var n={};for(var r in this.vEnd){var o=this.vStart[r],a=this.vEnd[r];Array.isArray(a)?n[r]=this.interpolationFunction(a,this.value):n[r]=o+(a-o)*this.value}e.push(n),(!this.parent.reverse&&1===this.percent||this.parent.reverse&&0===this.percent)&&(i=!0)}while(!i);if(this.yoyo){var h=e.slice();h.reverse(),e=e.concat(h)}return e},repeat:function(){if(this.yoyo){if(this.inReverse&&0===this.repeatCounter){for(var t in this.vStartCache)this.vStart[t]=this.vStartCache[t],this.vEnd[t]=this.vEndCache[t];return this.inReverse=!1,n.TweenData.COMPLETE}this.inReverse=!this.inReverse}else if(0===this.repeatCounter)return n.TweenData.COMPLETE;if(this.inReverse)for(var t in this.vStartCache)this.vStart[t]=this.vEndCache[t],this.vEnd[t]=this.vStartCache[t];else{for(var t in this.vStartCache)this.vStart[t]=this.vStartCache[t],this.vEnd[t]=this.vEndCache[t];this.repeatCounter>0&&this.repeatCounter--}return this.startTime=this.game.time.time,this.yoyo&&this.inReverse?this.startTime+=this.yoyoDelay:this.inReverse||(this.startTime+=this.repeatDelay),this.parent.reverse?this.dt=this.duration:this.dt=0,n.TweenData.LOOPED}},n.TweenData.prototype.constructor=n.TweenData,n.Easing={Linear:{None:function(t){return t}},Quadratic:{In:function(t){return t*t},Out:function(t){return t*(2-t)},InOut:function(t){return(t*=2)<1?.5*t*t:-.5*(--t*(t-2)-1)}},Cubic:{In:function(t){return t*t*t},Out:function(t){return--t*t*t+1},InOut:function(t){return(t*=2)<1?.5*t*t*t:.5*((t-=2)*t*t+2)}},Quartic:{In:function(t){return t*t*t*t},Out:function(t){return 1- --t*t*t*t},InOut:function(t){return(t*=2)<1?.5*t*t*t*t:-.5*((t-=2)*t*t*t-2)}},Quintic:{In:function(t){return t*t*t*t*t},Out:function(t){return--t*t*t*t*t+1},InOut:function(t){return(t*=2)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2)}},Sinusoidal:{In:function(t){return 0===t?0:1===t?1:1-Math.cos(t*Math.PI/2)},Out:function(t){return 0===t?0:1===t?1:Math.sin(t*Math.PI/2)},InOut:function(t){return 0===t?0:1===t?1:.5*(1-Math.cos(Math.PI*t))}},Exponential:{In:function(t){return 0===t?0:Math.pow(1024,t-1)},Out:function(t){return 1===t?1:1-Math.pow(2,-10*t)},InOut:function(t){return 0===t?0:1===t?1:(t*=2)<1?.5*Math.pow(1024,t-1):.5*(2-Math.pow(2,-10*(t-1)))}},Circular:{In:function(t){return 1-Math.sqrt(1-t*t)},Out:function(t){return Math.sqrt(1- --t*t)},InOut:function(t){return(t*=2)<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1)}},Elastic:{In:function(t){var e,i=.1;return 0===t?0:1===t?1:(!i||i<1?(i=1,e=.1):e=.4*Math.asin(1/i)/(2*Math.PI),-i*Math.pow(2,10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4))},Out:function(t){var e,i=.1;return 0===t?0:1===t?1:(!i||i<1?(i=1,e=.1):e=.4*Math.asin(1/i)/(2*Math.PI),i*Math.pow(2,-10*t)*Math.sin((t-e)*(2*Math.PI)/.4)+1)},InOut:function(t){var e,i=.1;return 0===t?0:1===t?1:(!i||i<1?(i=1,e=.1):e=.4*Math.asin(1/i)/(2*Math.PI),(t*=2)<1?i*Math.pow(2,10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4)*-.5:i*Math.pow(2,-10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4)*.5+1)}},Back:{In:function(t){var e=1.70158;return t*t*((e+1)*t-e)},Out:function(t){var e=1.70158;return--t*t*((e+1)*t+e)+1},InOut:function(t){var e=2.5949095;return(t*=2)<1?t*t*((e+1)*t-e)*.5:.5*((t-=2)*t*((e+1)*t+e)+2)}},Bounce:{In:function(t){return 1-n.Easing.Bounce.Out(1-t)},Out:function(t){return t<1/2.75?7.5625*t*t:t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375},InOut:function(t){return t<.5?.5*n.Easing.Bounce.In(2*t):.5*n.Easing.Bounce.Out(2*t-1)+.5}}},n.Easing.Default=n.Easing.Linear.None,n.Easing.Power0=n.Easing.Linear.None,n.Easing.Power1=n.Easing.Quadratic.Out,n.Easing.Power2=n.Easing.Cubic.Out,n.Easing.Power3=n.Easing.Quartic.Out,n.Easing.Power4=n.Easing.Quintic.Out,n.Time=function(t){this.game=t,this.time=0,this.prevTime=0,this.now=0,this.elapsed=0,this.elapsedMS=0,this.physicsElapsed=1/60,this.physicsElapsedMS=1/60*1e3,this.desiredFpsMult=1/60,this._desiredFps=60,this.suggestedFps=this.desiredFps,this.slowMotion=1,this.advancedTiming=!1,this.frames=0,this.fps=0,this.fpsMin=1e3,this.fpsMax=0,this.msMin=1e3,this.msMax=0,this.pauseDuration=0,this.timeToCall=0,this.timeExpected=0,this.events=new n.Timer(this.game,!1),this._frameCount=0,this._elapsedAccumulator=0,this._started=0,this._timeLastSecond=0,this._pauseStarted=0,this._justResumed=!1,this._timers=[]},n.Time.prototype={boot:function(){this._started=Date.now(),this.time=Date.now(),this.events.start(),this.timeExpected=this.time},add:function(t){return this._timers.push(t),t},create:function(t){void 0===t&&(t=!0);var e=new n.Timer(this.game,t);return this._timers.push(e),e},removeAll:function(){for(var t=0;t<this._timers.length;t++)this._timers[t].destroy();this._timers=[],this.events.removeAll()},refresh:function(){var t=this.time;this.time=Date.now(),this.elapsedMS=this.time-t},update:function(t){var e=this.time;this.time=Date.now(),this.elapsedMS=this.time-e,this.prevTime=this.now,this.now=t,this.elapsed=this.now-this.prevTime,this.game.raf._isSetTimeOut&&(this.timeToCall=Math.floor(Math.max(0,1e3/this._desiredFps-(this.timeExpected-t))),this.timeExpected=t+this.timeToCall),this.advancedTiming&&this.updateAdvancedTiming(),this.game.paused||(this.events.update(this.time),this._timers.length&&this.updateTimers())},updateTimers:function(){for(var t=0,e=this._timers.length;t<e;)this._timers[t].update(this.time)?t++:(this._timers.splice(t,1),e--)},updateAdvancedTiming:function(){this._frameCount++,this._elapsedAccumulator+=this.elapsed,this._frameCount>=2*this._desiredFps&&(this.suggestedFps=5*Math.floor(200/(this._elapsedAccumulator/this._frameCount)),this._frameCount=0,this._elapsedAccumulator=0),this.msMin=Math.min(this.msMin,this.elapsed),this.msMax=Math.max(this.msMax,this.elapsed),this.frames++,this.now>this._timeLastSecond+1e3&&(this.fps=Math.round(1e3*this.frames/(this.now-this._timeLastSecond)),this.fpsMin=Math.min(this.fpsMin,this.fps),this.fpsMax=Math.max(this.fpsMax,this.fps),this._timeLastSecond=this.now,this.frames=0)},gamePaused:function(){this._pauseStarted=Date.now(),this.events.pause();for(var t=this._timers.length;t--;)this._timers[t]._pause()},gameResumed:function(){this.time=Date.now(),this.pauseDuration=this.time-this._pauseStarted,this.events.resume();for(var t=this._timers.length;t--;)this._timers[t]._resume()},totalElapsedSeconds:function(){return.001*(this.time-this._started)},elapsedSince:function(t){return this.time-t},elapsedSecondsSince:function(t){return.001*(this.time-t)},reset:function(){this._started=this.time,this.removeAll()}},Object.defineProperty(n.Time.prototype,"desiredFps",{get:function(){return this._desiredFps},set:function(t){this._desiredFps=t,this.physicsElapsed=1/t,this.physicsElapsedMS=1e3*this.physicsElapsed,this.desiredFpsMult=1/t}}),n.Time.prototype.constructor=n.Time,n.Timer=function(t,e){void 0===e&&(e=!0),this.game=t,this.running=!1,this.autoDestroy=e,this.expired=!1,this.elapsed=0,this.events=[],this.onComplete=new n.Signal,this.nextTick=0,this.timeCap=1e3,this.paused=!1,this._codePaused=!1,this._started=0,this._pauseStarted=0,this._pauseTotal=0,this._now=Date.now(),this._len=0,this._marked=0,this._i=0,this._diff=0,this._newTick=0},n.Timer.MINUTE=6e4,n.Timer.SECOND=1e3,n.Timer.HALF=500,n.Timer.QUARTER=250,n.Timer.prototype={create:function(t,e,i,s,r,o){t=Math.round(t);var a=t;0===this._now?a+=this.game.time.time:a+=this._now;var h=new n.TimerEvent(this,t,a,i,e,s,r,o);return this.events.push(h),this.order(),this.expired=!1,h},add:function(t,e,i){return this.create(t,!1,0,e,i,Array.prototype.slice.call(arguments,3))},repeat:function(t,e,i,s){return this.create(t,!1,e,i,s,Array.prototype.slice.call(arguments,4))},loop:function(t,e,i){return this.create(t,!0,0,e,i,Array.prototype.slice.call(arguments,3))},start:function(t){if(!this.running){this._started=this.game.time.time+(t||0),this.running=!0;for(var e=0;e<this.events.length;e++)this.events[e].tick=this.events[e].delay+this._started}},stop:function(t){this.running=!1,void 0===t&&(t=!0),t&&(this.events.length=0)},remove:function(t){for(var e=0;e<this.events.length;e++)if(this.events[e]===t)return this.events[e].pendingDelete=!0,!0;return!1},order:function(){this.events.length>0&&(this.events.sort(this.sortHandler),this.nextTick=this.events[0].tick)},sortHandler:function(t,e){return t.tick<e.tick?-1:t.tick>e.tick?1:0},clearPendingEvents:function(){for(this._i=this.events.length;this._i--;)this.events[this._i].pendingDelete&&this.events.splice(this._i,1);this._len=this.events.length,this._i=0},update:function(t){if(this.paused)return!0;if(this.elapsed=t-this._now,this._now=t,this.elapsed>this.timeCap&&this.adjustEvents(t-this.elapsed),this._marked=0,this.clearPendingEvents(),this.running&&this._now>=this.nextTick&&this._len>0){for(;this._i<this._len&&this.running&&this._now>=this.events[this._i].tick&&!this.events[this._i].pendingDelete;)this._newTick=this._now+this.events[this._i].delay-(this._now-this.events[this._i].tick),this._newTick<0&&(this._newTick=this._now+this.events[this._i].delay),!0===this.events[this._i].loop?(this.events[this._i].tick=this._newTick,this.events[this._i].callback.apply(this.events[this._i].callbackContext,this.events[this._i].args)):this.events[this._i].repeatCount>0?(this.events[this._i].repeatCount--,this.events[this._i].tick=this._newTick,this.events[this._i].callback.apply(this.events[this._i].callbackContext,this.events[this._i].args)):(this._marked++,this.events[this._i].pendingDelete=!0,this.events[this._i].callback.apply(this.events[this._i].callbackContext,this.events[this._i].args)),this._i++;this.events.length>this._marked?this.order():(this.expired=!0,this.onComplete.dispatch(this))}return!this.expired||!this.autoDestroy},pause:function(){this.running&&(this._codePaused=!0,this.paused||(this._pauseStarted=this.game.time.time,this.paused=!0))},_pause:function(){!this.paused&&this.running&&(this._pauseStarted=this.game.time.time,this.paused=!0)},adjustEvents:function(t){for(var e=0;e<this.events.length;e++)if(!this.events[e].pendingDelete){var i=this.events[e].tick-t;i<0&&(i=0),this.events[e].tick=this._now+i}var s=this.nextTick-t;this.nextTick=s<0?this._now:this._now+s},resume:function(){if(this.paused){var t=this.game.time.time;this._pauseTotal+=t-this._now,this._now=t,this.adjustEvents(this._pauseStarted),this.paused=!1,this._codePaused=!1}},_resume:function(){this._codePaused||this.resume()},removeAll:function(){this.onComplete.removeAll(),this.events.length=0,this._len=0,this._i=0},destroy:function(){this.onComplete.removeAll(),this.running=!1,this.events=[],this._len=0,this._i=0}},Object.defineProperty(n.Timer.prototype,"next",{get:function(){return this.nextTick}}),Object.defineProperty(n.Timer.prototype,"duration",{get:function(){return this.running&&this.nextTick>this._now?this.nextTick-this._now:0}}),Object.defineProperty(n.Timer.prototype,"length",{get:function(){return this.events.length}}),Object.defineProperty(n.Timer.prototype,"ms",{get:function(){return this.running?this._now-this._started-this._pauseTotal:0}}),Object.defineProperty(n.Timer.prototype,"seconds",{get:function(){return this.running?.001*this.ms:0}}),n.Timer.prototype.constructor=n.Timer,n.TimerEvent=function(t,e,i,s,n,r,o,a){this.timer=t,this.delay=e,this.tick=i,this.repeatCount=s-1,this.loop=n,this.callback=r,this.callbackContext=o,this.args=a,this.pendingDelete=!1},n.TimerEvent.prototype.constructor=n.TimerEvent,n.AnimationManager=function(t){this.sprite=t,this.game=t.game,this.currentFrame=null,this.currentAnim=null,this.updateIfVisible=!0,this.isLoaded=!1,this._frameData=null,this._anims={},this._outputFrames=[]},n.AnimationManager.prototype={loadFrameData:function(t,e){if(void 0===t)return!1;if(this.isLoaded)for(var i in this._anims)this._anims[i].updateFrameData(t);return this._frameData=t,void 0===e||null===e?this.frame=0:"string"==typeof e?this.frameName=e:this.frame=e,this.isLoaded=!0,!0},copyFrameData:function(t,e){if(this._frameData=t.clone(),this.isLoaded)for(var i in this._anims)this._anims[i].updateFrameData(this._frameData);return void 0===e||null===e?this.frame=0:"string"==typeof e?this.frameName=e:this.frame=e,this.isLoaded=!0,!0},add:function(t,e,i,s,r){return e=e||[],i=i||60,void 0===s&&(s=!1),void 0===r&&(r=!(!e||"number"!=typeof e[0])),this._outputFrames=[],this._frameData.getFrameIndexes(e,r,this._outputFrames),this._anims[t]=new n.Animation(this.game,this.sprite,t,this._frameData,this._outputFrames,i,s),this.currentAnim=this._anims[t],this.sprite.tilingTexture&&(this.sprite.refreshTexture=!0),this._anims[t]},validateFrames:function(t,e){void 0===e&&(e=!0);for(var i=0;i<t.length;i++)if(!0===e){if(t[i]>this._frameData.total)return!1}else if(!1===this._frameData.checkFrameName(t[i]))return!1;return!0},play:function(t,e,i,s){if(this._anims[t])return this.currentAnim===this._anims[t]?!1===this.currentAnim.isPlaying?(this.currentAnim.paused=!1,this.currentAnim.play(e,i,s)):this.currentAnim:(this.currentAnim&&this.currentAnim.isPlaying&&this.currentAnim.stop(),this.currentAnim=this._anims[t],this.currentAnim.paused=!1,this.currentFrame=this.currentAnim.currentFrame,this.currentAnim.play(e,i,s))},stop:function(t,e){void 0===e&&(e=!1),!this.currentAnim||"string"==typeof t&&t!==this.currentAnim.name||this.currentAnim.stop(e)},update:function(){return!(this.updateIfVisible&&!this.sprite.visible)&&(!(!this.currentAnim||!this.currentAnim.update())&&(this.currentFrame=this.currentAnim.currentFrame,!0))},next:function(t){this.currentAnim&&(this.currentAnim.next(t),this.currentFrame=this.currentAnim.currentFrame)},previous:function(t){this.currentAnim&&(this.currentAnim.previous(t),this.currentFrame=this.currentAnim.currentFrame)},getAnimation:function(t){return"string"==typeof t&&this._anims[t]?this._anims[t]:null},refreshFrame:function(){},destroy:function(){var t=null;for(var t in this._anims)this._anims.hasOwnProperty(t)&&this._anims[t].destroy();this._anims={},this._outputFrames=[],this._frameData=null,this.currentAnim=null,this.currentFrame=null,this.sprite=null,this.game=null}},n.AnimationManager.prototype.constructor=n.AnimationManager,Object.defineProperty(n.AnimationManager.prototype,"frameData",{get:function(){return this._frameData}}),Object.defineProperty(n.AnimationManager.prototype,"frameTotal",{get:function(){return this._frameData.total}}),Object.defineProperty(n.AnimationManager.prototype,"paused",{get:function(){return this.currentAnim.isPaused},set:function(t){this.currentAnim.paused=t}}),Object.defineProperty(n.AnimationManager.prototype,"name",{get:function(){if(this.currentAnim)return this.currentAnim.name}}),Object.defineProperty(n.AnimationManager.prototype,"frame",{get:function(){if(this.currentFrame)return this.currentFrame.index},set:function(t){"number"==typeof t&&this._frameData&&null!==this._frameData.getFrame(t)&&(this.currentFrame=this._frameData.getFrame(t),this.currentFrame&&this.sprite.setFrame(this.currentFrame))}}),Object.defineProperty(n.AnimationManager.prototype,"frameName",{get:function(){if(this.currentFrame)return this.currentFrame.name},set:function(t){"string"==typeof t&&this._frameData&&null!==this._frameData.getFrameByName(t)?(this.currentFrame=this._frameData.getFrameByName(t),this.currentFrame&&(this._frameIndex=this.currentFrame.index,this.sprite.setFrame(this.currentFrame))):console.warn("Cannot set frameName: "+t)}}),n.Animation=function(t,e,i,s,r,o,a){void 0===a&&(a=!1),this.game=t,this._parent=e,this._frameData=s,this.name=i,this._frames=[],this._frames=this._frames.concat(r),this.delay=1e3/o,this.loop=a,this.loopCount=0,this.killOnComplete=!1,this.isFinished=!1,this.isPlaying=!1,this.isPaused=!1,this._pauseStartTime=0,this._frameIndex=0,this._frameDiff=0,this._frameSkip=1,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.onStart=new n.Signal,this.onUpdate=null,this.onComplete=new n.Signal,this.onLoop=new n.Signal,this.isReversed=!1,this.game.onPause.add(this.onPause,this),this.game.onResume.add(this.onResume,this)},n.Animation.prototype={play:function(t,e,i){return"number"==typeof t&&(this.delay=1e3/t),"boolean"==typeof e&&(this.loop=e),void 0!==i&&(this.killOnComplete=i),this.isPlaying=!0,this.isFinished=!1,this.paused=!1,this.loopCount=0,this._timeLastFrame=this.game.time.time,this._timeNextFrame=this.game.time.time+this.delay,this._frameIndex=this.isReversed?this._frames.length-1:0,this.updateCurrentFrame(!1,!0),this._parent.events.onAnimationStart$dispatch(this._parent,this),this.onStart.dispatch(this._parent,this),this._parent.animations.currentAnim=this,this._parent.animations.currentFrame=this.currentFrame,this},restart:function(){this.isPlaying=!0,this.isFinished=!1,this.paused=!1,this.loopCount=0,this._timeLastFrame=this.game.time.time,this._timeNextFrame=this.game.time.time+this.delay,this._frameIndex=0,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this._parent.setFrame(this.currentFrame),this._parent.animations.currentAnim=this,this._parent.animations.currentFrame=this.currentFrame,this.onStart.dispatch(this._parent,this)},reverse:function(){return this.reversed=!this.reversed,this},reverseOnce:function(){return this.onComplete.addOnce(this.reverse,this),this.reverse()},setFrame:function(t,e){var i;if(void 0===e&&(e=!1),"string"==typeof t)for(var s=0;s<this._frames.length;s++)this._frameData.getFrame(this._frames[s]).name===t&&(i=s);else if("number"==typeof t)if(e)i=t;else for(var s=0;s<this._frames.length;s++)this._frames[s]===t&&(i=s);i&&(this._frameIndex=i-1,this._timeNextFrame=this.game.time.time,this.update())},stop:function(t,e){void 0===t&&(t=!1),void 0===e&&(e=!1),this.isPlaying=!1,this.isFinished=!0,this.paused=!1,t&&(this.currentFrame=this._frameData.getFrame(this._frames[0]),this._parent.setFrame(this.currentFrame)),e&&(this._parent.events.onAnimationComplete$dispatch(this._parent,this),this.onComplete.dispatch(this._parent,this))},onPause:function(){this.isPlaying&&(this._frameDiff=this._timeNextFrame-this.game.time.time)},onResume:function(){this.isPlaying&&(this._timeNextFrame=this.game.time.time+this._frameDiff)},update:function(){return!this.isPaused&&(!!(this.isPlaying&&this.game.time.time>=this._timeNextFrame)&&(this._frameSkip=1,this._frameDiff=this.game.time.time-this._timeNextFrame,this._timeLastFrame=this.game.time.time,this._frameDiff>this.delay&&(this._frameSkip=Math.floor(this._frameDiff/this.delay),this._frameDiff-=this._frameSkip*this.delay),this._timeNextFrame=this.game.time.time+(this.delay-this._frameDiff),this.isReversed?this._frameIndex-=this._frameSkip:this._frameIndex+=this._frameSkip,!this.isReversed&&this._frameIndex>=this._frames.length||this.isReversed&&this._frameIndex<=-1?this.loop?(this._frameIndex=Math.abs(this._frameIndex)%this._frames.length,this.isReversed&&(this._frameIndex=this._frames.length-1-this._frameIndex),this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.currentFrame&&this._parent.setFrame(this.currentFrame),this.loopCount++,this._parent.events.onAnimationLoop$dispatch(this._parent,this),this.onLoop.dispatch(this._parent,this),!this.onUpdate||(this.onUpdate.dispatch(this,this.currentFrame),!!this._frameData)):(this.complete(),!1):this.updateCurrentFrame(!0)))},updateCurrentFrame:function(t,e){if(void 0===e&&(e=!1),!this._frameData)return!1;var i=this.currentFrame.index;return this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.currentFrame&&(e||!e&&i!==this.currentFrame.index)&&this._parent.setFrame(this.currentFrame),!this.onUpdate||!t||(this.onUpdate.dispatch(this,this.currentFrame),!!this._frameData)},next:function(t){void 0===t&&(t=1);var e=this._frameIndex+t;e>=this._frames.length&&(this.loop?e%=this._frames.length:e=this._frames.length-1),e!==this._frameIndex&&(this._frameIndex=e,this.updateCurrentFrame(!0))},previous:function(t){void 0===t&&(t=1);var e=this._frameIndex-t;e<0&&(this.loop?e=this._frames.length+e:e++),e!==this._frameIndex&&(this._frameIndex=e,this.updateCurrentFrame(!0))},updateFrameData:function(t){this._frameData=t,this.currentFrame=this._frameData?this._frameData.getFrame(this._frames[this._frameIndex%this._frames.length]):null},destroy:function(){this._frameData&&(this.game.onPause.remove(this.onPause,this),this.game.onResume.remove(this.onResume,this),this.game=null,this._parent=null,this._frames=null,this._frameData=null,this.currentFrame=null,this.isPlaying=!1,this.onStart.dispose(),this.onLoop.dispose(),this.onComplete.dispose(),this.onUpdate&&this.onUpdate.dispose())},complete:function(){this._frameIndex=this._frames.length-1,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.isPlaying=!1,this.isFinished=!0,this.paused=!1,this._parent.events.onAnimationComplete$dispatch(this._parent,this),this.onComplete.dispatch(this._parent,this),this.killOnComplete&&this._parent.kill()}},n.Animation.prototype.constructor=n.Animation,Object.defineProperty(n.Animation.prototype,"paused",{get:function(){return this.isPaused},set:function(t){this.isPaused=t,t?this._pauseStartTime=this.game.time.time:this.isPlaying&&(this._timeNextFrame=this.game.time.time+this.delay)}}),Object.defineProperty(n.Animation.prototype,"reversed",{get:function(){return this.isReversed},set:function(t){this.isReversed=t}}),Object.defineProperty(n.Animation.prototype,"frameTotal",{get:function(){return this._frames.length}}),Object.defineProperty(n.Animation.prototype,"frame",{get:function(){return null!==this.currentFrame?this.currentFrame.index:this._frameIndex},set:function(t){this.currentFrame=this._frameData.getFrame(this._frames[t]),null!==this.currentFrame&&(this._frameIndex=t,this._parent.setFrame(this.currentFrame),this.onUpdate&&this.onUpdate.dispatch(this,this.currentFrame))}}),Object.defineProperty(n.Animation.prototype,"speed",{get:function(){return 1e3/this.delay},set:function(t){t>0&&(this.delay=1e3/t)}}),Object.defineProperty(n.Animation.prototype,"enableUpdate",{get:function(){return null!==this.onUpdate},set:function(t){t&&null===this.onUpdate?this.onUpdate=new n.Signal:t||null===this.onUpdate||(this.onUpdate.dispose(),this.onUpdate=null)}}),n.Animation.generateFrameNames=function(t,e,i,s,r){void 0===s&&(s="");var o=[],a="";if(e<i)for(var h=e;h<=i;h++)a="number"==typeof r?n.Utils.pad(h.toString(),r,"0",1):h.toString(),a=t+a+s,o.push(a);else for(var h=e;h>=i;h--)a="number"==typeof r?n.Utils.pad(h.toString(),r,"0",1):h.toString(),a=t+a+s,o.push(a);return o},n.Frame=function(t,e,i,s,r,o){this.index=t,this.x=e,this.y=i,this.width=s,this.height=r,this.name=o,this.centerX=Math.floor(s/2),this.centerY=Math.floor(r/2),this.distance=n.Math.distance(0,0,s,r),this.rotated=!1,this.rotationDirection="cw",this.trimmed=!1,this.sourceSizeW=s,this.sourceSizeH=r,this.spriteSourceSizeX=0,this.spriteSourceSizeY=0,this.spriteSourceSizeW=0,this.spriteSourceSizeH=0,this.right=this.x+this.width,this.bottom=this.y+this.height},n.Frame.prototype={resize:function(t,e){this.width=t,this.height=e,this.centerX=Math.floor(t/2),this.centerY=Math.floor(e/2),this.distance=n.Math.distance(0,0,t,e),this.sourceSizeW=t,this.sourceSizeH=e,this.right=this.x+t,this.bottom=this.y+e},setTrim:function(t,e,i,s,n,r,o){this.trimmed=t,t&&(this.sourceSizeW=e,this.sourceSizeH=i,this.centerX=Math.floor(e/2),this.centerY=Math.floor(i/2),this.spriteSourceSizeX=s,this.spriteSourceSizeY=n,this.spriteSourceSizeW=r,this.spriteSourceSizeH=o)},clone:function(){var t=new n.Frame(this.index,this.x,this.y,this.width,this.height,this.name);for(var e in this)this.hasOwnProperty(e)&&(t[e]=this[e]);return t},getRect:function(t){return void 0===t?t=new n.Rectangle(this.x,this.y,this.width,this.height):t.setTo(this.x,this.y,this.width,this.height),t}},n.Frame.prototype.constructor=n.Frame,n.FrameData=function(){this._frames=[],this._frameNames=[]},n.FrameData.prototype={addFrame:function(t){return t.index=this._frames.length,this._frames.push(t),""!==t.name&&(this._frameNames[t.name]=t.index),t},getFrame:function(t){return t>=this._frames.length&&(t=0),this._frames[t]},getFrameByName:function(t){return"number"==typeof this._frameNames[t]?this._frames[this._frameNames[t]]:null},checkFrameName:function(t){return null!=this._frameNames[t]},clone:function(){for(var t=new n.FrameData,e=0;e<this._frames.length;e++)t._frames.push(this._frames[e].clone());for(var i in this._frameNames)this._frameNames.hasOwnProperty(i)&&t._frameNames.push(this._frameNames[i]);return t},getFrameRange:function(t,e,i){void 0===i&&(i=[]);for(var s=t;s<=e;s++)i.push(this._frames[s]);return i},getFrames:function(t,e,i){if(void 0===e&&(e=!0),void 0===i&&(i=[]),void 0===t||0===t.length)for(var s=0;s<this._frames.length;s++)i.push(this._frames[s]);else for(var s=0;s<t.length;s++)e?i.push(this.getFrame(t[s])):i.push(this.getFrameByName(t[s]));return i},getFrameIndexes:function(t,e,i){if(void 0===e&&(e=!0),void 0===i&&(i=[]),void 0===t||0===t.length)for(var s=0;s<this._frames.length;s++)i.push(this._frames[s].index);else for(var s=0;s<t.length;s++)e&&this._frames[t[s]]?i.push(this._frames[t[s]].index):this.getFrameByName(t[s])&&i.push(this.getFrameByName(t[s]).index);return i},destroy:function(){this._frames=null,this._frameNames=null}},n.FrameData.prototype.constructor=n.FrameData,Object.defineProperty(n.FrameData.prototype,"total",{get:function(){return this._frames.length}}),n.AnimationParser={spriteSheet:function(t,e,i,s,r,o,a){var h=e;if("string"==typeof e&&(h=t.cache.getImage(e)),null===h)return null;var l=h.width,c=h.height;i<=0&&(i=Math.floor(-l/Math.min(-1,i))),s<=0&&(s=Math.floor(-c/Math.min(-1,s)));var u=Math.floor((l-o)/(i+a)),d=Math.floor((c-o)/(s+a)),p=u*d;if(-1!==r&&(p=r),0===l||0===c||l<i||c<s||0===p)return console.warn("Phaser.AnimationParser.spriteSheet: '"+e+"'s width/height zero or width/height < given frameWidth/frameHeight"),null;for(var f=new n.FrameData,g=o,m=o,y=0;y<p;y++)f.addFrame(new n.Frame(y,g,m,i,s,"")),(g+=i+a)+i>l&&(g=o,m+=s+a);return f},JSONData:function(t,e){if(!e.frames)return console.warn("Phaser.AnimationParser.JSONData: Invalid Texture Atlas JSON given, missing 'frames' array"),void console.log(e);for(var i,s=new n.FrameData,r=e.frames,o=0;o<r.length;o++)i=s.addFrame(new n.Frame(o,r[o].frame.x,r[o].frame.y,r[o].frame.w,r[o].frame.h,r[o].filename)),r[o].trimmed&&i.setTrim(r[o].trimmed,r[o].sourceSize.w,r[o].sourceSize.h,r[o].spriteSourceSize.x,r[o].spriteSourceSize.y,r[o].spriteSourceSize.w,r[o].spriteSourceSize.h);return s},JSONDataPyxel:function(t,e){if(["layers","tilewidth","tileheight","tileswide","tileshigh"].forEach(function(t){if(!e[t])return console.warn('Phaser.AnimationParser.JSONDataPyxel: Invalid Pyxel Tilemap JSON given, missing "'+t+'" key.'),void console.log(e)}),1!==e.layers.length)return console.warn("Phaser.AnimationParser.JSONDataPyxel: Too many layers, this parser only supports flat Tilemaps."),void console.log(e);for(var i,s=new n.FrameData,r=e.tileheight,o=e.tilewidth,a=e.layers[0].tiles,h=0;h<a.length;h++)i=s.addFrame(new n.Frame(h,a[h].x,a[h].y,o,r,"frame_"+h)),i.setTrim(!1);return s},JSONDataHash:function(t,e){if(!e.frames)return console.warn("Phaser.AnimationParser.JSONDataHash: Invalid Texture Atlas JSON given, missing 'frames' object"),void console.log(e);var i,s=new n.FrameData,r=e.frames,o=0;for(var a in r)i=s.addFrame(new n.Frame(o,r[a].frame.x,r[a].frame.y,r[a].frame.w,r[a].frame.h,a)),r[a].trimmed&&i.setTrim(r[a].trimmed,r[a].sourceSize.w,r[a].sourceSize.h,r[a].spriteSourceSize.x,r[a].spriteSourceSize.y,r[a].spriteSourceSize.w,r[a].spriteSourceSize.h),o++;return s},XMLData:function(t,e){if(!e.getElementsByTagName("TextureAtlas"))return void console.warn("Phaser.AnimationParser.XMLData: Invalid Texture Atlas XML given, missing <TextureAtlas> tag");for(var i,s,r,o,a,h,l,c,u,d,p,f=new n.FrameData,g=e.getElementsByTagName("SubTexture"),m=0;m<g.length;m++)r=g[m].attributes,s=r.name.value,o=parseInt(r.x.value,10),a=parseInt(r.y.value,10),h=parseInt(r.width.value,10),l=parseInt(r.height.value,10),c=null,u=null,r.frameX&&(c=Math.abs(parseInt(r.frameX.value,10)),u=Math.abs(parseInt(r.frameY.value,10)),d=parseInt(r.frameWidth.value,10),p=parseInt(r.frameHeight.value,10)),i=f.addFrame(new n.Frame(m,o,a,h,l,s)),null===c&&null===u||i.setTrim(!0,h,l,c,u,d,p);return f}},n.Cache=function(t){this.game=t,this.autoResolveURL=!1,this._cache={canvas:{},image:{},texture:{},sound:{},video:{},text:{},json:{},xml:{},physics:{},tilemap:{},binary:{},bitmapData:{},bitmapFont:{},shader:{},renderTexture:{}},this._urlMap={},this._urlResolver=new Image,this._urlTemp=null,this.onSoundUnlock=new n.Signal,this._cacheMap=[],this._cacheMap[n.Cache.CANVAS]=this._cache.canvas,this._cacheMap[n.Cache.IMAGE]=this._cache.image,this._cacheMap[n.Cache.TEXTURE]=this._cache.texture,this._cacheMap[n.Cache.SOUND]=this._cache.sound,this._cacheMap[n.Cache.TEXT]=this._cache.text,this._cacheMap[n.Cache.PHYSICS]=this._cache.physics,this._cacheMap[n.Cache.TILEMAP]=this._cache.tilemap,this._cacheMap[n.Cache.BINARY]=this._cache.binary,this._cacheMap[n.Cache.BITMAPDATA]=this._cache.bitmapData,this._cacheMap[n.Cache.BITMAPFONT]=this._cache.bitmapFont,this._cacheMap[n.Cache.JSON]=this._cache.json,this._cacheMap[n.Cache.XML]=this._cache.xml,this._cacheMap[n.Cache.VIDEO]=this._cache.video,this._cacheMap[n.Cache.SHADER]=this._cache.shader,this._cacheMap[n.Cache.RENDER_TEXTURE]=this._cache.renderTexture,this.addDefaultImage(),this.addMissingImage()},n.Cache.CANVAS=1,n.Cache.IMAGE=2,n.Cache.TEXTURE=3,n.Cache.SOUND=4,n.Cache.TEXT=5,n.Cache.PHYSICS=6,n.Cache.TILEMAP=7,n.Cache.BINARY=8,n.Cache.BITMAPDATA=9,n.Cache.BITMAPFONT=10,n.Cache.JSON=11,n.Cache.XML=12,n.Cache.VIDEO=13,n.Cache.SHADER=14,n.Cache.RENDER_TEXTURE=15,n.Cache.DEFAULT=null,n.Cache.MISSING=null,n.Cache.prototype={addCanvas:function(t,e,i){void 0===i&&(i=e.getContext("2d")),this._cache.canvas[t]={canvas:e,context:i}},addImage:function(t,e,i){this.checkImageKey(t)&&this.removeImage(t);var s={key:t,url:e,data:i,base:new PIXI.BaseTexture(i),frame:new n.Frame(0,0,0,i.width,i.height,t),frameData:new n.FrameData};return s.frameData.addFrame(new n.Frame(0,0,0,i.width,i.height,e)),this._cache.image[t]=s,this._resolveURL(e,s),"__default"===t?n.Cache.DEFAULT=new PIXI.Texture(s.base):"__missing"===t&&(n.Cache.MISSING=new PIXI.Texture(s.base)),s},addDefaultImage:function(){var t=new Image;t.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgAQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg==";var e=this.addImage("__default",null,t);e.base.skipRender=!0,n.Cache.DEFAULT=new PIXI.Texture(e.base)},addMissingImage:function(){var t=new Image;t.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg==";var e=this.addImage("__missing",null,t);n.Cache.MISSING=new PIXI.Texture(e.base)},addSound:function(t,e,i,s,n){void 0===s&&(s=!0,n=!1),void 0===n&&(s=!1,n=!0);var r=!1;n&&(r=!0),this._cache.sound[t]={url:e,data:i,isDecoding:!1,decoded:r,webAudio:s,audioTag:n,locked:this.game.sound.touchLocked},this._resolveURL(e,this._cache.sound[t])},addText:function(t,e,i){this._cache.text[t]={url:e,data:i},this._resolveURL(e,this._cache.text[t])},addPhysicsData:function(t,e,i,s){this._cache.physics[t]={url:e,data:i,format:s},this._resolveURL(e,this._cache.physics[t])},addTilemap:function(t,e,i,s){this._cache.tilemap[t]={url:e,data:i,format:s},this._resolveURL(e,this._cache.tilemap[t])},addBinary:function(t,e){this._cache.binary[t]=e},addBitmapData:function(t,e,i){return e.key=t,void 0===i&&(i=new n.FrameData,i.addFrame(e.textureFrame)),this._cache.bitmapData[t]={data:e,frameData:i},e},addBitmapFont:function(t,e,i,s,r,o,a){var h={url:e,data:i,font:null,base:new PIXI.BaseTexture(i)};void 0===o&&(o=0),void 0===a&&(a=0),h.font="json"===r?n.LoaderParser.jsonBitmapFont(s,h.base,o,a):n.LoaderParser.xmlBitmapFont(s,h.base,o,a),this._cache.bitmapFont[t]=h,this._resolveURL(e,h)},addJSON:function(t,e,i){this._cache.json[t]={url:e,data:i},this._resolveURL(e,this._cache.json[t])},addXML:function(t,e,i){this._cache.xml[t]={url:e,data:i},this._resolveURL(e,this._cache.xml[t])},addVideo:function(t,e,i,s){this._cache.video[t]={url:e,data:i,isBlob:s,locked:!0},this._resolveURL(e,this._cache.video[t])},addShader:function(t,e,i){this._cache.shader[t]={url:e,data:i},this._resolveURL(e,this._cache.shader[t])},addRenderTexture:function(t,e){this._cache.renderTexture[t]={texture:e,frame:new n.Frame(0,0,0,e.width,e.height,"","")}},addSpriteSheet:function(t,e,i,s,r,o,a,h){void 0===o&&(o=-1),void 0===a&&(a=0),void 0===h&&(h=0);var l={key:t,url:e,data:i,frameWidth:s,frameHeight:r,margin:a,spacing:h,base:new PIXI.BaseTexture(i),frameData:n.AnimationParser.spriteSheet(this.game,i,s,r,o,a,h)};this._cache.image[t]=l,this._resolveURL(e,l)},addTextureAtlas:function(t,e,i,s,r){var o={key:t,url:e,data:i,base:new PIXI.BaseTexture(i)};r===n.Loader.TEXTURE_ATLAS_XML_STARLING?o.frameData=n.AnimationParser.XMLData(this.game,s,t):r===n.Loader.TEXTURE_ATLAS_JSON_PYXEL?o.frameData=n.AnimationParser.JSONDataPyxel(this.game,s,t):Array.isArray(s.frames)?o.frameData=n.AnimationParser.JSONData(this.game,s,t):o.frameData=n.AnimationParser.JSONDataHash(this.game,s,t),this._cache.image[t]=o,this._resolveURL(e,o)},reloadSound:function(t){var e=this,i=this.getSound(t);i&&(i.data.src=i.url,i.data.addEventListener("canplaythrough",function(){return e.reloadSoundComplete(t)},!1),i.data.load())},reloadSoundComplete:function(t){var e=this.getSound(t);e&&(e.locked=!1,this.onSoundUnlock.dispatch(t))},updateSound:function(t,e,i){var s=this.getSound(t);s&&(s[e]=i)},decodedSound:function(t,e){var i=this.getSound(t);i.data=e,i.decoded=!0,i.isDecoding=!1},isSoundDecoded:function(t){var e=this.getItem(t,n.Cache.SOUND,"isSoundDecoded");if(e)return e.decoded},isSoundReady:function(t){var e=this.getItem(t,n.Cache.SOUND,"isSoundDecoded");if(e)return e.decoded&&!this.game.sound.touchLocked},checkKey:function(t,e){return!!this._cacheMap[t][e]},checkURL:function(t){return!!this._urlMap[this._resolveURL(t)]},checkCanvasKey:function(t){return this.checkKey(n.Cache.CANVAS,t)},checkImageKey:function(t){return this.checkKey(n.Cache.IMAGE,t)},checkTextureKey:function(t){return this.checkKey(n.Cache.TEXTURE,t)},checkSoundKey:function(t){return this.checkKey(n.Cache.SOUND,t)},checkTextKey:function(t){return this.checkKey(n.Cache.TEXT,t)},checkPhysicsKey:function(t){return this.checkKey(n.Cache.PHYSICS,t)},checkTilemapKey:function(t){return this.checkKey(n.Cache.TILEMAP,t)},checkBinaryKey:function(t){return this.checkKey(n.Cache.BINARY,t)},checkBitmapDataKey:function(t){return this.checkKey(n.Cache.BITMAPDATA,t)},checkBitmapFontKey:function(t){return this.checkKey(n.Cache.BITMAPFONT,t)},checkJSONKey:function(t){return this.checkKey(n.Cache.JSON,t)},checkXMLKey:function(t){return this.checkKey(n.Cache.XML,t)},checkVideoKey:function(t){return this.checkKey(n.Cache.VIDEO,t)},checkShaderKey:function(t){return this.checkKey(n.Cache.SHADER,t)},checkRenderTextureKey:function(t){return this.checkKey(n.Cache.RENDER_TEXTURE,t)},getItem:function(t,e,i,s){return this.checkKey(e,t)?void 0===s?this._cacheMap[e][t]:this._cacheMap[e][t][s]:(i&&console.warn("Phaser.Cache."+i+': Key "'+t+'" not found in Cache.'),null)},getCanvas:function(t){return this.getItem(t,n.Cache.CANVAS,"getCanvas","canvas")},getImage:function(t,e){void 0!==t&&null!==t||(t="__default"),void 0===e&&(e=!1);var i=this.getItem(t,n.Cache.IMAGE,"getImage");return null===i&&(i=this.getItem("__missing",n.Cache.IMAGE,"getImage")),e?i:i.data},getTextureFrame:function(t){return this.getItem(t,n.Cache.TEXTURE,"getTextureFrame","frame")},getSound:function(t){return this.getItem(t,n.Cache.SOUND,"getSound")},getSoundData:function(t){return this.getItem(t,n.Cache.SOUND,"getSoundData","data")},getText:function(t){return this.getItem(t,n.Cache.TEXT,"getText","data")},getPhysicsData:function(t,e,i){var s=this.getItem(t,n.Cache.PHYSICS,"getPhysicsData","data");if(null===s||void 0===e||null===e)return s;if(s[e]){var r=s[e];if(!r||!i)return r;for(var o in r)if(o=r[o],o.fixtureKey===i)return o;console.warn('Phaser.Cache.getPhysicsData: Could not find given fixtureKey: "'+i+" in "+t+'"')}else console.warn('Phaser.Cache.getPhysicsData: Invalid key/object: "'+t+" / "+e+'"');return null},getTilemapData:function(t){return this.getItem(t,n.Cache.TILEMAP,"getTilemapData")},getBinary:function(t){return this.getItem(t,n.Cache.BINARY,"getBinary")},getBitmapData:function(t){return this.getItem(t,n.Cache.BITMAPDATA,"getBitmapData","data")},getBitmapFont:function(t){return this.getItem(t,n.Cache.BITMAPFONT,"getBitmapFont")},getJSON:function(t,e){var i=this.getItem(t,n.Cache.JSON,"getJSON","data");return i?e?n.Utils.extend(!0,Array.isArray(i)?[]:{},i):i:null},getXML:function(t){return this.getItem(t,n.Cache.XML,"getXML","data")},getVideo:function(t){return this.getItem(t,n.Cache.VIDEO,"getVideo")},getShader:function(t){return this.getItem(t,n.Cache.SHADER,"getShader","data")},getRenderTexture:function(t){return this.getItem(t,n.Cache.RENDER_TEXTURE,"getRenderTexture")},getBaseTexture:function(t,e){return void 0===e&&(e=n.Cache.IMAGE),this.getItem(t,e,"getBaseTexture","base")},getFrame:function(t,e){return void 0===e&&(e=n.Cache.IMAGE),this.getItem(t,e,"getFrame","frame")},getFrameCount:function(t,e){var i=this.getFrameData(t,e);return i?i.total:0},getFrameData:function(t,e){return void 0===e&&(e=n.Cache.IMAGE),this.getItem(t,e,"getFrameData","frameData")},hasFrameData:function(t,e){return void 0===e&&(e=n.Cache.IMAGE),null!==this.getItem(t,e,"","frameData")},updateFrameData:function(t,e,i){void 0===i&&(i=n.Cache.IMAGE),this._cacheMap[i][t]&&(this._cacheMap[i][t].frameData=e)},getFrameByIndex:function(t,e,i){var s=this.getFrameData(t,i);return s?s.getFrame(e):null},getFrameByName:function(t,e,i){var s=this.getFrameData(t,i);return s?s.getFrameByName(e):null},getURL:function(t){var t=this._resolveURL(t);return t?this._urlMap[t]:(console.warn('Phaser.Cache.getUrl: Invalid url: "'+t+'" or Cache.autoResolveURL was false'),null)},getKeys:function(t){void 0===t&&(t=n.Cache.IMAGE);var e=[];if(this._cacheMap[t])for(var i in this._cacheMap[t])"__default"!==i&&"__missing"!==i&&e.push(i);return e},removeCanvas:function(t){delete this._cache.canvas[t]},removeImage:function(t,e){void 0===e&&(e=!0);var i=this.getImage(t,!0);e&&i.base&&i.base.destroy(),delete this._cache.image[t]},removeSound:function(t){delete this._cache.sound[t]},removeText:function(t){delete this._cache.text[t]},removePhysics:function(t){delete this._cache.physics[t]},removeTilemap:function(t){delete this._cache.tilemap[t]},removeBinary:function(t){delete this._cache.binary[t]},removeBitmapData:function(t){delete this._cache.bitmapData[t]},removeBitmapFont:function(t){delete this._cache.bitmapFont[t]},removeJSON:function(t){delete this._cache.json[t]},removeXML:function(t){delete this._cache.xml[t]},removeVideo:function(t){delete this._cache.video[t]},removeShader:function(t){delete this._cache.shader[t]},removeRenderTexture:function(t){delete this._cache.renderTexture[t]},removeSpriteSheet:function(t){delete this._cache.spriteSheet[t]},removeTextureAtlas:function(t){delete this._cache.atlas[t]},clearGLTextures:function(){for(var t in this._cache.image)this._cache.image[t].base._glTextures=[]},_resolveURL:function(t,e){return this.autoResolveURL?(this._urlResolver.src=this.game.load.baseURL+t,this._urlTemp=this._urlResolver.src,this._urlResolver.src="",e&&(this._urlMap[this._urlTemp]=e),this._urlTemp):null},destroy:function(){for(var t=0;t<this._cacheMap.length;t++){var e=this._cacheMap[t];for(var i in e)"__default"!==i&&"__missing"!==i&&(e[i].destroy&&e[i].destroy(),delete e[i])}this._urlMap=null,this._urlResolver=null,this._urlTemp=null}},n.Cache.prototype.constructor=n.Cache,n.Loader=function(t){this.game=t,this.cache=t.cache,this.resetLocked=!1,this.isLoading=!1,this.hasLoaded=!1,this.preloadSprite=null,this.crossOrigin=!1,this.baseURL="",this.path="",this.headers={requestedWith:!1,json:"application/json",xml:"application/xml"},this.onLoadStart=new n.Signal,this.onLoadComplete=new n.Signal,this.onPackComplete=new n.Signal,this.onFileStart=new n.Signal,this.onFileComplete=new n.Signal,this.onFileError=new n.Signal,this.useXDomainRequest=!1,this._warnedAboutXDomainRequest=!1,this.enableParallel=!0,this.maxParallelDownloads=4,this._withSyncPointDepth=0,this._fileList=[],this._flightQueue=[],this._processingHead=0,this._fileLoadStarted=!1,this._totalPackCount=0,this._totalFileCount=0,this._loadedPackCount=0,this._loadedFileCount=0},n.Loader.TEXTURE_ATLAS_JSON_ARRAY=0,n.Loader.TEXTURE_ATLAS_JSON_HASH=1,n.Loader.TEXTURE_ATLAS_XML_STARLING=2,n.Loader.PHYSICS_LIME_CORONA_JSON=3,n.Loader.PHYSICS_PHASER_JSON=4,n.Loader.TEXTURE_ATLAS_JSON_PYXEL=5,n.Loader.prototype={setPreloadSprite:function(t,e){e=e||0,this.preloadSprite={sprite:t,direction:e,width:t.width,height:t.height,rect:null},this.preloadSprite.rect=0===e?new n.Rectangle(0,0,1,t.height):new n.Rectangle(0,0,t.width,1),t.crop(this.preloadSprite.rect),t.visible=!0},resize:function(){this.preloadSprite&&this.preloadSprite.height!==this.preloadSprite.sprite.height&&(this.preloadSprite.rect.height=this.preloadSprite.sprite.height)},checkKeyExists:function(t,e){return this.getAssetIndex(t,e)>-1},getAssetIndex:function(t,e){for(var i=-1,s=0;s<this._fileList.length;s++){var n=this._fileList[s];if(n.type===t&&n.key===e&&(i=s,!n.loaded&&!n.loading))break}return i},getAsset:function(t,e){var i=this.getAssetIndex(t,e);return i>-1&&{index:i,file:this._fileList[i]}},reset:function(t,e){void 0===e&&(e=!1),this.resetLocked||(t&&(this.preloadSprite=null),this.isLoading=!1,this._processingHead=0,this._fileList.length=0,this._flightQueue.length=0,this._fileLoadStarted=!1,this._totalFileCount=0,this._totalPackCount=0,this._loadedPackCount=0,this._loadedFileCount=0,e&&(this.onLoadStart.removeAll(),this.onLoadComplete.removeAll(),this.onPackComplete.removeAll(),this.onFileStart.removeAll(),this.onFileComplete.removeAll(),this.onFileError.removeAll()))},addToFileList:function(t,e,i,s,n,r){if(void 0===n&&(n=!1),void 0===e||""===e)return console.warn("Phaser.Loader: Invalid or no key given of type "+t),this;if(void 0===i||null===i){if(!r)return console.warn("Phaser.Loader: No URL given for file type: "+t+" key: "+e),this;i=e+r}var o={type:t,key:e,path:this.path,url:i,syncPoint:this._withSyncPointDepth>0,data:null,loading:!1,loaded:!1,error:!1};if(s)for(var a in s)o[a]=s[a];var h=this.getAssetIndex(t,e);if(n&&h>-1){var l=this._fileList[h];l.loading||l.loaded?(this._fileList.push(o),this._totalFileCount++):this._fileList[h]=o}else-1===h&&(this._fileList.push(o),this._totalFileCount++);return this},replaceInFileList:function(t,e,i,s){return this.addToFileList(t,e,i,s,!0)},pack:function(t,e,i,s){if(void 0===e&&(e=null),void 0===i&&(i=null),void 0===s&&(s=null),!e&&!i)return console.warn("Phaser.Loader.pack - Both url and data are null. One must be set."),this;var n={type:"packfile",key:t,url:e,path:this.path,syncPoint:!0,data:null,loading:!1,loaded:!1,error:!1,callbackContext:s};i&&("string"==typeof i&&(i=JSON.parse(i)),n.data=i||{},n.loaded=!0);for(var r=0;r<this._fileList.length+1;r++){var o=this._fileList[r];if(!o||!o.loaded&&!o.loading&&"packfile"!==o.type){this._fileList.splice(r,0,n),this._totalPackCount++;break}}return this},image:function(t,e,i){return this.addToFileList("image",t,e,void 0,i,".png")},images:function(t,e){if(Array.isArray(e))for(var i=0;i<t.length;i++)this.image(t[i],e[i]);else for(var i=0;i<t.length;i++)this.image(t[i]);return this},text:function(t,e,i){return this.addToFileList("text",t,e,void 0,i,".txt")},json:function(t,e,i){return this.addToFileList("json",t,e,void 0,i,".json")},shader:function(t,e,i){return this.addToFileList("shader",t,e,void 0,i,".frag")},xml:function(t,e,i){return this.addToFileList("xml",t,e,void 0,i,".xml")},script:function(t,e,i,s){return void 0===i&&(i=!1),!1!==i&&void 0===s&&(s=this),this.addToFileList("script",t,e,{syncPoint:!0,callback:i,callbackContext:s},!1,".js")},binary:function(t,e,i,s){return void 0===i&&(i=!1),!1!==i&&void 0===s&&(s=i),this.addToFileList("binary",t,e,{callback:i,callbackContext:s},!1,".bin")},spritesheet:function(t,e,i,s,n,r,o){return void 0===n&&(n=-1),void 0===r&&(r=0),void 0===o&&(o=0),this.addToFileList("spritesheet",t,e,{frameWidth:i,frameHeight:s,frameMax:n,margin:r,spacing:o},!1,".png")},audio:function(t,e,i){return this.game.sound.noAudio?this:(void 0===i&&(i=!0),"string"==typeof e&&(e=[e]),this.addToFileList("audio",t,e,{buffer:null,autoDecode:i}))},audioSprite:function(t,e,i,s,n){return this.game.sound.noAudio?this:(void 0===i&&(i=null),void 0===s&&(s=null),void 0===n&&(n=!0),this.audio(t,e,n),i?this.json(t+"-audioatlas",i):s?("string"==typeof s&&(s=JSON.parse(s)),this.cache.addJSON(t+"-audioatlas","",s)):console.warn("Phaser.Loader.audiosprite - You must specify either a jsonURL or provide a jsonData object"),this)},audiosprite:function(t,e,i,s,n){return this.audioSprite(t,e,i,s,n)},video:function(t,e,i,s){return void 0===i&&(i=this.game.device.firefox?"loadeddata":"canplaythrough"),void 0===s&&(s=!1),"string"==typeof e&&(e=[e]),this.addToFileList("video",t,e,{buffer:null,asBlob:s,loadEvent:i})},tilemap:function(t,e,i,s){if(void 0===e&&(e=null),void 0===i&&(i=null),void 0===s&&(s=n.Tilemap.CSV),e||i||(e=s===n.Tilemap.CSV?t+".csv":t+".json"),i){switch(s){case n.Tilemap.CSV:break;case n.Tilemap.TILED_JSON:"string"==typeof i&&(i=JSON.parse(i))}this.cache.addTilemap(t,null,i,s)}else this.addToFileList("tilemap",t,e,{format:s});return this},physics:function(t,e,i,s){return void 0===e&&(e=null),void 0===i&&(i=null),void 0===s&&(s=n.Physics.LIME_CORONA_JSON),e||i||(e=t+".json"),i?("string"==typeof i&&(i=JSON.parse(i)),this.cache.addPhysicsData(t,null,i,s)):this.addToFileList("physics",t,e,{format:s}),this},bitmapFont:function(t,e,i,s,n,r){if(void 0!==e&&null!==e||(e=t+".png"),void 0===i&&(i=null),void 0===s&&(s=null),null===i&&null===s&&(i=t+".xml"),void 0===n&&(n=0),void 0===r&&(r=0),i)this.addToFileList("bitmapfont",t,e,{atlasURL:i,xSpacing:n,ySpacing:r});else if("string"==typeof s){var o,a;try{o=JSON.parse(s)}catch(t){a=this.parseXml(s)}if(!a&&!o)throw new Error("Phaser.Loader. Invalid Bitmap Font atlas given");this.addToFileList("bitmapfont",t,e,{atlasURL:null,atlasData:o||a,atlasType:o?"json":"xml",xSpacing:n,ySpacing:r})}return this},atlasJSONArray:function(t,e,i,s){return this.atlas(t,e,i,s,n.Loader.TEXTURE_ATLAS_JSON_ARRAY)},atlasJSONHash:function(t,e,i,s){return this.atlas(t,e,i,s,n.Loader.TEXTURE_ATLAS_JSON_HASH)},atlasXML:function(t,e,i,s){return void 0===i&&(i=null),void 0===s&&(s=null),i||s||(i=t+".xml"),this.atlas(t,e,i,s,n.Loader.TEXTURE_ATLAS_XML_STARLING)},atlas:function(t,e,i,s,r){if(void 0!==e&&null!==e||(e=t+".png"),void 0===i&&(i=null),void 0===s&&(s=null),void 0===r&&(r=n.Loader.TEXTURE_ATLAS_JSON_ARRAY),i||s||(i=r===n.Loader.TEXTURE_ATLAS_XML_STARLING?t+".xml":t+".json"),i)this.addToFileList("textureatlas",t,e,{atlasURL:i,format:r});else{switch(r){case n.Loader.TEXTURE_ATLAS_JSON_ARRAY:"string"==typeof s&&(s=JSON.parse(s));break;case n.Loader.TEXTURE_ATLAS_XML_STARLING:if("string"==typeof s){var o=this.parseXml(s);if(!o)throw new Error("Phaser.Loader. Invalid Texture Atlas XML given");s=o}}this.addToFileList("textureatlas",t,e,{atlasURL:null,atlasData:s,format:r})}return this},withSyncPoint:function(t,e){this._withSyncPointDepth++;try{t.call(e||this,this)}finally{this._withSyncPointDepth--}return this},addSyncPoint:function(t,e){var i=this.getAsset(t,e);return i&&(i.file.syncPoint=!0),this},removeFile:function(t,e){var i=this.getAsset(t,e);i&&(i.loaded||i.loading||this._fileList.splice(i.index,1))},removeAll:function(){this._fileList.length=0,this._flightQueue.length=0},start:function(){this.isLoading||(this.hasLoaded=!1,this.isLoading=!0,this.updateProgress(),this.processLoadQueue())},processLoadQueue:function(){if(!this.isLoading)return console.warn("Phaser.Loader - active loading canceled / reset"),void this.finishedLoading(!0);for(var t=0;t<this._flightQueue.length;t++){var e=this._flightQueue[t];(e.loaded||e.error)&&(this._flightQueue.splice(t,1),t--,e.loading=!1,e.requestUrl=null,e.requestObject=null,e.error&&this.onFileError.dispatch(e.key,e),"packfile"!==e.type?(this._loadedFileCount++,this.onFileComplete.dispatch(this.progress,e.key,!e.error,this._loadedFileCount,this._totalFileCount)):"packfile"===e.type&&e.error&&(this._loadedPackCount++,this.onPackComplete.dispatch(e.key,!e.error,this._loadedPackCount,this._totalPackCount)))}for(var i=!1,s=this.enableParallel?n.Math.clamp(this.maxParallelDownloads,1,12):1,t=this._processingHead;t<this._fileList.length;t++){var e=this._fileList[t];if("packfile"===e.type&&!e.error&&e.loaded&&t===this._processingHead&&(this.processPack(e),this._loadedPackCount++,this.onPackComplete.dispatch(e.key,!e.error,this._loadedPackCount,this._totalPackCount)),e.loaded||e.error?t===this._processingHead&&(this._processingHead=t+1):!e.loading&&this._flightQueue.length<s&&("packfile"!==e.type||e.data?i||(this._fileLoadStarted||(this._fileLoadStarted=!0,this.onLoadStart.dispatch()),this._flightQueue.push(e),e.loading=!0,this.onFileStart.dispatch(this.progress,e.key,e.url),this.loadFile(e)):(this._flightQueue.push(e),e.loading=!0,this.loadFile(e))),!e.loaded&&e.syncPoint&&(i=!0),this._flightQueue.length>=s||i&&this._loadedPackCount===this._totalPackCount)break}if(this.updateProgress(),this._processingHead>=this._fileList.length)this.finishedLoading();else if(!this._flightQueue.length){console.warn("Phaser.Loader - aborting: processing queue empty, loading may have stalled");var r=this;setTimeout(function(){r.finishedLoading(!0)},2e3)}},finishedLoading:function(t){this.hasLoaded||(this.hasLoaded=!0,this.isLoading=!1,t||this._fileLoadStarted||(this._fileLoadStarted=!0,this.onLoadStart.dispatch()),this.onLoadComplete.dispatch(),this.game.state.loadComplete(),this.reset())},asyncComplete:function(t,e){void 0===e&&(e=""),t.loaded=!0,t.error=!!e,e&&(t.errorMessage=e,console.warn("Phaser.Loader - "+t.type+"["+t.key+"]: "+e)),this.processLoadQueue()},processPack:function(t){var e=t.data[t.key];if(!e)return void console.warn("Phaser.Loader - "+t.key+": pack has data, but not for pack key");for(var i=0;i<e.length;i++){var s=e[i];switch(s.type){case"image":this.image(s.key,s.url,s.overwrite);break;case"text":this.text(s.key,s.url,s.overwrite);break;case"json":this.json(s.key,s.url,s.overwrite);break;case"xml":this.xml(s.key,s.url,s.overwrite);break;case"script":this.script(s.key,s.url,s.callback,t.callbackContext||this);break;case"binary":this.binary(s.key,s.url,s.callback,t.callbackContext||this);break;case"spritesheet":this.spritesheet(s.key,s.url,s.frameWidth,s.frameHeight,s.frameMax,s.margin,s.spacing);break;case"video":this.video(s.key,s.urls);break;case"audio":this.audio(s.key,s.urls,s.autoDecode);break;case"audiosprite":this.audiosprite(s.key,s.urls,s.jsonURL,s.jsonData,s.autoDecode);break;case"tilemap":this.tilemap(s.key,s.url,s.data,n.Tilemap[s.format]);break;case"physics":this.physics(s.key,s.url,s.data,n.Loader[s.format]);break;case"bitmapFont":this.bitmapFont(s.key,s.textureURL,s.atlasURL,s.atlasData,s.xSpacing,s.ySpacing);break;case"atlasJSONArray":this.atlasJSONArray(s.key,s.textureURL,s.atlasURL,s.atlasData);break;case"atlasJSONHash":this.atlasJSONHash(s.key,s.textureURL,s.atlasURL,s.atlasData);break;case"atlasXML":this.atlasXML(s.key,s.textureURL,s.atlasURL,s.atlasData);break;case"atlas":this.atlas(s.key,s.textureURL,s.atlasURL,s.atlasData,n.Loader[s.format]);break;case"shader":this.shader(s.key,s.url,s.overwrite)}}},transformUrl:function(t,e){return!!t&&(t.match(/^(?:blob:|data:|http:\/\/|https:\/\/|\/\/)/)?t:this.baseURL+e.path+t)},loadFile:function(t){switch(t.type){case"packfile":this.xhrLoad(t,this.transformUrl(t.url,t),"text",this.fileComplete);break;case"image":case"spritesheet":case"textureatlas":case"bitmapfont":this.loadImageTag(t);break;case"audio":t.url=this.getAudioURL(t.url),t.url?this.game.sound.usingWebAudio?this.xhrLoad(t,this.transformUrl(t.url,t),"arraybuffer",this.fileComplete):this.game.sound.usingAudioTag&&this.loadAudioTag(t):this.fileError(t,null,"No supported audio URL specified or device does not have audio playback support");break;case"video":t.url=this.getVideoURL(t.url),t.url?t.asBlob?this.xhrLoad(t,this.transformUrl(t.url,t),"blob",this.fileComplete):this.loadVideoTag(t):this.fileError(t,null,"No supported video URL specified or device does not have video playback support");break;case"json":this.xhrLoad(t,this.transformUrl(t.url,t),"text",this.jsonLoadComplete);break;case"xml":this.xhrLoad(t,this.transformUrl(t.url,t),"text",this.xmlLoadComplete);break;case"tilemap":t.format===n.Tilemap.TILED_JSON?this.xhrLoad(t,this.transformUrl(t.url,t),"text",this.jsonLoadComplete):t.format===n.Tilemap.CSV?this.xhrLoad(t,this.transformUrl(t.url,t),"text",this.csvLoadComplete):this.asyncComplete(t,"invalid Tilemap format: "+t.format);break;case"text":case"script":case"shader":case"physics":this.xhrLoad(t,this.transformUrl(t.url,t),"text",this.fileComplete);break;case"binary":this.xhrLoad(t,this.transformUrl(t.url,t),"arraybuffer",this.fileComplete)}},loadImageTag:function(t){var e=this;t.data=new Image,t.data.name=t.key,this.crossOrigin&&(t.data.crossOrigin=this.crossOrigin),t.data.onload=function(){t.data.onload&&(t.data.onload=null,t.data.onerror=null,e.fileComplete(t))},t.data.onerror=function(){t.data.onload&&(t.data.onload=null,t.data.onerror=null,e.fileError(t))},t.data.src=this.transformUrl(t.url,t),t.data.complete&&t.data.width&&t.data.height&&(t.data.onload=null,t.data.onerror=null,this.fileComplete(t))},loadVideoTag:function(t){var e=this;t.data=document.createElement("video"),t.data.name=t.key,t.data.controls=!1,t.data.autoplay=!1;var i=function(){t.data.removeEventListener(t.loadEvent,i,!1),t.data.onerror=null,t.data.canplay=!0,n.GAMES[e.game.id].load.fileComplete(t)};t.data.onerror=function(){t.data.removeEventListener(t.loadEvent,i,!1),t.data.onerror=null,t.data.canplay=!1,e.fileError(t)},t.data.addEventListener(t.loadEvent,i,!1),t.data.src=this.transformUrl(t.url,t),t.data.load()},loadAudioTag:function(t){var e=this;if(this.game.sound.touchLocked)t.data=new Audio,t.data.name=t.key,t.data.preload="auto",t.data.src=this.transformUrl(t.url,t),this.fileComplete(t);else{t.data=new Audio,t.data.name=t.key;var i=function(){t.data.removeEventListener("canplaythrough",i,!1),t.data.onerror=null,e.fileComplete(t)};t.data.onerror=function(){t.data.removeEventListener("canplaythrough",i,!1),t.data.onerror=null,e.fileError(t)},t.data.preload="auto",t.data.src=this.transformUrl(t.url,t),t.data.addEventListener("canplaythrough",i,!1),t.data.load()}},xhrLoad:function(t,e,i,s,n){if(this.useXDomainRequest&&window.XDomainRequest)return void this.xhrLoadWithXDR(t,e,i,s,n);var r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType=i,!1!==this.headers.requestedWith&&r.setRequestHeader("X-Requested-With",this.headers.requestedWith),this.headers[t.type]&&r.setRequestHeader("Accept",this.headers[t.type]),n=n||this.fileError;var o=this;r.onload=function(){try{return 4===r.readyState&&r.status>=400&&r.status<=599?n.call(o,t,r):s.call(o,t,r)}catch(e){o.hasLoaded?window.console&&console.error(e):o.asyncComplete(t,e.message||"Exception")}},r.onerror=function(){try{return n.call(o,t,r)}catch(e){o.hasLoaded?window.console&&console.error(e):o.asyncComplete(t,e.message||"Exception")}},t.requestObject=r,t.requestUrl=e,r.send()},xhrLoadWithXDR:function(t,e,i,s,n){this._warnedAboutXDomainRequest||this.game.device.ie&&!(this.game.device.ieVersion>=10)||(this._warnedAboutXDomainRequest=!0,console.warn("Phaser.Loader - using XDomainRequest outside of IE 9"));var r=new window.XDomainRequest;r.open("GET",e,!0),r.responseType=i,r.timeout=3e3,n=n||this.fileError;var o=this;r.onerror=function(){try{return n.call(o,t,r)}catch(e){o.asyncComplete(t,e.message||"Exception")}},r.ontimeout=function(){try{return n.call(o,t,r)}catch(e){o.asyncComplete(t,e.message||"Exception")}},r.onprogress=function(){},r.onload=function(){try{return 4===r.readyState&&r.status>=400&&r.status<=599?n.call(o,t,r):s.call(o,t,r)}catch(e){o.asyncComplete(t,e.message||"Exception")}},t.requestObject=r,t.requestUrl=e,setTimeout(function(){r.send()},0)},getVideoURL:function(t){for(var e=0;e<t.length;e++){var i,s=t[e];if(s.uri){if(i=s.type,s=s.uri,this.game.device.canPlayVideo(i))return s}else{if(0===s.indexOf("blob:")||0===s.indexOf("data:"))return s;s.indexOf("?")>=0&&(s=s.substr(0,s.indexOf("?")));if(i=s.substr((Math.max(0,s.lastIndexOf("."))||1/0)+1).toLowerCase(),this.game.device.canPlayVideo(i))return t[e]}}return null},getAudioURL:function(t){if(this.game.sound.noAudio)return null;for(var e=0;e<t.length;e++){var i,s=t[e];if(s.uri){if(i=s.type,s=s.uri,this.game.device.canPlayAudio(i))return s}else{if(0===s.indexOf("blob:")||0===s.indexOf("data:"))return s;s.indexOf("?")>=0&&(s=s.substr(0,s.indexOf("?")));if(i=s.substr((Math.max(0,s.lastIndexOf("."))||1/0)+1).toLowerCase(),this.game.device.canPlayAudio(i))return t[e]}}return null},fileError:function(t,e,i){var s=t.requestUrl||this.transformUrl(t.url,t),n="error loading asset from URL "+s;!i&&e&&(i=e.status),i&&(n=n+" ("+i+")"),this.asyncComplete(t,n)},fileComplete:function(t,e){var i=!0;switch(t.type){case"packfile":var s=JSON.parse(e.responseText);t.data=s||{};break;case"image":this.cache.addImage(t.key,t.url,t.data);break;case"spritesheet":this.cache.addSpriteSheet(t.key,t.url,t.data,t.frameWidth,t.frameHeight,t.frameMax,t.margin,t.spacing);break;case"textureatlas":if(null==t.atlasURL)this.cache.addTextureAtlas(t.key,t.url,t.data,t.atlasData,t.format);else if(i=!1,t.format===n.Loader.TEXTURE_ATLAS_JSON_ARRAY||t.format===n.Loader.TEXTURE_ATLAS_JSON_HASH||t.format===n.Loader.TEXTURE_ATLAS_JSON_PYXEL)this.xhrLoad(t,this.transformUrl(t.atlasURL,t),"text",this.jsonLoadComplete);else{if(t.format!==n.Loader.TEXTURE_ATLAS_XML_STARLING)throw new Error("Phaser.Loader. Invalid Texture Atlas format: "+t.format);this.xhrLoad(t,this.transformUrl(t.atlasURL,t),"text",this.xmlLoadComplete)}break;case"bitmapfont":t.atlasURL?(i=!1,this.xhrLoad(t,this.transformUrl(t.atlasURL,t),"text",function(t,e){var i;try{i=JSON.parse(e.responseText)}catch(t){}i?(t.atlasType="json",this.jsonLoadComplete(t,e)):(t.atlasType="xml",this.xmlLoadComplete(t,e))})):this.cache.addBitmapFont(t.key,t.url,t.data,t.atlasData,t.atlasType,t.xSpacing,t.ySpacing);break;case"video":if(t.asBlob)try{t.data=e.response}catch(e){throw new Error("Phaser.Loader. Unable to parse video file as Blob: "+t.key)}this.cache.addVideo(t.key,t.url,t.data,t.asBlob);break;case"audio":this.game.sound.usingWebAudio?(t.data=e.response,this.cache.addSound(t.key,t.url,t.data,!0,!1),t.autoDecode&&this.game.sound.decode(t.key)):this.cache.addSound(t.key,t.url,t.data,!1,!0);break;case"text":t.data=e.responseText,this.cache.addText(t.key,t.url,t.data);break;case"shader":t.data=e.responseText,this.cache.addShader(t.key,t.url,t.data);break;case"physics":var s=JSON.parse(e.responseText);this.cache.addPhysicsData(t.key,t.url,s,t.format);break;case"script":t.data=document.createElement("script"),t.data.language="javascript",t.data.type="text/javascript",t.data.defer=!1,t.data.text=e.responseText,document.head.appendChild(t.data),t.callback&&(t.data=t.callback.call(t.callbackContext,t.key,e.responseText));break;case"binary":t.callback?t.data=t.callback.call(t.callbackContext,t.key,e.response):t.data=e.response,this.cache.addBinary(t.key,t.data)}i&&this.asyncComplete(t)},jsonLoadComplete:function(t,e){var i=JSON.parse(e.responseText);"tilemap"===t.type?this.cache.addTilemap(t.key,t.url,i,t.format):"bitmapfont"===t.type?this.cache.addBitmapFont(t.key,t.url,t.data,i,t.atlasType,t.xSpacing,t.ySpacing):"json"===t.type?this.cache.addJSON(t.key,t.url,i):this.cache.addTextureAtlas(t.key,t.url,t.data,i,t.format),this.asyncComplete(t)},csvLoadComplete:function(t,e){var i=e.responseText;this.cache.addTilemap(t.key,t.url,i,t.format),this.asyncComplete(t)},xmlLoadComplete:function(t,e){var i=e.responseText,s=this.parseXml(i);if(!s){var n=e.responseType||e.contentType;return console.warn("Phaser.Loader - "+t.key+": invalid XML ("+n+")"),void this.asyncComplete(t,"invalid XML")}"bitmapfont"===t.type?this.cache.addBitmapFont(t.key,t.url,t.data,s,t.atlasType,t.xSpacing,t.ySpacing):"textureatlas"===t.type?this.cache.addTextureAtlas(t.key,t.url,t.data,s,t.format):"xml"===t.type&&this.cache.addXML(t.key,t.url,s),this.asyncComplete(t)},parseXml:function(t){var e;try{if(window.DOMParser){var i=new DOMParser;e=i.parseFromString(t,"text/xml")}else e=new ActiveXObject("Microsoft.XMLDOM"),e.async="false",e.loadXML(t)}catch(t){e=null}return e&&e.documentElement&&!e.getElementsByTagName("parsererror").length?e:null},updateProgress:function(){this.preloadSprite&&(0===this.preloadSprite.direction?this.preloadSprite.rect.width=Math.floor(this.preloadSprite.width/100*this.progress):this.preloadSprite.rect.height=Math.floor(this.preloadSprite.height/100*this.progress),this.preloadSprite.sprite?this.preloadSprite.sprite.updateCrop():this.preloadSprite=null)},totalLoadedFiles:function(){return this._loadedFileCount},totalQueuedFiles:function(){return this._totalFileCount-this._loadedFileCount},totalLoadedPacks:function(){return this._totalPackCount},totalQueuedPacks:function(){return this._totalPackCount-this._loadedPackCount}},Object.defineProperty(n.Loader.prototype,"progressFloat",{get:function(){var t=this._loadedFileCount/this._totalFileCount*100;return n.Math.clamp(t||0,0,100)}}),Object.defineProperty(n.Loader.prototype,"progress",{get:function(){return Math.round(this.progressFloat)}}),n.Loader.prototype.constructor=n.Loader,n.LoaderParser={bitmapFont:function(t,e,i,s){return this.xmlBitmapFont(t,e,i,s)},xmlBitmapFont:function(t,e,i,s){var n={},r=t.getElementsByTagName("info")[0],o=t.getElementsByTagName("common")[0];n.font=r.getAttribute("face"),n.size=parseInt(r.getAttribute("size"),10),n.lineHeight=parseInt(o.getAttribute("lineHeight"),10)+s,n.chars={};for(var a=t.getElementsByTagName("char"),h=0;h<a.length;h++){var l=parseInt(a[h].getAttribute("id"),10);n.chars[l]={x:parseInt(a[h].getAttribute("x"),10),y:parseInt(a[h].getAttribute("y"),10),width:parseInt(a[h].getAttribute("width"),10),height:parseInt(a[h].getAttribute("height"),10),xOffset:parseInt(a[h].getAttribute("xoffset"),10),yOffset:parseInt(a[h].getAttribute("yoffset"),10),xAdvance:parseInt(a[h].getAttribute("xadvance"),10)+i,kerning:{}}}var c=t.getElementsByTagName("kerning");for(h=0;h<c.length;h++){var u=parseInt(c[h].getAttribute("first"),10),d=parseInt(c[h].getAttribute("second"),10),p=parseInt(c[h].getAttribute("amount"),10);n.chars[d].kerning[u]=p}return this.finalizeBitmapFont(e,n)},jsonBitmapFont:function(t,e,i,s){var n={font:t.font.info._face,size:parseInt(t.font.info._size,10),lineHeight:parseInt(t.font.common._lineHeight,10)+s,chars:{}};return t.font.chars.char.forEach(function(t){var e=parseInt(t._id,10);n.chars[e]={x:parseInt(t._x,10),y:parseInt(t._y,10),width:parseInt(t._width,10),height:parseInt(t._height,10),xOffset:parseInt(t._xoffset,10),yOffset:parseInt(t._yoffset,10),xAdvance:parseInt(t._xadvance,10)+i,kerning:{}}}),t.font.kernings&&t.font.kernings.kerning&&t.font.kernings.kerning.forEach(function(t){n.chars[t._second].kerning[t._first]=parseInt(t._amount,10)}),this.finalizeBitmapFont(e,n)},finalizeBitmapFont:function(t,e){return Object.keys(e.chars).forEach(function(i){var s=e.chars[i];s.texture=new PIXI.Texture(t,new n.Rectangle(s.x,s.y,s.width,s.height))}),e}},n.AudioSprite=function(t,e){this.game=t,this.key=e,this.config=this.game.cache.getJSON(e+"-audioatlas"),this.autoplayKey=null,this.autoplay=!1,this.sounds={};for(var i in this.config.spritemap){var s=this.config.spritemap[i],n=this.game.add.sound(this.key);n.addMarker(i,s.start,s.end-s.start,null,s.loop),this.sounds[i]=n}this.config.autoplay&&(this.autoplayKey=this.config.autoplay,this.play(this.autoplayKey),this.autoplay=this.sounds[this.autoplayKey])},n.AudioSprite.prototype={play:function(t,e){return void 0===e&&(e=1),this.sounds[t].play(t,null,e)},stop:function(t){if(t)this.sounds[t].stop();else for(var e in this.sounds)this.sounds[e].stop()},get:function(t){return this.sounds[t]}},n.AudioSprite.prototype.constructor=n.AudioSprite,n.Sound=function(t,e,i,s,r){void 0===i&&(i=1),void 0===s&&(s=!1),void 0===r&&(r=t.sound.connectToMaster),this.game=t,this.name=e,this.key=e,this.loop=s,this.markers={},this.context=null,this.autoplay=!1,this.totalDuration=0,this.startTime=0,this.currentTime=0,this.duration=0,this.durationMS=0,this.position=0,this.stopTime=0,this.paused=!1,this.pausedPosition=0,this.pausedTime=0,this.isPlaying=!1,this.currentMarker="",this.fadeTween=null,this.pendingPlayback=!1,this.override=!1,this.allowMultiple=!1,this.usingWebAudio=this.game.sound.usingWebAudio,this.usingAudioTag=this.game.sound.usingAudioTag,this.externalNode=null,this.masterGainNode=null,this.gainNode=null,this._sound=null,this.usingWebAudio?(this.context=this.game.sound.context,this.masterGainNode=this.game.sound.masterGain,void 0===this.context.createGain?this.gainNode=this.context.createGainNode():this.gainNode=this.context.createGain(),this.gainNode.gain.value=i*this.game.sound.volume,r&&this.gainNode.connect(this.masterGainNode)):this.usingAudioTag&&(this.game.cache.getSound(e)&&this.game.cache.isSoundReady(e)?(this._sound=this.game.cache.getSoundData(e),this.totalDuration=0,this._sound.duration&&(this.totalDuration=this._sound.duration)):this.game.cache.onSoundUnlock.add(this.soundHasUnlocked,this)),this.onDecoded=new n.Signal,this.onPlay=new n.Signal,this.onPause=new n.Signal,this.onResume=new n.Signal,this.onLoop=new n.Signal,this.onStop=new n.Signal,this.onMute=new n.Signal,this.onMarkerComplete=new n.Signal,this.onFadeComplete=new n.Signal,this._volume=i,this._buffer=null,this._muted=!1,this._tempMarker=0,this._tempPosition=0,this._tempVolume=0,this._tempPause=0,this._muteVolume=0,this._tempLoop=0,this._paused=!1,this._onDecodedEventDispatched=!1},n.Sound.prototype={soundHasUnlocked:function(t){t===this.key&&(this._sound=this.game.cache.getSoundData(this.key),this.totalDuration=this._sound.duration)},addMarker:function(t,e,i,s,n){void 0!==i&&null!==i||(i=1),void 0!==s&&null!==s||(s=1),void 0===n&&(n=!1),this.markers[t]={name:t,start:e,stop:e+i,volume:s,duration:i,durationMS:1e3*i,loop:n}},removeMarker:function(t){delete this.markers[t]},onEndedHandler:function(){this._sound.onended=null,this.isPlaying=!1,this.currentTime=this.durationMS,this.stop()},update:function(){if(!this.game.cache.checkSoundKey(this.key))return void this.destroy();this.isDecoded&&!this._onDecodedEventDispatched&&(this.onDecoded.dispatch(this),this._onDecodedEventDispatched=!0),this.pendingPlayback&&this.game.cache.isSoundReady(this.key)&&(this.pendingPlayback=!1,this.play(this._tempMarker,this._tempPosition,this._tempVolume,this._tempLoop)),this.isPlaying&&(this.currentTime=this.game.time.time-this.startTime,this.currentTime>=this.durationMS&&(this.usingWebAudio?this.loop?(this.onLoop.dispatch(this),this.isPlaying=!1,""===this.currentMarker?(this.currentTime=0,this.startTime=this.game.time.time,this.isPlaying=!0):(this.onMarkerComplete.dispatch(this.currentMarker,this),this.play(this.currentMarker,0,this.volume,!0,!0))):""!==this.currentMarker&&this.stop():this.loop?(this.onLoop.dispatch(this),""===this.currentMarker&&(this.currentTime=0,this.startTime=this.game.time.time),this.isPlaying=!1,this.play(this.currentMarker,0,this.volume,!0,!0)):this.stop()))},loopFull:function(t){return this.play(null,0,t,!0)},play:function(t,e,i,s,n){if(void 0!==t&&!1!==t&&null!==t||(t=""),void 0===n&&(n=!0),this.isPlaying&&!this.allowMultiple&&!n&&!this.override)return this;if(this._sound&&this.isPlaying&&!this.allowMultiple&&(this.override||n)){if(this.usingWebAudio){if(void 0===this._sound.stop)this._sound.noteOff(0);else try{this._sound.stop(0)}catch(t){}this.externalNode?this._sound.disconnect(this.externalNode):this.gainNode&&this._sound.disconnect(this.gainNode)}else this.usingAudioTag&&(this._sound.pause(),this._sound.currentTime=0);this.isPlaying=!1}if(""===t&&Object.keys(this.markers).length>0)return this;if(""!==t){if(!this.markers[t])return console.warn("Phaser.Sound.play: audio marker "+t+" doesn't exist"),this;this.currentMarker=t,this.position=this.markers[t].start,this.volume=this.markers[t].volume,this.loop=this.markers[t].loop,this.duration=this.markers[t].duration,this.durationMS=this.markers[t].durationMS,void 0!==i&&(this.volume=i),void 0!==s&&(this.loop=s),this._tempMarker=t,this._tempPosition=this.position,this._tempVolume=this.volume,this._tempLoop=this.loop}else e=e||0,void 0===i&&(i=this._volume),void 0===s&&(s=this.loop),this.position=Math.max(0,e),this.volume=i,this.loop=s,this.duration=0,this.durationMS=0,this._tempMarker=t,this._tempPosition=e,this._tempVolume=i,this._tempLoop=s;return this.usingWebAudio?this.game.cache.isSoundDecoded(this.key)?(this._sound=this.context.createBufferSource(),this.externalNode?this._sound.connect(this.externalNode):this._sound.connect(this.gainNode),this._buffer=this.game.cache.getSoundData(this.key),this._sound.buffer=this._buffer,this.loop&&""===t&&(this._sound.loop=!0),this.loop||""!==t||(this._sound.onended=this.onEndedHandler.bind(this)),this.totalDuration=this._sound.buffer.duration,0===this.duration&&(this.duration=this.totalDuration,this.durationMS=Math.ceil(1e3*this.totalDuration)),void 0===this._sound.start?this._sound.noteGrainOn(0,this.position,this.duration):this.loop&&""===t?this._sound.start(0,0):this._sound.start(0,this.position,this.duration),this.isPlaying=!0,this.startTime=this.game.time.time,this.currentTime=0,this.stopTime=this.startTime+this.durationMS,this.onPlay.dispatch(this)):(this.pendingPlayback=!0,this.game.cache.getSound(this.key)&&!1===this.game.cache.getSound(this.key).isDecoding&&this.game.sound.decode(this.key,this)):this.game.cache.getSound(this.key)&&this.game.cache.getSound(this.key).locked?(this.game.cache.reloadSound(this.key),this.pendingPlayback=!0):this._sound&&(this.game.device.cocoonJS||4===this._sound.readyState)?(this._sound.play(),this.totalDuration=this._sound.duration,0===this.duration&&(this.duration=this.totalDuration,this.durationMS=1e3*this.totalDuration),this._sound.currentTime=this.position,this._sound.muted=this._muted,this._muted||this.game.sound.mute?this._sound.volume=0:this._sound.volume=this._volume,this.isPlaying=!0,this.startTime=this.game.time.time,this.currentTime=0,this.stopTime=this.startTime+this.durationMS,this.onPlay.dispatch(this)):this.pendingPlayback=!0,this},restart:function(t,e,i,s){t=t||"",e=e||0,i=i||1,void 0===s&&(s=!1),this.play(t,e,i,s,!0)},pause:function(){this.isPlaying&&this._sound&&(this.paused=!0,this.pausedPosition=this.currentTime,this.pausedTime=this.game.time.time,this._tempPause=this._sound.currentTime,this.onPause.dispatch(this),this.stop())},resume:function(){if(this.paused&&this._sound){if(this.usingWebAudio){var t=Math.max(0,this.position+this.pausedPosition/1e3);this._sound=this.context.createBufferSource(),this._sound.buffer=this._buffer,this.externalNode?this._sound.connect(this.externalNode):this._sound.connect(this.gainNode),this.loop&&(this._sound.loop=!0),this.loop||""!==this.currentMarker||(this._sound.onended=this.onEndedHandler.bind(this));var e=this.duration-this.pausedPosition/1e3;void 0===this._sound.start?this._sound.noteGrainOn(0,t,e):this.loop&&this.game.device.chrome?42===this.game.device.chromeVersion?this._sound.start(0):this._sound.start(0,t):this._sound.start(0,t,e)}else this._sound.currentTime=this._tempPause,this._sound.play();this.isPlaying=!0,this.paused=!1,this.startTime+=this.game.time.time-this.pausedTime,this.onResume.dispatch(this)}},stop:function(){if(this.isPlaying&&this._sound)if(this.usingWebAudio){if(void 0===this._sound.stop)this._sound.noteOff(0);else try{this._sound.stop(0)}catch(t){}this.externalNode?this._sound.disconnect(this.externalNode):this.gainNode&&this._sound.disconnect(this.gainNode)}else this.usingAudioTag&&(this._sound.pause(),this._sound.currentTime=0);if(this.pendingPlayback=!1,this.isPlaying=!1,!this.paused){var t=this.currentMarker;""!==this.currentMarker&&this.onMarkerComplete.dispatch(this.currentMarker,this),this.currentMarker="",null!==this.fadeTween&&this.fadeTween.stop(),this.onStop.dispatch(this,t)}},fadeIn:function(t,e,i){void 0===e&&(e=!1),void 0===i&&(i=this.currentMarker),this.paused||(this.play(i,0,0,e),this.fadeTo(t,1))},fadeOut:function(t){this.fadeTo(t,0)},fadeTo:function(t,e){if(this.isPlaying&&!this.paused&&e!==this.volume){if(void 0===t&&(t=1e3),void 0===e)return void console.warn("Phaser.Sound.fadeTo: No Volume Specified.");this.fadeTween=this.game.add.tween(this).to({volume:e},t,n.Easing.Linear.None,!0),this.fadeTween.onComplete.add(this.fadeComplete,this)}},fadeComplete:function(){this.onFadeComplete.dispatch(this,this.volume),0===this.volume&&this.stop()},updateGlobalVolume:function(t){this.usingAudioTag&&this._sound&&(this._sound.volume=t*this._volume)},destroy:function(t){void 0===t&&(t=!0),this.stop(),t?this.game.sound.remove(this):(this.markers={},this.context=null,this._buffer=null,this.externalNode=null,this.onDecoded.dispose(),this.onPlay.dispose(),this.onPause.dispose(),this.onResume.dispose(),this.onLoop.dispose(),this.onStop.dispose(),this.onMute.dispose(),this.onMarkerComplete.dispose())}},n.Sound.prototype.constructor=n.Sound,Object.defineProperty(n.Sound.prototype,"isDecoding",{get:function(){return this.game.cache.getSound(this.key).isDecoding}}),Object.defineProperty(n.Sound.prototype,"isDecoded",{get:function(){return this.game.cache.isSoundDecoded(this.key)}}),Object.defineProperty(n.Sound.prototype,"mute",{get:function(){return this._muted||this.game.sound.mute},set:function(t){(t=t||!1)!==this._muted&&(t?(this._muted=!0,this._muteVolume=this._tempVolume,this.usingWebAudio?this.gainNode.gain.value=0:this.usingAudioTag&&this._sound&&(this._sound.volume=0)):(this._muted=!1,this.usingWebAudio?this.gainNode.gain.value=this._muteVolume:this.usingAudioTag&&this._sound&&(this._sound.volume=this._muteVolume)),this.onMute.dispatch(this))}}),Object.defineProperty(n.Sound.prototype,"volume",{get:function(){return this._volume},set:function(t){if(this.game.device.firefox&&this.usingAudioTag&&(t=this.game.math.clamp(t,0,1)),this._muted)return void(this._muteVolume=t);this._tempVolume=t,this._volume=t,this.usingWebAudio?this.gainNode.gain.value=t:this.usingAudioTag&&this._sound&&(this._sound.volume=t)}}),n.SoundManager=function(t){this.game=t,this.onSoundDecode=new n.Signal,this.onVolumeChange=new n.Signal,this.onMute=new n.Signal,this.onUnMute=new n.Signal,this.context=null,this.usingWebAudio=!1,this.usingAudioTag=!1,this.noAudio=!1,this.connectToMaster=!0,this.touchLocked=!1,this.channels=32,this.muteOnPause=!0,this._codeMuted=!1,this._muted=!1,this._unlockSource=null,this._volume=1,this._sounds=[],this._watchList=new n.ArraySet,this._watching=!1,this._watchCallback=null,this._watchContext=null},n.SoundManager.prototype={boot:function(){if(this.game.device.iOS&&!1===this.game.device.webAudio&&(this.channels=1),window.PhaserGlobal){if(!0===window.PhaserGlobal.disableAudio)return this.noAudio=!0,void(this.touchLocked=!1);if(!0===window.PhaserGlobal.disableWebAudio)return this.usingAudioTag=!0,void(this.touchLocked=!1)}if(window.PhaserGlobal&&window.PhaserGlobal.audioContext)this.context=window.PhaserGlobal.audioContext;else if(window.AudioContext)try{this.context=new window.AudioContext}catch(t){this.context=null,this.usingWebAudio=!1,this.touchLocked=!1}else if(window.webkitAudioContext)try{this.context=new window.webkitAudioContext}catch(t){this.context=null,this.usingWebAudio=!1,this.touchLocked=!1}if(null===this.context){if(void 0===window.Audio)return void(this.noAudio=!0);this.usingAudioTag=!0}else this.usingWebAudio=!0,void 0===this.context.createGain?this.masterGain=this.context.createGainNode():this.masterGain=this.context.createGain(),this.masterGain.gain.value=1,this.masterGain.connect(this.context.destination);this.noAudio||(!this.game.device.cocoonJS&&this.game.device.iOS||window.PhaserGlobal&&window.PhaserGlobal.fakeiOSTouchLock)&&this.setTouchLock()},setTouchLock:function(){this.noAudio||window.PhaserGlobal&&!0===window.PhaserGlobal.disableAudio||(this.game.device.iOSVersion>8?this.game.input.touch.addTouchLockCallback(this.unlock,this,!0):this.game.input.touch.addTouchLockCallback(this.unlock,this),this.touchLocked=!0)},unlock:function(){if(this.noAudio||!this.touchLocked||null!==this._unlockSource)return!0;if(this.usingAudioTag)this.touchLocked=!1,this._unlockSource=null;else if(this.usingWebAudio){var t=this.context.createBuffer(1,1,22050);this._unlockSource=this.context.createBufferSource(),this._unlockSource.buffer=t,this._unlockSource.connect(this.context.destination),void 0===this._unlockSource.start?this._unlockSource.noteOn(0):this._unlockSource.start(0)}return!0},stopAll:function(){if(!this.noAudio)for(var t=0;t<this._sounds.length;t++)this._sounds[t]&&this._sounds[t].stop()},pauseAll:function(){if(!this.noAudio)for(var t=0;t<this._sounds.length;t++)this._sounds[t]&&this._sounds[t].pause()},resumeAll:function(){if(!this.noAudio)for(var t=0;t<this._sounds.length;t++)this._sounds[t]&&this._sounds[t].resume()},decode:function(t,e){e=e||null;var i=this.game.cache.getSoundData(t);if(i&&!1===this.game.cache.isSoundDecoded(t)){this.game.cache.updateSound(t,"isDecoding",!0);var s=this;try{this.context.decodeAudioData(i,function(i){i&&(s.game.cache.decodedSound(t,i),s.onSoundDecode.dispatch(t,e))})}catch(t){}}},setDecodedCallback:function(t,e,i){"string"==typeof t&&(t=[t]),this._watchList.reset();for(var s=0;s<t.length;s++)t[s]instanceof n.Sound?this.game.cache.isSoundDecoded(t[s].key)||this._watchList.add(t[s].key):this.game.cache.isSoundDecoded(t[s])||this._watchList.add(t[s]);0===this._watchList.total?(this._watching=!1,e.call(i)):(this._watching=!0,this._watchCallback=e,this._watchContext=i)},update:function(){if(!this.noAudio){!this.touchLocked||null===this._unlockSource||this._unlockSource.playbackState!==this._unlockSource.PLAYING_STATE&&this._unlockSource.playbackState!==this._unlockSource.FINISHED_STATE||(this.touchLocked=!1,this._unlockSource=null);for(var t=0;t<this._sounds.length;t++)this._sounds[t].update();if(this._watching){for(var e=this._watchList.first;e;)this.game.cache.isSoundDecoded(e)&&this._watchList.remove(e),e=this._watchList.next;0===this._watchList.total&&(this._watching=!1,this._watchCallback.call(this._watchContext))}}},add:function(t,e,i,s){void 0===e&&(e=1),void 0===i&&(i=!1),void 0===s&&(s=this.connectToMaster);var r=new n.Sound(this.game,t,e,i,s);return this._sounds.push(r),r},addSprite:function(t){return new n.AudioSprite(this.game,t)},remove:function(t){for(var e=this._sounds.length;e--;)if(this._sounds[e]===t)return this._sounds[e].destroy(!1),this._sounds.splice(e,1),!0;return!1},removeByKey:function(t){for(var e=this._sounds.length,i=0;e--;)this._sounds[e].key===t&&(this._sounds[e].destroy(!1),this._sounds.splice(e,1),i++);return i},play:function(t,e,i){if(!this.noAudio){var s=this.add(t,e,i);return s.play(),s}},setMute:function(){if(!this._muted){this._muted=!0,this.usingWebAudio&&(this._muteVolume=this.masterGain.gain.value,this.masterGain.gain.value=0);for(var t=0;t<this._sounds.length;t++)this._sounds[t].usingAudioTag&&(this._sounds[t].mute=!0);this.onMute.dispatch()}},unsetMute:function(){if(this._muted&&!this._codeMuted){this._muted=!1,this.usingWebAudio&&(this.masterGain.gain.value=this._muteVolume);for(var t=0;t<this._sounds.length;t++)this._sounds[t].usingAudioTag&&(this._sounds[t].mute=!1);this.onUnMute.dispatch()}},destroy:function(){this.stopAll();for(var t=0;t<this._sounds.length;t++)this._sounds[t]&&this._sounds[t].destroy();this._sounds=[],this.onSoundDecode.dispose(),this.context&&(window.PhaserGlobal?window.PhaserGlobal.audioContext=this.context:this.context.close&&this.context.close())}},n.SoundManager.prototype.constructor=n.SoundManager,Object.defineProperty(n.SoundManager.prototype,"mute",{get:function(){return this._muted},set:function(t){if(t=t||!1){if(this._muted)return;this._codeMuted=!0,this.setMute()}else{if(!this._muted)return;this._codeMuted=!1,this.unsetMute()}}}),Object.defineProperty(n.SoundManager.prototype,"volume",{get:function(){return this._volume},set:function(t){if(t<0?t=0:t>1&&(t=1),this._volume!==t){if(this._volume=t,this.usingWebAudio)this.masterGain.gain.value=t;else for(var e=0;e<this._sounds.length;e++)this._sounds[e].usingAudioTag&&this._sounds[e].updateGlobalVolume(t);this.onVolumeChange.dispatch(t)}}}),n.ScaleManager=function(t,e,i){this.game=t,this.dom=n.DOM,this.grid=null,this.width=0,this.height=0,this.minWidth=null,this.maxWidth=null,this.minHeight=null,this.maxHeight=null,this.offset=new n.Point,this.forceLandscape=!1,this.forcePortrait=!1,this.incorrectOrientation=!1,this._pageAlignHorizontally=!1,this._pageAlignVertically=!1,this.onOrientationChange=new n.Signal,this.enterIncorrectOrientation=new n.Signal,this.leaveIncorrectOrientation=new n.Signal,this.hasPhaserSetFullScreen=!1,this.fullScreenTarget=null,this._createdFullScreenTarget=null,this.onFullScreenInit=new n.Signal,this.onFullScreenChange=new n.Signal,this.onFullScreenError=new n.Signal,this.screenOrientation=this.dom.getScreenOrientation(),this.scaleFactor=new n.Point(1,1),this.scaleFactorInversed=new n.Point(1,1),this.margin={left:0,top:0,right:0,bottom:0,x:0,y:0},this.bounds=new n.Rectangle,this.aspectRatio=0,this.sourceAspectRatio=0,this.event=null,this.windowConstraints={right:"layout",bottom:""},this.compatibility={supportsFullScreen:!1,orientationFallback:null,noMargins:!1,scrollTo:null,forceMinimumDocumentHeight:!1,canExpandParent:!0,clickTrampoline:""},this._scaleMode=n.ScaleManager.NO_SCALE,this._fullScreenScaleMode=n.ScaleManager.NO_SCALE,this.parentIsWindow=!1,this.parentNode=null,this.parentScaleFactor=new n.Point(1,1),this.trackParentInterval=2e3,this.onSizeChange=new n.Signal,this.onResize=null,this.onResizeContext=null,this._pendingScaleMode=null,this._fullScreenRestore=null,this._gameSize=new n.Rectangle,this._userScaleFactor=new n.Point(1,1),this._userScaleTrim=new n.Point(0,0),this._lastUpdate=0,this._updateThrottle=0,this._updateThrottleReset=100,this._parentBounds=new n.Rectangle,this._tempBounds=new n.Rectangle,this._lastReportedCanvasSize=new n.Rectangle,this._lastReportedGameSize=new n.Rectangle,this._booted=!1,t.config&&this.parseConfig(t.config),this.setupScale(e,i)},n.ScaleManager.EXACT_FIT=0,n.ScaleManager.NO_SCALE=1,n.ScaleManager.SHOW_ALL=2,n.ScaleManager.RESIZE=3,n.ScaleManager.USER_SCALE=4,n.ScaleManager.prototype={boot:function(){var t=this.compatibility;t.supportsFullScreen=this.game.device.fullscreen&&!this.game.device.cocoonJS,this.game.device.iPad||this.game.device.webApp||this.game.device.desktop||(this.game.device.android&&!this.game.device.chrome?t.scrollTo=new n.Point(0,1):t.scrollTo=new n.Point(0,0)),this.game.device.desktop?(t.orientationFallback="screen",t.clickTrampoline="when-not-mouse"):(t.orientationFallback="",t.clickTrampoline="");var e=this;this._orientationChange=function(t){return e.orientationChange(t)},this._windowResize=function(t){return e.windowResize(t)},window.addEventListener("orientationchange",this._orientationChange,!1),window.addEventListener("resize",this._windowResize,!1),this.compatibility.supportsFullScreen&&(this._fullScreenChange=function(t){return e.fullScreenChange(t)},this._fullScreenError=function(t){return e.fullScreenError(t)},document.addEventListener("webkitfullscreenchange",this._fullScreenChange,!1),document.addEventListener("mozfullscreenchange",this._fullScreenChange,!1),document.addEventListener("MSFullscreenChange",this._fullScreenChange,!1),document.addEventListener("fullscreenchange",this._fullScreenChange,!1),document.addEventListener("webkitfullscreenerror",this._fullScreenError,!1),document.addEventListener("mozfullscreenerror",this._fullScreenError,!1),document.addEventListener("MSFullscreenError",this._fullScreenError,!1),document.addEventListener("fullscreenerror",this._fullScreenError,!1)),this.game.onResume.add(this._gameResumed,this),this.dom.getOffset(this.game.canvas,this.offset),this.bounds.setTo(this.offset.x,this.offset.y,this.width,this.height),this.setGameSize(this.game.width,this.game.height),this.screenOrientation=this.dom.getScreenOrientation(this.compatibility.orientationFallback),n.FlexGrid&&(this.grid=new n.FlexGrid(this,this.width,this.height)),this._booted=!0,null!==this._pendingScaleMode&&(this.scaleMode=this._pendingScaleMode,this._pendingScaleMode=null)},parseConfig:function(t){void 0!==t.scaleMode&&(this._booted?this.scaleMode=t.scaleMode:this._pendingScaleMode=t.scaleMode),void 0!==t.fullScreenScaleMode&&(this.fullScreenScaleMode=t.fullScreenScaleMode),t.fullScreenTarget&&(this.fullScreenTarget=t.fullScreenTarget)},setupScale:function(t,e){var i,s=new n.Rectangle;""!==this.game.parent&&("string"==typeof this.game.parent?i=document.getElementById(this.game.parent):this.game.parent&&1===this.game.parent.nodeType&&(i=this.game.parent)),i?(this.parentNode=i,this.parentIsWindow=!1,this.getParentBounds(this._parentBounds),s.width=this._parentBounds.width,s.height=this._parentBounds.height,this.offset.set(this._parentBounds.x,this._parentBounds.y)):(this.parentNode=null,this.parentIsWindow=!0,s.width=this.dom.visualBounds.width,s.height=this.dom.visualBounds.height,this.offset.set(0,0));var r=0,o=0;"number"==typeof t?r=t:(this.parentScaleFactor.x=parseInt(t,10)/100,r=s.width*this.parentScaleFactor.x),"number"==typeof e?o=e:(this.parentScaleFactor.y=parseInt(e,10)/100,o=s.height*this.parentScaleFactor.y),r=Math.floor(r),o=Math.floor(o),this._gameSize.setTo(0,0,r,o),this.updateDimensions(r,o,!1)},_gameResumed:function(){this.queueUpdate(!0)},setGameSize:function(t,e){this._gameSize.setTo(0,0,t,e),this.currentScaleMode!==n.ScaleManager.RESIZE&&this.updateDimensions(t,e,!0),this.queueUpdate(!0)},setUserScale:function(t,e,i,s){this._userScaleFactor.setTo(t,e),this._userScaleTrim.setTo(0|i,0|s),this.queueUpdate(!0)},setResizeCallback:function(t,e){this.onResize=t,this.onResizeContext=e},signalSizeChange:function(){if(!n.Rectangle.sameDimensions(this,this._lastReportedCanvasSize)||!n.Rectangle.sameDimensions(this.game,this._lastReportedGameSize)){var t=this.width,e=this.height;this._lastReportedCanvasSize.setTo(0,0,t,e),this._lastReportedGameSize.setTo(0,0,this.game.width,this.game.height),this.grid&&this.grid.onResize(t,e),this.onSizeChange.dispatch(this,t,e),this.currentScaleMode===n.ScaleManager.RESIZE&&(this.game.state.resize(t,e),this.game.load.resize(t,e))}},setMinMax:function(t,e,i,s){this.minWidth=t,this.minHeight=e,void 0!==i&&(this.maxWidth=i),void 0!==s&&(this.maxHeight=s)},preUpdate:function(){if(!(this.game.time.time<this._lastUpdate+this._updateThrottle)){var t=this._updateThrottle;this._updateThrottleReset=t>=400?0:100,this.dom.getOffset(this.game.canvas,this.offset);var e=this._parentBounds.width,i=this._parentBounds.height,s=this.getParentBounds(this._parentBounds),r=s.width!==e||s.height!==i,o=this.updateOrientationState();(r||o)&&(this.onResize&&this.onResize.call(this.onResizeContext,this,s),this.updateLayout(),this.signalSizeChange());var a=2*this._updateThrottle;this._updateThrottle<t&&(a=Math.min(t,this._updateThrottleReset)),this._updateThrottle=n.Math.clamp(a,25,this.trackParentInterval),this._lastUpdate=this.game.time.time}},pauseUpdate:function(){this.preUpdate(),this._updateThrottle=this.trackParentInterval},updateDimensions:function(t,e,i){this.width=t*this.parentScaleFactor.x,this.height=e*this.parentScaleFactor.y,this.game.width=this.width,this.game.height=this.height,this.sourceAspectRatio=this.width/this.height,this.updateScalingAndBounds(),i&&(this.game.renderer.resize(this.width,this.height),this.game.camera.setSize(this.width,this.height),this.game.world.resize(this.width,this.height))},updateScalingAndBounds:function(){this.scaleFactor.x=this.game.width/this.width,this.scaleFactor.y=this.game.height/this.height,this.scaleFactorInversed.x=this.width/this.game.width,this.scaleFactorInversed.y=this.height/this.game.height,this.aspectRatio=this.width/this.height,this.game.canvas&&this.dom.getOffset(this.game.canvas,this.offset),this.bounds.setTo(this.offset.x,this.offset.y,this.width,this.height),this.game.input&&this.game.input.scale&&this.game.input.scale.setTo(this.scaleFactor.x,this.scaleFactor.y)},forceOrientation:function(t,e){void 0===e&&(e=!1),this.forceLandscape=t,this.forcePortrait=e,this.queueUpdate(!0)},classifyOrientation:function(t){return"portrait-primary"===t||"portrait-secondary"===t?"portrait":"landscape-primary"===t||"landscape-secondary"===t?"landscape":null},updateOrientationState:function(){var t=this.screenOrientation,e=this.incorrectOrientation;this.screenOrientation=this.dom.getScreenOrientation(this.compatibility.orientationFallback),this.incorrectOrientation=this.forceLandscape&&!this.isLandscape||this.forcePortrait&&!this.isPortrait;var i=t!==this.screenOrientation,s=e!==this.incorrectOrientation;return s&&(this.incorrectOrientation?this.enterIncorrectOrientation.dispatch():this.leaveIncorrectOrientation.dispatch()),(i||s)&&this.onOrientationChange.dispatch(this,t,e),i||s},orientationChange:function(t){this.event=t,this.queueUpdate(!0)},windowResize:function(t){this.event=t,this.queueUpdate(!0)},scrollTop:function(){var t=this.compatibility.scrollTo;t&&window.scrollTo(t.x,t.y)},refresh:function(){this.scrollTop(),this.queueUpdate(!0)},updateLayout:function(){var t=this.currentScaleMode;if(t===n.ScaleManager.RESIZE)return void this.reflowGame();if(this.scrollTop(),this.compatibility.forceMinimumDocumentHeight&&(document.documentElement.style.minHeight=window.innerHeight+"px"),this.incorrectOrientation?this.setMaximum():t===n.ScaleManager.EXACT_FIT?this.setExactFit():t===n.ScaleManager.SHOW_ALL?!this.isFullScreen&&this.boundingParent&&this.compatibility.canExpandParent?(this.setShowAll(!0),this.resetCanvas(),this.setShowAll()):this.setShowAll():t===n.ScaleManager.NO_SCALE?(this.width=this.game.width,this.height=this.game.height):t===n.ScaleManager.USER_SCALE&&(this.width=this.game.width*this._userScaleFactor.x-this._userScaleTrim.x,this.height=this.game.height*this._userScaleFactor.y-this._userScaleTrim.y),!this.compatibility.canExpandParent&&(t===n.ScaleManager.SHOW_ALL||t===n.ScaleManager.USER_SCALE)){var e=this.getParentBounds(this._tempBounds);this.width=Math.min(this.width,e.width),this.height=Math.min(this.height,e.height)}this.width=0|this.width,this.height=0|this.height,this.reflowCanvas()},getParentBounds:function(t){var e=t||new n.Rectangle,i=this.boundingParent,s=this.dom.visualBounds,r=this.dom.layoutBounds;if(i){var o=i.getBoundingClientRect(),a=i.offsetParent?i.offsetParent.getBoundingClientRect():i.getBoundingClientRect();e.setTo(o.left-a.left,o.top-a.top,o.width,o.height);var h=this.windowConstraints;if(h.right){var l="layout"===h.right?r:s;e.right=Math.min(e.right,l.width)}if(h.bottom){var l="layout"===h.bottom?r:s;e.bottom=Math.min(e.bottom,l.height)}}else e.setTo(0,0,s.width,s.height);return e.setTo(Math.round(e.x),Math.round(e.y),Math.round(e.width),Math.round(e.height)),e},alignCanvas:function(t,e){var i=this.getParentBounds(this._tempBounds),s=this.game.canvas,n=this.margin;if(t){n.left=n.right=0;var r=s.getBoundingClientRect();if(this.width<i.width&&!this.incorrectOrientation){var o=r.left-i.x,a=i.width/2-this.width/2;a=Math.max(a,0);var h=a-o;n.left=Math.round(h)}s.style.marginLeft=n.left+"px",0!==n.left&&(n.right=-(i.width-r.width-n.left),s.style.marginRight=n.right+"px")}if(e){n.top=n.bottom=0;var r=s.getBoundingClientRect();if(this.height<i.height&&!this.incorrectOrientation){var o=r.top-i.y,a=i.height/2-this.height/2;a=Math.max(a,0);var h=a-o;n.top=Math.round(h)}s.style.marginTop=n.top+"px",0!==n.top&&(n.bottom=-(i.height-r.height-n.top),s.style.marginBottom=n.bottom+"px")}n.x=n.left,n.y=n.top},reflowGame:function(){this.resetCanvas("","");var t=this.getParentBounds(this._tempBounds);this.updateDimensions(t.width,t.height,!0)},reflowCanvas:function(){this.incorrectOrientation||(this.width=n.Math.clamp(this.width,this.minWidth||0,this.maxWidth||this.width),this.height=n.Math.clamp(this.height,this.minHeight||0,this.maxHeight||this.height)),this.resetCanvas(),this.compatibility.noMargins||(this.isFullScreen&&this._createdFullScreenTarget?this.alignCanvas(!0,!0):this.alignCanvas(this.pageAlignHorizontally,this.pageAlignVertically)),this.updateScalingAndBounds()},resetCanvas:function(t,e){void 0===t&&(t=this.width+"px"),void 0===e&&(e=this.height+"px");var i=this.game.canvas;this.compatibility.noMargins||(i.style.marginLeft="",i.style.marginTop="",i.style.marginRight="",i.style.marginBottom=""),i.style.width=t,i.style.height=e},queueUpdate:function(t){t&&(this._parentBounds.width=0,this._parentBounds.height=0),this._updateThrottle=this._updateThrottleReset},reset:function(t){t&&this.grid&&this.grid.reset()},setMaximum:function(){this.width=this.dom.visualBounds.width,this.height=this.dom.visualBounds.height},setShowAll:function(t){var e,i=this.getParentBounds(this._tempBounds),s=i.width,n=i.height;e=t?Math.max(n/this.game.height,s/this.game.width):Math.min(n/this.game.height,s/this.game.width),this.width=Math.round(this.game.width*e),this.height=Math.round(this.game.height*e)},setExactFit:function(){var t=this.getParentBounds(this._tempBounds);this.width=t.width,this.height=t.height,this.isFullScreen||(this.maxWidth&&(this.width=Math.min(this.width,this.maxWidth)),this.maxHeight&&(this.height=Math.min(this.height,this.maxHeight)))},createFullScreenTarget:function(){var t=document.createElement("div");return t.style.margin="0",t.style.padding="0",t.style.background="#000",t},startFullScreen:function(t,e){if(this.isFullScreen)return!1;if(!this.compatibility.supportsFullScreen){var i=this;return void setTimeout(function(){i.fullScreenError()},10)}if("when-not-mouse"===this.compatibility.clickTrampoline){var s=this.game.input;if(s.activePointer&&s.activePointer!==s.mousePointer&&(e||!1!==e))return void s.activePointer.addClickTrampoline("startFullScreen",this.startFullScreen,this,[t,!1])}void 0!==t&&this.game.renderType===n.CANVAS&&(this.game.stage.smoothed=t);var r=this.fullScreenTarget;r||(this.cleanupCreatedTarget(),this._createdFullScreenTarget=this.createFullScreenTarget(),r=this._createdFullScreenTarget);var o={targetElement:r};if(this.hasPhaserSetFullScreen=!0,this.onFullScreenInit.dispatch(this,o),this._createdFullScreenTarget){var a=this.game.canvas;a.parentNode.insertBefore(r,a),r.appendChild(a)}return this.game.device.fullscreenKeyboard?r[this.game.device.requestFullscreen](Element.ALLOW_KEYBOARD_INPUT):r[this.game.device.requestFullscreen](),!0},stopFullScreen:function(){return!(!this.isFullScreen||!this.compatibility.supportsFullScreen)&&(this.hasPhaserSetFullScreen=!1,document[this.game.device.cancelFullscreen](),!0)},cleanupCreatedTarget:function(){var t=this._createdFullScreenTarget;if(t&&t.parentNode){var e=t.parentNode;e.insertBefore(this.game.canvas,t),e.removeChild(t)}this._createdFullScreenTarget=null},prepScreenMode:function(t){var e=!!this._createdFullScreenTarget,i=this._createdFullScreenTarget||this.fullScreenTarget;t?(e||this.fullScreenScaleMode===n.ScaleManager.EXACT_FIT)&&i!==this.game.canvas&&(this._fullScreenRestore={targetWidth:i.style.width,targetHeight:i.style.height},i.style.width="100%",i.style.height="100%"):(this._fullScreenRestore&&(i.style.width=this._fullScreenRestore.targetWidth,i.style.height=this._fullScreenRestore.targetHeight,this._fullScreenRestore=null),this.updateDimensions(this._gameSize.width,this._gameSize.height,!0),this.resetCanvas())},fullScreenChange:function(t){this.event=t,this.isFullScreen?(this.prepScreenMode(!0),this.updateLayout(),this.queueUpdate(!0)):(this.prepScreenMode(!1),this.cleanupCreatedTarget(),this.updateLayout(),this.queueUpdate(!0)),this.onFullScreenChange.dispatch(this,this.width,this.height)},fullScreenError:function(t){this.event=t,this.cleanupCreatedTarget(),console.warn("Phaser.ScaleManager: requestFullscreen failed or device does not support the Fullscreen API"),this.onFullScreenError.dispatch(this)},scaleSprite:function(t,e,i,s){if(void 0===e&&(e=this.width),void 0===i&&(i=this.height),void 0===s&&(s=!1),!t||!t.scale)return t;if(t.scale.x=1,t.scale.y=1,t.width<=0||t.height<=0||e<=0||i<=0)return t;var n=e,r=t.height*e/t.width,o=t.width*i/t.height,a=i,h=o>e;return h=h?s:!s,h?(t.width=Math.floor(n),t.height=Math.floor(r)):(t.width=Math.floor(o),t.height=Math.floor(a)),t},destroy:function(){this.game.onResume.remove(this._gameResumed,this),window.removeEventListener("orientationchange",this._orientationChange,!1),window.removeEventListener("resize",this._windowResize,!1),this.compatibility.supportsFullScreen&&(document.removeEventListener("webkitfullscreenchange",this._fullScreenChange,!1),document.removeEventListener("mozfullscreenchange",this._fullScreenChange,!1),document.removeEventListener("MSFullscreenChange",this._fullScreenChange,!1),document.removeEventListener("fullscreenchange",this._fullScreenChange,!1),document.removeEventListener("webkitfullscreenerror",this._fullScreenError,!1),document.removeEventListener("mozfullscreenerror",this._fullScreenError,!1),document.removeEventListener("MSFullscreenError",this._fullScreenError,!1),document.removeEventListener("fullscreenerror",this._fullScreenError,!1))}},n.ScaleManager.prototype.constructor=n.ScaleManager,Object.defineProperty(n.ScaleManager.prototype,"boundingParent",{get:function(){return this.parentIsWindow||this.isFullScreen&&this.hasPhaserSetFullScreen&&!this._createdFullScreenTarget?null:this.game.canvas&&this.game.canvas.parentNode||null}}),Object.defineProperty(n.ScaleManager.prototype,"scaleMode",{get:function(){return this._scaleMode},set:function(t){return t!==this._scaleMode&&(this.isFullScreen||(this.updateDimensions(this._gameSize.width,this._gameSize.height,!0),this.queueUpdate(!0)),this._scaleMode=t),this._scaleMode}}),Object.defineProperty(n.ScaleManager.prototype,"fullScreenScaleMode",{get:function(){return this._fullScreenScaleMode},set:function(t){return t!==this._fullScreenScaleMode&&(this.isFullScreen?(this.prepScreenMode(!1),this._fullScreenScaleMode=t,this.prepScreenMode(!0),this.queueUpdate(!0)):this._fullScreenScaleMode=t),this._fullScreenScaleMode}}),Object.defineProperty(n.ScaleManager.prototype,"currentScaleMode",{get:function(){return this.isFullScreen?this._fullScreenScaleMode:this._scaleMode}}),Object.defineProperty(n.ScaleManager.prototype,"pageAlignHorizontally",{get:function(){return this._pageAlignHorizontally},set:function(t){t!==this._pageAlignHorizontally&&(this._pageAlignHorizontally=t,this.queueUpdate(!0))}}),Object.defineProperty(n.ScaleManager.prototype,"pageAlignVertically",{get:function(){return this._pageAlignVertically},set:function(t){t!==this._pageAlignVertically&&(this._pageAlignVertically=t,this.queueUpdate(!0))}}),Object.defineProperty(n.ScaleManager.prototype,"isFullScreen",{get:function(){return!!(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)}}),Object.defineProperty(n.ScaleManager.prototype,"isPortrait",{get:function(){return"portrait"===this.classifyOrientation(this.screenOrientation)}}),Object.defineProperty(n.ScaleManager.prototype,"isLandscape",{get:function(){return"landscape"===this.classifyOrientation(this.screenOrientation)}}),Object.defineProperty(n.ScaleManager.prototype,"isGamePortrait",{get:function(){return this.height>this.width}}),Object.defineProperty(n.ScaleManager.prototype,"isGameLandscape",{get:function(){return this.width>this.height}}),n.Utils.Debug=function(t){this.game=t,this.sprite=null,this.bmd=null,this.canvas=null,this.context=null,this.font="14px Courier",this.columnWidth=100,this.lineHeight=16,this.renderShadow=!0,this.currentX=0,this.currentY=0,this.currentAlpha=1,this.dirty=!1},n.Utils.Debug.prototype={boot:function(){this.game.renderType===n.CANVAS?this.context=this.game.context:(this.bmd=new n.BitmapData(this.game,"__DEBUG",this.game.width,this.game.height,!0),this.sprite=this.game.make.image(0,0,this.bmd),this.game.stage.addChild(this.sprite),this.game.scale.onSizeChange.add(this.resize,this),this.canvas=PIXI.CanvasPool.create(this,this.game.width,this.game.height),this.context=this.canvas.getContext("2d"))},resize:function(t,e,i){this.bmd.resize(e,i),this.canvas.width=e,this.canvas.height=i},preUpdate:function(){this.dirty&&this.sprite&&(this.bmd.clear(),this.bmd.draw(this.canvas,0,0),this.context.clearRect(0,0,this.game.width,this.game.height),this.dirty=!1)},reset:function(){this.context&&this.context.clearRect(0,0,this.game.width,this.game.height),this.sprite&&this.bmd.clear()},start:function(t,e,i,s){"number"!=typeof t&&(t=0),"number"!=typeof e&&(e=0),i=i||"rgb(255,255,255)",void 0===s&&(s=0),this.currentX=t,this.currentY=e,this.currentColor=i,this.columnWidth=s,this.dirty=!0,this.context.save(),this.context.setTransform(1,0,0,1,0,0),this.context.strokeStyle=i,this.context.fillStyle=i,this.context.font=this.font,this.context.globalAlpha=this.currentAlpha},stop:function(){this.context.restore()},line:function(){for(var t=this.currentX,e=0;e<arguments.length;e++)this.renderShadow&&(this.context.fillStyle="rgb(0,0,0)",this.context.fillText(arguments[e],t+1,this.currentY+1),this.context.fillStyle=this.currentColor),this.context.fillText(arguments[e],t,this.currentY),t+=this.columnWidth;this.currentY+=this.lineHeight},soundInfo:function(t,e,i,s){this.start(e,i,s),this.line("Sound: "+t.key+" Locked: "+t.game.sound.touchLocked),this.line("Is Ready?: "+this.game.cache.isSoundReady(t.key)+" Pending Playback: "+t.pendingPlayback),this.line("Decoded: "+t.isDecoded+" Decoding: "+t.isDecoding),this.line("Total Duration: "+t.totalDuration+" Playing: "+t.isPlaying),this.line("Time: "+t.currentTime),this.line("Volume: "+t.volume+" Muted: "+t.mute),this.line("WebAudio: "+t.usingWebAudio+" Audio: "+t.usingAudioTag),""!==t.currentMarker&&(this.line("Marker: "+t.currentMarker+" Duration: "+t.duration+" (ms: "+t.durationMS+")"),this.line("Start: "+t.markers[t.currentMarker].start+" Stop: "+t.markers[t.currentMarker].stop),this.line("Position: "+t.position)),this.stop()},cameraInfo:function(t,e,i,s){this.start(e,i,s),this.line("Camera ("+t.width+" x "+t.height+")"),this.line("X: "+t.x+" Y: "+t.y),t.bounds&&this.line("Bounds x: "+t.bounds.x+" Y: "+t.bounds.y+" w: "+t.bounds.width+" h: "+t.bounds.height),this.line("View x: "+t.view.x+" Y: "+t.view.y+" w: "+t.view.width+" h: "+t.view.height),this.line("Total in view: "+t.totalInView),this.stop()},timer:function(t,e,i,s){this.start(e,i,s),this.line("Timer (running: "+t.running+" expired: "+t.expired+")"),this.line("Next Tick: "+t.next+" Duration: "+t.duration),this.line("Paused: "+t.paused+" Length: "+t.length),this.stop()},pointer:function(t,e,i,s,n){null!=t&&(void 0===e&&(e=!1),i=i||"rgba(0,255,0,0.5)",s=s||"rgba(255,0,0,0.5)",!0===e&&!0===t.isUp||(this.start(t.x,t.y-100,n),this.context.beginPath(),this.context.arc(t.x,t.y,t.circle.radius,0,2*Math.PI),t.active?this.context.fillStyle=i:this.context.fillStyle=s,this.context.fill(),this.context.closePath(),this.context.beginPath(),this.context.moveTo(t.positionDown.x,t.positionDown.y),this.context.lineTo(t.position.x,t.position.y),this.context.lineWidth=2,this.context.stroke(),this.context.closePath(),this.line("ID: "+t.id+" Active: "+t.active),this.line("World X: "+t.worldX+" World Y: "+t.worldY),this.line("Screen X: "+t.x+" Screen Y: "+t.y+" In: "+t.withinGame),this.line("Duration: "+t.duration+" ms"),this.line("is Down: "+t.isDown+" is Up: "+t.isUp),this.stop()))},spriteInputInfo:function(t,e,i,s){this.start(e,i,s),this.line("Sprite Input: ("+t.width+" x "+t.height+")"),this.line("x: "+t.input.pointerX().toFixed(1)+" y: "+t.input.pointerY().toFixed(1)),this.line("over: "+t.input.pointerOver()+" duration: "+t.input.overDuration().toFixed(0)),this.line("down: "+t.input.pointerDown()+" duration: "+t.input.downDuration().toFixed(0)),this.line("just over: "+t.input.justOver()+" just out: "+t.input.justOut()),this.stop()},key:function(t,e,i,s){this.start(e,i,s,150),this.line("Key:",t.keyCode,"isDown:",t.isDown),this.line("justDown:",t.justDown,"justUp:",t.justUp),this.line("Time Down:",t.timeDown.toFixed(0),"duration:",t.duration.toFixed(0)),this.stop()},inputInfo:function(t,e,i){this.start(t,e,i),this.line("Input"),this.line("X: "+this.game.input.x+" Y: "+this.game.input.y),this.line("World X: "+this.game.input.worldX+" World Y: "+this.game.input.worldY),this.line("Scale X: "+this.game.input.scale.x.toFixed(1)+" Scale Y: "+this.game.input.scale.x.toFixed(1)),this.line("Screen X: "+this.game.input.activePointer.screenX+" Screen Y: "+this.game.input.activePointer.screenY),this.stop()},spriteBounds:function(t,e,i){var s=t.getBounds();s.x+=this.game.camera.x,s.y+=this.game.camera.y,this.rectangle(s,e,i)},ropeSegments:function(t,e,i){var s=this;t.segments.forEach(function(t){s.rectangle(t,e,i)},this)},spriteInfo:function(t,e,i,s){this.start(e,i,s),this.line("Sprite: ("+t.width+" x "+t.height+") anchor: "+t.anchor.x+" x "+t.anchor.y),this.line("x: "+t.x.toFixed(1)+" y: "+t.y.toFixed(1)),this.line("angle: "+t.angle.toFixed(1)+" rotation: "+t.rotation.toFixed(1)),this.line("visible: "+t.visible+" in camera: "+t.inCamera),this.line("bounds x: "+t._bounds.x.toFixed(1)+" y: "+t._bounds.y.toFixed(1)+" w: "+t._bounds.width.toFixed(1)+" h: "+t._bounds.height.toFixed(1)),this.stop()},spriteCoords:function(t,e,i,s){this.start(e,i,s,100),t.name&&this.line(t.name),this.line("x:",t.x.toFixed(2),"y:",t.y.toFixed(2)),this.line("pos x:",t.position.x.toFixed(2),"pos y:",t.position.y.toFixed(2)),this.line("world x:",t.world.x.toFixed(2),"world y:",t.world.y.toFixed(2)),this.stop()},lineInfo:function(t,e,i,s){this.start(e,i,s,80),this.line("start.x:",t.start.x.toFixed(2),"start.y:",t.start.y.toFixed(2)),this.line("end.x:",t.end.x.toFixed(2),"end.y:",t.end.y.toFixed(2)),this.line("length:",t.length.toFixed(2),"angle:",t.angle),this.stop()},pixel:function(t,e,i,s){s=s||2,this.start(),this.context.fillStyle=i,this.context.fillRect(t,e,s,s),this.stop()},geom:function(t,e,i,s){void 0===i&&(i=!0),void 0===s&&(s=0),e=e||"rgba(0,255,0,0.4)",this.start(),this.context.fillStyle=e,this.context.strokeStyle=e,t instanceof n.Rectangle||1===s?i?this.context.fillRect(t.x-this.game.camera.x,t.y-this.game.camera.y,t.width,t.height):this.context.strokeRect(t.x-this.game.camera.x,t.y-this.game.camera.y,t.width,t.height):t instanceof n.Circle||2===s?(this.context.beginPath(),this.context.arc(t.x-this.game.camera.x,t.y-this.game.camera.y,t.radius,0,2*Math.PI,!1),this.context.closePath(),i?this.context.fill():this.context.stroke()):t instanceof n.Point||3===s?this.context.fillRect(t.x-this.game.camera.x,t.y-this.game.camera.y,4,4):(t instanceof n.Line||4===s)&&(this.context.lineWidth=1,this.context.beginPath(),this.context.moveTo(t.start.x+.5-this.game.camera.x,t.start.y+.5-this.game.camera.y),this.context.lineTo(t.end.x+.5-this.game.camera.x,t.end.y+.5-this.game.camera.y),this.context.closePath(),this.context.stroke()),this.stop()},rectangle:function(t,e,i){void 0===i&&(i=!0),e=e||"rgba(0, 255, 0, 0.4)",this.start(),i?(this.context.fillStyle=e,this.context.fillRect(t.x-this.game.camera.x,t.y-this.game.camera.y,t.width,t.height)):(this.context.strokeStyle=e,this.context.strokeRect(t.x-this.game.camera.x,t.y-this.game.camera.y,t.width,t.height)),this.stop()},text:function(t,e,i,s,n){s=s||"rgb(255,255,255)",n=n||"16px Courier",this.start(),this.context.font=n,this.renderShadow&&(this.context.fillStyle="rgb(0,0,0)",this.context.fillText(t,e+1,i+1)),this.context.fillStyle=s,this.context.fillText(t,e,i),this.stop()},quadTree:function(t,e){e=e||"rgba(255,0,0,0.3)",this.start();var i=t.bounds;if(0===t.nodes.length){this.context.strokeStyle=e,this.context.strokeRect(i.x,i.y,i.width,i.height),this.text("size: "+t.objects.length,i.x+4,i.y+16,"rgb(0,200,0)","12px Courier"),this.context.strokeStyle="rgb(0,255,0)";for(var s=0;s<t.objects.length;s++)this.context.strokeRect(t.objects[s].x,t.objects[s].y,t.objects[s].width,t.objects[s].height)}else for(var s=0;s<t.nodes.length;s++)this.quadTree(t.nodes[s]);this.stop()},body:function(t,e,i){t.body&&(this.start(),t.body.type===n.Physics.ARCADE?n.Physics.Arcade.Body.render(this.context,t.body,e,i):t.body.type===n.Physics.NINJA?n.Physics.Ninja.Body.render(this.context,t.body,e,i):t.body.type===n.Physics.BOX2D&&n.Physics.Box2D.renderBody(this.context,t.body,e),this.stop())},bodyInfo:function(t,e,i,s){t.body&&(this.start(e,i,s,210),t.body.type===n.Physics.ARCADE?n.Physics.Arcade.Body.renderBodyInfo(this,t.body):t.body.type===n.Physics.BOX2D&&this.game.physics.box2d.renderBodyInfo(this,t.body),this.stop())},box2dWorld:function(){this.start(),this.context.translate(-this.game.camera.view.x,-this.game.camera.view.y,0),this.game.physics.box2d.renderDebugDraw(this.context),this.stop()},box2dBody:function(t,e){this.start(),n.Physics.Box2D.renderBody(this.context,t,e),this.stop()},displayList:function(t){if(void 0===t&&(t=this.game.world),t.hasOwnProperty("renderOrderID")?console.log("["+t.renderOrderID+"]",t):console.log("[]",t),t.children&&t.children.length>0)for(var e=0;e<t.children.length;e++)this.game.debug.displayList(t.children[e])},destroy:function(){PIXI.CanvasPool.remove(this)}},n.Utils.Debug.prototype.constructor=n.Utils.Debug,n.DOM={getOffset:function(t,e){e=e||new n.Point;var i=t.getBoundingClientRect(),s=n.DOM.scrollY,r=n.DOM.scrollX,o=document.documentElement.clientTop,a=document.documentElement.clientLeft;return e.x=i.left+r-a,e.y=i.top+s-o,e},getBounds:function(t,e){return void 0===e&&(e=0),!(!(t=t&&!t.nodeType?t[0]:t)||1!==t.nodeType)&&this.calibrate(t.getBoundingClientRect(),e)},calibrate:function(t,e){e=+e||0;var i={width:0,height:0,left:0,right:0,top:0,bottom:0};return i.width=(i.right=t.right+e)-(i.left=t.left-e),i.height=(i.bottom=t.bottom+e)-(i.top=t.top-e),i},getAspectRatio:function(t){t=null==t?this.visualBounds:1===t.nodeType?this.getBounds(t):t;var e=t.width,i=t.height;return"function"==typeof e&&(e=e.call(t)),"function"==typeof i&&(i=i.call(t)),e/i},inLayoutViewport:function(t,e){var i=this.getBounds(t,e);return!!i&&i.bottom>=0&&i.right>=0&&i.top<=this.layoutBounds.width&&i.left<=this.layoutBounds.height},getScreenOrientation:function(t){var e=window.screen,i=e.orientation||e.mozOrientation||e.msOrientation;if(i&&"string"==typeof i.type)return i.type;if("string"==typeof i)return i;var s="portrait-primary",n="landscape-primary";if("screen"===t)return e.height>e.width?s:n;if("viewport"===t)return this.visualBounds.height>this.visualBounds.width?s:n;if("window.orientation"===t&&"number"==typeof window.orientation)return 0===window.orientation||180===window.orientation?s:n;if(window.matchMedia){if(window.matchMedia("(orientation: portrait)").matches)return s;if(window.matchMedia("(orientation: landscape)").matches)return n}return this.visualBounds.height>this.visualBounds.width?s:n},visualBounds:new n.Rectangle,layoutBounds:new n.Rectangle,documentBounds:new n.Rectangle},n.Device.whenReady(function(t){var e=window&&"pageXOffset"in window?function(){return window.pageXOffset}:function(){return document.documentElement.scrollLeft},i=window&&"pageYOffset"in window?function(){return window.pageYOffset}:function(){return document.documentElement.scrollTop};if(Object.defineProperty(n.DOM,"scrollX",{get:e}),Object.defineProperty(n.DOM,"scrollY",{get:i}),Object.defineProperty(n.DOM.visualBounds,"x",{get:e}),Object.defineProperty(n.DOM.visualBounds,"y",{get:i}),Object.defineProperty(n.DOM.layoutBounds,"x",{value:0}),Object.defineProperty(n.DOM.layoutBounds,"y",{value:0}),t.desktop&&document.documentElement.clientWidth<=window.innerWidth&&document.documentElement.clientHeight<=window.innerHeight){var s=function(){return Math.max(window.innerWidth,document.documentElement.clientWidth)},r=function(){return Math.max(window.innerHeight,document.documentElement.clientHeight)};Object.defineProperty(n.DOM.visualBounds,"width",{get:s}),Object.defineProperty(n.DOM.visualBounds,"height",{get:r}),Object.defineProperty(n.DOM.layoutBounds,"width",{get:s}),Object.defineProperty(n.DOM.layoutBounds,"height",{get:r})}else Object.defineProperty(n.DOM.visualBounds,"width",{get:function(){return window.innerWidth}}),Object.defineProperty(n.DOM.visualBounds,"height",{get:function(){return window.innerHeight}}),Object.defineProperty(n.DOM.layoutBounds,"width",{get:function(){var t=document.documentElement.clientWidth,e=window.innerWidth;return t<e?e:t}}),Object.defineProperty(n.DOM.layoutBounds,"height",{get:function(){var t=document.documentElement.clientHeight,e=window.innerHeight;return t<e?e:t}});Object.defineProperty(n.DOM.documentBounds,"x",{value:0}),Object.defineProperty(n.DOM.documentBounds,"y",{value:0}),Object.defineProperty(n.DOM.documentBounds,"width",{get:function(){var t=document.documentElement;return Math.max(t.clientWidth,t.offsetWidth,t.scrollWidth)}}),Object.defineProperty(n.DOM.documentBounds,"height",{get:function(){var t=document.documentElement;return Math.max(t.clientHeight,t.offsetHeight,t.scrollHeight)}})},null,!0),n.ArraySet=function(t){this.position=0,this.list=t||[]},n.ArraySet.prototype={add:function(t){return this.exists(t)||this.list.push(t),t},getIndex:function(t){return this.list.indexOf(t)},getByKey:function(t,e){for(var i=this.list.length;i--;)if(this.list[i][t]===e)return this.list[i];return null},exists:function(t){return this.list.indexOf(t)>-1},reset:function(){this.list.length=0},remove:function(t){var e=this.list.indexOf(t);if(e>-1)return this.list.splice(e,1),t},setAll:function(t,e){for(var i=this.list.length;i--;)this.list[i]&&(this.list[i][t]=e)},callAll:function(t){for(var e=Array.prototype.slice.call(arguments,1),i=this.list.length;i--;)this.list[i]&&this.list[i][t]&&this.list[i][t].apply(this.list[i],e)},removeAll:function(t){void 0===t&&(t=!1);for(var e=this.list.length;e--;)if(this.list[e]){var i=this.remove(this.list[e]);t&&i.destroy()}this.position=0,this.list=[]}},Object.defineProperty(n.ArraySet.prototype,"total",{get:function(){return this.list.length}}),Object.defineProperty(n.ArraySet.prototype,"first",{get:function(){return this.position=0,this.list.length>0?this.list[0]:null}}),Object.defineProperty(n.ArraySet.prototype,"next",{get:function(){return this.position<this.list.length?(this.position++,this.list[this.position]):null}}),n.ArraySet.prototype.constructor=n.ArraySet,n.ArrayUtils={getRandomItem:function(t,e,i){if(null===t)return null;void 0===e&&(e=0),void 0===i&&(i=t.length);var s=e+Math.floor(Math.random()*i);return void 0===t[s]?null:t[s]},removeRandomItem:function(t,e,i){if(null==t)return null;void 0===e&&(e=0),void 0===i&&(i=t.length);var s=e+Math.floor(Math.random()*i);if(s<t.length){var n=t.splice(s,1);return void 0===n[0]?null:n[0]}return null},shuffle:function(t){for(var e=t.length-1;e>0;e--){var i=Math.floor(Math.random()*(e+1)),s=t[e];t[e]=t[i],t[i]=s}return t},transposeMatrix:function(t){for(var e=t.length,i=t[0].length,s=new Array(i),n=0;n<i;n++){s[n]=new Array(e);for(var r=e-1;r>-1;r--)s[n][r]=t[r][n]}return s},rotateMatrix:function(t,e){if("string"!=typeof e&&(e=(e%360+360)%360),90===e||-270===e||"rotateLeft"===e)t=n.ArrayUtils.transposeMatrix(t),t=t.reverse();else if(-90===e||270===e||"rotateRight"===e)t=t.reverse(),t=n.ArrayUtils.transposeMatrix(t);else if(180===Math.abs(e)||"rotate180"===e){for(var i=0;i<t.length;i++)t[i].reverse();t=t.reverse()}return t},findClosest:function(t,e){if(!e.length)return NaN;if(1===e.length||t<e[0])return e[0];for(var i=1;e[i]<t;)i++;var s=e[i-1],n=i<e.length?e[i]:Number.POSITIVE_INFINITY;return n-t<=t-s?n:s},rotateRight:function(t){var e=t.pop();return t.unshift(e),e},rotateLeft:function(t){var e=t.shift();return t.push(e),e},rotate:function(t){var e=t.shift();return t.push(e),e},numberArray:function(t,e){for(var i=[],s=t;s<=e;s++)i.push(s);return i},numberArrayStep:function(t,e,i){void 0!==t&&null!==t||(t=0),void 0!==e&&null!==e||(e=t,t=0),void 0===i&&(i=1);for(var s=[],r=Math.max(n.Math.roundAwayFromZero((e-t)/(i||1)),0),o=0;o<r;o++)s.push(t),t+=i;return s}},n.LinkedList=function(){this.next=null,this.prev=null,this.first=null,this.last=null,this.total=0},n.LinkedList.prototype={add:function(t){return 0===this.total&&null===this.first&&null===this.last?(this.first=t,this.last=t,this.next=t,t.prev=this,this.total++,t):(this.last.next=t,t.prev=this.last,this.last=t,this.total++,t)},reset:function(){this.first=null,this.last=null,this.next=null,this.prev=null,this.total=0},remove:function(t){if(1===this.total)return this.reset(),void(t.next=t.prev=null);t===this.first?this.first=this.first.next:t===this.last&&(this.last=this.last.prev),t.prev&&(t.prev.next=t.next),t.next&&(t.next.prev=t.prev),t.next=t.prev=null,null===this.first&&(this.last=null),this.total--},callAll:function(t){if(this.first&&this.last){var e=this.first;do{e&&e[t]&&e[t].call(e),e=e.next}while(e!==this.last.next)}}},n.LinkedList.prototype.constructor=n.LinkedList,n.Create=function(t){this.game=t,this.bmd=null,this.canvas=null,this.ctx=null,this.palettes=[{0:"#000",1:"#9D9D9D",2:"#FFF",3:"#BE2633",4:"#E06F8B",5:"#493C2B",6:"#A46422",7:"#EB8931",8:"#F7E26B",9:"#2F484E",A:"#44891A",B:"#A3CE27",C:"#1B2632",D:"#005784",E:"#31A2F2",F:"#B2DCEF"},{0:"#000",1:"#191028",2:"#46af45",3:"#a1d685",4:"#453e78",5:"#7664fe",6:"#833129",7:"#9ec2e8",8:"#dc534b",9:"#e18d79",A:"#d6b97b",B:"#e9d8a1",C:"#216c4b",D:"#d365c8",E:"#afaab9",F:"#f5f4eb"},{0:"#000",1:"#2234d1",2:"#0c7e45",3:"#44aacc",4:"#8a3622",5:"#5c2e78",6:"#aa5c3d",7:"#b5b5b5",8:"#5e606e",9:"#4c81fb",A:"#6cd947",B:"#7be2f9",C:"#eb8a60",D:"#e23d69",E:"#ffd93f",F:"#fff"},{0:"#000",1:"#fff",2:"#8b4131",3:"#7bbdc5",4:"#8b41ac",5:"#6aac41",6:"#3931a4",7:"#d5de73",8:"#945a20",9:"#5a4100",A:"#bd736a",B:"#525252",C:"#838383",D:"#acee8b",E:"#7b73de",F:"#acacac"},{0:"#000",1:"#191028",2:"#46af45",3:"#a1d685",4:"#453e78",5:"#7664fe",6:"#833129",7:"#9ec2e8",8:"#dc534b",9:"#e18d79",A:"#d6b97b",B:"#e9d8a1",C:"#216c4b",D:"#d365c8",E:"#afaab9",F:"#fff"}]},n.Create.PALETTE_ARNE=0,n.Create.PALETTE_JMP=1,n.Create.PALETTE_CGA=2,n.Create.PALETTE_C64=3,n.Create.PALETTE_JAPANESE_MACHINE=4,n.Create.prototype={texture:function(t,e,i,s,n){void 0===i&&(i=8),void 0===s&&(s=i),void 0===n&&(n=0);var r=e[0].length*i,o=e.length*s;null===this.bmd&&(this.bmd=this.game.make.bitmapData(),this.canvas=this.bmd.canvas,this.ctx=this.bmd.context),this.bmd.resize(r,o),this.bmd.clear();for(var a=0;a<e.length;a++)for(var h=e[a],l=0;l<h.length;l++){var c=h[l];"."!==c&&" "!==c&&(this.ctx.fillStyle=this.palettes[n][c],this.ctx.fillRect(l*i,a*s,i,s))}return this.bmd.generateTexture(t)},grid:function(t,e,i,s,n,r){null===this.bmd&&(this.bmd=this.game.make.bitmapData(),this.canvas=this.bmd.canvas,this.ctx=this.bmd.context),this.bmd.resize(e,i),this.ctx.fillStyle=r;for(var o=0;o<i;o+=n)this.ctx.fillRect(0,o,e,1);for(var a=0;a<e;a+=s)this.ctx.fillRect(a,0,1,i);return this.bmd.generateTexture(t)}},n.Create.prototype.constructor=n.Create,n.FlexGrid=function(t,e,i){this.game=t.game,this.manager=t,this.width=e,this.height=i,this.boundsCustom=new n.Rectangle(0,0,e,i),this.boundsFluid=new n.Rectangle(0,0,e,i),this.boundsFull=new n.Rectangle(0,0,e,i),this.boundsNone=new n.Rectangle(0,0,e,i),this.positionCustom=new n.Point(0,0),this.positionFluid=new n.Point(0,0),this.positionFull=new n.Point(0,0),this.positionNone=new n.Point(0,0),this.scaleCustom=new n.Point(1,1),this.scaleFluid=new n.Point(1,1),this.scaleFluidInversed=new n.Point(1,1),this.scaleFull=new n.Point(1,1),this.scaleNone=new n.Point(1,1),this.customWidth=0,this.customHeight=0,this.customOffsetX=0,this.customOffsetY=0,this.ratioH=e/i,this.ratioV=i/e,this.multiplier=0,this.layers=[]},n.FlexGrid.prototype={setSize:function(t,e){this.width=t,this.height=e,this.ratioH=t/e,this.ratioV=e/t,this.scaleNone=new n.Point(1,1),this.boundsNone.width=this.width,this.boundsNone.height=this.height,this.refresh()},createCustomLayer:function(t,e,i,s){void 0===s&&(s=!0),this.customWidth=t,this.customHeight=e,this.boundsCustom.width=t,this.boundsCustom.height=e;var r=new n.FlexLayer(this,this.positionCustom,this.boundsCustom,this.scaleCustom);return s&&this.game.world.add(r),this.layers.push(r),void 0!==i&&null!==typeof i&&r.addMultiple(i),r},createFluidLayer:function(t,e){void 0===e&&(e=!0);var i=new n.FlexLayer(this,this.positionFluid,this.boundsFluid,this.scaleFluid);return e&&this.game.world.add(i),this.layers.push(i),void 0!==t&&null!==typeof t&&i.addMultiple(t),i},createFullLayer:function(t){var e=new n.FlexLayer(this,this.positionFull,this.boundsFull,this.scaleFluid);return this.game.world.add(e),this.layers.push(e),void 0!==t&&e.addMultiple(t),e},createFixedLayer:function(t){var e=new n.FlexLayer(this,this.positionNone,this.boundsNone,this.scaleNone);return this.game.world.add(e),this.layers.push(e),void 0!==t&&e.addMultiple(t),e},reset:function(){for(var t=this.layers.length;t--;)this.layers[t].persist||(this.layers[t].position=null,this.layers[t].scale=null,this.layers.slice(t,1))},onResize:function(t,e){this.ratioH=t/e,this.ratioV=e/t,this.refresh(t,e)},refresh:function(){this.multiplier=Math.min(this.manager.height/this.height,this.manager.width/this.width),this.boundsFluid.width=Math.round(this.width*this.multiplier),this.boundsFluid.height=Math.round(this.height*this.multiplier),this.scaleFluid.set(this.boundsFluid.width/this.width,this.boundsFluid.height/this.height),this.scaleFluidInversed.set(this.width/this.boundsFluid.width,this.height/this.boundsFluid.height),this.scaleFull.set(this.boundsFull.width/this.width,this.boundsFull.height/this.height),this.boundsFull.width=Math.round(this.manager.width*this.scaleFluidInversed.x),this.boundsFull.height=Math.round(this.manager.height*this.scaleFluidInversed.y),this.boundsFluid.centerOn(this.manager.bounds.centerX,this.manager.bounds.centerY),this.boundsNone.centerOn(this.manager.bounds.centerX,this.manager.bounds.centerY),this.positionFluid.set(this.boundsFluid.x,this.boundsFluid.y),this.positionNone.set(this.boundsNone.x,this.boundsNone.y)},fitSprite:function(t){this.manager.scaleSprite(t),t.x=this.manager.bounds.centerX,t.y=this.manager.bounds.centerY},debug:function(){this.game.debug.text(this.boundsFluid.width+" x "+this.boundsFluid.height,this.boundsFluid.x+4,this.boundsFluid.y+16),this.game.debug.geom(this.boundsFluid,"rgba(255,0,0,0.9",!1)}},n.FlexGrid.prototype.constructor=n.FlexGrid,n.FlexLayer=function(t,e,i,s){n.Group.call(this,t.game,null,"__flexLayer"+t.game.rnd.uuid(),!1),this.manager=t.manager,this.grid=t,this.persist=!1,this.position=e,this.bounds=i,this.scale=s,this.topLeft=i.topLeft,this.topMiddle=new n.Point(i.halfWidth,0),this.topRight=i.topRight,this.bottomLeft=i.bottomLeft,this.bottomMiddle=new n.Point(i.halfWidth,i.bottom),this.bottomRight=i.bottomRight},n.FlexLayer.prototype=Object.create(n.Group.prototype),n.FlexLayer.prototype.constructor=n.FlexLayer,n.FlexLayer.prototype.resize=function(){},n.FlexLayer.prototype.debug=function(){this.game.debug.text(this.bounds.width+" x "+this.bounds.height,this.bounds.x+4,this.bounds.y+16),this.game.debug.geom(this.bounds,"rgba(0,0,255,0.9",!1),this.game.debug.geom(this.topLeft,"rgba(255,255,255,0.9"),this.game.debug.geom(this.topMiddle,"rgba(255,255,255,0.9"),this.game.debug.geom(this.topRight,"rgba(255,255,255,0.9")},n.Color={packPixel:function(t,e,i,s){return n.Device.LITTLE_ENDIAN?(s<<24|i<<16|e<<8|t)>>>0:(t<<24|e<<16|i<<8|s)>>>0},unpackPixel:function(t,e,i,s){return void 0!==e&&null!==e||(e=n.Color.createColor()),void 0!==i&&null!==i||(i=!1),void 0!==s&&null!==s||(s=!1),n.Device.LITTLE_ENDIAN?(e.a=(4278190080&t)>>>24,e.b=(16711680&t)>>>16,e.g=(65280&t)>>>8,e.r=255&t):(e.r=(4278190080&t)>>>24,e.g=(16711680&t)>>>16,e.b=(65280&t)>>>8,e.a=255&t),e.color=t,e.rgba="rgba("+e.r+","+e.g+","+e.b+","+e.a/255+")",i&&n.Color.RGBtoHSL(e.r,e.g,e.b,e),s&&n.Color.RGBtoHSV(e.r,e.g,e.b,e),e},fromRGBA:function(t,e){return e||(e=n.Color.createColor()),e.r=(4278190080&t)>>>24,e.g=(16711680&t)>>>16,e.b=(65280&t)>>>8,e.a=255&t,e.rgba="rgba("+e.r+","+e.g+","+e.b+","+e.a+")",e},toRGBA:function(t,e,i,s){return t<<24|e<<16|i<<8|s},toABGR:function(t,e,i,s){return(s<<24|i<<16|e<<8|t)>>>0},RGBtoHSL:function(t,e,i,s){s||(s=n.Color.createColor(t,e,i,1)),t/=255,e/=255,i/=255;var r=Math.min(t,e,i),o=Math.max(t,e,i);if(s.h=0,s.s=0,s.l=(o+r)/2,o!==r){var a=o-r;s.s=s.l>.5?a/(2-o-r):a/(o+r),o===t?s.h=(e-i)/a+(e<i?6:0):o===e?s.h=(i-t)/a+2:o===i&&(s.h=(t-e)/a+4),s.h/=6}return s},HSLtoRGB:function(t,e,i,s){if(s?(s.r=i,s.g=i,s.b=i):s=n.Color.createColor(i,i,i),0!==e){var r=i<.5?i*(1+e):i+e-i*e,o=2*i-r;s.r=n.Color.hueToColor(o,r,t+1/3),s.g=n.Color.hueToColor(o,r,t),s.b=n.Color.hueToColor(o,r,t-1/3)}return s.r=Math.floor(255*s.r|0),s.g=Math.floor(255*s.g|0),s.b=Math.floor(255*s.b|0),n.Color.updateColor(s),s},RGBtoHSV:function(t,e,i,s){s||(s=n.Color.createColor(t,e,i,255)),t/=255,e/=255,i/=255;var r=Math.min(t,e,i),o=Math.max(t,e,i),a=o-r;return s.h=0,s.s=0===o?0:a/o,s.v=o,o!==r&&(o===t?s.h=(e-i)/a+(e<i?6:0):o===e?s.h=(i-t)/a+2:o===i&&(s.h=(t-e)/a+4),s.h/=6),s},HSVtoRGB:function(t,e,i,s){void 0===s&&(s=n.Color.createColor(0,0,0,1,t,e,0,i));var r,o,a,h=Math.floor(6*t),l=6*t-h,c=i*(1-e),u=i*(1-l*e),d=i*(1-(1-l)*e);switch(h%6){case 0:r=i,o=d,a=c;break;case 1:r=u,o=i,a=c;break;case 2:r=c,o=i,a=d;break;case 3:r=c,o=u,a=i;break;case 4:r=d,o=c,a=i;break;case 5:r=i,o=c,a=u}return s.r=Math.floor(255*r),s.g=Math.floor(255*o),s.b=Math.floor(255*a),n.Color.updateColor(s),s},hueToColor:function(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t},createColor:function(t,e,i,s,r,o,a,h){var l={r:t||0,g:e||0,b:i||0,a:s||1,h:r||0,s:o||0,l:a||0,v:h||0,color:0,color32:0,rgba:""};return n.Color.updateColor(l)},updateColor:function(t){return t.rgba="rgba("+t.r.toString()+","+t.g.toString()+","+t.b.toString()+","+t.a.toString()+")",t.color=n.Color.getColor(t.r,t.g,t.b),t.color32=n.Color.getColor32(255*t.a,t.r,t.g,t.b),t},getColor32:function(t,e,i,s){return t<<24|e<<16|i<<8|s},getColor:function(t,e,i){return t<<16|e<<8|i},RGBtoString:function(t,e,i,s,r){return void 0===s&&(s=255),void 0===r&&(r="#"),"#"===r?"#"+((1<<24)+(t<<16)+(e<<8)+i).toString(16).slice(1):"0x"+n.Color.componentToHex(s)+n.Color.componentToHex(t)+n.Color.componentToHex(e)+n.Color.componentToHex(i)},hexToRGB:function(t){var e=n.Color.hexToColor(t);if(e)return n.Color.getColor32(e.a,e.r,e.g,e.b)},hexToColor:function(t,e){t=t.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i,function(t,e,i,s){return e+e+i+i+s+s});var i=/^(?:#|0x)?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);if(i){var s=parseInt(i[1],16),r=parseInt(i[2],16),o=parseInt(i[3],16);e?(e.r=s,e.g=r,e.b=o):e=n.Color.createColor(s,r,o)}return e},webToColor:function(t,e){e||(e=n.Color.createColor());var i=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?))?\s*\)$/.exec(t);return i&&(e.r=parseInt(i[1],10),e.g=parseInt(i[2],10),e.b=parseInt(i[3],10),e.a=void 0!==i[4]?parseFloat(i[4]):1,n.Color.updateColor(e)),e},valueToColor:function(t,e){if(e||(e=n.Color.createColor()),"string"==typeof t)return 0===t.indexOf("rgb")?n.Color.webToColor(t,e):(e.a=1,n.Color.hexToColor(t,e));if("number"==typeof t){var i=n.Color.getRGB(t);return e.r=i.r,e.g=i.g,e.b=i.b,e.a=i.a/255,e}return e},componentToHex:function(t){var e=t.toString(16);return 1===e.length?"0"+e:e},HSVColorWheel:function(t,e){void 0===t&&(t=1),void 0===e&&(e=1);for(var i=[],s=0;s<=359;s++)i.push(n.Color.HSVtoRGB(s/359,t,e));return i},HSLColorWheel:function(t,e){void 0===t&&(t=.5),void 0===e&&(e=.5);for(var i=[],s=0;s<=359;s++)i.push(n.Color.HSLtoRGB(s/359,t,e));return i},interpolateColor:function(t,e,i,s,r){void 0===r&&(r=255);var o=n.Color.getRGB(t),a=n.Color.getRGB(e),h=(a.red-o.red)*s/i+o.red,l=(a.green-o.green)*s/i+o.green,c=(a.blue-o.blue)*s/i+o.blue;return n.Color.getColor32(r,h,l,c)},interpolateColorWithRGB:function(t,e,i,s,r,o){var a=n.Color.getRGB(t),h=(e-a.red)*o/r+a.red,l=(i-a.green)*o/r+a.green,c=(s-a.blue)*o/r+a.blue;return n.Color.getColor(h,l,c)},interpolateRGB:function(t,e,i,s,r,o,a,h){var l=(s-t)*h/a+t,c=(r-e)*h/a+e,u=(o-i)*h/a+i;return n.Color.getColor(l,c,u)},getRandomColor:function(t,e,i){if(void 0===t&&(t=0),void 0===e&&(e=255),void 0===i&&(i=255),e>255||t>e)return n.Color.getColor(255,255,255);var s=t+Math.round(Math.random()*(e-t)),r=t+Math.round(Math.random()*(e-t)),o=t+Math.round(Math.random()*(e-t));return n.Color.getColor32(i,s,r,o)},getRGB:function(t){return t>16777215?{alpha:t>>>24,red:t>>16&255,green:t>>8&255,blue:255&t,a:t>>>24,r:t>>16&255,g:t>>8&255,b:255&t}:{alpha:255,red:t>>16&255,green:t>>8&255,blue:255&t,a:255,r:t>>16&255,g:t>>8&255,b:255&t}},getWebRGB:function(t){if("object"==typeof t)return"rgba("+t.r.toString()+","+t.g.toString()+","+t.b.toString()+","+(t.a/255).toString()+")";var e=n.Color.getRGB(t);return"rgba("+e.r.toString()+","+e.g.toString()+","+e.b.toString()+","+(e.a/255).toString()+")"},getAlpha:function(t){return t>>>24},getAlphaFloat:function(t){return(t>>>24)/255},getRed:function(t){return t>>16&255},getGreen:function(t){return t>>8&255},getBlue:function(t){return 255&t},blendNormal:function(t){return t},blendLighten:function(t,e){return e>t?e:t},blendDarken:function(t,e){return e>t?t:e},blendMultiply:function(t,e){return t*e/255},blendAverage:function(t,e){return(t+e)/2},blendAdd:function(t,e){return Math.min(255,t+e)},blendSubtract:function(t,e){return Math.max(0,t+e-255)},blendDifference:function(t,e){return Math.abs(t-e)},blendNegation:function(t,e){return 255-Math.abs(255-t-e)},blendScreen:function(t,e){return 255-((255-t)*(255-e)>>8)},blendExclusion:function(t,e){return t+e-2*t*e/255},blendOverlay:function(t,e){return e<128?2*t*e/255:255-2*(255-t)*(255-e)/255},blendSoftLight:function(t,e){return e<128?2*(64+(t>>1))*(e/255):255-2*(255-(64+(t>>1)))*(255-e)/255},blendHardLight:function(t,e){return n.Color.blendOverlay(e,t)},blendColorDodge:function(t,e){return 255===e?e:Math.min(255,(t<<8)/(255-e))},blendColorBurn:function(t,e){return 0===e?e:Math.max(0,255-(255-t<<8)/e)},blendLinearDodge:function(t,e){return n.Color.blendAdd(t,e)},blendLinearBurn:function(t,e){return n.Color.blendSubtract(t,e)},blendLinearLight:function(t,e){return e<128?n.Color.blendLinearBurn(t,2*e):n.Color.blendLinearDodge(t,2*(e-128))},blendVividLight:function(t,e){return e<128?n.Color.blendColorBurn(t,2*e):n.Color.blendColorDodge(t,2*(e-128))},blendPinLight:function(t,e){return e<128?n.Color.blendDarken(t,2*e):n.Color.blendLighten(t,2*(e-128))},blendHardMix:function(t,e){return n.Color.blendVividLight(t,e)<128?0:255},blendReflect:function(t,e){return 255===e?e:Math.min(255,t*t/(255-e))},blendGlow:function(t,e){return n.Color.blendReflect(e,t)},blendPhoenix:function(t,e){return Math.min(t,e)-Math.max(t,e)+255}},n.Physics=function(t,e){e=e||{},this.game=t,this.config=e,this.arcade=null,this.p2=null,this.ninja=null,this.box2d=null,this.chipmunk=null,this.matter=null,this.parseConfig()},n.Physics.ARCADE=0,n.Physics.P2JS=1,n.Physics.NINJA=2,n.Physics.BOX2D=3,n.Physics.CHIPMUNK=4,n.Physics.MATTERJS=5,n.Physics.prototype={parseConfig:function(){this.config.hasOwnProperty("arcade")&&!0!==this.config.arcade||!n.Physics.hasOwnProperty("Arcade")||(this.arcade=new n.Physics.Arcade(this.game)),this.config.hasOwnProperty("ninja")&&!0===this.config.ninja&&n.Physics.hasOwnProperty("Ninja")&&(this.ninja=new n.Physics.Ninja(this.game)),this.config.hasOwnProperty("p2")&&!0===this.config.p2&&n.Physics.hasOwnProperty("P2")&&(this.p2=new n.Physics.P2(this.game,this.config)),this.config.hasOwnProperty("box2d")&&!0===this.config.box2d&&n.Physics.hasOwnProperty("BOX2D")&&(this.box2d=new n.Physics.BOX2D(this.game,this.config)),this.config.hasOwnProperty("matter")&&!0===this.config.matter&&n.Physics.hasOwnProperty("Matter")&&(this.matter=new n.Physics.Matter(this.game,this.config))},startSystem:function(t){t===n.Physics.ARCADE?this.arcade=new n.Physics.Arcade(this.game):t===n.Physics.P2JS?null===this.p2?this.p2=new n.Physics.P2(this.game,this.config):this.p2.reset():t===n.Physics.NINJA?this.ninja=new n.Physics.Ninja(this.game):t===n.Physics.BOX2D?null===this.box2d?this.box2d=new n.Physics.Box2D(this.game,this.config):this.box2d.reset():t===n.Physics.MATTERJS&&(null===this.matter?this.matter=new n.Physics.Matter(this.game,this.config):this.matter.reset())},enable:function(t,e,i){void 0===e&&(e=n.Physics.ARCADE),void 0===i&&(i=!1),e===n.Physics.ARCADE?this.arcade.enable(t):e===n.Physics.P2JS&&this.p2?this.p2.enable(t,i):e===n.Physics.NINJA&&this.ninja?this.ninja.enableAABB(t):e===n.Physics.BOX2D&&this.box2d?this.box2d.enable(t):e===n.Physics.MATTERJS&&this.matter?this.matter.enable(t):console.warn(t.key+" is attempting to enable a physics body using an unknown physics system.")},preUpdate:function(){this.p2&&this.p2.preUpdate(),this.box2d&&this.box2d.preUpdate(),this.matter&&this.matter.preUpdate()},update:function(){this.p2&&this.p2.update(),this.box2d&&this.box2d.update(),this.matter&&this.matter.update()},setBoundsToWorld:function(){this.arcade&&this.arcade.setBoundsToWorld(),this.ninja&&this.ninja.setBoundsToWorld(),this.p2&&this.p2.setBoundsToWorld(),this.box2d&&this.box2d.setBoundsToWorld(),this.matter&&this.matter.setBoundsToWorld()},clear:function(){this.p2&&this.p2.clear(),this.box2d&&this.box2d.clear(),this.matter&&this.matter.clear()},reset:function(){this.p2&&this.p2.reset(),this.box2d&&this.box2d.reset(),this.matter&&this.matter.reset()},destroy:function(){this.p2&&this.p2.destroy(),this.box2d&&this.box2d.destroy(),this.matter&&this.matter.destroy(),this.arcade=null,this.ninja=null,this.p2=null,this.box2d=null,this.matter=null}},n.Physics.prototype.constructor=n.Physics,n.Physics.Arcade=function(t){this.game=t,this.gravity=new n.Point,this.bounds=new n.Rectangle(0,0,t.world.width,t.world.height),this.checkCollision={up:!0,down:!0,left:!0,right:!0},this.maxObjects=10,this.maxLevels=4,this.OVERLAP_BIAS=4,this.forceX=!1,this.sortDirection=n.Physics.Arcade.LEFT_RIGHT,this.skipQuadTree=!0,this.isPaused=!1,this.quadTree=new n.QuadTree(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height,this.maxObjects,this.maxLevels),this._total=0,this.setBoundsToWorld()},n.Physics.Arcade.prototype.constructor=n.Physics.Arcade,n.Physics.Arcade.SORT_NONE=0,n.Physics.Arcade.LEFT_RIGHT=1,n.Physics.Arcade.RIGHT_LEFT=2,n.Physics.Arcade.TOP_BOTTOM=3,n.Physics.Arcade.BOTTOM_TOP=4,n.Physics.Arcade.prototype={setBounds:function(t,e,i,s){this.bounds.setTo(t,e,i,s)},setBoundsToWorld:function(){this.bounds.copyFrom(this.game.world.bounds)},enable:function(t,e){void 0===e&&(e=!0);var i=1;if(Array.isArray(t))for(i=t.length;i--;)t[i]instanceof n.Group?this.enable(t[i].children,e):(this.enableBody(t[i]),e&&t[i].hasOwnProperty("children")&&t[i].children.length>0&&this.enable(t[i],!0));else t instanceof n.Group?this.enable(t.children,e):(this.enableBody(t),e&&t.hasOwnProperty("children")&&t.children.length>0&&this.enable(t.children,!0))},enableBody:function(t){t.hasOwnProperty("body")&&null===t.body&&(t.body=new n.Physics.Arcade.Body(t),t.parent&&t.parent instanceof n.Group&&t.parent.addToHash(t))},updateMotion:function(t){var e=this.computeVelocity(0,t,t.angularVelocity,t.angularAcceleration,t.angularDrag,t.maxAngular)-t.angularVelocity;t.angularVelocity+=e,t.rotation+=t.angularVelocity*this.game.time.physicsElapsed,t.velocity.x=this.computeVelocity(1,t,t.velocity.x,t.acceleration.x,t.drag.x,t.maxVelocity.x),t.velocity.y=this.computeVelocity(2,t,t.velocity.y,t.acceleration.y,t.drag.y,t.maxVelocity.y)},computeVelocity:function(t,e,i,s,n,r){return void 0===r&&(r=1e4),1===t&&e.allowGravity?i+=(this.gravity.x+e.gravity.x)*this.game.time.physicsElapsed:2===t&&e.allowGravity&&(i+=(this.gravity.y+e.gravity.y)*this.game.time.physicsElapsed),s?i+=s*this.game.time.physicsElapsed:n&&(n*=this.game.time.physicsElapsed,i-n>0?i-=n:i+n<0?i+=n:i=0),i>r?i=r:i<-r&&(i=-r),i},overlap:function(t,e,i,s,n){if(i=i||null,s=s||null,n=n||i,this._total=0,!Array.isArray(t)&&Array.isArray(e))for(var r=0;r<e.length;r++)this.collideHandler(t,e[r],i,s,n,!0);else if(Array.isArray(t)&&!Array.isArray(e))for(var r=0;r<t.length;r++)this.collideHandler(t[r],e,i,s,n,!0);else if(Array.isArray(t)&&Array.isArray(e))for(var r=0;r<t.length;r++)for(var o=0;o<e.length;o++)this.collideHandler(t[r],e[o],i,s,n,!0);else this.collideHandler(t,e,i,s,n,!0);return this._total>0},collide:function(t,e,i,s,n){if(i=i||null,s=s||null,n=n||i,this._total=0,!Array.isArray(t)&&Array.isArray(e))for(var r=0;r<e.length;r++)this.collideHandler(t,e[r],i,s,n,!1);else if(Array.isArray(t)&&!Array.isArray(e))for(var r=0;r<t.length;r++)this.collideHandler(t[r],e,i,s,n,!1);else if(Array.isArray(t)&&Array.isArray(e))for(var r=0;r<t.length;r++)for(var o=0;o<e.length;o++)this.collideHandler(t[r],e[o],i,s,n,!1);else this.collideHandler(t,e,i,s,n,!1);return this._total>0},sortLeftRight:function(t,e){return t.body&&e.body?t.body.x-e.body.x:0},sortRightLeft:function(t,e){return t.body&&e.body?e.body.x-t.body.x:0},sortTopBottom:function(t,e){return t.body&&e.body?t.body.y-e.body.y:0},sortBottomTop:function(t,e){return t.body&&e.body?e.body.y-t.body.y:0},sort:function(t,e){null!==t.physicsSortDirection?e=t.physicsSortDirection:void 0===e&&(e=this.sortDirection),e===n.Physics.Arcade.LEFT_RIGHT?t.hash.sort(this.sortLeftRight):e===n.Physics.Arcade.RIGHT_LEFT?t.hash.sort(this.sortRightLeft):e===n.Physics.Arcade.TOP_BOTTOM?t.hash.sort(this.sortTopBottom):e===n.Physics.Arcade.BOTTOM_TOP&&t.hash.sort(this.sortBottomTop)},collideHandler:function(t,e,i,s,r,o){if(void 0===e&&t.physicsType===n.GROUP)return this.sort(t),void this.collideGroupVsSelf(t,i,s,r,o);t&&e&&t.exists&&e.exists&&(this.sortDirection!==n.Physics.Arcade.SORT_NONE&&(t.physicsType===n.GROUP&&this.sort(t),e.physicsType===n.GROUP&&this.sort(e)),t.physicsType===n.SPRITE?e.physicsType===n.SPRITE?this.collideSpriteVsSprite(t,e,i,s,r,o):e.physicsType===n.GROUP?this.collideSpriteVsGroup(t,e,i,s,r,o):e.physicsType===n.TILEMAPLAYER&&this.collideSpriteVsTilemapLayer(t,e,i,s,r,o):t.physicsType===n.GROUP?e.physicsType===n.SPRITE?this.collideSpriteVsGroup(e,t,i,s,r,o):e.physicsType===n.GROUP?this.collideGroupVsGroup(t,e,i,s,r,o):e.physicsType===n.TILEMAPLAYER&&this.collideGroupVsTilemapLayer(t,e,i,s,r,o):t.physicsType===n.TILEMAPLAYER&&(e.physicsType===n.SPRITE?this.collideSpriteVsTilemapLayer(e,t,i,s,r,o):e.physicsType===n.GROUP&&this.collideGroupVsTilemapLayer(e,t,i,s,r,o)))},collideSpriteVsSprite:function(t,e,i,s,n,r){return!(!t.body||!e.body)&&(this.separate(t.body,e.body,s,n,r)&&(i&&i.call(n,t,e),this._total++),!0)},collideSpriteVsGroup:function(t,e,i,s,r,o){if(0!==e.length&&t.body)if(this.skipQuadTree||t.body.skipQuadTree)for(var a={},h=0;h<e.hash.length;h++){var l=e.hash[h];if(l&&l.exists&&l.body){if(a=l.body.getBounds(a),this.sortDirection===n.Physics.Arcade.LEFT_RIGHT){if(t.body.right<a.x)break;if(a.right<t.body.x)continue}else if(this.sortDirection===n.Physics.Arcade.RIGHT_LEFT){if(t.body.x>a.right)break;if(a.x>t.body.right)continue}else if(this.sortDirection===n.Physics.Arcade.TOP_BOTTOM){if(t.body.bottom<a.y)break;if(a.bottom<t.body.y)continue}else if(this.sortDirection===n.Physics.Arcade.BOTTOM_TOP){if(t.body.y>a.bottom)break;if(a.y>t.body.bottom)continue}this.collideSpriteVsSprite(t,l,i,s,r,o)}}else{this.quadTree.clear(),this.quadTree.reset(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height,this.maxObjects,this.maxLevels),this.quadTree.populate(e);for(var c=this.quadTree.retrieve(t),h=0;h<c.length;h++)this.separate(t.body,c[h],s,r,o)&&(i&&i.call(r,t,c[h].sprite),this._total++)}},collideGroupVsSelf:function(t,e,i,s,r){if(0!==t.length)for(var o=0;o<t.hash.length;o++){var a={},h=t.hash[o];if(h&&h.exists&&h.body){a=h.body.getBounds(a);for(var l=o+1;l<t.hash.length;l++){var c={},u=t.hash[l];if(u&&u.exists&&u.body){if(c=u.body.getBounds(c),this.sortDirection===n.Physics.Arcade.LEFT_RIGHT){if(a.right<c.x)break;if(c.right<a.x)continue}else if(this.sortDirection===n.Physics.Arcade.RIGHT_LEFT){if(a.x>c.right)continue;if(c.x>a.right)break}else if(this.sortDirection===n.Physics.Arcade.TOP_BOTTOM){if(a.bottom<c.y)continue;if(c.bottom<a.y)break}else if(this.sortDirection===n.Physics.Arcade.BOTTOM_TOP){if(a.y>c.bottom)continue;if(c.y>h.body.bottom)break}this.collideSpriteVsSprite(h,u,e,i,s,r)}}}}},collideGroupVsGroup:function(t,e,i,s,r,o){if(0!==t.length&&0!==e.length)for(var a=0;a<t.children.length;a++)t.children[a].exists&&(t.children[a].physicsType===n.GROUP?this.collideGroupVsGroup(t.children[a],e,i,s,r,o):this.collideSpriteVsGroup(t.children[a],e,i,s,r,o))},separate:function(t,e,i,s,n){if(!t.enable||!e.enable||t.checkCollision.none||e.checkCollision.none||!this.intersects(t,e))return!1;if(i&&!1===i.call(s,t.sprite,e.sprite))return!1;if(t.isCircle&&e.isCircle)return this.separateCircle(t,e,n);if(t.isCircle!==e.isCircle){var r=t.isCircle?e:t,o=t.isCircle?t:e,a={x:r.x,y:r.y,right:r.right,bottom:r.bottom},h={x:o.x+o.radius,y:o.y+o.radius};if((h.y<a.y||h.y>a.bottom)&&(h.x<a.x||h.x>a.right))return this.separateCircle(t,e,n)}var l=!1,c=!1;this.forceX||Math.abs(this.gravity.y+t.gravity.y)<Math.abs(this.gravity.x+t.gravity.x)?(l=this.separateX(t,e,n),this.intersects(t,e)&&(c=this.separateY(t,e,n))):(c=this.separateY(t,e,n),this.intersects(t,e)&&(l=this.separateX(t,e,n)));var u=l||c;return u&&(n?(t.onOverlap&&t.onOverlap.dispatch(t.sprite,e.sprite),e.onOverlap&&e.onOverlap.dispatch(e.sprite,t.sprite)):(t.onCollide&&t.onCollide.dispatch(t.sprite,e.sprite),e.onCollide&&e.onCollide.dispatch(e.sprite,t.sprite))),u},intersects:function(t,e){return t!==e&&(t.isCircle?e.isCircle?n.Math.distance(t.center.x,t.center.y,e.center.x,e.center.y)<=t.radius+e.radius:this.circleBodyIntersects(t,e):e.isCircle?this.circleBodyIntersects(e,t):!(t.right<=e.position.x)&&(!(t.bottom<=e.position.y)&&(!(t.position.x>=e.right)&&!(t.position.y>=e.bottom))))},circleBodyIntersects:function(t,e){var i=n.Math.clamp(t.center.x,e.left,e.right),s=n.Math.clamp(t.center.y,e.top,e.bottom);return(t.center.x-i)*(t.center.x-i)+(t.center.y-s)*(t.center.y-s)<=t.radius*t.radius},separateCircle:function(t,e,i){this.getOverlapX(t,e),this.getOverlapY(t,e);var s=e.center.x-t.center.x,r=e.center.y-t.center.y,o=Math.atan2(r,s),a=0;if(t.isCircle!==e.isCircle){var h={x:e.isCircle?t.position.x:e.position.x,y:e.isCircle?t.position.y:e.position.y,right:e.isCircle?t.right:e.right,bottom:e.isCircle?t.bottom:e.bottom},l={x:t.isCircle?t.position.x+t.radius:e.position.x+e.radius,y:t.isCircle?t.position.y+t.radius:e.position.y+e.radius,radius:t.isCircle?t.radius:e.radius};l.y<h.y?l.x<h.x?a=n.Math.distance(l.x,l.y,h.x,h.y)-l.radius:l.x>h.right&&(a=n.Math.distance(l.x,l.y,h.right,h.y)-l.radius):l.y>h.bottom&&(l.x<h.x?a=n.Math.distance(l.x,l.y,h.x,h.bottom)-l.radius:l.x>h.right&&(a=n.Math.distance(l.x,l.y,h.right,h.bottom)-l.radius)),a*=-1}else a=t.radius+e.radius-n.Math.distance(t.center.x,t.center.y,e.center.x,e.center.y);if(i||0===a||t.immovable&&e.immovable||t.customSeparateX||e.customSeparateX)return 0!==a&&(t.onOverlap&&t.onOverlap.dispatch(t.sprite,e.sprite),e.onOverlap&&e.onOverlap.dispatch(e.sprite,t.sprite)),0!==a;var c={x:t.velocity.x*Math.cos(o)+t.velocity.y*Math.sin(o),y:t.velocity.x*Math.sin(o)-t.velocity.y*Math.cos(o)},u={x:e.velocity.x*Math.cos(o)+e.velocity.y*Math.sin(o),y:e.velocity.x*Math.sin(o)-e.velocity.y*Math.cos(o)},d=((t.mass-e.mass)*c.x+2*e.mass*u.x)/(t.mass+e.mass),p=(2*t.mass*c.x+(e.mass-t.mass)*u.x)/(t.mass+e.mass);return t.immovable||(t.velocity.x=(d*Math.cos(o)-c.y*Math.sin(o))*t.bounce.x,t.velocity.y=(c.y*Math.cos(o)+d*Math.sin(o))*t.bounce.y),e.immovable||(e.velocity.x=(p*Math.cos(o)-u.y*Math.sin(o))*e.bounce.x,e.velocity.y=(u.y*Math.cos(o)+p*Math.sin(o))*e.bounce.y),Math.abs(o)<Math.PI/2?t.velocity.x>0&&!t.immovable&&e.velocity.x>t.velocity.x?t.velocity.x*=-1:e.velocity.x<0&&!e.immovable&&t.velocity.x<e.velocity.x?e.velocity.x*=-1:t.velocity.y>0&&!t.immovable&&e.velocity.y>t.velocity.y?t.velocity.y*=-1:e.velocity.y<0&&!e.immovable&&t.velocity.y<e.velocity.y&&(e.velocity.y*=-1):Math.abs(o)>Math.PI/2&&(t.velocity.x<0&&!t.immovable&&e.velocity.x<t.velocity.x?t.velocity.x*=-1:e.velocity.x>0&&!e.immovable&&t.velocity.x>e.velocity.x?e.velocity.x*=-1:t.velocity.y<0&&!t.immovable&&e.velocity.y<t.velocity.y?t.velocity.y*=-1:e.velocity.y>0&&!e.immovable&&t.velocity.x>e.velocity.y&&(e.velocity.y*=-1)),t.immovable||(t.x+=t.velocity.x*this.game.time.physicsElapsed-a*Math.cos(o),t.y+=t.velocity.y*this.game.time.physicsElapsed-a*Math.sin(o)),e.immovable||(e.x+=e.velocity.x*this.game.time.physicsElapsed+a*Math.cos(o),e.y+=e.velocity.y*this.game.time.physicsElapsed+a*Math.sin(o)),t.onCollide&&t.onCollide.dispatch(t.sprite,e.sprite),e.onCollide&&e.onCollide.dispatch(e.sprite,t.sprite),!0},getOverlapX:function(t,e,i){var s=0,n=t.deltaAbsX()+e.deltaAbsX()+this.OVERLAP_BIAS;return 0===t.deltaX()&&0===e.deltaX()?(t.embedded=!0,e.embedded=!0):t.deltaX()>e.deltaX()?(s=t.right-e.x,s>n&&!i||!1===t.checkCollision.right||!1===e.checkCollision.left?s=0:(t.touching.none=!1,t.touching.right=!0,e.touching.none=!1,e.touching.left=!0)):t.deltaX()<e.deltaX()&&(s=t.x-e.width-e.x,-s>n&&!i||!1===t.checkCollision.left||!1===e.checkCollision.right?s=0:(t.touching.none=!1,t.touching.left=!0,e.touching.none=!1,e.touching.right=!0)),t.overlapX=s,e.overlapX=s,s},getOverlapY:function(t,e,i){var s=0,n=t.deltaAbsY()+e.deltaAbsY()+this.OVERLAP_BIAS;return 0===t.deltaY()&&0===e.deltaY()?(t.embedded=!0,e.embedded=!0):t.deltaY()>e.deltaY()?(s=t.bottom-e.y,s>n&&!i||!1===t.checkCollision.down||!1===e.checkCollision.up?s=0:(t.touching.none=!1,t.touching.down=!0,e.touching.none=!1,e.touching.up=!0)):t.deltaY()<e.deltaY()&&(s=t.y-e.bottom,-s>n&&!i||!1===t.checkCollision.up||!1===e.checkCollision.down?s=0:(t.touching.none=!1,t.touching.up=!0,e.touching.none=!1,e.touching.down=!0)),t.overlapY=s,e.overlapY=s,s},separateX:function(t,e,i){var s=this.getOverlapX(t,e,i);if(i||0===s||t.immovable&&e.immovable||t.customSeparateX||e.customSeparateX)return 0!==s||t.embedded&&e.embedded;var n=t.velocity.x,r=e.velocity.x;if(t.immovable||e.immovable)t.immovable?(e.x+=s,e.velocity.x=n-r*e.bounce.x,t.moves&&(e.y+=(t.y-t.prev.y)*t.friction.y)):(t.x-=s,t.velocity.x=r-n*t.bounce.x,e.moves&&(t.y+=(e.y-e.prev.y)*e.friction.y));else{s*=.5,t.x-=s,e.x+=s;var o=Math.sqrt(r*r*e.mass/t.mass)*(r>0?1:-1),a=Math.sqrt(n*n*t.mass/e.mass)*(n>0?1:-1),h=.5*(o+a);o-=h,a-=h,t.velocity.x=h+o*t.bounce.x,e.velocity.x=h+a*e.bounce.x}return!0},separateY:function(t,e,i){var s=this.getOverlapY(t,e,i);if(i||0===s||t.immovable&&e.immovable||t.customSeparateY||e.customSeparateY)return 0!==s||t.embedded&&e.embedded;var n=t.velocity.y,r=e.velocity.y;if(t.immovable||e.immovable)t.immovable?(e.y+=s,e.velocity.y=n-r*e.bounce.y,t.moves&&(e.x+=(t.x-t.prev.x)*t.friction.x)):(t.y-=s,t.velocity.y=r-n*t.bounce.y,e.moves&&(t.x+=(e.x-e.prev.x)*e.friction.x));else{s*=.5,t.y-=s,e.y+=s;var o=Math.sqrt(r*r*e.mass/t.mass)*(r>0?1:-1),a=Math.sqrt(n*n*t.mass/e.mass)*(n>0?1:-1),h=.5*(o+a);o-=h,a-=h,t.velocity.y=h+o*t.bounce.y,e.velocity.y=h+a*e.bounce.y}return!0},getObjectsUnderPointer:function(t,e,i,s){if(0!==e.length&&t.exists)return this.getObjectsAtLocation(t.x,t.y,e,i,s,t)},getObjectsAtLocation:function(t,e,i,s,r,o){this.quadTree.clear(),this.quadTree.reset(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height,this.maxObjects,this.maxLevels),this.quadTree.populate(i);for(var a=new n.Rectangle(t,e,1,1),h=[],l=this.quadTree.retrieve(a),c=0;c<l.length;c++)l[c].hitTest(t,e)&&(s&&s.call(r,o,l[c].sprite),h.push(l[c].sprite));return h},moveToObject:function(t,e,i,s){void 0===i&&(i=60),void 0===s&&(s=0);var n=Math.atan2(e.y-t.y,e.x-t.x);return s>0&&(i=this.distanceBetween(t,e)/(s/1e3)),t.body.velocity.x=Math.cos(n)*i,t.body.velocity.y=Math.sin(n)*i,n},moveToPointer:function(t,e,i,s){void 0===e&&(e=60),i=i||this.game.input.activePointer,void 0===s&&(s=0);var n=this.angleToPointer(t,i);return s>0&&(e=this.distanceToPointer(t,i)/(s/1e3)),t.body.velocity.x=Math.cos(n)*e,t.body.velocity.y=Math.sin(n)*e,n},moveToXY:function(t,e,i,s,n){void 0===s&&(s=60),void 0===n&&(n=0);var r=Math.atan2(i-t.y,e-t.x);return n>0&&(s=this.distanceToXY(t,e,i)/(n/1e3)),t.body.velocity.x=Math.cos(r)*s,t.body.velocity.y=Math.sin(r)*s,r},velocityFromAngle:function(t,e,i){return void 0===e&&(e=60),i=i||new n.Point,i.setTo(Math.cos(this.game.math.degToRad(t))*e,Math.sin(this.game.math.degToRad(t))*e)},velocityFromRotation:function(t,e,i){return void 0===e&&(e=60),i=i||new n.Point,i.setTo(Math.cos(t)*e,Math.sin(t)*e)},accelerationFromRotation:function(t,e,i){return void 0===e&&(e=60),i=i||new n.Point,i.setTo(Math.cos(t)*e,Math.sin(t)*e)},accelerateToObject:function(t,e,i,s,n){void 0===i&&(i=60),void 0===s&&(s=1e3),void 0===n&&(n=1e3);var r=this.angleBetween(t,e);return t.body.acceleration.setTo(Math.cos(r)*i,Math.sin(r)*i),t.body.maxVelocity.setTo(s,n),r},accelerateToPointer:function(t,e,i,s,n){void 0===i&&(i=60),void 0===e&&(e=this.game.input.activePointer),void 0===s&&(s=1e3),void 0===n&&(n=1e3);var r=this.angleToPointer(t,e);return t.body.acceleration.setTo(Math.cos(r)*i,Math.sin(r)*i),t.body.maxVelocity.setTo(s,n),r},accelerateToXY:function(t,e,i,s,n,r){void 0===s&&(s=60),void 0===n&&(n=1e3),void 0===r&&(r=1e3);var o=this.angleToXY(t,e,i);return t.body.acceleration.setTo(Math.cos(o)*s,Math.sin(o)*s),t.body.maxVelocity.setTo(n,r),o},distanceBetween:function(t,e,i){void 0===i&&(i=!1);var s=i?t.world.x-e.world.x:t.x-e.x,n=i?t.world.y-e.world.y:t.y-e.y;return Math.sqrt(s*s+n*n)},distanceToXY:function(t,e,i,s){void 0===s&&(s=!1);var n=s?t.world.x-e:t.x-e,r=s?t.world.y-i:t.y-i;return Math.sqrt(n*n+r*r)},distanceToPointer:function(t,e,i){void 0===e&&(e=this.game.input.activePointer),void 0===i&&(i=!1);var s=i?t.world.x-e.worldX:t.x-e.worldX,n=i?t.world.y-e.worldY:t.y-e.worldY;return Math.sqrt(s*s+n*n)},angleBetween:function(t,e,i){return void 0===i&&(i=!1),i?Math.atan2(e.world.y-t.world.y,e.world.x-t.world.x):Math.atan2(e.y-t.y,e.x-t.x)},angleBetweenCenters:function(t,e){var i=e.centerX-t.centerX,s=e.centerY-t.centerY;return Math.atan2(s,i)},angleToXY:function(t,e,i,s){return void 0===s&&(s=!1),s?Math.atan2(i-t.world.y,e-t.world.x):Math.atan2(i-t.y,e-t.x)},angleToPointer:function(t,e,i){return void 0===e&&(e=this.game.input.activePointer),void 0===i&&(i=!1),i?Math.atan2(e.worldY-t.world.y,e.worldX-t.world.x):Math.atan2(e.worldY-t.y,e.worldX-t.x)},worldAngleToPointer:function(t,e){return this.angleToPointer(t,e,!0)}},n.Physics.Arcade.Body=function(t){this.sprite=t,this.game=t.game,this.type=n.Physics.ARCADE,this.enable=!0,this.isCircle=!1,this.radius=0,this.offset=new n.Point,this.position=new n.Point(t.x,t.y),this.prev=new n.Point(this.position.x,this.position.y),this.allowRotation=!0,this.rotation=t.angle,this.preRotation=t.angle,this.width=t.width,this.height=t.height,this.sourceWidth=t.width,this.sourceHeight=t.height,t.texture&&(this.sourceWidth=t.texture.frame.width,this.sourceHeight=t.texture.frame.height),this.halfWidth=Math.abs(t.width/2),this.halfHeight=Math.abs(t.height/2),this.center=new n.Point(t.x+this.halfWidth,t.y+this.halfHeight),this.velocity=new n.Point,this.newVelocity=new n.Point,this.deltaMax=new n.Point,this.acceleration=new n.Point,this.drag=new n.Point,this.allowGravity=!0,this.gravity=new n.Point,this.bounce=new n.Point,this.worldBounce=null,this.onWorldBounds=null,this.onCollide=null,this.onOverlap=null,this.maxVelocity=new n.Point(1e4,1e4),this.friction=new n.Point(1,0),this.angularVelocity=0,this.angularAcceleration=0,this.angularDrag=0,this.maxAngular=1e3,this.mass=1,this.angle=0,this.speed=0,this.facing=n.NONE,this.immovable=!1,this.moves=!0,this.customSeparateX=!1,this.customSeparateY=!1,this.overlapX=0,this.overlapY=0,this.overlapR=0,this.embedded=!1,this.collideWorldBounds=!1,this.checkCollision={none:!1,any:!0,up:!0,down:!0,left:!0,right:!0},this.touching={none:!0,up:!1,down:!1,left:!1,right:!1},this.wasTouching={none:!0,up:!1,down:!1,left:!1,right:!1},this.blocked={up:!1,down:!1,left:!1,right:!1},this.tilePadding=new n.Point,this.dirty=!1,this.skipQuadTree=!1,this.syncBounds=!1,this.isMoving=!1,this.stopVelocityOnCollide=!0,this.moveTimer=0,this.moveDistance=0,this.moveDuration=0,this.moveTarget=null,this.moveEnd=null,this.onMoveComplete=new n.Signal,this.movementCallback=null,this.movementCallbackContext=null,this._reset=!0,this._sx=t.scale.x,this._sy=t.scale.y,this._dx=0,this._dy=0},n.Physics.Arcade.Body.prototype={updateBounds:function(){if(this.syncBounds){var t=this.sprite.getBounds();t.ceilAll(),t.width===this.width&&t.height===this.height||(this.width=t.width,this.height=t.height,this._reset=!0)}else{var e=Math.abs(this.sprite.scale.x),i=Math.abs(this.sprite.scale.y);e===this._sx&&i===this._sy||(this.width=this.sourceWidth*e,this.height=this.sourceHeight*i,this._sx=e,this._sy=i,this._reset=!0)}this._reset&&(this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight))},preUpdate:function(){this.enable&&!this.game.physics.arcade.isPaused&&(this.dirty=!0,this.wasTouching.none=this.touching.none,this.wasTouching.up=this.touching.up,this.wasTouching.down=this.touching.down,this.wasTouching.left=this.touching.left,this.wasTouching.right=this.touching.right,this.touching.none=!0,this.touching.up=!1,this.touching.down=!1,this.touching.left=!1,this.touching.right=!1,this.blocked.up=!1,this.blocked.down=!1,this.blocked.left=!1,this.blocked.right=!1,this.embedded=!1,this.updateBounds(),this.position.x=this.sprite.world.x-this.sprite.anchor.x*this.sprite.width+this.sprite.scale.x*this.offset.x,this.position.x-=this.sprite.scale.x<0?this.width:0,this.position.y=this.sprite.world.y-this.sprite.anchor.y*this.sprite.height+this.sprite.scale.y*this.offset.y,this.position.y-=this.sprite.scale.y<0?this.height:0,this.rotation=this.sprite.angle,this.preRotation=this.rotation,(this._reset||this.sprite.fresh)&&(this.prev.x=this.position.x,this.prev.y=this.position.y),this.moves&&(this.game.physics.arcade.updateMotion(this),this.newVelocity.set(this.velocity.x*this.game.time.physicsElapsed,this.velocity.y*this.game.time.physicsElapsed),this.position.x+=this.newVelocity.x,this.position.y+=this.newVelocity.y,this.position.x===this.prev.x&&this.position.y===this.prev.y||(this.angle=Math.atan2(this.velocity.y,this.velocity.x)),this.speed=Math.sqrt(this.velocity.x*this.velocity.x+this.velocity.y*this.velocity.y),this.collideWorldBounds&&this.checkWorldBounds()&&this.onWorldBounds&&this.onWorldBounds.dispatch(this.sprite,this.blocked.up,this.blocked.down,this.blocked.left,this.blocked.right)),this._dx=this.deltaX(),this._dy=this.deltaY(),this._reset=!1)},updateMovement:function(){var t=0,e=0!==this.overlapX||0!==this.overlapY;if(this.moveDuration>0?(this.moveTimer+=this.game.time.elapsedMS,t=this.moveTimer/this.moveDuration):(this.moveTarget.end.set(this.position.x,this.position.y),t=this.moveTarget.length/this.moveDistance),this.movementCallback)var i=this.movementCallback.call(this.movementCallbackContext,this,this.velocity,t);return!(e||t>=1||void 0!==i&&!0!==i)||(this.stopMovement(t>=1||this.stopVelocityOnCollide&&e),!1)},stopMovement:function(t){this.isMoving&&(this.isMoving=!1,t&&this.velocity.set(0),this.onMoveComplete.dispatch(this.sprite,0!==this.overlapX||0!==this.overlapY))},postUpdate:function(){this.enable&&this.dirty&&(this.isMoving&&this.updateMovement(),this.dirty=!1,this.deltaX()<0?this.facing=n.LEFT:this.deltaX()>0&&(this.facing=n.RIGHT),this.deltaY()<0?this.facing=n.UP:this.deltaY()>0&&(this.facing=n.DOWN),this.moves&&(this._dx=this.deltaX(),this._dy=this.deltaY(),0!==this.deltaMax.x&&0!==this._dx&&(this._dx<0&&this._dx<-this.deltaMax.x?this._dx=-this.deltaMax.x:this._dx>0&&this._dx>this.deltaMax.x&&(this._dx=this.deltaMax.x)),0!==this.deltaMax.y&&0!==this._dy&&(this._dy<0&&this._dy<-this.deltaMax.y?this._dy=-this.deltaMax.y:this._dy>0&&this._dy>this.deltaMax.y&&(this._dy=this.deltaMax.y)),this.sprite.position.x+=this._dx,this.sprite.position.y+=this._dy,this._reset=!0),this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight),this.allowRotation&&(this.sprite.angle+=this.deltaZ()),this.prev.x=this.position.x,this.prev.y=this.position.y)},checkWorldBounds:function(){var t=this.position,e=this.game.physics.arcade.bounds,i=this.game.physics.arcade.checkCollision,s=this.worldBounce?-this.worldBounce.x:-this.bounce.x,n=this.worldBounce?-this.worldBounce.y:-this.bounce.y;if(this.isCircle){var r={x:this.center.x-this.radius,y:this.center.y-this.radius,right:this.center.x+this.radius,bottom:this.center.y+this.radius};r.x<e.x&&i.left?(t.x=e.x-this.halfWidth+this.radius,this.velocity.x*=s,this.blocked.left=!0):r.right>e.right&&i.right&&(t.x=e.right-this.halfWidth-this.radius,this.velocity.x*=s,this.blocked.right=!0),r.y<e.y&&i.up?(t.y=e.y-this.halfHeight+this.radius,this.velocity.y*=n,this.blocked.up=!0):r.bottom>e.bottom&&i.down&&(t.y=e.bottom-this.halfHeight-this.radius,this.velocity.y*=n,this.blocked.down=!0)}else t.x<e.x&&i.left?(t.x=e.x,this.velocity.x*=s,this.blocked.left=!0):this.right>e.right&&i.right&&(t.x=e.right-this.width,this.velocity.x*=s,this.blocked.right=!0),t.y<e.y&&i.up?(t.y=e.y,this.velocity.y*=n,this.blocked.up=!0):this.bottom>e.bottom&&i.down&&(t.y=e.bottom-this.height,this.velocity.y*=n,this.blocked.down=!0);return this.blocked.up||this.blocked.down||this.blocked.left||this.blocked.right},moveFrom:function(t,e,i){if(void 0===e&&(e=this.speed),0===e)return!1;var s;return void 0===i?(s=this.angle,i=this.game.math.radToDeg(s)):s=this.game.math.degToRad(i),this.moveTimer=0,this.moveDuration=t,0===i||180===i?this.velocity.set(Math.cos(s)*e,0):90===i||270===i?this.velocity.set(0,Math.sin(s)*e):this.velocity.set(Math.cos(s)*e,Math.sin(s)*e),this.isMoving=!0,!0},moveTo:function(t,e,i){var s=e/(t/1e3);if(0===s)return!1;var r;return void 0===i?(r=this.angle,i=this.game.math.radToDeg(r)):r=this.game.math.degToRad(i),e=Math.abs(e),this.moveDuration=0,this.moveDistance=e,null===this.moveTarget&&(this.moveTarget=new n.Line,this.moveEnd=new n.Point),this.moveTarget.fromAngle(this.x,this.y,r,e),this.moveEnd.set(this.moveTarget.end.x,this.moveTarget.end.y),this.moveTarget.setTo(this.x,this.y,this.x,this.y),0===i||180===i?this.velocity.set(Math.cos(r)*s,0):90===i||270===i?this.velocity.set(0,Math.sin(r)*s):this.velocity.set(Math.cos(r)*s,Math.sin(r)*s),this.isMoving=!0,!0},setSize:function(t,e,i,s){void 0===i&&(i=this.offset.x),void 0===s&&(s=this.offset.y),this.sourceWidth=t,this.sourceHeight=e,this.width=this.sourceWidth*this._sx,this.height=this.sourceHeight*this._sy,this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.offset.setTo(i,s),this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight),this.isCircle=!1,this.radius=0},setCircle:function(t,e,i){void 0===e&&(e=this.offset.x),void 0===i&&(i=this.offset.y),t>0?(this.isCircle=!0,this.radius=t,this.sourceWidth=2*t,this.sourceHeight=2*t,this.width=this.sourceWidth*this._sx,this.height=this.sourceHeight*this._sy,this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.offset.setTo(e,i),this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight)):this.isCircle=!1},reset:function(t,e){this.velocity.set(0),this.acceleration.set(0),this.speed=0,this.angularVelocity=0,this.angularAcceleration=0,this.position.x=t-this.sprite.anchor.x*this.sprite.width+this.sprite.scale.x*this.offset.x,this.position.x-=this.sprite.scale.x<0?this.width:0,this.position.y=e-this.sprite.anchor.y*this.sprite.height+this.sprite.scale.y*this.offset.y,this.position.y-=this.sprite.scale.y<0?this.height:0,this.prev.x=this.position.x,this.prev.y=this.position.y,this.rotation=this.sprite.angle,this.preRotation=this.rotation,this._sx=this.sprite.scale.x,this._sy=this.sprite.scale.y,this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight)},getBounds:function(t){return this.isCircle?(t.x=this.center.x-this.radius,t.y=this.center.y-this.radius,t.right=this.center.x+this.radius,t.bottom=this.center.y+this.radius):(t.x=this.x,t.y=this.y,t.right=this.right,t.bottom=this.bottom),t},hitTest:function(t,e){return this.isCircle?n.Circle.contains(this,t,e):n.Rectangle.contains(this,t,e)},onFloor:function(){return this.blocked.down},onCeiling:function(){return this.blocked.up},onWall:function(){return this.blocked.left||this.blocked.right},deltaAbsX:function(){return this.deltaX()>0?this.deltaX():-this.deltaX()},deltaAbsY:function(){return this.deltaY()>0?this.deltaY():-this.deltaY()},deltaX:function(){return this.position.x-this.prev.x},deltaY:function(){return this.position.y-this.prev.y},deltaZ:function(){return this.rotation-this.preRotation},destroy:function(){this.sprite.parent&&this.sprite.parent instanceof n.Group&&this.sprite.parent.removeFromHash(this.sprite),this.sprite.body=null,this.sprite=null}},Object.defineProperty(n.Physics.Arcade.Body.prototype,"left",{get:function(){return this.position.x}}),Object.defineProperty(n.Physics.Arcade.Body.prototype,"right",{get:function(){return this.position.x+this.width}}),Object.defineProperty(n.Physics.Arcade.Body.prototype,"top",{get:function(){return this.position.y}}),Object.defineProperty(n.Physics.Arcade.Body.prototype,"bottom",{get:function(){return this.position.y+this.height}}),Object.defineProperty(n.Physics.Arcade.Body.prototype,"x",{get:function(){return this.position.x},set:function(t){this.position.x=t}}),Object.defineProperty(n.Physics.Arcade.Body.prototype,"y",{get:function(){return this.position.y},set:function(t){this.position.y=t}}),n.Physics.Arcade.Body.render=function(t,e,i,s){void 0===s&&(s=!0),i=i||"rgba(0,255,0,0.4)",t.fillStyle=i,t.strokeStyle=i,e.isCircle?(t.beginPath(),t.arc(e.center.x-e.game.camera.x,e.center.y-e.game.camera.y,e.radius,0,2*Math.PI),s?t.fill():t.stroke()):s?t.fillRect(e.position.x-e.game.camera.x,e.position.y-e.game.camera.y,e.width,e.height):t.strokeRect(e.position.x-e.game.camera.x,e.position.y-e.game.camera.y,e.width,e.height)},n.Physics.Arcade.Body.renderBodyInfo=function(t,e){t.line("x: "+e.x.toFixed(2),"y: "+e.y.toFixed(2),"width: "+e.width,"height: "+e.height),t.line("velocity x: "+e.velocity.x.toFixed(2),"y: "+e.velocity.y.toFixed(2),"deltaX: "+e._dx.toFixed(2),"deltaY: "+e._dy.toFixed(2)),t.line("acceleration x: "+e.acceleration.x.toFixed(2),"y: "+e.acceleration.y.toFixed(2),"speed: "+e.speed.toFixed(2),"angle: "+e.angle.toFixed(2)),t.line("gravity x: "+e.gravity.x,"y: "+e.gravity.y,"bounce x: "+e.bounce.x.toFixed(2),"y: "+e.bounce.y.toFixed(2)),t.line("touching left: "+e.touching.left,"right: "+e.touching.right,"up: "+e.touching.up,"down: "+e.touching.down),t.line("blocked left: "+e.blocked.left,"right: "+e.blocked.right,"up: "+e.blocked.up,"down: "+e.blocked.down)},n.Physics.Arcade.Body.prototype.constructor=n.Physics.Arcade.Body,n.Physics.Arcade.TilemapCollision=function(){},n.Physics.Arcade.TilemapCollision.prototype={TILE_BIAS:16,collideSpriteVsTilemapLayer:function(t,e,i,s,n,r){if(t.body){var o=e.getTiles(t.body.position.x-t.body.tilePadding.x,t.body.position.y-t.body.tilePadding.y,t.body.width+t.body.tilePadding.x,t.body.height+t.body.tilePadding.y,!1,!1);if(0!==o.length)for(var a=0;a<o.length;a++)s?s.call(n,t,o[a])&&this.separateTile(a,t.body,o[a],e,r)&&(this._total++,i&&i.call(n,t,o[a])):this.separateTile(a,t.body,o[a],e,r)&&(this._total++,i&&i.call(n,t,o[a]))}},collideGroupVsTilemapLayer:function(t,e,i,s,n,r){if(0!==t.length)for(var o=0;o<t.children.length;o++)t.children[o].exists&&this.collideSpriteVsTilemapLayer(t.children[o],e,i,s,n,r)},separateTile:function(t,e,i,s,n){if(!e.enable)return!1;var r=s.fixedToCamera?0:s.position.x,o=s.fixedToCamera?0:s.position.y;if(!i.intersects(e.position.x-r,e.position.y-o,e.right-r,e.bottom-o))return!1;if(n)return!0;if(i.collisionCallback&&!i.collisionCallback.call(i.collisionCallbackContext,e.sprite,i))return!1;if(void 0!==i.layer.callbacks&&i.layer.callbacks[i.index]&&!i.layer.callbacks[i.index].callback.call(i.layer.callbacks[i.index].callbackContext,e.sprite,i))return!1;if(!(i.faceLeft||i.faceRight||i.faceTop||i.faceBottom))return!1;var a=0,h=0,l=0,c=1;if(e.deltaAbsX()>e.deltaAbsY()?l=-1:e.deltaAbsX()<e.deltaAbsY()&&(c=-1),0!==e.deltaX()&&0!==e.deltaY()&&(i.faceLeft||i.faceRight)&&(i.faceTop||i.faceBottom)&&(l=Math.min(Math.abs(e.position.x-r-i.right),Math.abs(e.right-r-i.left)),c=Math.min(Math.abs(e.position.y-o-i.bottom),Math.abs(e.bottom-o-i.top))),l<c){if((i.faceLeft||i.faceRight)&&0!==(a=this.tileCheckX(e,i,s))&&!i.intersects(e.position.x-r,e.position.y-o,e.right-r,e.bottom-o))return!0;(i.faceTop||i.faceBottom)&&(h=this.tileCheckY(e,i,s))}else{if((i.faceTop||i.faceBottom)&&0!==(h=this.tileCheckY(e,i,s))&&!i.intersects(e.position.x-r,e.position.y-o,e.right-r,e.bottom-o))return!0;(i.faceLeft||i.faceRight)&&(a=this.tileCheckX(e,i,s))}return 0!==a||0!==h},tileCheckX:function(t,e,i){var s=0,n=i.fixedToCamera?0:i.position.x;return t.deltaX()<0&&!t.blocked.left&&e.collideRight&&t.checkCollision.left?e.faceRight&&t.x-n<e.right&&(s=t.x-n-e.right)<-this.TILE_BIAS&&(s=0):t.deltaX()>0&&!t.blocked.right&&e.collideLeft&&t.checkCollision.right&&e.faceLeft&&t.right-n>e.left&&(s=t.right-n-e.left)>this.TILE_BIAS&&(s=0),0!==s&&(t.customSeparateX?t.overlapX=s:this.processTileSeparationX(t,s)),s},tileCheckY:function(t,e,i){var s=0,n=i.fixedToCamera?0:i.position.y;return t.deltaY()<0&&!t.blocked.up&&e.collideDown&&t.checkCollision.up?e.faceBottom&&t.y-n<e.bottom&&(s=t.y-n-e.bottom)<-this.TILE_BIAS&&(s=0):t.deltaY()>0&&!t.blocked.down&&e.collideUp&&t.checkCollision.down&&e.faceTop&&t.bottom-n>e.top&&(s=t.bottom-n-e.top)>this.TILE_BIAS&&(s=0),0!==s&&(t.customSeparateY?t.overlapY=s:this.processTileSeparationY(t,s)),s},processTileSeparationX:function(t,e){e<0?t.blocked.left=!0:e>0&&(t.blocked.right=!0),t.position.x-=e,0===t.bounce.x?t.velocity.x=0:t.velocity.x=-t.velocity.x*t.bounce.x},processTileSeparationY:function(t,e){e<0?t.blocked.up=!0:e>0&&(t.blocked.down=!0),t.position.y-=e,0===t.bounce.y?t.velocity.y=0:t.velocity.y=-t.velocity.y*t.bounce.y}},n.Utils.mixinPrototype(n.Physics.Arcade.prototype,n.Physics.Arcade.TilemapCollision.prototype),p2.Body.prototype.parent=null,p2.Spring.prototype.parent=null,n.Physics.P2=function(t,e){this.game=t,void 0===e?e={gravity:[0,0],broadphase:new p2.SAPBroadphase}:(e.hasOwnProperty("gravity")||(e.gravity=[0,0]),e.hasOwnProperty("broadphase")||(e.broadphase=new p2.SAPBroadphase)),this.config=e,this.world=new p2.World(this.config),this.frameRate=1/60,this.useElapsedTime=!1,this.paused=!1,this.materials=[],this.gravity=new n.Physics.P2.InversePointProxy(this,this.world.gravity),this.walls={left:null,right:null,top:null,bottom:null},this.onBodyAdded=new n.Signal,this.onBodyRemoved=new n.Signal,this.onSpringAdded=new n.Signal,this.onSpringRemoved=new n.Signal,this.onConstraintAdded=new n.Signal,this.onConstraintRemoved=new n.Signal,this.onContactMaterialAdded=new n.Signal,this.onContactMaterialRemoved=new n.Signal,this.postBroadphaseCallback=null,this.callbackContext=null,this.onBeginContact=new n.Signal,this.onEndContact=new n.Signal,e.hasOwnProperty("mpx")&&e.hasOwnProperty("pxm")&&e.hasOwnProperty("mpxi")&&e.hasOwnProperty("pxmi")&&(this.mpx=e.mpx,this.mpxi=e.mpxi,this.pxm=e.pxm,this.pxmi=e.pxmi),this.world.on("beginContact",this.beginContactHandler,this),this.world.on("endContact",this.endContactHandler,this),this.collisionGroups=[],this.nothingCollisionGroup=new n.Physics.P2.CollisionGroup(1),this.boundsCollisionGroup=new n.Physics.P2.CollisionGroup(2),this.everythingCollisionGroup=new n.Physics.P2.CollisionGroup(2147483648),this.boundsCollidesWith=[],this._toRemove=[],this._collisionGroupID=2,this._boundsLeft=!0,this._boundsRight=!0,this._boundsTop=!0,this._boundsBottom=!0,this._boundsOwnGroup=!1,this.setBoundsToWorld(!0,!0,!0,!0,!1)},n.Physics.P2.prototype={removeBodyNextStep:function(t){this._toRemove.push(t)},preUpdate:function(){for(var t=this._toRemove.length;t--;)this.removeBody(this._toRemove[t]);this._toRemove.length=0},enable:function(t,e,i){void 0===e&&(e=!1),void 0===i&&(i=!0);var s=1;if(Array.isArray(t))for(s=t.length;s--;)t[s]instanceof n.Group?this.enable(t[s].children,e,i):(this.enableBody(t[s],e),i&&t[s].hasOwnProperty("children")&&t[s].children.length>0&&this.enable(t[s],e,!0));else t instanceof n.Group?this.enable(t.children,e,i):(this.enableBody(t,e),i&&t.hasOwnProperty("children")&&t.children.length>0&&this.enable(t.children,e,!0))},enableBody:function(t,e){t.hasOwnProperty("body")&&null===t.body&&(t.body=new n.Physics.P2.Body(this.game,t,t.x,t.y,1),t.body.debug=e,void 0!==t.anchor&&t.anchor.set(.5))},setImpactEvents:function(t){t?this.world.on("impact",this.impactHandler,this):this.world.off("impact",this.impactHandler,this)},setPostBroadphaseCallback:function(t,e){this.postBroadphaseCallback=t,this.callbackContext=e,null!==t?this.world.on("postBroadphase",this.postBroadphaseHandler,this):this.world.off("postBroadphase",this.postBroadphaseHandler,this)},postBroadphaseHandler:function(t){if(this.postBroadphaseCallback&&0!==t.pairs.length)for(var e=t.pairs.length-2;e>=0;e-=2)t.pairs[e].parent&&t.pairs[e+1].parent&&!this.postBroadphaseCallback.call(this.callbackContext,t.pairs[e].parent,t.pairs[e+1].parent)&&t.pairs.splice(e,2)},impactHandler:function(t){if(t.bodyA.parent&&t.bodyB.parent){var e=t.bodyA.parent,i=t.bodyB.parent;e._bodyCallbacks[t.bodyB.id]&&e._bodyCallbacks[t.bodyB.id].call(e._bodyCallbackContext[t.bodyB.id],e,i,t.shapeA,t.shapeB),i._bodyCallbacks[t.bodyA.id]&&i._bodyCallbacks[t.bodyA.id].call(i._bodyCallbackContext[t.bodyA.id],i,e,t.shapeB,t.shapeA),e._groupCallbacks[t.shapeB.collisionGroup]&&e._groupCallbacks[t.shapeB.collisionGroup].call(e._groupCallbackContext[t.shapeB.collisionGroup],e,i,t.shapeA,t.shapeB),i._groupCallbacks[t.shapeA.collisionGroup]&&i._groupCallbacks[t.shapeA.collisionGroup].call(i._groupCallbackContext[t.shapeA.collisionGroup],i,e,t.shapeB,t.shapeA)}},beginContactHandler:function(t){t.bodyA&&t.bodyB&&(this.onBeginContact.dispatch(t.bodyA,t.bodyB,t.shapeA,t.shapeB,t.contactEquations),t.bodyA.parent&&t.bodyA.parent.onBeginContact.dispatch(t.bodyB.parent,t.bodyB,t.shapeA,t.shapeB,t.contactEquations),t.bodyB.parent&&t.bodyB.parent.onBeginContact.dispatch(t.bodyA.parent,t.bodyA,t.shapeB,t.shapeA,t.contactEquations))},endContactHandler:function(t){t.bodyA&&t.bodyB&&(this.onEndContact.dispatch(t.bodyA,t.bodyB,t.shapeA,t.shapeB),t.bodyA.parent&&t.bodyA.parent.onEndContact.dispatch(t.bodyB.parent,t.bodyB,t.shapeA,t.shapeB),t.bodyB.parent&&t.bodyB.parent.onEndContact.dispatch(t.bodyA.parent,t.bodyA,t.shapeB,t.shapeA))},setBoundsToWorld:function(t,e,i,s,n){this.setBounds(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height,t,e,i,s,n)},setWorldMaterial:function(t,e,i,s,n){void 0===e&&(e=!0),void 0===i&&(i=!0),void 0===s&&(s=!0),void 0===n&&(n=!0),e&&this.walls.left&&(this.walls.left.shapes[0].material=t),i&&this.walls.right&&(this.walls.right.shapes[0].material=t),s&&this.walls.top&&(this.walls.top.shapes[0].material=t),n&&this.walls.bottom&&(this.walls.bottom.shapes[0].material=t)},updateBoundsCollisionGroup:function(t){void 0===t&&(t=!0);var e=t?this.boundsCollisionGroup.mask:this.everythingCollisionGroup.mask;this.walls.left&&(this.walls.left.shapes[0].collisionGroup=e),this.walls.right&&(this.walls.right.shapes[0].collisionGroup=e),this.walls.top&&(this.walls.top.shapes[0].collisionGroup=e),this.walls.bottom&&(this.walls.bottom.shapes[0].collisionGroup=e),this._boundsOwnGroup=t},setBounds:function(t,e,i,s,n,r,o,a,h){void 0===n&&(n=this._boundsLeft),void 0===r&&(r=this._boundsRight),void 0===o&&(o=this._boundsTop),void 0===a&&(a=this._boundsBottom),void 0===h&&(h=this._boundsOwnGroup),this.setupWall(n,"left",t,e,1.5707963267948966,h),this.setupWall(r,"right",t+i,e,-1.5707963267948966,h),this.setupWall(o,"top",t,e,-3.141592653589793,h),this.setupWall(a,"bottom",t,e+s,0,h),this._boundsLeft=n,this._boundsRight=r,this._boundsTop=o,this._boundsBottom=a,this._boundsOwnGroup=h},setupWall:function(t,e,i,s,n,r){t?(this.walls[e]?this.walls[e].position=[this.pxmi(i),this.pxmi(s)]:(this.walls[e]=new p2.Body({mass:0,position:[this.pxmi(i),this.pxmi(s)],angle:n}),this.walls[e].addShape(new p2.Plane),this.world.addBody(this.walls[e])),r&&(this.walls[e].shapes[0].collisionGroup=this.boundsCollisionGroup.mask)):this.walls[e]&&(this.world.removeBody(this.walls[e]),this.walls[e]=null)},pause:function(){this.paused=!0},resume:function(){this.paused=!1},update:function(){this.paused||(this.useElapsedTime?this.world.step(this.game.time.physicsElapsed):this.world.step(this.frameRate))},reset:function(){this.world.on("beginContact",this.beginContactHandler,this),this.world.on("endContact",this.endContactHandler,this),this.nothingCollisionGroup=new n.Physics.P2.CollisionGroup(1),this.boundsCollisionGroup=new n.Physics.P2.CollisionGroup(2),this.everythingCollisionGroup=new n.Physics.P2.CollisionGroup(2147483648),this._collisionGroupID=2,this.setBoundsToWorld(!0,!0,!0,!0,!1)},clear:function(){this.world.time=0,this.world.fixedStepTime=0,this.world.solver&&this.world.solver.equations.length&&this.world.solver.removeAllEquations();for(var t=this.world.constraints,e=t.length-1;e>=0;e--)this.world.removeConstraint(t[e]);for(var i=this.world.bodies,e=i.length-1;e>=0;e--)this.world.removeBody(i[e]);for(var s=this.world.springs,e=s.length-1;e>=0;e--)this.world.removeSpring(s[e]);for(var n=this.world.contactMaterials,e=n.length-1;e>=0;e--)this.world.removeContactMaterial(n[e]);this.world.off("beginContact",this.beginContactHandler,this),this.world.off("endContact",this.endContactHandler,this),this.postBroadphaseCallback=null,this.callbackContext=null,this.impactCallback=null,this.collisionGroups=[],this._toRemove=[],this.boundsCollidesWith=[],this.walls={left:null,right:null,top:null,bottom:null}},destroy:function(){this.clear(),this.game=null},addBody:function(t){return!t.data.world&&(this.world.addBody(t.data),this.onBodyAdded.dispatch(t),!0)},removeBody:function(t){return t.data.world===this.world&&(this.world.removeBody(t.data),this.onBodyRemoved.dispatch(t)),t},addSpring:function(t){return t instanceof n.Physics.P2.Spring||t instanceof n.Physics.P2.RotationalSpring?this.world.addSpring(t.data):this.world.addSpring(t),this.onSpringAdded.dispatch(t),t},removeSpring:function(t){return t instanceof n.Physics.P2.Spring||t instanceof n.Physics.P2.RotationalSpring?this.world.removeSpring(t.data):this.world.removeSpring(t),this.onSpringRemoved.dispatch(t),t},createDistanceConstraint:function(t,e,i,s,r,o){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new n.Physics.P2.DistanceConstraint(this,t,e,i,s,r,o));console.warn("Cannot create Constraint, invalid body objects given")},createGearConstraint:function(t,e,i,s){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new n.Physics.P2.GearConstraint(this,t,e,i,s));console.warn("Cannot create Constraint, invalid body objects given")},createRevoluteConstraint:function(t,e,i,s,r,o){if(t=this.getBody(t),i=this.getBody(i),t&&i)return this.addConstraint(new n.Physics.P2.RevoluteConstraint(this,t,e,i,s,r,o));console.warn("Cannot create Constraint, invalid body objects given")},createLockConstraint:function(t,e,i,s,r){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new n.Physics.P2.LockConstraint(this,t,e,i,s,r));console.warn("Cannot create Constraint, invalid body objects given")},createPrismaticConstraint:function(t,e,i,s,r,o,a){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new n.Physics.P2.PrismaticConstraint(this,t,e,i,s,r,o,a));console.warn("Cannot create Constraint, invalid body objects given")},addConstraint:function(t){return this.world.addConstraint(t),this.onConstraintAdded.dispatch(t),t},removeConstraint:function(t){return this.world.removeConstraint(t),this.onConstraintRemoved.dispatch(t),t},addContactMaterial:function(t){return this.world.addContactMaterial(t),this.onContactMaterialAdded.dispatch(t),t},removeContactMaterial:function(t){return this.world.removeContactMaterial(t),this.onContactMaterialRemoved.dispatch(t),t},getContactMaterial:function(t,e){return this.world.getContactMaterial(t,e)},setMaterial:function(t,e){for(var i=e.length;i--;)e[i].setMaterial(t)},createMaterial:function(t,e){t=t||"";var i=new n.Physics.P2.Material(t);return this.materials.push(i),void 0!==e&&e.setMaterial(i),i},createContactMaterial:function(t,e,i){void 0===t&&(t=this.createMaterial()),void 0===e&&(e=this.createMaterial());var s=new n.Physics.P2.ContactMaterial(t,e,i);return this.addContactMaterial(s)},getBodies:function(){for(var t=[],e=this.world.bodies.length;e--;)t.push(this.world.bodies[e].parent);return t},getBody:function(t){return t instanceof p2.Body?t:t instanceof n.Physics.P2.Body?t.data:t.body&&t.body.type===n.Physics.P2JS?t.body.data:null},getSprings:function(){for(var t=[],e=this.world.springs.length;e--;)t.push(this.world.springs[e].parent);return t},getConstraints:function(){for(var t=[],e=this.world.constraints.length;e--;)t.push(this.world.constraints[e]);return t},hitTest:function(t,e,i,s){void 0===e&&(e=this.world.bodies),void 0===i&&(i=5),void 0===s&&(s=!1);for(var r=[this.pxmi(t.x),this.pxmi(t.y)],o=[],a=e.length;a--;)e[a]instanceof n.Physics.P2.Body&&(!s||e[a].data.type!==p2.Body.STATIC)?o.push(e[a].data):e[a]instanceof p2.Body&&e[a].parent&&(!s||e[a].type!==p2.Body.STATIC)?o.push(e[a]):e[a]instanceof n.Sprite&&e[a].hasOwnProperty("body")&&(!s||e[a].body.data.type!==p2.Body.STATIC)&&o.push(e[a].body.data);return this.world.hitTest(r,o,i)},toJSON:function(){return this.world.toJSON()},createCollisionGroup:function(t){var e=Math.pow(2,this._collisionGroupID);this.walls.left&&(this.walls.left.shapes[0].collisionMask=this.walls.left.shapes[0].collisionMask|e),this.walls.right&&(this.walls.right.shapes[0].collisionMask=this.walls.right.shapes[0].collisionMask|e),this.walls.top&&(this.walls.top.shapes[0].collisionMask=this.walls.top.shapes[0].collisionMask|e),this.walls.bottom&&(this.walls.bottom.shapes[0].collisionMask=this.walls.bottom.shapes[0].collisionMask|e),this._collisionGroupID++;var i=new n.Physics.P2.CollisionGroup(e);return this.collisionGroups.push(i),t&&this.setCollisionGroup(t,i),i},setCollisionGroup:function(t,e){if(t instanceof n.Group)for(var i=0;i<t.total;i++)t.children[i].body&&t.children[i].body.type===n.Physics.P2JS&&t.children[i].body.setCollisionGroup(e);else t.body.setCollisionGroup(e)},createSpring:function(t,e,i,s,r,o,a,h,l){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addSpring(new n.Physics.P2.Spring(this,t,e,i,s,r,o,a,h,l));console.warn("Cannot create Spring, invalid body objects given")},createRotationalSpring:function(t,e,i,s,r){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addSpring(new n.Physics.P2.RotationalSpring(this,t,e,i,s,r));console.warn("Cannot create Rotational Spring, invalid body objects given")},createBody:function(t,e,i,s,r,o){void 0===s&&(s=!1);var a=new n.Physics.P2.Body(this.game,null,t,e,i);if(o){if(!a.addPolygon(r,o))return!1}return s&&this.world.addBody(a.data),a},createParticle:function(t,e,i,s,r,o){void 0===s&&(s=!1);var a=new n.Physics.P2.Body(this.game,null,t,e,i);if(o){if(!a.addPolygon(r,o))return!1}return s&&this.world.addBody(a.data),a},convertCollisionObjects:function(t,e,i){void 0===i&&(i=!0);for(var s=[],n=0,r=t.collision[e].length;n<r;n++){var o=t.collision[e][n],a=this.createBody(o.x,o.y,0,i,{},o.polyline);a&&s.push(a)}return s},clearTilemapLayerBodies:function(t,e){e=t.getLayer(e);for(var i=t.layers[e].bodies.length;i--;)t.layers[e].bodies[i].destroy();t.layers[e].bodies.length=0},convertTilemap:function(t,e,i,s){e=t.getLayer(e),void 0===i&&(i=!0),void 0===s&&(s=!0),this.clearTilemapLayerBodies(t,e);for(var n=0,r=0,o=0,a=0,h=t.layers[e].height;a<h;a++){n=0;for(var l=0,c=t.layers[e].width;l<c;l++){var u=t.layers[e].data[a][l];if(u&&u.index>-1&&u.collides)if(s){var d=t.getTileRight(e,l,a);if(0===n&&(r=u.x*u.width,o=u.y*u.height,n=u.width),d&&d.collides)n+=u.width;else{var p=this.createBody(r,o,0,!1);p.addRectangle(n,u.height,n/2,u.height/2,0),i&&this.addBody(p),t.layers[e].bodies.push(p),n=0}}else{var p=this.createBody(u.x*u.width,u.y*u.height,0,!1);p.addRectangle(u.width,u.height,u.width/2,u.height/2,0),i&&this.addBody(p),t.layers[e].bodies.push(p)}}}return t.layers[e].bodies},mpx:function(t){return t*=20},pxm:function(t){return.05*t},mpxi:function(t){return t*=-20},pxmi:function(t){return-.05*t}},Object.defineProperty(n.Physics.P2.prototype,"friction",{get:function(){return this.world.defaultContactMaterial.friction},set:function(t){this.world.defaultContactMaterial.friction=t}}),Object.defineProperty(n.Physics.P2.prototype,"restitution",{get:function(){return this.world.defaultContactMaterial.restitution},set:function(t){this.world.defaultContactMaterial.restitution=t}}),Object.defineProperty(n.Physics.P2.prototype,"contactMaterial",{get:function(){return this.world.defaultContactMaterial},set:function(t){this.world.defaultContactMaterial=t}}),Object.defineProperty(n.Physics.P2.prototype,"applySpringForces",{get:function(){return this.world.applySpringForces},set:function(t){this.world.applySpringForces=t}}),Object.defineProperty(n.Physics.P2.prototype,"applyDamping",{get:function(){return this.world.applyDamping},set:function(t){this.world.applyDamping=t}}),Object.defineProperty(n.Physics.P2.prototype,"applyGravity",{get:function(){return this.world.applyGravity},set:function(t){this.world.applyGravity=t}}),Object.defineProperty(n.Physics.P2.prototype,"solveConstraints",{get:function(){return this.world.solveConstraints},set:function(t){this.world.solveConstraints=t}}),Object.defineProperty(n.Physics.P2.prototype,"time",{get:function(){return this.world.time}}),Object.defineProperty(n.Physics.P2.prototype,"emitImpactEvent",{get:function(){return this.world.emitImpactEvent},set:function(t){this.world.emitImpactEvent=t}}),Object.defineProperty(n.Physics.P2.prototype,"sleepMode",{get:function(){return this.world.sleepMode},set:function(t){this.world.sleepMode=t}}),Object.defineProperty(n.Physics.P2.prototype,"total",{get:function(){return this.world.bodies.length}}),n.Physics.P2.FixtureList=function(t){Array.isArray(t)||(t=[t]),this.rawList=t,this.init(),this.parse(this.rawList)},n.Physics.P2.FixtureList.prototype={init:function(){this.namedFixtures={},this.groupedFixtures=[],this.allFixtures=[]},setCategory:function(t,e){var i=function(e){e.collisionGroup=t};this.getFixtures(e).forEach(i)},setMask:function(t,e){var i=function(e){e.collisionMask=t};this.getFixtures(e).forEach(i)},setSensor:function(t,e){var i=function(e){e.sensor=t};this.getFixtures(e).forEach(i)},setMaterial:function(t,e){var i=function(e){e.material=t};this.getFixtures(e).forEach(i)},getFixtures:function(t){var e=[];if(t){t instanceof Array||(t=[t]);var i=this;return t.forEach(function(t){i.namedFixtures[t]&&e.push(i.namedFixtures[t])}),this.flatten(e)}return this.allFixtures},getFixtureByKey:function(t){return this.namedFixtures[t]},getGroup:function(t){return this.groupedFixtures[t]},parse:function(){var t,e,i,s;i=this.rawList,s=[];for(t in i)e=i[t],isNaN(t-0)?this.namedFixtures[t]=this.flatten(e):(this.groupedFixtures[t]=this.groupedFixtures[t]||[],this.groupedFixtures[t]=this.groupedFixtures[t].concat(e)),s.push(this.allFixtures=this.flatten(this.groupedFixtures))},flatten:function(t){var e,i;return e=[],i=arguments.callee,t.forEach(function(t){return Array.prototype.push.apply(e,Array.isArray(t)?i(t):[t])}),e}},n.Physics.P2.PointProxy=function(t,e){this.world=t,this.destination=e},n.Physics.P2.PointProxy.prototype.constructor=n.Physics.P2.PointProxy,Object.defineProperty(n.Physics.P2.PointProxy.prototype,"x",{get:function(){return this.world.mpx(this.destination[0])},set:function(t){this.destination[0]=this.world.pxm(t)}}),Object.defineProperty(n.Physics.P2.PointProxy.prototype,"y",{get:function(){return this.world.mpx(this.destination[1])},set:function(t){this.destination[1]=this.world.pxm(t)}}),Object.defineProperty(n.Physics.P2.PointProxy.prototype,"mx",{get:function(){return this.destination[0]},set:function(t){this.destination[0]=t}}),Object.defineProperty(n.Physics.P2.PointProxy.prototype,"my",{get:function(){return this.destination[1]},set:function(t){this.destination[1]=t}}),n.Physics.P2.InversePointProxy=function(t,e){this.world=t,this.destination=e},n.Physics.P2.InversePointProxy.prototype.constructor=n.Physics.P2.InversePointProxy,Object.defineProperty(n.Physics.P2.InversePointProxy.prototype,"x",{get:function(){return this.world.mpxi(this.destination[0])},set:function(t){this.destination[0]=this.world.pxmi(t)}}),Object.defineProperty(n.Physics.P2.InversePointProxy.prototype,"y",{get:function(){return this.world.mpxi(this.destination[1])},set:function(t){this.destination[1]=this.world.pxmi(t)}}),Object.defineProperty(n.Physics.P2.InversePointProxy.prototype,"mx",{get:function(){return this.destination[0]},set:function(t){this.destination[0]=-t}}),Object.defineProperty(n.Physics.P2.InversePointProxy.prototype,"my",{get:function(){return this.destination[1]},set:function(t){this.destination[1]=-t}}),n.Physics.P2.Body=function(t,e,i,s,r){e=e||null,i=i||0,s=s||0,void 0===r&&(r=1),this.game=t,this.world=t.physics.p2,this.sprite=e,this.type=n.Physics.P2JS,this.offset=new n.Point,this.data=new p2.Body({position:[this.world.pxmi(i),this.world.pxmi(s)],mass:r}),this.data.parent=this,this.velocity=new n.Physics.P2.InversePointProxy(this.world,this.data.velocity),this.force=new n.Physics.P2.InversePointProxy(this.world,this.data.force),this.gravity=new n.Point,this.onBeginContact=new n.Signal,this.onEndContact=new n.Signal,this.collidesWith=[],this.removeNextStep=!1,this.debugBody=null,this.dirty=!1,this._collideWorldBounds=!0,this._bodyCallbacks={},this._bodyCallbackContext={},this._groupCallbacks={},this._groupCallbackContext={},this._reset=!1,e&&(this.setRectangleFromSprite(e),e.exists&&this.game.physics.p2.addBody(this))},n.Physics.P2.Body.prototype={createBodyCallback:function(t,e,i){var s=-1;t.id?s=t.id:t.body&&(s=t.body.id),s>-1&&(null===e?(delete this._bodyCallbacks[s],delete this._bodyCallbackContext[s]):(this._bodyCallbacks[s]=e,this._bodyCallbackContext[s]=i))},createGroupCallback:function(t,e,i){null===e?(delete this._groupCallbacks[t.mask],delete this._groupCallbackContext[t.mask]):(this._groupCallbacks[t.mask]=e,this._groupCallbackContext[t.mask]=i)},getCollisionMask:function(){var t=0;this._collideWorldBounds&&(t=this.game.physics.p2.boundsCollisionGroup.mask);for(var e=0;e<this.collidesWith.length;e++)t|=this.collidesWith[e].mask;return t},updateCollisionMask:function(t){var e=this.getCollisionMask();if(void 0===t)for(var i=this.data.shapes.length-1;i>=0;i--)this.data.shapes[i].collisionMask=e;else t.collisionMask=e},setCollisionGroup:function(t,e){var i=this.getCollisionMask();if(void 0===e)for(var s=this.data.shapes.length-1;s>=0;s--)this.data.shapes[s].collisionGroup=t.mask,this.data.shapes[s].collisionMask=i;else e.collisionGroup=t.mask,e.collisionMask=i},clearCollision:function(t,e,i){if(void 0===t&&(t=!0),void 0===e&&(e=!0),void 0===i)for(var s=this.data.shapes.length-1;s>=0;s--)t&&(this.data.shapes[s].collisionGroup=null),e&&(this.data.shapes[s].collisionMask=null);else t&&(i.collisionGroup=null),e&&(i.collisionMask=null);t&&(this.collidesWith.length=0)},removeCollisionGroup:function(t,e,i){void 0===e&&(e=!0);var s;if(Array.isArray(t))for(var n=0;n<t.length;n++)(s=this.collidesWith.indexOf(t[n]))>-1&&(this.collidesWith.splice(s,1),e&&(delete this._groupCallbacks[t.mask],delete this._groupCallbackContext[t.mask]));else(s=this.collidesWith.indexOf(t))>-1&&(this.collidesWith.splice(s,1),e&&(delete this._groupCallbacks[t.mask],delete this._groupCallbackContext[t.mask]));var r=this.getCollisionMask();if(void 0===i)for(var n=this.data.shapes.length-1;n>=0;n--)this.data.shapes[n].collisionMask=r;else i.collisionMask=r},collides:function(t,e,i,s){if(Array.isArray(t))for(var n=0;n<t.length;n++)-1===this.collidesWith.indexOf(t[n])&&(this.collidesWith.push(t[n]),e&&this.createGroupCallback(t[n],e,i));else-1===this.collidesWith.indexOf(t)&&(this.collidesWith.push(t),e&&this.createGroupCallback(t,e,i));var r=this.getCollisionMask();if(void 0===s)for(var n=this.data.shapes.length-1;n>=0;n--)this.data.shapes[n].collisionMask=r;else s.collisionMask=r},adjustCenterOfMass:function(){this.data.adjustCenterOfMass(),this.shapeChanged()},getVelocityAtPoint:function(t,e){return this.data.getVelocityAtPoint(t,e)},applyDamping:function(t){this.data.applyDamping(t)},applyImpulse:function(t,e,i){this.data.applyImpulse(t,[this.world.pxmi(e),this.world.pxmi(i)])},applyImpulseLocal:function(t,e,i){this.data.applyImpulseLocal(t,[this.world.pxmi(e),this.world.pxmi(i)])},applyForce:function(t,e,i){this.data.applyForce(t,[this.world.pxmi(e),this.world.pxmi(i)])},setZeroForce:function(){this.data.setZeroForce()},setZeroRotation:function(){this.data.angularVelocity=0},setZeroVelocity:function(){this.data.velocity[0]=0,this.data.velocity[1]=0},setZeroDamping:function(){this.data.damping=0,this.data.angularDamping=0},toLocalFrame:function(t,e){return this.data.toLocalFrame(t,e)},toWorldFrame:function(t,e){return this.data.toWorldFrame(t,e)},rotateLeft:function(t){this.data.angularVelocity=this.world.pxm(-t)},rotateRight:function(t){this.data.angularVelocity=this.world.pxm(t)},moveForward:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.velocity[0]=e*Math.cos(i),this.data.velocity[1]=e*Math.sin(i)},moveBackward:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.velocity[0]=-e*Math.cos(i),this.data.velocity[1]=-e*Math.sin(i)},thrust:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.force[0]+=e*Math.cos(i),this.data.force[1]+=e*Math.sin(i)},thrustLeft:function(t){var e=this.world.pxmi(-t),i=this.data.angle;this.data.force[0]+=e*Math.cos(i),this.data.force[1]+=e*Math.sin(i)},thrustRight:function(t){var e=this.world.pxmi(-t),i=this.data.angle;this.data.force[0]-=e*Math.cos(i),this.data.force[1]-=e*Math.sin(i)},reverse:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.force[0]-=e*Math.cos(i),this.data.force[1]-=e*Math.sin(i)},moveLeft:function(t){this.data.velocity[0]=this.world.pxmi(-t)},moveRight:function(t){this.data.velocity[0]=this.world.pxmi(t)},moveUp:function(t){this.data.velocity[1]=this.world.pxmi(-t)},moveDown:function(t){this.data.velocity[1]=this.world.pxmi(t)},preUpdate:function(){this.dirty=!0,this.removeNextStep&&(this.removeFromWorld(),this.removeNextStep=!1)},postUpdate:function(){this.sprite.x=this.world.mpxi(this.data.position[0])+this.offset.x,this.sprite.y=this.world.mpxi(this.data.position[1])+this.offset.y,this.fixedRotation||(this.sprite.rotation=this.data.angle),this.debugBody&&this.debugBody.updateSpriteTransform(),this.dirty=!1},reset:function(t,e,i,s){void 0===i&&(i=!1),void 0===s&&(s=!1),this.setZeroForce(),this.setZeroVelocity(),this.setZeroRotation(),i&&this.setZeroDamping(),s&&(this.mass=1),this.x=t,this.y=e},addToWorld:function(){if(this.game.physics.p2._toRemove)for(var t=0;t<this.game.physics.p2._toRemove.length;t++)this.game.physics.p2._toRemove[t]===this&&this.game.physics.p2._toRemove.splice(t,1);this.data.world!==this.game.physics.p2.world&&this.game.physics.p2.addBody(this)},removeFromWorld:function(){this.data.world===this.game.physics.p2.world&&this.game.physics.p2.removeBodyNextStep(this)},destroy:function(){this.removeFromWorld(),this.clearShapes(),this._bodyCallbacks={},this._bodyCallbackContext={},this._groupCallbacks={},this._groupCallbackContext={},this.debugBody&&this.debugBody.destroy(!0,!0),this.debugBody=null,this.sprite&&(this.sprite.body=null,this.sprite=null)},clearShapes:function(){for(var t=this.data.shapes.length;t--;)this.data.removeShape(this.data.shapes[t]);this.shapeChanged()},addShape:function(t,e,i,s){return void 0===e&&(e=0),void 0===i&&(i=0),void 0===s&&(s=0),this.data.addShape(t,[this.world.pxmi(e),this.world.pxmi(i)],s),this.shapeChanged(),t},addCircle:function(t,e,i,s){var n=new p2.Circle({radius:this.world.pxm(t)});return this.addShape(n,e,i,s)},addRectangle:function(t,e,i,s,n){var r=new p2.Box({width:this.world.pxm(t),height:this.world.pxm(e)});return this.addShape(r,i,s,n)},addPlane:function(t,e,i){var s=new p2.Plane;return this.addShape(s,t,e,i)},addParticle:function(t,e,i){var s=new p2.Particle;return this.addShape(s,t,e,i)},addLine:function(t,e,i,s){var n=new p2.Line({length:this.world.pxm(t)});return this.addShape(n,e,i,s)},addCapsule:function(t,e,i,s,n){var r=new p2.Capsule({length:this.world.pxm(t),radius:this.world.pxm(e)});return this.addShape(r,i,s,n)},addPolygon:function(t,e){t=t||{},Array.isArray(e)||(e=Array.prototype.slice.call(arguments,1));var i=[];if(1===e.length&&Array.isArray(e[0]))i=e[0].slice(0);else if(Array.isArray(e[0]))i=e.slice();else if("number"==typeof e[0])for(var s=0,n=e.length;s<n;s+=2)i.push([e[s],e[s+1]]);var r=i.length-1;i[r][0]===i[0][0]&&i[r][1]===i[0][1]&&i.pop();for(var o=0;o<i.length;o++)i[o][0]=this.world.pxmi(i[o][0]),i[o][1]=this.world.pxmi(i[o][1]);var a=this.data.fromPolygon(i,t);return this.shapeChanged(),a},removeShape:function(t){var e=this.data.removeShape(t);return this.shapeChanged(),e},setCircle:function(t,e,i,s){return this.clearShapes(),this.addCircle(t,e,i,s)},setRectangle:function(t,e,i,s,n){return void 0===t&&(t=16),void 0===e&&(e=16),this.clearShapes(),this.addRectangle(t,e,i,s,n)},setRectangleFromSprite:function(t){return void 0===t&&(t=this.sprite),this.clearShapes(),this.addRectangle(t.width,t.height,0,0,t.rotation)},setMaterial:function(t,e){if(void 0===e)for(var i=this.data.shapes.length-1;i>=0;i--)this.data.shapes[i].material=t;else e.material=t},shapeChanged:function(){this.debugBody&&this.debugBody.draw()},addPhaserPolygon:function(t,e){for(var i=this.game.cache.getPhysicsData(t,e),s=[],n=0;n<i.length;n++){var r=i[n],o=this.addFixture(r);s[r.filter.group]=s[r.filter.group]||[],s[r.filter.group]=s[r.filter.group].concat(o),r.fixtureKey&&(s[r.fixtureKey]=o)}return this.data.aabbNeedsUpdate=!0,this.shapeChanged(),s},addFixture:function(t){var e=[];if(t.circle){var i=new p2.Circle({radius:this.world.pxm(t.circle.radius)});i.collisionGroup=t.filter.categoryBits,i.collisionMask=t.filter.maskBits,i.sensor=t.isSensor;var s=p2.vec2.create();s[0]=this.world.pxmi(t.circle.position[0]-this.sprite.width/2),s[1]=this.world.pxmi(t.circle.position[1]-this.sprite.height/2),this.data.addShape(i,s),e.push(i)}else for(var n=t.polygons,r=p2.vec2.create(),o=0;o<n.length;o++){for(var a=n[o],h=[],l=0;l<a.length;l+=2)h.push([this.world.pxmi(a[l]),this.world.pxmi(a[l+1])]);for(var i=new p2.Convex({vertices:h}),c=0;c!==i.vertices.length;c++){var u=i.vertices[c];p2.vec2.sub(u,u,i.centerOfMass)}p2.vec2.scale(r,i.centerOfMass,1),r[0]-=this.world.pxmi(this.sprite.width/2),r[1]-=this.world.pxmi(this.sprite.height/2),i.updateTriangles(),i.updateCenterOfMass(),i.updateBoundingRadius(),i.collisionGroup=t.filter.categoryBits,i.collisionMask=t.filter.maskBits,i.sensor=t.isSensor,this.data.addShape(i,r),e.push(i)}return e},loadPolygon:function(t,e){if(null===t)var i=e;else var i=this.game.cache.getPhysicsData(t,e);for(var s=p2.vec2.create(),n=0;n<i.length;n++){for(var r=[],o=0;o<i[n].shape.length;o+=2)r.push([this.world.pxmi(i[n].shape[o]),this.world.pxmi(i[n].shape[o+1])]);for(var a=new p2.Convex({vertices:r}),h=0;h!==a.vertices.length;h++){var l=a.vertices[h];p2.vec2.sub(l,l,a.centerOfMass)}p2.vec2.scale(s,a.centerOfMass,1),s[0]-=this.world.pxmi(this.sprite.width/2),s[1]-=this.world.pxmi(this.sprite.height/2),a.updateTriangles(),a.updateCenterOfMass(),a.updateBoundingRadius(),this.data.addShape(a,s)}return this.data.aabbNeedsUpdate=!0,this.shapeChanged(),!0}},n.Physics.P2.Body.prototype.constructor=n.Physics.P2.Body,n.Physics.P2.Body.DYNAMIC=1,n.Physics.P2.Body.STATIC=2,n.Physics.P2.Body.KINEMATIC=4,Object.defineProperty(n.Physics.P2.Body.prototype,"static",{get:function(){return this.data.type===n.Physics.P2.Body.STATIC},set:function(t){t&&this.data.type!==n.Physics.P2.Body.STATIC?(this.data.type=n.Physics.P2.Body.STATIC,this.mass=0):t||this.data.type!==n.Physics.P2.Body.STATIC||(this.data.type=n.Physics.P2.Body.DYNAMIC,this.mass=1)}}),Object.defineProperty(n.Physics.P2.Body.prototype,"dynamic",{get:function(){return this.data.type===n.Physics.P2.Body.DYNAMIC},set:function(t){t&&this.data.type!==n.Physics.P2.Body.DYNAMIC?(this.data.type=n.Physics.P2.Body.DYNAMIC,this.mass=1):t||this.data.type!==n.Physics.P2.Body.DYNAMIC||(this.data.type=n.Physics.P2.Body.STATIC,this.mass=0)}}),Object.defineProperty(n.Physics.P2.Body.prototype,"kinematic",{get:function(){return this.data.type===n.Physics.P2.Body.KINEMATIC},set:function(t){t&&this.data.type!==n.Physics.P2.Body.KINEMATIC?(this.data.type=n.Physics.P2.Body.KINEMATIC,this.mass=4):t||this.data.type!==n.Physics.P2.Body.KINEMATIC||(this.data.type=n.Physics.P2.Body.STATIC,this.mass=0)}}),Object.defineProperty(n.Physics.P2.Body.prototype,"allowSleep",{get:function(){return this.data.allowSleep},set:function(t){t!==this.data.allowSleep&&(this.data.allowSleep=t)}}),Object.defineProperty(n.Physics.P2.Body.prototype,"angle",{get:function(){return n.Math.wrapAngle(n.Math.radToDeg(this.data.angle))},set:function(t){this.data.angle=n.Math.degToRad(n.Math.wrapAngle(t))}}),Object.defineProperty(n.Physics.P2.Body.prototype,"angularDamping",{get:function(){return this.data.angularDamping},set:function(t){this.data.angularDamping=t}}),Object.defineProperty(n.Physics.P2.Body.prototype,"angularForce",{get:function(){return this.data.angularForce},set:function(t){this.data.angularForce=t}}),Object.defineProperty(n.Physics.P2.Body.prototype,"angularVelocity",{get:function(){return this.data.angularVelocity},set:function(t){this.data.angularVelocity=t}}),Object.defineProperty(n.Physics.P2.Body.prototype,"damping",{get:function(){return this.data.damping},set:function(t){this.data.damping=t}}),Object.defineProperty(n.Physics.P2.Body.prototype,"fixedRotation",{get:function(){return this.data.fixedRotation},set:function(t){t!==this.data.fixedRotation&&(this.data.fixedRotation=t)}}),Object.defineProperty(n.Physics.P2.Body.prototype,"inertia",{get:function(){return this.data.inertia},set:function(t){this.data.inertia=t}}),Object.defineProperty(n.Physics.P2.Body.prototype,"mass",{get:function(){return this.data.mass},set:function(t){t!==this.data.mass&&(this.data.mass=t,this.data.updateMassProperties())}}),Object.defineProperty(n.Physics.P2.Body.prototype,"motionState",{get:function(){return this.data.type},set:function(t){t!==this.data.type&&(this.data.type=t)}}),Object.defineProperty(n.Physics.P2.Body.prototype,"rotation",{get:function(){return this.data.angle},set:function(t){this.data.angle=t}}),Object.defineProperty(n.Physics.P2.Body.prototype,"sleepSpeedLimit",{get:function(){return this.data.sleepSpeedLimit},set:function(t){this.data.sleepSpeedLimit=t}}),Object.defineProperty(n.Physics.P2.Body.prototype,"x",{get:function(){return this.world.mpxi(this.data.position[0])},set:function(t){this.data.position[0]=this.world.pxmi(t)}}),Object.defineProperty(n.Physics.P2.Body.prototype,"y",{get:function(){return this.world.mpxi(this.data.position[1])},set:function(t){this.data.position[1]=this.world.pxmi(t)}}),Object.defineProperty(n.Physics.P2.Body.prototype,"id",{get:function(){return this.data.id}}),Object.defineProperty(n.Physics.P2.Body.prototype,"debug",{get:function(){return null!==this.debugBody},set:function(t){t&&!this.debugBody?this.debugBody=new n.Physics.P2.BodyDebug(this.game,this.data):!t&&this.debugBody&&(this.debugBody.destroy(),this.debugBody=null)}}),Object.defineProperty(n.Physics.P2.Body.prototype,"collideWorldBounds",{get:function(){return this._collideWorldBounds},set:function(t){t&&!this._collideWorldBounds?(this._collideWorldBounds=!0,this.updateCollisionMask()):!t&&this._collideWorldBounds&&(this._collideWorldBounds=!1,this.updateCollisionMask())}}),n.Physics.P2.BodyDebug=function(t,e,i){n.Group.call(this,t);var s={pixelsPerLengthUnit:t.physics.p2.mpx(1),debugPolygons:!1,lineWidth:1,alpha:.5};this.settings=n.Utils.extend(s,i),this.ppu=this.settings.pixelsPerLengthUnit,this.ppu=-1*this.ppu,this.body=e,this.canvas=new n.Graphics(t),this.canvas.alpha=this.settings.alpha,this.add(this.canvas),this.draw(),this.updateSpriteTransform()},n.Physics.P2.BodyDebug.prototype=Object.create(n.Group.prototype),n.Physics.P2.BodyDebug.prototype.constructor=n.Physics.P2.BodyDebug,n.Utils.extend(n.Physics.P2.BodyDebug.prototype,{updateSpriteTransform:function(){this.position.x=this.body.position[0]*this.ppu,this.position.y=this.body.position[1]*this.ppu,this.rotation=this.body.angle},draw:function(){var t,e,i,s,n,r,o,a,h,l,c,u,d,p,f;if(a=this.body,l=this.canvas,l.clear(),i=parseInt(this.randomPastelHex(),16),r=16711680,o=this.lineWidth,a instanceof p2.Body&&a.shapes.length){var g=a.shapes.length;for(s=0;s!==g;){if(e=a.shapes[s],h=e.position||0,t=e.angle||0,e instanceof p2.Circle)this.drawCircle(l,h[0]*this.ppu,h[1]*this.ppu,t,e.radius*this.ppu,i,o);else if(e instanceof p2.Capsule)this.drawCapsule(l,h[0]*this.ppu,h[1]*this.ppu,t,e.length*this.ppu,e.radius*this.ppu,r,i,o);else if(e instanceof p2.Plane)this.drawPlane(l,h[0]*this.ppu,-h[1]*this.ppu,i,r,5*o,10*o,10*o,100*this.ppu,t);else if(e instanceof p2.Line)this.drawLine(l,e.length*this.ppu,r,o);else if(e instanceof p2.Box)this.drawRectangle(l,h[0]*this.ppu,h[1]*this.ppu,t,e.width*this.ppu,e.height*this.ppu,r,i,o);else if(e instanceof p2.Convex){for(u=[],d=p2.vec2.create(),n=p=0,f=e.vertices.length;0<=f?p<f:p>f;n=0<=f?++p:--p)c=e.vertices[n],p2.vec2.rotate(d,c,t),u.push([(d[0]+h[0])*this.ppu,-(d[1]+h[1])*this.ppu]);this.drawConvex(l,u,e.triangles,r,i,o,this.settings.debugPolygons,[h[0]*this.ppu,-h[1]*this.ppu])}s++}}},drawRectangle:function(t,e,i,s,n,r,o,a,h){void 0===h&&(h=1),void 0===o&&(o=0),t.lineStyle(h,o,1),t.beginFill(a),t.drawRect(e-n/2,i-r/2,n,r)},drawCircle:function(t,e,i,s,n,r,o){void 0===o&&(o=1),void 0===r&&(r=16777215),t.lineStyle(o,0,1),t.beginFill(r,1),t.drawCircle(e,i,2*-n),t.endFill(),t.moveTo(e,i),t.lineTo(e+n*Math.cos(-s),i+n*Math.sin(-s))},drawLine:function(t,e,i,s){void 0===s&&(s=1),void 0===i&&(i=0),t.lineStyle(5*s,i,1),t.moveTo(-e/2,0),t.lineTo(e/2,0)},drawConvex:function(t,e,i,s,n,r,o,a){var h,l,c,u,d,p,f,g,m,y,v;if(void 0===r&&(r=1),void 0===s&&(s=0),o){for(h=[16711680,65280,255],l=0;l!==e.length+1;)u=e[l%e.length],d=e[(l+1)%e.length],f=u[0],y=u[1],g=d[0],v=d[1],t.lineStyle(r,h[l%h.length],1),t.moveTo(f,-y),t.lineTo(g,-v),t.drawCircle(f,-y,2*r),l++;return t.lineStyle(r,0,1),t.drawCircle(a[0],a[1],2*r)}for(t.lineStyle(r,s,1),t.beginFill(n),l=0;l!==e.length;)c=e[l],p=c[0],m=c[1],0===l?t.moveTo(p,-m):t.lineTo(p,-m),l++;if(t.endFill(),e.length>2)return t.moveTo(e[e.length-1][0],-e[e.length-1][1]),t.lineTo(e[0][0],-e[0][1])},drawPath:function(t,e,i,s,n){var r,o,a,h,l,c,u,d,p,f,g,m;for(void 0===n&&(n=1),void 0===i&&(i=0),t.lineStyle(n,i,1),"number"==typeof s&&t.beginFill(s),o=null,a=null,r=0;r<e.length;)f=e[r],g=f[0],m=f[1],g===o&&m===a||(0===r?t.moveTo(g,m):(h=o,l=a,c=g,u=m,d=e[(r+1)%e.length][0],p=e[(r+1)%e.length][1],0!==(c-h)*(p-l)-(d-h)*(u-l)&&t.lineTo(g,m)),o=g,a=m),r++;"number"==typeof s&&t.endFill(),e.length>2&&"number"==typeof s&&(t.moveTo(e[e.length-1][0],e[e.length-1][1]),t.lineTo(e[0][0],e[0][1]))},drawPlane:function(t,e,i,s,n,r,o,a,h,l){var c,u;void 0===r&&(r=1),void 0===s&&(s=16777215),t.lineStyle(r,n,11),t.beginFill(s),t.moveTo(e,-i),c=e+Math.cos(l)*this.game.width,u=i+Math.sin(l)*this.game.height,t.lineTo(c,-u),t.moveTo(e,-i),c=e+Math.cos(l)*-this.game.width,u=i+Math.sin(l)*-this.game.height,t.lineTo(c,-u)},drawCapsule:function(t,e,i,s,n,r,o,a,h){void 0===h&&(h=1),void 0===o&&(o=0),t.lineStyle(h,o,1);var l=Math.cos(s),c=Math.sin(s);t.beginFill(a,1),t.drawCircle(-n/2*l+e,-n/2*c+i,2*-r),t.drawCircle(n/2*l+e,n/2*c+i,2*-r),t.endFill(),t.lineStyle(h,o,0),t.beginFill(a,1),t.moveTo(-n/2*l+r*c+e,-n/2*c+r*l+i),t.lineTo(n/2*l+r*c+e,n/2*c+r*l+i),t.lineTo(n/2*l-r*c+e,n/2*c-r*l+i),t.lineTo(-n/2*l-r*c+e,-n/2*c-r*l+i),t.endFill(),t.lineStyle(h,o,1),t.moveTo(-n/2*l+r*c+e,-n/2*c+r*l+i),t.lineTo(n/2*l+r*c+e,n/2*c+r*l+i),t.moveTo(-n/2*l-r*c+e,-n/2*c-r*l+i),t.lineTo(n/2*l-r*c+e,n/2*c-r*l+i)},randomPastelHex:function(){var t,e,i,s;return i=[255,255,255],s=Math.floor(256*Math.random()),e=Math.floor(256*Math.random()),t=Math.floor(256*Math.random()),s=Math.floor((s+3*i[0])/4),e=Math.floor((e+3*i[1])/4),t=Math.floor((t+3*i[2])/4),this.rgbToHex(s,e,t)},rgbToHex:function(t,e,i){return this.componentToHex(t)+this.componentToHex(e)+this.componentToHex(i)},componentToHex:function(t){var e;return e=t.toString(16),2===e.length?e:e+"0"}}),n.Physics.P2.Spring=function(t,e,i,s,n,r,o,a,h,l){this.game=t.game,this.world=t,void 0===s&&(s=1),void 0===n&&(n=100),void 0===r&&(r=1),s=t.pxm(s);var c={restLength:s,stiffness:n,damping:r};void 0!==o&&null!==o&&(c.worldAnchorA=[t.pxm(o[0]),t.pxm(o[1])]),void 0!==a&&null!==a&&(c.worldAnchorB=[t.pxm(a[0]),t.pxm(a[1])]),void 0!==h&&null!==h&&(c.localAnchorA=[t.pxm(h[0]),t.pxm(h[1])]),void 0!==l&&null!==l&&(c.localAnchorB=[t.pxm(l[0]),t.pxm(l[1])]),this.data=new p2.LinearSpring(e,i,c),this.data.parent=this},n.Physics.P2.Spring.prototype.constructor=n.Physics.P2.Spring,n.Physics.P2.RotationalSpring=function(t,e,i,s,n,r){this.game=t.game,this.world=t,void 0===s&&(s=null),void 0===n&&(n=100),void 0===r&&(r=1),s&&(s=t.pxm(s));var o={restAngle:s,stiffness:n,damping:r};this.data=new p2.RotationalSpring(e,i,o),this.data.parent=this},n.Physics.P2.Spring.prototype.constructor=n.Physics.P2.Spring,n.Physics.P2.Material=function(t){this.name=t,p2.Material.call(this)},n.Physics.P2.Material.prototype=Object.create(p2.Material.prototype),n.Physics.P2.Material.prototype.constructor=n.Physics.P2.Material,n.Physics.P2.ContactMaterial=function(t,e,i){p2.ContactMaterial.call(this,t,e,i)},n.Physics.P2.ContactMaterial.prototype=Object.create(p2.ContactMaterial.prototype),n.Physics.P2.ContactMaterial.prototype.constructor=n.Physics.P2.ContactMaterial,n.Physics.P2.CollisionGroup=function(t){this.mask=t},n.Physics.P2.DistanceConstraint=function(t,e,i,s,n,r,o){void 0===s&&(s=100),void 0===n&&(n=[0,0]),void 0===r&&(r=[0,0]),void 0===o&&(o=Number.MAX_VALUE),this.game=t.game,this.world=t,s=t.pxm(s),n=[t.pxmi(n[0]),t.pxmi(n[1])],r=[t.pxmi(r[0]),t.pxmi(r[1])];var a={distance:s,localAnchorA:n,localAnchorB:r,maxForce:o};p2.DistanceConstraint.call(this,e,i,a)},n.Physics.P2.DistanceConstraint.prototype=Object.create(p2.DistanceConstraint.prototype),n.Physics.P2.DistanceConstraint.prototype.constructor=n.Physics.P2.DistanceConstraint,n.Physics.P2.GearConstraint=function(t,e,i,s,n){void 0===s&&(s=0),void 0===n&&(n=1),this.game=t.game,this.world=t;var r={angle:s,ratio:n};p2.GearConstraint.call(this,e,i,r)},n.Physics.P2.GearConstraint.prototype=Object.create(p2.GearConstraint.prototype),n.Physics.P2.GearConstraint.prototype.constructor=n.Physics.P2.GearConstraint,n.Physics.P2.LockConstraint=function(t,e,i,s,n,r){void 0===s&&(s=[0,0]),void 0===n&&(n=0),void 0===r&&(r=Number.MAX_VALUE),this.game=t.game,this.world=t,s=[t.pxm(s[0]),t.pxm(s[1])];var o={localOffsetB:s,localAngleB:n,maxForce:r};p2.LockConstraint.call(this,e,i,o)},n.Physics.P2.LockConstraint.prototype=Object.create(p2.LockConstraint.prototype),n.Physics.P2.LockConstraint.prototype.constructor=n.Physics.P2.LockConstraint,n.Physics.P2.PrismaticConstraint=function(t,e,i,s,n,r,o,a){void 0===s&&(s=!0),void 0===n&&(n=[0,0]),void 0===r&&(r=[0,0]),void 0===o&&(o=[0,0]),void 0===a&&(a=Number.MAX_VALUE),this.game=t.game,this.world=t,n=[t.pxmi(n[0]),t.pxmi(n[1])],r=[t.pxmi(r[0]),t.pxmi(r[1])];var h={localAnchorA:n,localAnchorB:r,localAxisA:o,maxForce:a,disableRotationalLock:!s};p2.PrismaticConstraint.call(this,e,i,h)},n.Physics.P2.PrismaticConstraint.prototype=Object.create(p2.PrismaticConstraint.prototype),n.Physics.P2.PrismaticConstraint.prototype.constructor=n.Physics.P2.PrismaticConstraint,n.Physics.P2.RevoluteConstraint=function(t,e,i,s,n,r,o){void 0===r&&(r=Number.MAX_VALUE),void 0===o&&(o=null),this.game=t.game,this.world=t,i=[t.pxmi(i[0]),t.pxmi(i[1])],n=[t.pxmi(n[0]),t.pxmi(n[1])],o&&(o=[t.pxmi(o[0]),t.pxmi(o[1])]);var a={worldPivot:o,localPivotA:i,localPivotB:n,maxForce:r};p2.RevoluteConstraint.call(this,e,s,a)},n.Physics.P2.RevoluteConstraint.prototype=Object.create(p2.RevoluteConstraint.prototype),n.Physics.P2.RevoluteConstraint.prototype.constructor=n.Physics.P2.RevoluteConstraint,n.ImageCollection=function(t,e,i,s,n,r,o){(void 0===i||i<=0)&&(i=32),(void 0===s||s<=0)&&(s=32),void 0===n&&(n=0),void 0===r&&(r=0),this.name=t,this.firstgid=0|e,this.imageWidth=0|i,this.imageHeight=0|s,this.imageMargin=0|n,this.imageSpacing=0|r,this.properties=o||{},this.images=[],this.total=0},n.ImageCollection.prototype={containsImageIndex:function(t){return t>=this.firstgid&&t<this.firstgid+this.total},addImage:function(t,e){this.images.push({gid:t,image:e}),this.total++}},n.ImageCollection.prototype.constructor=n.ImageCollection,n.Tile=function(t,e,i,s,n,r){this.layer=t,this.index=e,this.x=i,this.y=s,this.rotation=0,this.flipped=!1,this.worldX=i*n,this.worldY=s*r,this.width=n,this.height=r,this.centerX=Math.abs(n/2),this.centerY=Math.abs(r/2),this.alpha=1,this.properties={},this.scanned=!1,this.faceTop=!1,this.faceBottom=!1,this.faceLeft=!1,this.faceRight=!1,this.collideLeft=!1,this.collideRight=!1,this.collideUp=!1,this.collideDown=!1,this.collisionCallback=null,this.collisionCallbackContext=this},n.Tile.prototype={containsPoint:function(t,e){return!(t<this.worldX||e<this.worldY||t>this.right||e>this.bottom)},intersects:function(t,e,i,s){return!(i<=this.worldX)&&(!(s<=this.worldY)&&(!(t>=this.worldX+this.width)&&!(e>=this.worldY+this.height)))},setCollisionCallback:function(t,e){this.collisionCallback=t,this.collisionCallbackContext=e},destroy:function(){this.collisionCallback=null,this.collisionCallbackContext=null,this.properties=null},setCollision:function(t,e,i,s){this.collideLeft=t,this.collideRight=e,this.collideUp=i,this.collideDown=s,this.faceLeft=t,this.faceRight=e,this.faceTop=i,this.faceBottom=s},resetCollision:function(){this.collideLeft=!1,this.collideRight=!1,this.collideUp=!1,this.collideDown=!1,this.faceTop=!1,this.faceBottom=!1,this.faceLeft=!1,this.faceRight=!1},isInteresting:function(t,e){return t&&e?this.collideLeft||this.collideRight||this.collideUp||this.collideDown||this.faceTop||this.faceBottom||this.faceLeft||this.faceRight||this.collisionCallback:t?this.collideLeft||this.collideRight||this.collideUp||this.collideDown:!!e&&(this.faceTop||this.faceBottom||this.faceLeft||this.faceRight)},copy:function(t){this.index=t.index,this.alpha=t.alpha,this.properties=t.properties,this.collideUp=t.collideUp,this.collideDown=t.collideDown,this.collideLeft=t.collideLeft,this.collideRight=t.collideRight,this.collisionCallback=t.collisionCallback,this.collisionCallbackContext=t.collisionCallbackContext}},n.Tile.prototype.constructor=n.Tile,Object.defineProperty(n.Tile.prototype,"collides",{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown}}),Object.defineProperty(n.Tile.prototype,"canCollide",{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown||this.collisionCallback}}),Object.defineProperty(n.Tile.prototype,"left",{get:function(){return this.worldX}}),Object.defineProperty(n.Tile.prototype,"right",{get:function(){return this.worldX+this.width}}),Object.defineProperty(n.Tile.prototype,"top",{get:function(){return this.worldY}}),Object.defineProperty(n.Tile.prototype,"bottom",{get:function(){return this.worldY+this.height}}),n.Tilemap=function(t,e,i,s,r,o){this.game=t,this.key=e;var a=n.TilemapParser.parse(this.game,e,i,s,r,o);null!==a&&(this.width=a.width,this.height=a.height,this.tileWidth=a.tileWidth,this.tileHeight=a.tileHeight,this.orientation=a.orientation,this.format=a.format,this.version=a.version,this.properties=a.properties,this.widthInPixels=a.widthInPixels,this.heightInPixels=a.heightInPixels,this.layers=a.layers,this.tilesets=a.tilesets,this.imagecollections=a.imagecollections,this.tiles=a.tiles,this.objects=a.objects,this.collideIndexes=[],this.collision=a.collision,this.images=a.images,this.enableDebug=!1,this.currentLayer=0,this.debugMap=[],this._results=[],this._tempA=0,this._tempB=0)},n.Tilemap.CSV=0,n.Tilemap.TILED_JSON=1,n.Tilemap.NORTH=0,n.Tilemap.EAST=1,n.Tilemap.SOUTH=2,n.Tilemap.WEST=3,n.Tilemap.prototype={create:function(t,e,i,s,n,r){return void 0===r&&(r=this.game.world),this.width=e,this.height=i,this.setTileSize(s,n),this.layers.length=0,this.createBlankLayer(t,e,i,s,n,r)},setTileSize:function(t,e){this.tileWidth=t,this.tileHeight=e,this.widthInPixels=this.width*t,this.heightInPixels=this.height*e},addTilesetImage:function(t,e,i,s,r,o,a){if(void 0===t)return null;void 0===i&&(i=this.tileWidth),void 0===s&&(s=this.tileHeight),void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=0),0===i&&(i=32),0===s&&(s=32);var h=null;if(void 0!==e&&null!==e||(e=t),e instanceof n.BitmapData)h=e.canvas;else{if(!this.game.cache.checkImageKey(e))return console.warn('Phaser.Tilemap.addTilesetImage: Invalid image key given: "'+e+'"'),null;h=this.game.cache.getImage(e)}var l=this.getTilesetIndex(t);if(null===l&&this.format===n.Tilemap.TILED_JSON)return console.warn('Phaser.Tilemap.addTilesetImage: No data found in the JSON matching the tileset name: "'+t+'"'),null;if(this.tilesets[l])return this.tilesets[l].setImage(h),this.tilesets[l];var c=new n.Tileset(t,a,i,s,r,o,{});c.setImage(h),this.tilesets.push(c);for(var u=this.tilesets.length-1,d=r,p=r,f=0,g=0,m=0,y=a;y<a+c.total&&(this.tiles[y]=[d,p,u],d+=i+o,++f!==c.total)&&(++g!==c.columns||(d=r,p+=s+o,g=0,++m!==c.rows));y++);return c},createFromObjects:function(t,e,i,s,r,o,a,h,l){if(void 0===r&&(r=!0),void 0===o&&(o=!1),void 0===a&&(a=this.game.world),void 0===h&&(h=n.Sprite),void 0===l&&(l=!0),!this.objects[t])return void console.warn("Tilemap.createFromObjects: Invalid objectgroup name given: "+t);for(var c=0;c<this.objects[t].length;c++){var u=!1,d=this.objects[t][c];if(void 0!==d.gid&&"number"==typeof e&&d.gid===e?u=!0:void 0!==d.id&&"number"==typeof e&&d.id===e?u=!0:void 0!==d.name&&"string"==typeof e&&d.name===e&&(u=!0),u){var p=new h(this.game,parseFloat(d.x,10),parseFloat(d.y,10),i,s);p.name=d.name,p.visible=d.visible,p.autoCull=o,p.exists=r,d.width&&(p.width=d.width),d.height&&(p.height=d.height),d.rotation&&(p.angle=d.rotation),l&&(p.y-=p.height),a.add(p);for(var f in d.properties)a.set(p,f,d.properties[f],!1,!1,0,!0)}}},createFromTiles:function(t,e,i,s,r,o){"number"==typeof t&&(t=[t]),void 0===e||null===e?e=[]:"number"==typeof e&&(e=[e]),s=this.getLayer(s),void 0===r&&(r=this.game.world),void 0===o&&(o={}),void 0===o.customClass&&(o.customClass=n.Sprite),void 0===o.adjustY&&(o.adjustY=!0);var a=this.layers[s].width,h=this.layers[s].height;if(this.copy(0,0,a,h,s),this._results.length<2)return 0;for(var l,c=0,u=1,d=this._results.length;u<d;u++)if(-1!==t.indexOf(this._results[u].index)){l=new o.customClass(this.game,this._results[u].worldX,this._results[u].worldY,i);for(var p in o)l[p]=o[p];r.add(l),c++}if(1===e.length)for(u=0;u<t.length;u++)this.replace(t[u],e[0],0,0,a,h,s);else if(e.length>1)for(u=0;u<t.length;u++)this.replace(t[u],e[u],0,0,a,h,s);return c},createLayer:function(t,e,i,s){void 0===e&&(e=this.game.width),void 0===i&&(i=this.game.height),void 0===s&&(s=this.game.world);var r=t;if("string"==typeof t&&(r=this.getLayerIndex(t)),null===r||r>this.layers.length)return void console.warn("Tilemap.createLayer: Invalid layer ID given: "+r);void 0===e||e<=0?e=Math.min(this.game.width,this.layers[r].widthInPixels):e>this.game.width&&(e=this.game.width),void 0===i||i<=0?i=Math.min(this.game.height,this.layers[r].heightInPixels):i>this.game.height&&(i=this.game.height),this.enableDebug&&(console.group("Tilemap.createLayer"),console.log("Name:",this.layers[r].name),console.log("Size:",e,"x",i),console.log("Tileset:",this.tilesets[0].name,"index:",r));var o=s.add(new n.TilemapLayer(this.game,this,r,e,i));return this.enableDebug&&console.groupEnd(),o},createBlankLayer:function(t,e,i,s,r,o){if(void 0===o&&(o=this.game.world),null!==this.getLayerIndex(t))return void console.warn("Tilemap.createBlankLayer: Layer with matching name already exists: "+t);for(var a,h={name:t,x:0,y:0,width:e,height:i,widthInPixels:e*s,heightInPixels:i*r,alpha:1,visible:!0,properties:{},indexes:[],callbacks:[],bodies:[],data:null},l=[],c=0;c<i;c++){a=[];for(var u=0;u<e;u++)a.push(new n.Tile(h,-1,u,c,s,r));l.push(a)}h.data=l,this.layers.push(h),this.currentLayer=this.layers.length-1;var d=h.widthInPixels,p=h.heightInPixels;d>this.game.width&&(d=this.game.width),p>this.game.height&&(p=this.game.height);var l=new n.TilemapLayer(this.game,this,this.layers.length-1,d,p);return l.name=t,o.add(l)},getIndex:function(t,e){for(var i=0;i<t.length;i++)if(t[i].name===e)return i;return null},getLayerIndex:function(t){return this.getIndex(this.layers,t)},getTilesetIndex:function(t){return this.getIndex(this.tilesets,t)},getImageIndex:function(t){return this.getIndex(this.images,t)},setTileIndexCallback:function(t,e,i,s){if(s=this.getLayer(s),"number"==typeof t)this.layers[s].callbacks[t]={callback:e,callbackContext:i};else for(var n=0,r=t.length;n<r;n++)this.layers[s].callbacks[t[n]]={callback:e,callbackContext:i}},setTileLocationCallback:function(t,e,i,s,n,r,o){if(o=this.getLayer(o),this.copy(t,e,i,s,o),!(this._results.length<2))for(var a=1;a<this._results.length;a++)this._results[a].setCollisionCallback(n,r)},setCollision:function(t,e,i,s){if(void 0===e&&(e=!0),void 0===s&&(s=!0),i=this.getLayer(i),"number"==typeof t)return this.setCollisionByIndex(t,e,i,!0);if(Array.isArray(t)){for(var n=0;n<t.length;n++)this.setCollisionByIndex(t[n],e,i,!1);s&&this.calculateFaces(i)}},setCollisionBetween:function(t,e,i,s,n){if(void 0===i&&(i=!0),void 0===n&&(n=!0),s=this.getLayer(s),!(t>e)){for(var r=t;r<=e;r++)this.setCollisionByIndex(r,i,s,!1);n&&this.calculateFaces(s)}},setCollisionByExclusion:function(t,e,i,s){void 0===e&&(e=!0),void 0===s&&(s=!0),i=this.getLayer(i);for(var n=0,r=this.tiles.length;n<r;n++)-1===t.indexOf(n)&&this.setCollisionByIndex(n,e,i,!1);s&&this.calculateFaces(i)},setCollisionByIndex:function(t,e,i,s){if(void 0===e&&(e=!0),void 0===i&&(i=this.currentLayer),void 0===s&&(s=!0),e)this.collideIndexes.push(t);else{var n=this.collideIndexes.indexOf(t);n>-1&&this.collideIndexes.splice(n,1)}for(var r=0;r<this.layers[i].height;r++)for(var o=0;o<this.layers[i].width;o++){var a=this.layers[i].data[r][o];a&&a.index===t&&(e?a.setCollision(!0,!0,!0,!0):a.resetCollision(),a.faceTop=e,a.faceBottom=e,a.faceLeft=e,a.faceRight=e)}return s&&this.calculateFaces(i),i},getLayer:function(t){return void 0===t?t=this.currentLayer:"string"==typeof t?t=this.getLayerIndex(t):t instanceof n.TilemapLayer&&(t=t.index),t},setPreventRecalculate:function(t){if(!0===t&&!0!==this.preventingRecalculate&&(this.preventingRecalculate=!0,this.needToRecalculate={}),!1===t&&!0===this.preventingRecalculate){this.preventingRecalculate=!1;for(var e in this.needToRecalculate)this.calculateFaces(e);this.needToRecalculate=!1}},calculateFaces:function(t){if(this.preventingRecalculate)return void(this.needToRecalculate[t]=!0);for(var e=null,i=null,s=null,n=null,r=0,o=this.layers[t].height;r<o;r++)for(var a=0,h=this.layers[t].width;a<h;a++){var l=this.layers[t].data[r][a];l&&(e=this.getTileAbove(t,a,r),i=this.getTileBelow(t,a,r),s=this.getTileLeft(t,a,r),n=this.getTileRight(t,a,r),l.collides&&(l.faceTop=!0,l.faceBottom=!0,l.faceLeft=!0,l.faceRight=!0),e&&e.collides&&(l.faceTop=!1),i&&i.collides&&(l.faceBottom=!1),s&&s.collides&&(l.faceLeft=!1),n&&n.collides&&(l.faceRight=!1))}},getTileAbove:function(t,e,i){return i>0?this.layers[t].data[i-1][e]:null},getTileBelow:function(t,e,i){return i<this.layers[t].height-1?this.layers[t].data[i+1][e]:null},getTileLeft:function(t,e,i){return e>0?this.layers[t].data[i][e-1]:null},getTileRight:function(t,e,i){return e<this.layers[t].width-1?this.layers[t].data[i][e+1]:null},setLayer:function(t){t=this.getLayer(t),this.layers[t]&&(this.currentLayer=t)},hasTile:function(t,e,i){return i=this.getLayer(i),void 0!==this.layers[i].data[e]&&void 0!==this.layers[i].data[e][t]&&this.layers[i].data[e][t].index>-1},removeTile:function(t,e,i){if(i=this.getLayer(i),t>=0&&t<this.layers[i].width&&e>=0&&e<this.layers[i].height&&this.hasTile(t,e,i)){var s=this.layers[i].data[e][t];return this.layers[i].data[e][t]=new n.Tile(this.layers[i],-1,t,e,this.tileWidth,this.tileHeight),this.layers[i].dirty=!0,this.calculateFaces(i),s}},removeTileWorldXY:function(t,e,i,s,n){return n=this.getLayer(n),t=this.game.math.snapToFloor(t,i)/i,e=this.game.math.snapToFloor(e,s)/s,this.removeTile(t,e,n)},putTile:function(t,e,i,s){if(null===t)return this.removeTile(e,i,s);if(s=this.getLayer(s),e>=0&&e<this.layers[s].width&&i>=0&&i<this.layers[s].height){var r;return t instanceof n.Tile?(r=t.index,this.hasTile(e,i,s)?this.layers[s].data[i][e].copy(t):this.layers[s].data[i][e]=new n.Tile(s,r,e,i,t.width,t.height)):(r=t,this.hasTile(e,i,s)?this.layers[s].data[i][e].index=r:this.layers[s].data[i][e]=new n.Tile(this.layers[s],r,e,i,this.tileWidth,this.tileHeight)),this.collideIndexes.indexOf(r)>-1?this.layers[s].data[i][e].setCollision(!0,!0,!0,!0):this.layers[s].data[i][e].resetCollision(),this.layers[s].dirty=!0,this.calculateFaces(s),this.layers[s].data[i][e]}return null},putTileWorldXY:function(t,e,i,s,n,r){return r=this.getLayer(r),e=this.game.math.snapToFloor(e,s)/s,i=this.game.math.snapToFloor(i,n)/n,this.putTile(t,e,i,r)},searchTileIndex:function(t,e,i,s){void 0===e&&(e=0),void 0===i&&(i=!1),s=this.getLayer(s);var n=0;if(i){for(var r=this.layers[s].height-1;r>=0;r--)for(var o=this.layers[s].width-1;o>=0;o--)if(this.layers[s].data[r][o].index===t){if(n===e)return this.layers[s].data[r][o];n++}}else for(var r=0;r<this.layers[s].height;r++)for(var o=0;o<this.layers[s].width;o++)if(this.layers[s].data[r][o].index===t){if(n===e)return this.layers[s].data[r][o];n++}return null},getTile:function(t,e,i,s){return void 0===s&&(s=!1),i=this.getLayer(i),t>=0&&t<this.layers[i].width&&e>=0&&e<this.layers[i].height?-1===this.layers[i].data[e][t].index?s?this.layers[i].data[e][t]:null:this.layers[i].data[e][t]:null},getTileWorldXY:function(t,e,i,s,n,r){return void 0===i&&(i=this.tileWidth),void 0===s&&(s=this.tileHeight),n=this.getLayer(n),t=this.game.math.snapToFloor(t,i)/i,e=this.game.math.snapToFloor(e,s)/s,this.getTile(t,e,n,r)},copy:function(t,e,i,s,n){if(n=this.getLayer(n),!this.layers[n])return void(this._results.length=0);void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=this.layers[n].width),void 0===s&&(s=this.layers[n].height),t<0&&(t=0),e<0&&(e=0),i>this.layers[n].width&&(i=this.layers[n].width),s>this.layers[n].height&&(s=this.layers[n].height),this._results.length=0,this._results.push({x:t,y:e,width:i,height:s,layer:n});for(var r=e;r<e+s;r++)for(var o=t;o<t+i;o++)this._results.push(this.layers[n].data[r][o]);return this._results},paste:function(t,e,i,s){if(void 0===t&&(t=0),void 0===e&&(e=0),s=this.getLayer(s),i&&!(i.length<2)){for(var n=t-i[1].x,r=e-i[1].y,o=1;o<i.length;o++)this.layers[s].data[r+i[o].y][n+i[o].x].copy(i[o]);this.layers[s].dirty=!0,this.calculateFaces(s)}},swap:function(t,e,i,s,n,r,o){o=this.getLayer(o),this.copy(i,s,n,r,o),this._results.length<2||(this._tempA=t,this._tempB=e,this._results.forEach(this.swapHandler,this),this.paste(i,s,this._results,o))},swapHandler:function(t){t.index===this._tempA?t.index=this._tempB:t.index===this._tempB&&(t.index=this._tempA)},forEach:function(t,e,i,s,n,r,o){o=this.getLayer(o),this.copy(i,s,n,r,o),this._results.length<2||(this._results.forEach(t,e),this.paste(i,s,this._results,o))},replace:function(t,e,i,s,n,r,o){if(o=this.getLayer(o),this.copy(i,s,n,r,o),!(this._results.length<2)){for(var a=1;a<this._results.length;a++)this._results[a].index===t&&(this._results[a].index=e);this.paste(i,s,this._results,o)}},random:function(t,e,i,s,n){if(n=this.getLayer(n),this.copy(t,e,i,s,n),!(this._results.length<2)){for(var r=[],o=1;o<this._results.length;o++)if(this._results[o].index){var a=this._results[o].index;-1===r.indexOf(a)&&r.push(a)}for(var h=1;h<this._results.length;h++)this._results[h].index=this.game.rnd.pick(r);this.paste(t,e,this._results,n)}},shuffle:function(t,e,i,s,r){if(r=this.getLayer(r),this.copy(t,e,i,s,r),!(this._results.length<2)){for(var o=[],a=1;a<this._results.length;a++)this._results[a].index&&o.push(this._results[a].index);n.ArrayUtils.shuffle(o);for(var h=1;h<this._results.length;h++)this._results[h].index=o[h-1];this.paste(t,e,this._results,r)}},fill:function(t,e,i,s,n,r){if(r=this.getLayer(r),this.copy(e,i,s,n,r),!(this._results.length<2)){for(var o=1;o<this._results.length;o++)this._results[o].index=t;this.paste(e,i,this._results,r)}},removeAllLayers:function(){this.layers.length=0,this.currentLayer=0},dump:function(){for(var t="",e=[""],i=0;i<this.layers[this.currentLayer].height;i++){for(var s=0;s<this.layers[this.currentLayer].width;s++)t+="%c ",this.layers[this.currentLayer].data[i][s]>1?this.debugMap[this.layers[this.currentLayer].data[i][s]]?e.push("background: "+this.debugMap[this.layers[this.currentLayer].data[i][s]]):e.push("background: #ffffff"):e.push("background: rgb(0, 0, 0)");t+="\n"}e[0]=t,console.log.apply(console,e)},destroy:function(){this.removeAllLayers(),this.data=[],this.game=null}},n.Tilemap.prototype.constructor=n.Tilemap,Object.defineProperty(n.Tilemap.prototype,"layer",{get:function(){return this.layers[this.currentLayer]},set:function(t){t!==this.currentLayer&&this.setLayer(t)}}),n.TilemapLayer=function(t,e,i,s,r){s|=0,r|=0,n.Sprite.call(this,t,0,0),this.map=e,this.index=i,this.layer=e.layers[i],this.canvas=PIXI.CanvasPool.create(this,s,r),this.context=this.canvas.getContext("2d"),this.setTexture(new PIXI.Texture(new PIXI.BaseTexture(this.canvas))),this.type=n.TILEMAPLAYER,this.physicsType=n.TILEMAPLAYER,this.renderSettings={enableScrollDelta:!1,overdrawRatio:.2,copyCanvas:null},this.debug=!1,this.exists=!0,this.debugSettings={missingImageFill:"rgb(255,255,255)",debuggedTileOverfill:"rgba(0,255,0,0.4)",forceFullRedraw:!0,debugAlpha:.5,facingEdgeStroke:"rgba(0,255,0,1)",collidingTileOverfill:"rgba(0,255,0,0.2)"},this.scrollFactorX=1,this.scrollFactorY=1,this.dirty=!0,this.rayStepRate=4,this._wrap=!1,this._mc={scrollX:0,scrollY:0,renderWidth:0,renderHeight:0,tileWidth:e.tileWidth,tileHeight:e.tileHeight,cw:e.tileWidth,ch:e.tileHeight,tilesets:[]},this._scrollX=0,this._scrollY=0,this._results=[],t.device.canvasBitBltShift||(this.renderSettings.copyCanvas=n.TilemapLayer.ensureSharedCopyCanvas()),this.fixedToCamera=!0},n.TilemapLayer.prototype=Object.create(n.Sprite.prototype),n.TilemapLayer.prototype.constructor=n.TilemapLayer,n.TilemapLayer.prototype.preUpdateCore=n.Component.Core.preUpdate,n.TilemapLayer.sharedCopyCanvas=null,n.TilemapLayer.ensureSharedCopyCanvas=function(){return this.sharedCopyCanvas||(this.sharedCopyCanvas=PIXI.CanvasPool.create(this,2,2)),this.sharedCopyCanvas},n.TilemapLayer.prototype.preUpdate=function(){return this.preUpdateCore()},n.TilemapLayer.prototype.postUpdate=function(){this.fixedToCamera&&(this.position.x=(this.game.camera.view.x+this.cameraOffset.x)/this.game.camera.scale.x,this.position.y=(this.game.camera.view.y+this.cameraOffset.y)/this.game.camera.scale.y),this._scrollX=this.game.camera.view.x*this.scrollFactorX/this.scale.x,this._scrollY=this.game.camera.view.y*this.scrollFactorY/this.scale.y},n.TilemapLayer.prototype._renderCanvas=function(t){this.fixedToCamera&&(this.position.x=(this.game.camera.view.x+this.cameraOffset.x)/this.game.camera.scale.x,this.position.y=(this.game.camera.view.y+this.cameraOffset.y)/this.game.camera.scale.y),this._scrollX=this.game.camera.view.x*this.scrollFactorX/this.scale.x,this._scrollY=this.game.camera.view.y*this.scrollFactorY/this.scale.y,this.render(),PIXI.Sprite.prototype._renderCanvas.call(this,t)},n.TilemapLayer.prototype._renderWebGL=function(t){this.fixedToCamera&&(this.position.x=(this.game.camera.view.x+this.cameraOffset.x)/this.game.camera.scale.x,this.position.y=(this.game.camera.view.y+this.cameraOffset.y)/this.game.camera.scale.y),this._scrollX=this.game.camera.view.x*this.scrollFactorX/this.scale.x,this._scrollY=this.game.camera.view.y*this.scrollFactorY/this.scale.y,this.render(),PIXI.Sprite.prototype._renderWebGL.call(this,t)},n.TilemapLayer.prototype.destroy=function(){PIXI.CanvasPool.remove(this),n.Component.Destroy.prototype.destroy.call(this)},n.TilemapLayer.prototype.resize=function(t,e){this.canvas.width=t,this.canvas.height=e,this.texture.frame.resize(t,e),this.texture.width=t,this.texture.height=e,this.texture.crop.width=t,this.texture.crop.height=e,this.texture.baseTexture.width=t,this.texture.baseTexture.height=e,this.texture.baseTexture.dirty(),this.texture.requiresUpdate=!0,this.texture._updateUvs(),this.dirty=!0},n.TilemapLayer.prototype.resizeWorld=function(){this.game.world.setBounds(0,0,this.layer.widthInPixels*this.scale.x,this.layer.heightInPixels*this.scale.y)},n.TilemapLayer.prototype._fixX=function(t){return 1===this.scrollFactorX||0===this.scrollFactorX&&0===this.position.x?t:0===this.scrollFactorX&&0!==this.position.x?t-this.position.x:this._scrollX+(t-this._scrollX/this.scrollFactorX)},n.TilemapLayer.prototype._unfixX=function(t){return 1===this.scrollFactorX?t:this._scrollX/this.scrollFactorX+(t-this._scrollX)},n.TilemapLayer.prototype._fixY=function(t){return 1===this.scrollFactorY||0===this.scrollFactorY&&0===this.position.y?t:0===this.scrollFactorY&&0!==this.position.y?t-this.position.y:this._scrollY+(t-this._scrollY/this.scrollFactorY)},n.TilemapLayer.prototype._unfixY=function(t){return 1===this.scrollFactorY?t:this._scrollY/this.scrollFactorY+(t-this._scrollY)},n.TilemapLayer.prototype.getTileX=function(t){return Math.floor(this._fixX(t)/this._mc.tileWidth)},n.TilemapLayer.prototype.getTileY=function(t){return Math.floor(this._fixY(t)/this._mc.tileHeight)},n.TilemapLayer.prototype.getTileXY=function(t,e,i){return i.x=this.getTileX(t),i.y=this.getTileY(e),i},n.TilemapLayer.prototype.getRayCastTiles=function(t,e,i,s){e||(e=this.rayStepRate),void 0===i&&(i=!1),void 0===s&&(s=!1);var n=this.getTiles(t.x,t.y,t.width,t.height,i,s);if(0===n.length)return[];for(var r=t.coordinatesOnLine(e),o=[],a=0;a<n.length;a++)for(var h=0;h<r.length;h++){var l=n[a],c=r[h];if(l.containsPoint(c[0],c[1])){o.push(l);break}}return o},n.TilemapLayer.prototype.getTiles=function(t,e,i,s,n,r){void 0===n&&(n=!1),void 0===r&&(r=!1);var o=!(n||r);t=this._fixX(t),e=this._fixY(e);for(var a=Math.floor(t/(this._mc.cw*this.scale.x)),h=Math.floor(e/(this._mc.ch*this.scale.y)),l=Math.ceil((t+i)/(this._mc.cw*this.scale.x))-a,c=Math.ceil((e+s)/(this._mc.ch*this.scale.y))-h;this._results.length;)this._results.pop();for(var u=h;u<h+c;u++)for(var d=a;d<a+l;d++){var p=this.layer.data[u];p&&p[d]&&(o||p[d].isInteresting(n,r))&&this._results.push(p[d])}return this._results.slice()},n.TilemapLayer.prototype.resolveTileset=function(t){var e=this._mc.tilesets;if(t<2e3)for(;e.length<t;)e.push(void 0);var i=this.map.tiles[t]&&this.map.tiles[t][2];if(null!==i){var s=this.map.tilesets[i];if(s&&s.containsTileIndex(t))return e[t]=s}return e[t]=null},n.TilemapLayer.prototype.resetTilesetCache=function(){for(var t=this._mc.tilesets;t.length;)t.pop()},n.TilemapLayer.prototype.setScale=function(t,e){t=t||1,e=e||t;for(var i=0;i<this.layer.data.length;i++)for(var s=this.layer.data[i],n=0;n<s.length;n++){var r=s[n];r.width=this.map.tileWidth*t,r.height=this.map.tileHeight*e,r.worldX=r.x*r.width,r.worldY=r.y*r.height}this.scale.setTo(t,e)},n.TilemapLayer.prototype.shiftCanvas=function(t,e,i){var s=t.canvas,n=s.width-Math.abs(e),r=s.height-Math.abs(i),o=0,a=0,h=e,l=i;e<0&&(o=-e,h=0),i<0&&(a=-i,l=0);var c=this.renderSettings.copyCanvas;if(c){(c.width<n||c.height<r)&&(c.width=n,c.height=r);var u=c.getContext("2d");u.clearRect(0,0,n,r),u.drawImage(s,o,a,n,r,0,0,n,r),t.clearRect(h,l,n,r),t.drawImage(c,0,0,n,r,h,l,n,r)}else t.save(),t.globalCompositeOperation="copy",t.drawImage(s,o,a,n,r,h,l,n,r),t.restore()},n.TilemapLayer.prototype.renderRegion=function(t,e,i,s,n,r){var o=this.context,a=this.layer.width,h=this.layer.height,l=this._mc.tileWidth,c=this._mc.tileHeight,u=this._mc.tilesets,d=NaN;this._wrap||(i<=n&&(i=Math.max(0,i),n=Math.min(a-1,n)),s<=r&&(s=Math.max(0,s),r=Math.min(h-1,r)));var p,f,g,m,y,v,b=i*l-t,x=s*c-e,w=(i+(1<<20)*a)%a,_=(s+(1<<20)*h)%h;for(m=_,v=r-s,f=x;v>=0;m++,v--,f+=c){m>=h&&(m-=h);var P=this.layer.data[m];for(g=w,y=n-i,p=b;y>=0;g++,y--,p+=l){g>=a&&(g-=a);var T=P[g];if(T&&!(T.index<0)){var C=T.index,S=u[C];void 0===S&&(S=this.resolveTileset(C)),T.alpha===d||this.debug||(o.globalAlpha=T.alpha,d=T.alpha),S?T.rotation||T.flipped?(o.save(),o.translate(p+T.centerX,f+T.centerY),o.rotate(T.rotation),T.flipped&&o.scale(-1,1),S.draw(o,-T.centerX,-T.centerY,C),o.restore()):S.draw(o,p,f,C):this.debugSettings.missingImageFill&&(o.fillStyle=this.debugSettings.missingImageFill,o.fillRect(p,f,l,c)),T.debug&&this.debugSettings.debuggedTileOverfill&&(o.fillStyle=this.debugSettings.debuggedTileOverfill,o.fillRect(p,f,l,c))}}}},n.TilemapLayer.prototype.renderDeltaScroll=function(t,e){var i=this._mc.scrollX,s=this._mc.scrollY,n=this.canvas.width,r=this.canvas.height,o=this._mc.tileWidth,a=this._mc.tileHeight,h=0,l=-o,c=0,u=-a;if(t<0?(h=n+t,l=n-1):t>0&&(l=t),e<0?(c=r+e,u=r-1):e>0&&(u=e),this.shiftCanvas(this.context,t,e),h=Math.floor((h+i)/o),l=Math.floor((l+i)/o),c=Math.floor((c+s)/a),u=Math.floor((u+s)/a),h<=l){this.context.clearRect(h*o-i,0,(l-h+1)*o,r);var d=Math.floor((0+s)/a),p=Math.floor((r-1+s)/a);this.renderRegion(i,s,h,d,l,p)}if(c<=u){this.context.clearRect(0,c*a-s,n,(u-c+1)*a);var f=Math.floor((0+i)/o),g=Math.floor((n-1+i)/o);this.renderRegion(i,s,f,c,g,u)}},n.TilemapLayer.prototype.renderFull=function(){var t=this._mc.scrollX,e=this._mc.scrollY,i=this.canvas.width,s=this.canvas.height,n=this._mc.tileWidth,r=this._mc.tileHeight,o=Math.floor(t/n),a=Math.floor((i-1+t)/n),h=Math.floor(e/r),l=Math.floor((s-1+e)/r);this.context.clearRect(0,0,i,s),this.renderRegion(t,e,o,h,a,l)},n.TilemapLayer.prototype.render=function(){var t=!1;if(this.visible){(this.dirty||this.layer.dirty)&&(this.layer.dirty=!1,t=!0);var e=this.canvas.width,i=this.canvas.height,s=0|this._scrollX,n=0|this._scrollY,r=this._mc,o=r.scrollX-s,a=r.scrollY-n;if(t||0!==o||0!==a||r.renderWidth!==e||r.renderHeight!==i)return this.context.save(),r.scrollX=s,r.scrollY=n,r.renderWidth===e&&r.renderHeight===i||(r.renderWidth=e,r.renderHeight=i),this.debug&&(this.context.globalAlpha=this.debugSettings.debugAlpha,this.debugSettings.forceFullRedraw&&(t=!0)),!t&&this.renderSettings.enableScrollDelta&&Math.abs(o)+Math.abs(a)<Math.min(e,i)?this.renderDeltaScroll(o,a):this.renderFull(),this.debug&&(this.context.globalAlpha=1,this.renderDebug()),this.texture.baseTexture.dirty(),this.dirty=!1,this.context.restore(),!0}},n.TilemapLayer.prototype.renderDebug=function(){var t,e,i,s,n,r,o=this._mc.scrollX,a=this._mc.scrollY,h=this.context,l=this.canvas.width,c=this.canvas.height,u=this.layer.width,d=this.layer.height,p=this._mc.tileWidth,f=this._mc.tileHeight,g=Math.floor(o/p),m=Math.floor((l-1+o)/p),y=Math.floor(a/f),v=Math.floor((c-1+a)/f),b=g*p-o,x=y*f-a,w=(g+(1<<20)*u)%u,_=(y+(1<<20)*d)%d;for(h.strokeStyle=this.debugSettings.facingEdgeStroke,s=_,r=v-y,e=x;r>=0;s++,r--,e+=f){s>=d&&(s-=d);var P=this.layer.data[s];for(i=w,n=m-g,t=b;n>=0;i++,n--,t+=p){i>=u&&(i-=u);var T=P[i];!T||T.index<0||!T.collides||(this.debugSettings.collidingTileOverfill&&(h.fillStyle=this.debugSettings.collidingTileOverfill,h.fillRect(t,e,this._mc.cw,this._mc.ch)),this.debugSettings.facingEdgeStroke&&(h.beginPath(),T.faceTop&&(h.moveTo(t,e),h.lineTo(t+this._mc.cw,e)),T.faceBottom&&(h.moveTo(t,e+this._mc.ch),h.lineTo(t+this._mc.cw,e+this._mc.ch)),T.faceLeft&&(h.moveTo(t,e),h.lineTo(t,e+this._mc.ch)),T.faceRight&&(h.moveTo(t+this._mc.cw,e),h.lineTo(t+this._mc.cw,e+this._mc.ch)),h.closePath(),h.stroke()))}}},Object.defineProperty(n.TilemapLayer.prototype,"wrap",{get:function(){return this._wrap},set:function(t){this._wrap=t,this.dirty=!0}}),Object.defineProperty(n.TilemapLayer.prototype,"scrollX",{get:function(){return this._scrollX},set:function(t){this._scrollX=t}}),Object.defineProperty(n.TilemapLayer.prototype,"scrollY",{get:function(){return this._scrollY},set:function(t){this._scrollY=t}}),Object.defineProperty(n.TilemapLayer.prototype,"collisionWidth",{get:function(){return this._mc.cw},set:function(t){this._mc.cw=0|t,this.dirty=!0}}),Object.defineProperty(n.TilemapLayer.prototype,"collisionHeight",{get:function(){return this._mc.ch},set:function(t){this._mc.ch=0|t,this.dirty=!0}}),n.TilemapParser={INSERT_NULL:!1,parse:function(t,e,i,s,r,o){if(void 0===i&&(i=32),void 0===s&&(s=32),void 0===r&&(r=10),void 0===o&&(o=10),void 0===e)return this.getEmptyData();if(null===e)return this.getEmptyData(i,s,r,o);var a=t.cache.getTilemapData(e);if(a){if(a.format===n.Tilemap.CSV)return this.parseCSV(e,a.data,i,s);if(!a.format||a.format===n.Tilemap.TILED_JSON)return this.parseTiledJSON(a.data)}else console.warn("Phaser.TilemapParser.parse - No map data found for key "+e)},parseCSV:function(t,e,i,s){var r=this.getEmptyData();e=e.trim();for(var o=[],a=e.split("\n"),h=a.length,l=0,c=0;c<a.length;c++){o[c]=[];for(var u=a[c].split(","),d=0;d<u.length;d++)o[c][d]=new n.Tile(r.layers[0],parseInt(u[d],10),d,c,i,s);0===l&&(l=u.length)}return r.format=n.Tilemap.CSV,r.name=t,r.width=l,r.height=h,r.tileWidth=i,r.tileHeight=s,r.widthInPixels=l*i,r.heightInPixels=h*s,r.layers[0].width=l,r.layers[0].height=h,r.layers[0].widthInPixels=r.widthInPixels,r.layers[0].heightInPixels=r.heightInPixels,r.layers[0].data=o,r},getEmptyData:function(t,e,i,s){return{width:void 0!==i&&null!==i?i:0,height:void 0!==s&&null!==s?s:0,tileWidth:void 0!==t&&null!==t?t:0,tileHeight:void 0!==e&&null!==e?e:0,orientation:"orthogonal",version:"1",properties:{},widthInPixels:0,heightInPixels:0,layers:[{name:"layer",x:0,y:0,width:0,height:0,widthInPixels:0,heightInPixels:0,alpha:1,visible:!0,properties:{},indexes:[],callbacks:[],bodies:[],data:[]}],images:[],objects:{},collision:{},tilesets:[],tiles:[]}},parseTiledJSON:function(t){function e(t,e){var i={};for(var s in e){var n=e[s];void 0!==t[n]&&(i[n]=t[n])}return i}if("orthogonal"!==t.orientation)return console.warn("TilemapParser.parseTiledJSON - Only orthogonal map types are supported in this version of Phaser"),null;for(var i={width:t.width,height:t.height,tileWidth:t.tilewidth,tileHeight:t.tileheight,orientation:t.orientation,format:n.Tilemap.TILED_JSON,version:t.version,properties:t.properties,widthInPixels:t.width*t.tilewidth,heightInPixels:t.height*t.tileheight},s=[],r=0;r<t.layers.length;r++)if("tilelayer"===t.layers[r].type){var o=t.layers[r];if(!o.compression&&o.encoding&&"base64"===o.encoding){for(var a=window.atob(o.data),h=a.length,l=new Array(h),c=0;c<h;c+=4)l[c/4]=(a.charCodeAt(c)|a.charCodeAt(c+1)<<8|a.charCodeAt(c+2)<<16|a.charCodeAt(c+3)<<24)>>>0;o.data=l,delete o.encoding}else if(o.compression){console.warn("TilemapParser.parseTiledJSON - Layer compression is unsupported, skipping layer '"+o.name+"'");continue}var u={name:o.name,x:o.x,y:o.y,width:o.width,height:o.height,widthInPixels:o.width*t.tilewidth,heightInPixels:o.height*t.tileheight,alpha:o.opacity,visible:o.visible,properties:{},indexes:[],callbacks:[],bodies:[]};o.properties&&(u.properties=o.properties);for(var d,p,f,g,m=0,y=[],v=[],b=0,h=o.data.length;b<h;b++){if(d=0,p=!1,g=o.data[b],f=0,g>536870912)switch(g>2147483648&&(g-=2147483648,f+=4),g>1073741824&&(g-=1073741824,f+=2),g>536870912&&(g-=536870912,f+=1),f){case 5:d=Math.PI/2;break;case 6:d=Math.PI;break;case 3:d=3*Math.PI/2;break;case 4:d=0,p=!0;break;case 7:d=Math.PI/2,p=!0;break;case 2:d=Math.PI,p=!0;break;case 1:d=3*Math.PI/2,p=!0}if(g>0){var x=new n.Tile(u,g,m,v.length,t.tilewidth,t.tileheight);x.rotation=d,x.flipped=p,0!==f&&(x.flippedVal=f),y.push(x)}else n.TilemapParser.INSERT_NULL?y.push(null):y.push(new n.Tile(u,-1,m,v.length,t.tilewidth,t.tileheight));m++,m===o.width&&(v.push(y),m=0,y=[])}u.data=v,s.push(u)}i.layers=s;for(var w=[],r=0;r<t.layers.length;r++)if("imagelayer"===t.layers[r].type){var _=t.layers[r],P={name:_.name,image:_.image,x:_.x,y:_.y,alpha:_.opacity,visible:_.visible,properties:{}};_.properties&&(P.properties=_.properties),w.push(P)}i.images=w;for(var T=[],C=[],S=null,r=0;r<t.tilesets.length;r++){var A=t.tilesets[r];if(A.image){var E=new n.Tileset(A.name,A.firstgid,A.tilewidth,A.tileheight,A.margin,A.spacing,A.properties);A.tileproperties&&(E.tileProperties=A.tileproperties),E.updateTileData(A.imagewidth,A.imageheight),T.push(E)}else{var I=new n.ImageCollection(A.name,A.firstgid,A.tilewidth,A.tileheight,A.margin,A.spacing,A.properties);for(var M in A.tiles){var P=A.tiles[M].image,g=A.firstgid+parseInt(M,10);I.addImage(g,P)}C.push(I)}S&&(S.lastgid=A.firstgid-1),S=A}i.tilesets=T,i.imagecollections=C;for(var R={},B={},r=0;r<t.layers.length;r++)if("objectgroup"===t.layers[r].type){var L=t.layers[r];R[L.name]=[],B[L.name]=[];for(var O=0,h=L.objects.length;O<h;O++)if(L.objects[O].gid){var k={gid:L.objects[O].gid,name:L.objects[O].name,type:L.objects[O].hasOwnProperty("type")?L.objects[O].type:"",x:L.objects[O].x,y:L.objects[O].y,visible:L.objects[O].visible,properties:L.objects[O].properties};L.objects[O].rotation&&(k.rotation=L.objects[O].rotation),R[L.name].push(k)}else if(L.objects[O].polyline){var k={name:L.objects[O].name,type:L.objects[O].type,x:L.objects[O].x,y:L.objects[O].y,width:L.objects[O].width,height:L.objects[O].height,visible:L.objects[O].visible,properties:L.objects[O].properties};L.objects[O].rotation&&(k.rotation=L.objects[O].rotation),k.polyline=[];for(var F=0;F<L.objects[O].polyline.length;F++)k.polyline.push([L.objects[O].polyline[F].x,L.objects[O].polyline[F].y]);B[L.name].push(k),R[L.name].push(k)}else if(L.objects[O].polygon){var k=e(L.objects[O],["name","type","x","y","visible","rotation","properties"]);k.polygon=[];for(var F=0;F<L.objects[O].polygon.length;F++)k.polygon.push([L.objects[O].polygon[F].x,L.objects[O].polygon[F].y]);R[L.name].push(k)}else if(L.objects[O].ellipse){var k=e(L.objects[O],["name","type","ellipse","x","y","width","height","visible","rotation","properties"]);R[L.name].push(k)}else{var k=e(L.objects[O],["name","type","x","y","width","height","visible","rotation","properties"]);k.rectangle=!0,R[L.name].push(k)}}i.objects=R,i.collision=B,i.tiles=[];for(var r=0;r<i.tilesets.length;r++)for(var A=i.tilesets[r],m=A.tileMargin,D=A.tileMargin,U=0,G=0,N=0,b=A.firstgid;b<A.firstgid+A.total&&(i.tiles[b]=[m,D,r],m+=A.tileWidth+A.tileSpacing,++U!==A.total)&&(++G!==A.columns||(m=A.tileMargin,D+=A.tileHeight+A.tileSpacing,G=0,++N!==A.rows));b++);for(var u,x,X,A,r=0;r<i.layers.length;r++){u=i.layers[r],A=null;for(var c=0;c<u.data.length;c++){y=u.data[c];for(var W=0;W<y.length;W++)null===(x=y[W])||x.index<0||(X=i.tiles[x.index][2],A=i.tilesets[X],A.tileProperties&&A.tileProperties[x.index-A.firstgid]&&(x.properties=n.Utils.mixin(A.tileProperties[x.index-A.firstgid],x.properties)))}}return i}},n.Tileset=function(t,e,i,s,n,r,o){(void 0===i||i<=0)&&(i=32),(void 0===s||s<=0)&&(s=32),void 0===n&&(n=0),void 0===r&&(r=0),this.name=t,this.firstgid=0|e,this.tileWidth=0|i,this.tileHeight=0|s,this.tileMargin=0|n,this.tileSpacing=0|r,this.properties=o||{},this.image=null,this.rows=0,this.columns=0,this.total=0,this.drawCoords=[]},n.Tileset.prototype={draw:function(t,e,i,s){var n=s-this.firstgid<<1;n>=0&&n+1<this.drawCoords.length&&t.drawImage(this.image,this.drawCoords[n],this.drawCoords[n+1],this.tileWidth,this.tileHeight,e,i,this.tileWidth,this.tileHeight)},containsTileIndex:function(t){return t>=this.firstgid&&t<this.firstgid+this.total},setImage:function(t){this.image=t,this.updateTileData(t.width,t.height)},setSpacing:function(t,e){this.tileMargin=0|t,this.tileSpacing=0|e,this.image&&this.updateTileData(this.image.width,this.image.height)},updateTileData:function(t,e){var i=(e-2*this.tileMargin+this.tileSpacing)/(this.tileHeight+this.tileSpacing),s=(t-2*this.tileMargin+this.tileSpacing)/(this.tileWidth+this.tileSpacing);i%1==0&&s%1==0||console.warn("Phaser.Tileset - "+this.name+" image tile area is not an even multiple of tile size"),i=Math.floor(i),s=Math.floor(s),(this.rows&&this.rows!==i||this.columns&&this.columns!==s)&&console.warn("Phaser.Tileset - actual and expected number of tile rows and columns differ"),this.rows=i,this.columns=s,this.total=i*s,this.drawCoords.length=0;for(var n=this.tileMargin,r=this.tileMargin,o=0;o<this.rows;o++){for(var a=0;a<this.columns;a++)this.drawCoords.push(n),this.drawCoords.push(r),n+=this.tileWidth+this.tileSpacing;n=this.tileMargin,r+=this.tileHeight+this.tileSpacing}}},n.Tileset.prototype.constructor=n.Tileset,n.Particle=function(t,e,i,s,r){n.Sprite.call(this,t,e,i,s,r),this.autoScale=!1,this.scaleData=null,this._s=0,this.autoAlpha=!1,this.alphaData=null,this._a=0},n.Particle.prototype=Object.create(n.Sprite.prototype),n.Particle.prototype.constructor=n.Particle,n.Particle.prototype.update=function(){this.autoScale&&(this._s--,this._s?this.scale.set(this.scaleData[this._s].x,this.scaleData[this._s].y):this.autoScale=!1),this.autoAlpha&&(this._a--,this._a?this.alpha=this.alphaData[this._a].v:this.autoAlpha=!1)},n.Particle.prototype.onEmit=function(){},n.Particle.prototype.setAlphaData=function(t){this.alphaData=t,this._a=t.length-1,this.alpha=this.alphaData[this._a].v,this.autoAlpha=!0},n.Particle.prototype.setScaleData=function(t){this.scaleData=t,this._s=t.length-1,this.scale.set(this.scaleData[this._s].x,this.scaleData[this._s].y),this.autoScale=!0},n.Particle.prototype.reset=function(t,e,i){return n.Component.Reset.prototype.reset.call(this,t,e,i),this.alpha=1,this.scale.set(1),this.autoScale=!1,this.autoAlpha=!1,this},n.Particles=function(t){this.game=t,this.emitters={},this.ID=0},n.Particles.prototype={add:function(t){return this.emitters[t.name]=t,t},remove:function(t){delete this.emitters[t.name]},update:function(){for(var t in this.emitters)this.emitters[t].exists&&this.emitters[t].update()}},n.Particles.prototype.constructor=n.Particles,n.Particles.Arcade={},n.Particles.Arcade.Emitter=function(t,e,i,s){this.maxParticles=s||50,n.Group.call(this,t),this.name="emitter"+this.game.particles.ID++,this.type=n.EMITTER,this.physicsType=n.GROUP,this.area=new n.Rectangle(e,i,1,1),this.minParticleSpeed=new n.Point(-100,-100),this.maxParticleSpeed=new n.Point(100,100),this.minParticleScale=1,this.maxParticleScale=1,this.scaleData=null,this.minRotation=-360,this.maxRotation=360,this.minParticleAlpha=1,this.maxParticleAlpha=1,this.alphaData=null,this.gravity=100,this.particleClass=n.Particle,this.particleDrag=new n.Point,this.angularDrag=0,this.frequency=100,this.lifespan=2e3,this.bounce=new n.Point,this.on=!1,this.particleAnchor=new n.Point(.5,.5),this.blendMode=n.blendModes.NORMAL,this.emitX=e,this.emitY=i,this.autoScale=!1,this.autoAlpha=!1,this.particleBringToTop=!1,this.particleSendToBack=!1,this._minParticleScale=new n.Point(1,1),this._maxParticleScale=new n.Point(1,1),this._quantity=0,this._timer=0,this._counter=0,this._flowQuantity=0,this._flowTotal=0,this._explode=!0,this._frames=null},n.Particles.Arcade.Emitter.prototype=Object.create(n.Group.prototype),n.Particles.Arcade.Emitter.prototype.constructor=n.Particles.Arcade.Emitter,n.Particles.Arcade.Emitter.prototype.update=function(){if(this.on&&this.game.time.time>=this._timer)if(this._timer=this.game.time.time+this.frequency*this.game.time.slowMotion,0!==this._flowTotal)if(this._flowQuantity>0){for(var t=0;t<this._flowQuantity;t++)if(this.emitParticle()&&(this._counter++,-1!==this._flowTotal&&this._counter>=this._flowTotal)){this.on=!1;break}}else this.emitParticle()&&(this._counter++,-1!==this._flowTotal&&this._counter>=this._flowTotal&&(this.on=!1));else this.emitParticle()&&(this._counter++,this._quantity>0&&this._counter>=this._quantity&&(this.on=!1));for(var t=this.children.length;t--;)this.children[t].exists&&this.children[t].update()},n.Particles.Arcade.Emitter.prototype.makeParticles=function(t,e,i,s,n){void 0===e&&(e=0),void 0===i&&(i=this.maxParticles),void 0===s&&(s=!1),void 0===n&&(n=!1);var r,o=0,a=t,h=e;for(this._frames=e,i>this.maxParticles&&(this.maxParticles=i);o<i;)Array.isArray(t)&&(a=this.game.rnd.pick(t)),Array.isArray(e)&&(h=this.game.rnd.pick(e)),r=new this.particleClass(this.game,0,0,a,h),this.game.physics.arcade.enable(r,!1),s?(r.body.checkCollision.any=!0,r.body.checkCollision.none=!1):r.body.checkCollision.none=!0,r.body.collideWorldBounds=n,r.body.skipQuadTree=!0,r.exists=!1,r.visible=!1,r.anchor.copyFrom(this.particleAnchor),this.add(r),o++;return this},n.Particles.Arcade.Emitter.prototype.kill=function(){return this.on=!1,this.alive=!1,this.exists=!1,this},n.Particles.Arcade.Emitter.prototype.revive=function(){return this.alive=!0,this.exists=!0,this},n.Particles.Arcade.Emitter.prototype.explode=function(t,e){return this._flowTotal=0,this.start(!0,t,0,e,!1),this},n.Particles.Arcade.Emitter.prototype.flow=function(t,e,i,s,n){return void 0!==i&&0!==i||(i=1),void 0===s&&(s=-1),void 0===n&&(n=!0),i>this.maxParticles&&(i=this.maxParticles),this._counter=0,this._flowQuantity=i,this._flowTotal=s,n?(this.start(!0,t,e,i),this._counter+=i,this.on=!0,this._timer=this.game.time.time+e*this.game.time.slowMotion):this.start(!1,t,e,i),this},n.Particles.Arcade.Emitter.prototype.start=function(t,e,i,s,n){if(void 0===t&&(t=!0),void 0===e&&(e=0),void 0!==i&&null!==i||(i=250),void 0===s&&(s=0),void 0===n&&(n=!1),s>this.maxParticles&&(s=this.maxParticles),this.revive(),this.visible=!0,this.lifespan=e,this.frequency=i,t||n)for(var r=0;r<s;r++)this.emitParticle();else this.on=!0,this._quantity=s,this._counter=0,this._timer=this.game.time.time+i*this.game.time.slowMotion;return this},n.Particles.Arcade.Emitter.prototype.emitParticle=function(t,e,i,s){void 0===t&&(t=null),void 0===e&&(e=null);var n=this.getFirstExists(!1);if(null===n)return!1;var r=this.game.rnd;void 0!==i&&void 0!==s?n.loadTexture(i,s):void 0!==i&&n.loadTexture(i);var o=this.emitX,a=this.emitY;null!==t?o=t:this.width>1&&(o=r.between(this.left,this.right)),null!==e?a=e:this.height>1&&(a=r.between(this.top,this.bottom)),n.reset(o,a),n.angle=0,n.lifespan=this.lifespan,this.particleBringToTop?this.bringToTop(n):this.particleSendToBack&&this.sendToBack(n),this.autoScale?n.setScaleData(this.scaleData):1!==this.minParticleScale||1!==this.maxParticleScale?n.scale.set(r.realInRange(this.minParticleScale,this.maxParticleScale)):this._minParticleScale.x===this._maxParticleScale.x&&this._minParticleScale.y===this._maxParticleScale.y||n.scale.set(r.realInRange(this._minParticleScale.x,this._maxParticleScale.x),r.realInRange(this._minParticleScale.y,this._maxParticleScale.y)),void 0===s&&(Array.isArray(this._frames)?n.frame=this.game.rnd.pick(this._frames):n.frame=this._frames),this.autoAlpha?n.setAlphaData(this.alphaData):n.alpha=r.realInRange(this.minParticleAlpha,this.maxParticleAlpha),n.blendMode=this.blendMode;var h=n.body;return h.updateBounds(),h.bounce.copyFrom(this.bounce),h.drag.copyFrom(this.particleDrag),h.velocity.x=r.between(this.minParticleSpeed.x,this.maxParticleSpeed.x),h.velocity.y=r.between(this.minParticleSpeed.y,this.maxParticleSpeed.y),h.angularVelocity=r.between(this.minRotation,this.maxRotation),h.gravity.y=this.gravity,h.angularDrag=this.angularDrag,n.onEmit(),!0},n.Particles.Arcade.Emitter.prototype.destroy=function(){this.game.particles.remove(this),n.Group.prototype.destroy.call(this,!0,!1)},n.Particles.Arcade.Emitter.prototype.setSize=function(t,e){return this.area.width=t,this.area.height=e,this},n.Particles.Arcade.Emitter.prototype.setXSpeed=function(t,e){return t=t||0,e=e||0,this.minParticleSpeed.x=t,this.maxParticleSpeed.x=e,this},n.Particles.Arcade.Emitter.prototype.setYSpeed=function(t,e){return t=t||0,e=e||0,this.minParticleSpeed.y=t,this.maxParticleSpeed.y=e,this},n.Particles.Arcade.Emitter.prototype.setRotation=function(t,e){return t=t||0,e=e||0,this.minRotation=t,this.maxRotation=e,this},n.Particles.Arcade.Emitter.prototype.setAlpha=function(t,e,i,s,r){if(void 0===t&&(t=1),void 0===e&&(e=1),void 0===i&&(i=0),void 0===s&&(s=n.Easing.Linear.None),void 0===r&&(r=!1),this.minParticleAlpha=t,this.maxParticleAlpha=e,this.autoAlpha=!1,i>0&&t!==e){var o={v:t},a=this.game.make.tween(o).to({v:e},i,s);a.yoyo(r),this.alphaData=a.generateData(60),this.alphaData.reverse(),this.autoAlpha=!0}return this},n.Particles.Arcade.Emitter.prototype.setScale=function(t,e,i,s,r,o,a){if(void 0===t&&(t=1),void 0===e&&(e=1),void 0===i&&(i=1),void 0===s&&(s=1),void 0===r&&(r=0),void 0===o&&(o=n.Easing.Linear.None),void 0===a&&(a=!1),this.minParticleScale=1,this.maxParticleScale=1,this._minParticleScale.set(t,i),this._maxParticleScale.set(e,s),this.autoScale=!1,r>0&&(t!==e||i!==s)){var h={x:t,y:i},l=this.game.make.tween(h).to({x:e,y:s},r,o);l.yoyo(a),this.scaleData=l.generateData(60),this.scaleData.reverse(),this.autoScale=!0}return this},n.Particles.Arcade.Emitter.prototype.at=function(t){return t.center?(this.emitX=t.center.x,this.emitY=t.center.y):(this.emitX=t.world.x+t.anchor.x*t.width,this.emitY=t.world.y+t.anchor.y*t.height),this},Object.defineProperty(n.Particles.Arcade.Emitter.prototype,"width",{get:function(){return this.area.width},set:function(t){this.area.width=t}}),Object.defineProperty(n.Particles.Arcade.Emitter.prototype,"height",{get:function(){return this.area.height},set:function(t){this.area.height=t}}),Object.defineProperty(n.Particles.Arcade.Emitter.prototype,"x",{get:function(){return this.emitX},set:function(t){this.emitX=t}}),Object.defineProperty(n.Particles.Arcade.Emitter.prototype,"y",{get:function(){return this.emitY},set:function(t){this.emitY=t}}),Object.defineProperty(n.Particles.Arcade.Emitter.prototype,"left",{get:function(){return Math.floor(this.x-this.area.width/2)}}),Object.defineProperty(n.Particles.Arcade.Emitter.prototype,"right",{get:function(){return Math.floor(this.x+this.area.width/2)}}),Object.defineProperty(n.Particles.Arcade.Emitter.prototype,"top",{get:function(){return Math.floor(this.y-this.area.height/2)}}),Object.defineProperty(n.Particles.Arcade.Emitter.prototype,"bottom",{get:function(){return Math.floor(this.y+this.area.height/2)}}),n.Weapon=function(t,e){n.Plugin.call(this,t,e),this.bullets=null,this.autoExpandBulletsGroup=!1,this.autofire=!1,this.shots=0,this.fireLimit=0,this.fireRate=100,this.fireRateVariance=0,this.fireFrom=new n.Rectangle(0,0,1,1),this.fireAngle=n.ANGLE_UP,this.bulletInheritSpriteSpeed=!1,this.bulletAnimation="",this.bulletFrameRandom=!1,this.bulletFrameCycle=!1,this.bulletWorldWrap=!1,this.bulletWorldWrapPadding=0,this.bulletAngleOffset=0,this.bulletAngleVariance=0,this.bulletSpeed=200,this.bulletSpeedVariance=0,this.bulletLifespan=0,this.bulletKillDistance=0,this.bulletGravity=new n.Point(0,0),this.bulletRotateToVelocity=!1,this.bulletKey="",this.bulletFrame="",this._bulletClass=n.Bullet,this._bulletCollideWorldBounds=!1,this._bulletKillType=n.Weapon.KILL_WORLD_BOUNDS,this._data={customBody:!1,width:0,height:0,offsetX:0,offsetY:0},this.bounds=new n.Rectangle,this.bulletBounds=t.world.bounds,this.bulletFrames=[],this.bulletFrameIndex=0,this.anims={},this.onFire=new n.Signal,this.onKill=new n.Signal,this.onFireLimit=new n.Signal,this.trackedSprite=null,this.trackedPointer=null,this.trackRotation=!1,this.trackOffset=new n.Point,this._nextFire=0,this._rotatedPoint=new n.Point},n.Weapon.prototype=Object.create(n.Plugin.prototype),n.Weapon.prototype.constructor=n.Weapon,n.Weapon.KILL_NEVER=0,n.Weapon.KILL_LIFESPAN=1,n.Weapon.KILL_DISTANCE=2,n.Weapon.KILL_WEAPON_BOUNDS=3,n.Weapon.KILL_CAMERA_BOUNDS=4,n.Weapon.KILL_WORLD_BOUNDS=5,n.Weapon.KILL_STATIC_BOUNDS=6,n.Weapon.prototype.createBullets=function(t,e,i,s){return void 0===t&&(t=1),void 0===s&&(s=this.game.world),this.bullets||(this.bullets=this.game.add.physicsGroup(n.Physics.ARCADE,s),this.bullets.classType=this._bulletClass),0!==t&&(-1===t&&(this.autoExpandBulletsGroup=!0,t=1),this.bullets.createMultiple(t,e,i),this.bullets.setAll("data.bulletManager",this),this.bulletKey=e,this.bulletFrame=i),this},n.Weapon.prototype.forEach=function(t,e){return this.bullets.forEachExists(t,e,arguments),this},n.Weapon.prototype.pauseAll=function(){return this.bullets.setAll("body.enable",!1),this},n.Weapon.prototype.resumeAll=function(){return this.bullets.setAll("body.enable",!0),this},n.Weapon.prototype.killAll=function(){return this.bullets.callAllExists("kill",!0),this.bullets.setAll("body.enable",!0),this},n.Weapon.prototype.resetShots=function(t){return this.shots=0,void 0!==t&&(this.fireLimit=t),this},n.Weapon.prototype.destroy=function(){this.parent.remove(this,!1),this.bullets.destroy(),this.game=null,this.parent=null,this.active=!1,this.visible=!1},n.Weapon.prototype.update=function(){this._bulletKillType===n.Weapon.KILL_WEAPON_BOUNDS&&(this.trackedSprite?(this.trackedSprite.updateTransform(),this.bounds.centerOn(this.trackedSprite.worldPosition.x,this.trackedSprite.worldPosition.y)):this.trackedPointer&&this.bounds.centerOn(this.trackedPointer.worldX,this.trackedPointer.worldY)),this.autofire&&this.fire()},n.Weapon.prototype.trackSprite=function(t,e,i,s){return void 0===e&&(e=0),void 0===i&&(i=0),void 0===s&&(s=!1),this.trackedPointer=null,this.trackedSprite=t,this.trackRotation=s,this.trackOffset.set(e,i),this},n.Weapon.prototype.trackPointer=function(t,e,i){return void 0===t&&(t=this.game.input.activePointer),void 0===e&&(e=0),void 0===i&&(i=0),this.trackedPointer=t,this.trackedSprite=null,this.trackRotation=!1,this.trackOffset.set(e,i),this},n.Weapon.prototype.fire=function(t,e,i){if(this.game.time.now<this._nextFire||this.fireLimit>0&&this.shots===this.fireLimit)return!1;var s=this.bulletSpeed;0!==this.bulletSpeedVariance&&(s+=n.Math.between(-this.bulletSpeedVariance,this.bulletSpeedVariance)),t?this.fireFrom.width>1?this.fireFrom.centerOn(t.x,t.y):(this.fireFrom.x=t.x,this.fireFrom.y=t.y):this.trackedSprite?(this.trackRotation?(this._rotatedPoint.set(this.trackedSprite.world.x+this.trackOffset.x,this.trackedSprite.world.y+this.trackOffset.y),this._rotatedPoint.rotate(this.trackedSprite.world.x,this.trackedSprite.world.y,this.trackedSprite.rotation),this.fireFrom.width>1?this.fireFrom.centerOn(this._rotatedPoint.x,this._rotatedPoint.y):(this.fireFrom.x=this._rotatedPoint.x,this.fireFrom.y=this._rotatedPoint.y)):this.fireFrom.width>1?this.fireFrom.centerOn(this.trackedSprite.world.x+this.trackOffset.x,this.trackedSprite.world.y+this.trackOffset.y):(this.fireFrom.x=this.trackedSprite.world.x+this.trackOffset.x,this.fireFrom.y=this.trackedSprite.world.y+this.trackOffset.y),this.bulletInheritSpriteSpeed&&(s+=this.trackedSprite.body.speed)):this.trackedPointer&&(this.fireFrom.width>1?this.fireFrom.centerOn(this.trackedPointer.world.x+this.trackOffset.x,this.trackedPointer.world.y+this.trackOffset.y):(this.fireFrom.x=this.trackedPointer.world.x+this.trackOffset.x,this.fireFrom.y=this.trackedPointer.world.y+this.trackOffset.y));var r=this.fireFrom.width>1?this.fireFrom.randomX:this.fireFrom.x,o=this.fireFrom.height>1?this.fireFrom.randomY:this.fireFrom.y,a=this.trackRotation?this.trackedSprite.angle:this.fireAngle;void 0!==e&&void 0!==i&&(a=this.game.math.radToDeg(Math.atan2(i-o,e-r))),0!==this.bulletAngleVariance&&(a+=n.Math.between(-this.bulletAngleVariance,this.bulletAngleVariance));var h=0,l=0;0===a||180===a?h=Math.cos(this.game.math.degToRad(a))*s:90===a||270===a?l=Math.sin(this.game.math.degToRad(a))*s:(h=Math.cos(this.game.math.degToRad(a))*s,l=Math.sin(this.game.math.degToRad(a))*s);var c=null;if(this.autoExpandBulletsGroup?(c=this.bullets.getFirstExists(!1,!0,r,o,this.bulletKey,this.bulletFrame),c.data.bulletManager=this):c=this.bullets.getFirstExists(!1),c){if(c.reset(r,o),c.data.fromX=r,c.data.fromY=o,c.data.killType=this.bulletKillType,c.data.killDistance=this.bulletKillDistance,c.data.rotateToVelocity=this.bulletRotateToVelocity,this.bulletKillType===n.Weapon.KILL_LIFESPAN&&(c.lifespan=this.bulletLifespan),c.angle=a+this.bulletAngleOffset,""!==this.bulletAnimation){if(null===c.animations.getAnimation(this.bulletAnimation)){var u=this.anims[this.bulletAnimation];c.animations.add(u.name,u.frames,u.frameRate,u.loop,u.useNumericIndex)}c.animations.play(this.bulletAnimation)}else this.bulletFrameCycle?(c.frame=this.bulletFrames[this.bulletFrameIndex],++this.bulletFrameIndex>=this.bulletFrames.length&&(this.bulletFrameIndex=0)):this.bulletFrameRandom&&(c.frame=this.bulletFrames[Math.floor(Math.random()*this.bulletFrames.length)]);if(c.data.bodyDirty&&(this._data.customBody&&c.body.setSize(this._data.width,this._data.height,this._data.offsetX,this._data.offsetY),c.body.collideWorldBounds=this.bulletCollideWorldBounds,c.data.bodyDirty=!1),c.body.velocity.set(h,l),c.body.gravity.set(this.bulletGravity.x,this.bulletGravity.y),0!==this.bulletSpeedVariance){var d=this.fireRate;d+=n.Math.between(-this.fireRateVariance,this.fireRateVariance),d<0&&(d=0),this._nextFire=this.game.time.now+d}else this._nextFire=this.game.time.now+this.fireRate;this.shots++,this.onFire.dispatch(c,this,s),this.fireLimit>0&&this.shots===this.fireLimit&&this.onFireLimit.dispatch(this,this.fireLimit)}return c},n.Weapon.prototype.fireAtPointer=function(t){return void 0===t&&(t=this.game.input.activePointer),this.fire(null,t.worldX,t.worldY)},n.Weapon.prototype.fireAtSprite=function(t){return this.fire(null,t.world.x,t.world.y)},n.Weapon.prototype.fireAtXY=function(t,e){return this.fire(null,t,e)},n.Weapon.prototype.setBulletBodyOffset=function(t,e,i,s){return void 0===i&&(i=0),void 0===s&&(s=0),this._data.customBody=!0,this._data.width=t,this._data.height=e,this._data.offsetX=i,this._data.offsetY=s,this.bullets.callAll("body.setSize","body",t,e,i,s),this.bullets.setAll("data.bodyDirty",!1),this},n.Weapon.prototype.setBulletFrames=function(t,e,i,s){return void 0===i&&(i=!0),void 0===s&&(s=!1),this.bulletFrames=n.ArrayUtils.numberArray(t,e),this.bulletFrameIndex=0,this.bulletFrameCycle=i,this.bulletFrameRandom=s,this},n.Weapon.prototype.addBulletAnimation=function(t,e,i,s,n){return this.anims[t]={name:t,frames:e,frameRate:i,loop:s,useNumericIndex:n},this.bullets.callAll("animations.add","animations",t,e,i,s,n),this.bulletAnimation=t,this},n.Weapon.prototype.debug=function(t,e,i){void 0===t&&(t=16),void 0===e&&(e=32),void 0===i&&(i=!1),this.game.debug.text("Weapon Plugin",t,e),this.game.debug.text("Bullets Alive: "+this.bullets.total+" - Total: "+this.bullets.length,t,e+24),i&&this.bullets.forEachExists(this.game.debug.body,this.game.debug,"rgba(255, 0, 255, 0.8)")},Object.defineProperty(n.Weapon.prototype,"bulletClass",{get:function(){return this._bulletClass},set:function(t){this._bulletClass=t,this.bullets.classType=this._bulletClass}}),Object.defineProperty(n.Weapon.prototype,"bulletKillType",{get:function(){return this._bulletKillType},set:function(t){switch(t){case n.Weapon.KILL_STATIC_BOUNDS:case n.Weapon.KILL_WEAPON_BOUNDS:this.bulletBounds=this.bounds;break;case n.Weapon.KILL_CAMERA_BOUNDS:this.bulletBounds=this.game.camera.view;break;case n.Weapon.KILL_WORLD_BOUNDS:this.bulletBounds=this.game.world.bounds}this._bulletKillType=t}}),Object.defineProperty(n.Weapon.prototype,"bulletCollideWorldBounds",{get:function(){return this._bulletCollideWorldBounds},set:function(t){this._bulletCollideWorldBounds=t,this.bullets.setAll("body.collideWorldBounds",t),this.bullets.setAll("data.bodyDirty",!1)}}),Object.defineProperty(n.Weapon.prototype,"x",{get:function(){return this.fireFrom.x},set:function(t){this.fireFrom.x=t}}),Object.defineProperty(n.Weapon.prototype,"y",{get:function(){return this.fireFrom.y},set:function(t){this.fireFrom.y=t}}),n.Bullet=function(t,e,i,s,r){n.Sprite.call(this,t,e,i,s,r),this.anchor.set(.5),this.data={bulletManager:null,fromX:0,fromY:0,bodyDirty:!0,rotateToVelocity:!1,killType:0,killDistance:0}},n.Bullet.prototype=Object.create(n.Sprite.prototype),n.Bullet.prototype.constructor=n.Bullet,n.Bullet.prototype.kill=function(){return this.alive=!1,this.exists=!1,this.visible=!1,this.data.bulletManager.onKill.dispatch(this),this},n.Bullet.prototype.update=function(){this.exists&&(this.data.killType>n.Weapon.KILL_LIFESPAN&&(this.data.killType===n.Weapon.KILL_DISTANCE?this.game.physics.arcade.distanceToXY(this,this.data.fromX,this.data.fromY,!0)>this.data.killDistance&&this.kill():this.data.bulletManager.bulletBounds.intersects(this)||this.kill()),this.data.rotateToVelocity&&(this.rotation=Math.atan2(this.body.velocity.y,this.body.velocity.x)),this.data.bulletManager.bulletWorldWrap&&this.game.world.wrap(this,this.data.bulletManager.bulletWorldWrapPadding))},n.Video=function(t,e,i){if(void 0===e&&(e=null),void 0===i&&(i=null),this.game=t,this.key=e,this.width=0,this.height=0,this.type=n.VIDEO,this.disableTextureUpload=!1,this.touchLocked=!1,this.onPlay=new n.Signal,this.onChangeSource=new n.Signal,this.onComplete=new n.Signal,this.onAccess=new n.Signal,this.onError=new n.Signal,this.onTimeout=new n.Signal,this.timeout=15e3,this._timeOutID=null,this.video=null,this.videoStream=null,this.isStreaming=!1,this.retryLimit=20,this.retry=0,this.retryInterval=500,this._retryID=null,this._codeMuted=!1,this._muted=!1,this._codePaused=!1,this._paused=!1,this._pending=!1,this._autoplay=!1,this._endCallback=null,this._playCallback=null,e&&this.game.cache.checkVideoKey(e)){var s=this.game.cache.getVideo(e);s.isBlob?this.createVideoFromBlob(s.data):this.video=s.data,this.width=this.video.videoWidth,this.height=this.video.videoHeight}else i&&this.createVideoFromURL(i,!1);this.video&&!i?(this.baseTexture=new PIXI.BaseTexture(this.video),this.baseTexture.forceLoaded(this.width,this.height)):(this.baseTexture=new PIXI.BaseTexture(n.Cache.DEFAULT.baseTexture.source),this.baseTexture.forceLoaded(this.width,this.height)),this.texture=new PIXI.Texture(this.baseTexture),this.textureFrame=new n.Frame(0,0,0,this.width,this.height,"video"),this.texture.setFrame(this.textureFrame),this.texture.valid=!1,null!==e&&this.video&&(this.texture.valid=this.video.canplay),this.snapshot=null,n.BitmapData&&(this.snapshot=new n.BitmapData(this.game,"",this.width,this.height)),!this.game.device.cocoonJS&&(this.game.device.iOS||this.game.device.android)||window.PhaserGlobal&&window.PhaserGlobal.fakeiOSTouchLock?this.setTouchLock():s&&(s.locked=!1)},n.Video.prototype={connectToMediaStream:function(t,e){return t&&e&&(this.video=t,this.videoStream=e,this.isStreaming=!0,this.baseTexture.source=this.video,this.updateTexture(null,this.video.videoWidth,this.video.videoHeight),this.onAccess.dispatch(this)),this},startMediaStream:function(t,e,i){if(void 0===t&&(t=!1),void 0===e&&(e=null),void 0===i&&(i=null),!this.game.device.getUserMedia)return this.onError.dispatch(this,"No getUserMedia"),!1;null!==this.videoStream&&(this.videoStream.active?this.videoStream.active=!1:this.videoStream.stop()),this.removeVideoElement(),this.video=document.createElement("video"),this.video.setAttribute("autoplay","autoplay"),null!==e&&(this.video.width=e),null!==i&&(this.video.height=i),this._timeOutID=window.setTimeout(this.getUserMediaTimeout.bind(this),this.timeout);try{navigator.getUserMedia({audio:t,video:!0},this.getUserMediaSuccess.bind(this),this.getUserMediaError.bind(this))}catch(t){this.getUserMediaError(t)}return this},getUserMediaTimeout:function(){clearTimeout(this._timeOutID),this.onTimeout.dispatch(this)},getUserMediaError:function(t){clearTimeout(this._timeOutID),this.onError.dispatch(this,t)},getUserMediaSuccess:function(t){clearTimeout(this._timeOutID),this.videoStream=t,void 0!==this.video.mozSrcObject?this.video.mozSrcObject=t:this.video.src=window.URL&&window.URL.createObjectURL(t)||t;var e=this;this.video.onloadeddata=function(){function t(){if(i>0)if(e.video.videoWidth>0){var s=e.video.videoWidth,n=e.video.videoHeight;isNaN(e.video.videoHeight)&&(n=s/(4/3)),e.video.play(),e.isStreaming=!0,e.baseTexture.source=e.video,e.updateTexture(null,s,n),e.onAccess.dispatch(e)}else window.setTimeout(t,500);else console.warn("Unable to connect to video stream. Webcam error?");i--}var i=10;t()}},createVideoFromBlob:function(t){var e=this;return this.video=document.createElement("video"),this.video.controls=!1,this.video.setAttribute("autoplay","autoplay"),this.video.addEventListener("loadeddata",function(t){e.updateTexture(t)},!0),this.video.src=window.URL.createObjectURL(t),this.video.canplay=!0,this},createVideoFromURL:function(t,e){return void 0===e&&(e=!1),this.texture&&(this.texture.valid=!1),this.video=document.createElement("video"),this.video.controls=!1,e&&this.video.setAttribute("autoplay","autoplay"),this.video.src=t,this.video.canplay=!0,this.video.load(),this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval),this.key=t,this},updateTexture:function(t,e,i){var s=!1;void 0!==e&&null!==e||(e=this.video.videoWidth,s=!0),void 0!==i&&null!==i||(i=this.video.videoHeight),this.width=e,this.height=i,this.baseTexture.source!==this.video&&(this.baseTexture.source=this.video),this.baseTexture.forceLoaded(e,i),this.texture.frame.resize(e,i),this.texture.width=e,this.texture.height=i,this.texture.valid=!0,this.snapshot&&this.snapshot.resize(e,i),s&&null!==this.key&&(this.onChangeSource.dispatch(this,e,i),this._autoplay&&(this.video.play(),this.onPlay.dispatch(this,this.loop,this.playbackRate)))},complete:function(){this.onComplete.dispatch(this)},play:function(t,e){return void 0===t&&(t=!1),void 0===e&&(e=1),this.game.sound.onMute&&(this.game.sound.onMute.add(this.setMute,this),this.game.sound.onUnMute.add(this.unsetMute,this),this.game.sound.mute&&this.setMute()),this.game.onPause.add(this.setPause,this),this.game.onResume.add(this.setResume,this),this._endCallback=this.complete.bind(this),this.video.addEventListener("ended",this._endCallback,!0),this.video.addEventListener("webkitendfullscreen",this._endCallback,!0),this.video.loop=t?"loop":"",this.video.playbackRate=e,this.touchLocked?this._pending=!0:(this._pending=!1,null!==this.key&&(4!==this.video.readyState?(this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval)):(this._playCallback=this.playHandler.bind(this),this.video.addEventListener("playing",this._playCallback,!0))),this.video.play(),this.onPlay.dispatch(this,t,e)),this},playHandler:function(){this.video.removeEventListener("playing",this._playCallback,!0),this.updateTexture()},stop:function(){return this.game.sound.onMute&&(this.game.sound.onMute.remove(this.setMute,this),this.game.sound.onUnMute.remove(this.unsetMute,this)),this.game.onPause.remove(this.setPause,this),this.game.onResume.remove(this.setResume,this),this.isStreaming?(this.video.mozSrcObject?(this.video.mozSrcObject.stop(),this.video.src=null):(this.video.src="",this.videoStream.active?this.videoStream.active=!1:this.videoStream.getTracks?this.videoStream.getTracks().forEach(function(t){t.stop()}):this.videoStream.stop()),this.videoStream=null,this.isStreaming=!1):(this.video.removeEventListener("ended",this._endCallback,!0),this.video.removeEventListener("webkitendfullscreen",this._endCallback,!0),this.video.removeEventListener("playing",this._playCallback,!0),this.touchLocked?this._pending=!1:this.video.pause()),this},add:function(t){if(Array.isArray(t))for(var e=0;e<t.length;e++)t[e].loadTexture&&t[e].loadTexture(this);else t.loadTexture(this);return this},addToWorld:function(t,e,i,s,n,r){n=n||1,r=r||1;var o=this.game.add.image(t,e,this);return o.anchor.set(i,s),o.scale.set(n,r),o},render:function(){!this.disableTextureUpload&&this.playing&&this.baseTexture.dirty()},setMute:function(){this._muted||(this._muted=!0,this.video.muted=!0)},unsetMute:function(){this._muted&&!this._codeMuted&&(this._muted=!1,this.video.muted=!1)},setPause:function(){this._paused||this.touchLocked||(this._paused=!0,this.video.pause())},setResume:function(){!this._paused||this._codePaused||this.touchLocked||(this._paused=!1,this.video.ended||this.video.play())},changeSource:function(t,e){return void 0===e&&(e=!0),this.texture.valid=!1,this.video.pause(),this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval),this.video.src=t,this.video.load(),this._autoplay=e,e||(this.paused=!0),this},checkVideoProgress:function(){4===this.video.readyState?this.updateTexture():(this.retry--,this.retry>0?this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval):console.warn("Phaser.Video: Unable to start downloading video in time",this.isStreaming))},setTouchLock:function(){this.game.input.touch.addTouchLockCallback(this.unlock,this),this.touchLocked=!0},unlock:function(){if(this.touchLocked=!1,this.video.play(),this.onPlay.dispatch(this,this.loop,this.playbackRate),this.key){var t=this.game.cache.getVideo(this.key);t&&!t.isBlob&&(t.locked=!1)}return!0},grab:function(t,e,i){return void 0===t&&(t=!1),void 0===e&&(e=1),void 0===i&&(i=null),null===this.snapshot?void console.warn("Video.grab cannot run because Phaser.BitmapData is unavailable"):(t&&this.snapshot.cls(),this.snapshot.copy(this.video,0,0,this.width,this.height,0,0,this.width,this.height,0,0,0,1,1,e,i),this.snapshot)},removeVideoElement:function(){if(this.video){for(this.video.parentNode&&this.video.parentNode.removeChild(this.video);this.video.hasChildNodes();)this.video.removeChild(this.video.firstChild);this.video.removeAttribute("autoplay"),this.video.removeAttribute("src"),this.video=null}},destroy:function(){this.stop(),this.removeVideoElement(),this.touchLocked&&this.game.input.touch.removeTouchLockCallback(this.unlock,this),this._retryID&&window.clearTimeout(this._retryID)}},Object.defineProperty(n.Video.prototype,"currentTime",{get:function(){return this.video?this.video.currentTime:0},set:function(t){this.video.currentTime=t}}),Object.defineProperty(n.Video.prototype,"duration",{get:function(){return this.video?this.video.duration:0}}),Object.defineProperty(n.Video.prototype,"progress",{get:function(){return this.video?this.video.currentTime/this.video.duration:0}}),Object.defineProperty(n.Video.prototype,"mute",{get:function(){return this._muted},set:function(t){if(t=t||null){if(this._muted)return;this._codeMuted=!0,this.setMute()}else{if(!this._muted)return;this._codeMuted=!1,this.unsetMute()}}}),Object.defineProperty(n.Video.prototype,"paused",{get:function(){return this._paused},set:function(t){if(t=t||null,!this.touchLocked)if(t){if(this._paused)return;this._codePaused=!0,this.setPause()}else{if(!this._paused)return;this._codePaused=!1,this.setResume()}}}),Object.defineProperty(n.Video.prototype,"volume",{get:function(){return this.video?this.video.volume:1},set:function(t){t<0?t=0:t>1&&(t=1),this.video&&(this.video.volume=t)}}),Object.defineProperty(n.Video.prototype,"playbackRate",{get:function(){return this.video?this.video.playbackRate:1},set:function(t){this.video&&(this.video.playbackRate=t)}}),Object.defineProperty(n.Video.prototype,"loop",{get:function(){return!!this.video&&this.video.loop},set:function(t){t&&this.video?this.video.loop="loop":this.video&&(this.video.loop="")}}),Object.defineProperty(n.Video.prototype,"playing",{get:function(){return!(this.video.paused&&this.video.ended)}}),n.Video.prototype.constructor=n.Video,void 0===PIXI.blendModes&&(PIXI.blendModes=n.blendModes),void 0===PIXI.scaleModes&&(PIXI.scaleModes=n.scaleModes),void 0===PIXI.Texture.emptyTexture&&(PIXI.Texture.emptyTexture=new PIXI.Texture(new PIXI.BaseTexture)),void 0===PIXI.DisplayObject._tempMatrix&&(PIXI.DisplayObject._tempMatrix=new PIXI.Matrix),void 0===PIXI.RenderTexture.tempMatrix&&(PIXI.RenderTexture.tempMatrix=new PIXI.Matrix),PIXI.Graphics&&void 0===PIXI.Graphics.POLY&&(PIXI.Graphics.POLY=n.POLYGON,PIXI.Graphics.RECT=n.RECTANGLE,PIXI.Graphics.CIRC=n.CIRCLE,PIXI.Graphics.ELIP=n.ELLIPSE,PIXI.Graphics.RREC=n.ROUNDEDRECTANGLE),PIXI.TextureSilentFail=!0,void 0!==t&&t.exports&&(e=t.exports=n),e.Phaser=n,n}).call(this)}).call(e,i(4))},function(t,e,i){/**
<add>return n.Math.degToRad=function(t){return t*h},n.Math.radToDeg=function(t){return t*l},n.RandomDataGenerator=function(t){void 0===t&&(t=[]),this.c=1,this.s0=0,this.s1=0,this.s2=0,"string"==typeof t?this.state(t):this.sow(t)},n.RandomDataGenerator.prototype={rnd:function(){var t=2091639*this.s0+2.3283064365386963e-10*this.c;return this.c=0|t,this.s0=this.s1,this.s1=this.s2,this.s2=t-this.c,this.s2},sow:function(t){if(this.s0=this.hash(" "),this.s1=this.hash(this.s0),this.s2=this.hash(this.s1),this.c=1,t)for(var e=0;e<t.length&&null!=t[e];e++){var i=t[e];this.s0-=this.hash(i),this.s0+=~~(this.s0<0),this.s1-=this.hash(i),this.s1+=~~(this.s1<0),this.s2-=this.hash(i),this.s2+=~~(this.s2<0)}},hash:function(t){var e,i,s;for(s=4022871197,t=t.toString(),i=0;i<t.length;i++)s+=t.charCodeAt(i),e=.02519603282416938*s,s=e>>>0,e-=s,e*=s,s=e>>>0,e-=s,s+=4294967296*e;return 2.3283064365386963e-10*(s>>>0)},integer:function(){return 4294967296*this.rnd.apply(this)},frac:function(){return this.rnd.apply(this)+1.1102230246251565e-16*(2097152*this.rnd.apply(this)|0)},real:function(){return this.integer()+this.frac()},integerInRange:function(t,e){return Math.floor(this.realInRange(0,e-t+1)+t)},between:function(t,e){return this.integerInRange(t,e)},realInRange:function(t,e){return this.frac()*(e-t)+t},normal:function(){return 1-2*this.frac()},uuid:function(){var t="",e="";for(e=t="";t++<36;e+=~t%5|3*t&4?(15^t?8^this.frac()*(20^t?16:4):4).toString(16):"-");return e},pick:function(t){return t[this.integerInRange(0,t.length-1)]},sign:function(){return this.pick([-1,1])},weightedPick:function(t){return t[~~(Math.pow(this.frac(),2)*(t.length-1)+.5)]},timestamp:function(t,e){return this.realInRange(t||9466848e5,e||1577862e6)},angle:function(){return this.integerInRange(-180,180)},state:function(t){return"string"==typeof t&&t.match(/^!rnd/)&&(t=t.split(","),this.c=parseFloat(t[1]),this.s0=parseFloat(t[2]),this.s1=parseFloat(t[3]),this.s2=parseFloat(t[4])),["!rnd",this.c,this.s0,this.s1,this.s2].join(",")}},n.RandomDataGenerator.prototype.constructor=n.RandomDataGenerator,n.QuadTree=function(t,e,i,s,n,r,o){this.maxObjects=10,this.maxLevels=4,this.level=0,this.bounds={},this.objects=[],this.nodes=[],this._empty=[],this.reset(t,e,i,s,n,r,o)},n.QuadTree.prototype={reset:function(t,e,i,s,n,r,o){this.maxObjects=n||10,this.maxLevels=r||4,this.level=o||0,this.bounds={x:Math.round(t),y:Math.round(e),width:i,height:s,subWidth:Math.floor(i/2),subHeight:Math.floor(s/2),right:Math.round(t)+Math.floor(i/2),bottom:Math.round(e)+Math.floor(s/2)},this.objects.length=0,this.nodes.length=0},populate:function(t){t.forEach(this.populateHandler,this,!0)},populateHandler:function(t){t.body&&t.exists&&this.insert(t.body)},split:function(){this.nodes[0]=new n.QuadTree(this.bounds.right,this.bounds.y,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[1]=new n.QuadTree(this.bounds.x,this.bounds.y,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[2]=new n.QuadTree(this.bounds.x,this.bounds.bottom,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1),this.nodes[3]=new n.QuadTree(this.bounds.right,this.bounds.bottom,this.bounds.subWidth,this.bounds.subHeight,this.maxObjects,this.maxLevels,this.level+1)},insert:function(t){var e,i=0;if(null!=this.nodes[0]&&-1!==(e=this.getIndex(t)))return void this.nodes[e].insert(t);if(this.objects.push(t),this.objects.length>this.maxObjects&&this.level<this.maxLevels)for(null==this.nodes[0]&&this.split();i<this.objects.length;)e=this.getIndex(this.objects[i]),-1!==e?this.nodes[e].insert(this.objects.splice(i,1)[0]):i++},getIndex:function(t){var e=-1;return t.x<this.bounds.right&&t.right<this.bounds.right?t.y<this.bounds.bottom&&t.bottom<this.bounds.bottom?e=1:t.y>this.bounds.bottom&&(e=2):t.x>this.bounds.right&&(t.y<this.bounds.bottom&&t.bottom<this.bounds.bottom?e=0:t.y>this.bounds.bottom&&(e=3)),e},retrieve:function(t){if(t instanceof n.Rectangle)var e=this.objects,i=this.getIndex(t);else{if(!t.body)return this._empty;var e=this.objects,i=this.getIndex(t.body)}return this.nodes[0]&&(-1!==i?e=e.concat(this.nodes[i].retrieve(t)):(e=e.concat(this.nodes[0].retrieve(t)),e=e.concat(this.nodes[1].retrieve(t)),e=e.concat(this.nodes[2].retrieve(t)),e=e.concat(this.nodes[3].retrieve(t)))),e},clear:function(){this.objects.length=0;for(var t=this.nodes.length;t--;)this.nodes[t].clear(),this.nodes.splice(t,1);this.nodes.length=0}},n.QuadTree.prototype.constructor=n.QuadTree,n.Net=function(t){this.game=t},n.Net.prototype={getHostName:function(){return window.location&&window.location.hostname?window.location.hostname:null},checkDomainName:function(t){return-1!==window.location.hostname.indexOf(t)},updateQueryString:function(t,e,i,s){void 0===i&&(i=!1),void 0!==s&&""!==s||(s=window.location.href);var n="",r=new RegExp("([?|&])"+t+"=.*?(&|#|$)(.*)","gi");if(r.test(s))n=void 0!==e&&null!==e?s.replace(r,"$1"+t+"="+e+"$2$3"):s.replace(r,"$1$3").replace(/(&|\?)$/,"");else if(void 0!==e&&null!==e){var o=-1!==s.indexOf("?")?"&":"?",a=s.split("#");s=a[0]+o+t+"="+e,a[1]&&(s+="#"+a[1]),n=s}else n=s;if(!i)return n;window.location.href=n},getQueryString:function(t){void 0===t&&(t="");var e={},i=location.search.substring(1).split("&");for(var s in i){var n=i[s].split("=");if(n.length>1){if(t&&t===this.decodeURI(n[0]))return this.decodeURI(n[1]);e[this.decodeURI(n[0])]=this.decodeURI(n[1])}}return e},decodeURI:function(t){return decodeURIComponent(t.replace(/\+/g," "))}},n.Net.prototype.constructor=n.Net,n.TweenManager=function(t){this.game=t,this.frameBased=!1,this._tweens=[],this._add=[],this.easeMap={Power0:n.Easing.Power0,Power1:n.Easing.Power1,Power2:n.Easing.Power2,Power3:n.Easing.Power3,Power4:n.Easing.Power4,Linear:n.Easing.Linear.None,Quad:n.Easing.Quadratic.Out,Cubic:n.Easing.Cubic.Out,Quart:n.Easing.Quartic.Out,Quint:n.Easing.Quintic.Out,Sine:n.Easing.Sinusoidal.Out,Expo:n.Easing.Exponential.Out,Circ:n.Easing.Circular.Out,Elastic:n.Easing.Elastic.Out,Back:n.Easing.Back.Out,Bounce:n.Easing.Bounce.Out,"Quad.easeIn":n.Easing.Quadratic.In,"Cubic.easeIn":n.Easing.Cubic.In,"Quart.easeIn":n.Easing.Quartic.In,"Quint.easeIn":n.Easing.Quintic.In,"Sine.easeIn":n.Easing.Sinusoidal.In,"Expo.easeIn":n.Easing.Exponential.In,"Circ.easeIn":n.Easing.Circular.In,"Elastic.easeIn":n.Easing.Elastic.In,"Back.easeIn":n.Easing.Back.In,"Bounce.easeIn":n.Easing.Bounce.In,"Quad.easeOut":n.Easing.Quadratic.Out,"Cubic.easeOut":n.Easing.Cubic.Out,"Quart.easeOut":n.Easing.Quartic.Out,"Quint.easeOut":n.Easing.Quintic.Out,"Sine.easeOut":n.Easing.Sinusoidal.Out,"Expo.easeOut":n.Easing.Exponential.Out,"Circ.easeOut":n.Easing.Circular.Out,"Elastic.easeOut":n.Easing.Elastic.Out,"Back.easeOut":n.Easing.Back.Out,"Bounce.easeOut":n.Easing.Bounce.Out,"Quad.easeInOut":n.Easing.Quadratic.InOut,"Cubic.easeInOut":n.Easing.Cubic.InOut,"Quart.easeInOut":n.Easing.Quartic.InOut,"Quint.easeInOut":n.Easing.Quintic.InOut,"Sine.easeInOut":n.Easing.Sinusoidal.InOut,"Expo.easeInOut":n.Easing.Exponential.InOut,"Circ.easeInOut":n.Easing.Circular.InOut,"Elastic.easeInOut":n.Easing.Elastic.InOut,"Back.easeInOut":n.Easing.Back.InOut,"Bounce.easeInOut":n.Easing.Bounce.InOut},this.game.onPause.add(this._pauseAll,this),this.game.onResume.add(this._resumeAll,this)},n.TweenManager.prototype={getAll:function(){return this._tweens},removeAll:function(){for(var t=0;t<this._tweens.length;t++)this._tweens[t].pendingDelete=!0;this._add=[]},removeFrom:function(t,e){void 0===e&&(e=!0);var i,s;if(Array.isArray(t))for(i=0,s=t.length;i<s;i++)this.removeFrom(t[i]);else if(t.type===n.GROUP&&e)for(var i=0,s=t.children.length;i<s;i++)this.removeFrom(t.children[i]);else{for(i=0,s=this._tweens.length;i<s;i++)t===this._tweens[i].target&&this.remove(this._tweens[i]);for(i=0,s=this._add.length;i<s;i++)t===this._add[i].target&&this.remove(this._add[i])}},add:function(t){t._manager=this,this._add.push(t)},create:function(t){return new n.Tween(t,this.game,this)},remove:function(t){var e=this._tweens.indexOf(t);-1!==e?this._tweens[e].pendingDelete=!0:-1!==(e=this._add.indexOf(t))&&(this._add[e].pendingDelete=!0)},update:function(){var t=this._add.length,e=this._tweens.length;if(0===e&&0===t)return!1;for(var i=0;i<e;)this._tweens[i].update(this.game.time.time)?i++:(this._tweens.splice(i,1),e--);return t>0&&(this._tweens=this._tweens.concat(this._add),this._add.length=0),!0},isTweening:function(t){return this._tweens.some(function(e){return e.target===t})},_pauseAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t]._pause()},_resumeAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t]._resume()},pauseAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t].pause()},resumeAll:function(){for(var t=this._tweens.length-1;t>=0;t--)this._tweens[t].resume(!0)}},n.TweenManager.prototype.constructor=n.TweenManager,n.Tween=function(t,e,i){this.game=e,this.target=t,this.manager=i,this.timeline=[],this.reverse=!1,this.timeScale=1,this.repeatCounter=0,this.pendingDelete=!1,this.onStart=new n.Signal,this.onLoop=new n.Signal,this.onRepeat=new n.Signal,this.onChildComplete=new n.Signal,this.onComplete=new n.Signal,this.isRunning=!1,this.current=0,this.properties={},this.chainedTween=null,this.isPaused=!1,this.frameBased=i.frameBased,this._onUpdateCallback=null,this._onUpdateCallbackContext=null,this._pausedTime=0,this._codePaused=!1,this._hasStarted=!1},n.Tween.prototype={to:function(t,e,i,s,r,o,a){return(void 0===e||e<=0)&&(e=1e3),void 0!==i&&null!==i||(i=n.Easing.Default),void 0===s&&(s=!1),void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=!1),"string"==typeof i&&this.manager.easeMap[i]&&(i=this.manager.easeMap[i]),this.isRunning?(console.warn("Phaser.Tween.to cannot be called after Tween.start"),this):(this.timeline.push(new n.TweenData(this).to(t,e,i,r,o,a)),s&&this.start(),this)},from:function(t,e,i,s,r,o,a){return void 0===e&&(e=1e3),void 0!==i&&null!==i||(i=n.Easing.Default),void 0===s&&(s=!1),void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=!1),"string"==typeof i&&this.manager.easeMap[i]&&(i=this.manager.easeMap[i]),this.isRunning?(console.warn("Phaser.Tween.from cannot be called after Tween.start"),this):(this.timeline.push(new n.TweenData(this).from(t,e,i,r,o,a)),s&&this.start(),this)},start:function(t){if(void 0===t&&(t=0),null===this.game||null===this.target||0===this.timeline.length||this.isRunning)return this;for(var e=0;e<this.timeline.length;e++)for(var i in this.timeline[e].vEnd)this.properties[i]=this.target[i]||0,Array.isArray(this.properties[i])||(this.properties[i]*=1);for(var e=0;e<this.timeline.length;e++)this.timeline[e].loadValues();return this.manager.add(this),this.isRunning=!0,(t<0||t>this.timeline.length-1)&&(t=0),this.current=t,this.timeline[this.current].start(),this},stop:function(t){return void 0===t&&(t=!1),this.isRunning=!1,this._onUpdateCallback=null,this._onUpdateCallbackContext=null,t&&(this.onComplete.dispatch(this.target,this),this._hasStarted=!1,this.chainedTween&&this.chainedTween.start()),this.manager.remove(this),this},updateTweenData:function(t,e,i){if(0===this.timeline.length)return this;if(void 0===i&&(i=0),-1===i)for(var s=0;s<this.timeline.length;s++)this.timeline[s][t]=e;else this.timeline[i][t]=e;return this},delay:function(t,e){return this.updateTweenData("delay",t,e)},repeat:function(t,e,i){return void 0===e&&(e=0),this.updateTweenData("repeatCounter",t,i),this.updateTweenData("repeatDelay",e,i)},repeatDelay:function(t,e){return this.updateTweenData("repeatDelay",t,e)},yoyo:function(t,e,i){return void 0===e&&(e=0),this.updateTweenData("yoyo",t,i),this.updateTweenData("yoyoDelay",e,i)},yoyoDelay:function(t,e){return this.updateTweenData("yoyoDelay",t,e)},easing:function(t,e){return"string"==typeof t&&this.manager.easeMap[t]&&(t=this.manager.easeMap[t]),this.updateTweenData("easingFunction",t,e)},interpolation:function(t,e,i){return void 0===e&&(e=n.Math),this.updateTweenData("interpolationFunction",t,i),this.updateTweenData("interpolationContext",e,i)},repeatAll:function(t){return void 0===t&&(t=0),this.repeatCounter=t,this},chain:function(){for(var t=arguments.length;t--;)t>0?arguments[t-1].chainedTween=arguments[t]:this.chainedTween=arguments[t];return this},loop:function(t){return void 0===t&&(t=!0),this.repeatCounter=t?-1:0,this},onUpdateCallback:function(t,e){return this._onUpdateCallback=t,this._onUpdateCallbackContext=e,this},pause:function(){this.isPaused=!0,this._codePaused=!0,this._pausedTime=this.game.time.time},_pause:function(){this._codePaused||(this.isPaused=!0,this._pausedTime=this.game.time.time)},resume:function(){if(this.isPaused){this.isPaused=!1,this._codePaused=!1;for(var t=0;t<this.timeline.length;t++)this.timeline[t].isRunning||(this.timeline[t].startTime+=this.game.time.time-this._pausedTime)}},_resume:function(){this._codePaused||this.resume()},update:function(t){if(this.pendingDelete||!this.target)return!1;if(this.isPaused)return!0;var e=this.timeline[this.current].update(t);if(e===n.TweenData.PENDING)return!0;if(e===n.TweenData.RUNNING)return this._hasStarted||(this.onStart.dispatch(this.target,this),this._hasStarted=!0),null!==this._onUpdateCallback&&this._onUpdateCallback.call(this._onUpdateCallbackContext,this,this.timeline[this.current].value,this.timeline[this.current]),this.isRunning;if(e===n.TweenData.LOOPED)return-1===this.timeline[this.current].repeatCounter?this.onLoop.dispatch(this.target,this):this.onRepeat.dispatch(this.target,this),!0;if(e===n.TweenData.COMPLETE){var i=!1;return this.reverse?--this.current<0&&(this.current=this.timeline.length-1,i=!0):++this.current===this.timeline.length&&(this.current=0,i=!0),i?-1===this.repeatCounter?(this.timeline[this.current].start(),this.onLoop.dispatch(this.target,this),!0):this.repeatCounter>0?(this.repeatCounter--,this.timeline[this.current].start(),this.onRepeat.dispatch(this.target,this),!0):(this.isRunning=!1,this.onComplete.dispatch(this.target,this),this._hasStarted=!1,this.chainedTween&&this.chainedTween.start(),!1):(this.onChildComplete.dispatch(this.target,this),this.timeline[this.current].start(),!0)}},generateData:function(t,e){if(null===this.game||null===this.target)return null;void 0===t&&(t=60),void 0===e&&(e=[]);for(var i=0;i<this.timeline.length;i++)for(var s in this.timeline[i].vEnd)this.properties[s]=this.target[s]||0,Array.isArray(this.properties[s])||(this.properties[s]*=1);for(var i=0;i<this.timeline.length;i++)this.timeline[i].loadValues();for(var i=0;i<this.timeline.length;i++)e=e.concat(this.timeline[i].generateData(t));return e}},Object.defineProperty(n.Tween.prototype,"totalDuration",{get:function(){for(var t=0,e=0;e<this.timeline.length;e++)t+=this.timeline[e].duration;return t}}),n.Tween.prototype.constructor=n.Tween,n.TweenData=function(t){this.parent=t,this.game=t.game,this.vStart={},this.vStartCache={},this.vEnd={},this.vEndCache={},this.duration=1e3,this.percent=0,this.value=0,this.repeatCounter=0,this.repeatDelay=0,this.repeatTotal=0,this.interpolate=!1,this.yoyo=!1,this.yoyoDelay=0,this.inReverse=!1,this.delay=0,this.dt=0,this.startTime=null,this.easingFunction=n.Easing.Default,this.interpolationFunction=n.Math.linearInterpolation,this.interpolationContext=n.Math,this.isRunning=!1,this.isFrom=!1},n.TweenData.PENDING=0,n.TweenData.RUNNING=1,n.TweenData.LOOPED=2,n.TweenData.COMPLETE=3,n.TweenData.prototype={to:function(t,e,i,s,n,r){return this.vEnd=t,this.duration=e,this.easingFunction=i,this.delay=s,this.repeatTotal=n,this.yoyo=r,this.isFrom=!1,this},from:function(t,e,i,s,n,r){return this.vEnd=t,this.duration=e,this.easingFunction=i,this.delay=s,this.repeatTotal=n,this.yoyo=r,this.isFrom=!0,this},start:function(){if(this.startTime=this.game.time.time+this.delay,this.parent.reverse?this.dt=this.duration:this.dt=0,this.delay>0?this.isRunning=!1:this.isRunning=!0,this.isFrom)for(var t in this.vStartCache)this.vStart[t]=this.vEndCache[t],this.vEnd[t]=this.vStartCache[t],this.parent.target[t]=this.vStart[t];return this.value=0,this.yoyoCounter=0,this.repeatCounter=this.repeatTotal,this},loadValues:function(){for(var t in this.parent.properties){if(this.vStart[t]=this.parent.properties[t],Array.isArray(this.vEnd[t])){if(0===this.vEnd[t].length)continue;0===this.percent&&(this.vEnd[t]=[this.vStart[t]].concat(this.vEnd[t]))}void 0!==this.vEnd[t]?("string"==typeof this.vEnd[t]&&(this.vEnd[t]=this.vStart[t]+parseFloat(this.vEnd[t],10)),this.parent.properties[t]=this.vEnd[t]):this.vEnd[t]=this.vStart[t],this.vStartCache[t]=this.vStart[t],this.vEndCache[t]=this.vEnd[t]}return this},update:function(t){if(this.isRunning){if(t<this.startTime)return n.TweenData.RUNNING}else{if(!(t>=this.startTime))return n.TweenData.PENDING;this.isRunning=!0}var e=this.parent.frameBased?this.game.time.physicsElapsedMS:this.game.time.elapsedMS;this.parent.reverse?(this.dt-=e*this.parent.timeScale,this.dt=Math.max(this.dt,0)):(this.dt+=e*this.parent.timeScale,this.dt=Math.min(this.dt,this.duration)),this.percent=this.dt/this.duration,this.value=this.easingFunction(this.percent);for(var i in this.vEnd){var s=this.vStart[i],r=this.vEnd[i];Array.isArray(r)?this.parent.target[i]=this.interpolationFunction.call(this.interpolationContext,r,this.value):this.parent.target[i]=s+(r-s)*this.value}return!this.parent.reverse&&1===this.percent||this.parent.reverse&&0===this.percent?this.repeat():n.TweenData.RUNNING},generateData:function(t){this.parent.reverse?this.dt=this.duration:this.dt=0;var e=[],i=!1,s=1/t*1e3;do{this.parent.reverse?(this.dt-=s,this.dt=Math.max(this.dt,0)):(this.dt+=s,this.dt=Math.min(this.dt,this.duration)),this.percent=this.dt/this.duration,this.value=this.easingFunction(this.percent);var n={};for(var r in this.vEnd){var o=this.vStart[r],a=this.vEnd[r];Array.isArray(a)?n[r]=this.interpolationFunction(a,this.value):n[r]=o+(a-o)*this.value}e.push(n),(!this.parent.reverse&&1===this.percent||this.parent.reverse&&0===this.percent)&&(i=!0)}while(!i);if(this.yoyo){var h=e.slice();h.reverse(),e=e.concat(h)}return e},repeat:function(){if(this.yoyo){if(this.inReverse&&0===this.repeatCounter){for(var t in this.vStartCache)this.vStart[t]=this.vStartCache[t],this.vEnd[t]=this.vEndCache[t];return this.inReverse=!1,n.TweenData.COMPLETE}this.inReverse=!this.inReverse}else if(0===this.repeatCounter)return n.TweenData.COMPLETE;if(this.inReverse)for(var t in this.vStartCache)this.vStart[t]=this.vEndCache[t],this.vEnd[t]=this.vStartCache[t];else{for(var t in this.vStartCache)this.vStart[t]=this.vStartCache[t],this.vEnd[t]=this.vEndCache[t];this.repeatCounter>0&&this.repeatCounter--}return this.startTime=this.game.time.time,this.yoyo&&this.inReverse?this.startTime+=this.yoyoDelay:this.inReverse||(this.startTime+=this.repeatDelay),this.parent.reverse?this.dt=this.duration:this.dt=0,n.TweenData.LOOPED}},n.TweenData.prototype.constructor=n.TweenData,n.Easing={Linear:{None:function(t){return t}},Quadratic:{In:function(t){return t*t},Out:function(t){return t*(2-t)},InOut:function(t){return(t*=2)<1?.5*t*t:-.5*(--t*(t-2)-1)}},Cubic:{In:function(t){return t*t*t},Out:function(t){return--t*t*t+1},InOut:function(t){return(t*=2)<1?.5*t*t*t:.5*((t-=2)*t*t+2)}},Quartic:{In:function(t){return t*t*t*t},Out:function(t){return 1- --t*t*t*t},InOut:function(t){return(t*=2)<1?.5*t*t*t*t:-.5*((t-=2)*t*t*t-2)}},Quintic:{In:function(t){return t*t*t*t*t},Out:function(t){return--t*t*t*t*t+1},InOut:function(t){return(t*=2)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2)}},Sinusoidal:{In:function(t){return 0===t?0:1===t?1:1-Math.cos(t*Math.PI/2)},Out:function(t){return 0===t?0:1===t?1:Math.sin(t*Math.PI/2)},InOut:function(t){return 0===t?0:1===t?1:.5*(1-Math.cos(Math.PI*t))}},Exponential:{In:function(t){return 0===t?0:Math.pow(1024,t-1)},Out:function(t){return 1===t?1:1-Math.pow(2,-10*t)},InOut:function(t){return 0===t?0:1===t?1:(t*=2)<1?.5*Math.pow(1024,t-1):.5*(2-Math.pow(2,-10*(t-1)))}},Circular:{In:function(t){return 1-Math.sqrt(1-t*t)},Out:function(t){return Math.sqrt(1- --t*t)},InOut:function(t){return(t*=2)<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1)}},Elastic:{In:function(t){var e,i=.1;return 0===t?0:1===t?1:(!i||i<1?(i=1,e=.1):e=.4*Math.asin(1/i)/(2*Math.PI),-i*Math.pow(2,10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4))},Out:function(t){var e,i=.1;return 0===t?0:1===t?1:(!i||i<1?(i=1,e=.1):e=.4*Math.asin(1/i)/(2*Math.PI),i*Math.pow(2,-10*t)*Math.sin((t-e)*(2*Math.PI)/.4)+1)},InOut:function(t){var e,i=.1;return 0===t?0:1===t?1:(!i||i<1?(i=1,e=.1):e=.4*Math.asin(1/i)/(2*Math.PI),(t*=2)<1?i*Math.pow(2,10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4)*-.5:i*Math.pow(2,-10*(t-=1))*Math.sin((t-e)*(2*Math.PI)/.4)*.5+1)}},Back:{In:function(t){var e=1.70158;return t*t*((e+1)*t-e)},Out:function(t){var e=1.70158;return--t*t*((e+1)*t+e)+1},InOut:function(t){var e=2.5949095;return(t*=2)<1?t*t*((e+1)*t-e)*.5:.5*((t-=2)*t*((e+1)*t+e)+2)}},Bounce:{In:function(t){return 1-n.Easing.Bounce.Out(1-t)},Out:function(t){return t<1/2.75?7.5625*t*t:t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375},InOut:function(t){return t<.5?.5*n.Easing.Bounce.In(2*t):.5*n.Easing.Bounce.Out(2*t-1)+.5}}},n.Easing.Default=n.Easing.Linear.None,n.Easing.Power0=n.Easing.Linear.None,n.Easing.Power1=n.Easing.Quadratic.Out,n.Easing.Power2=n.Easing.Cubic.Out,n.Easing.Power3=n.Easing.Quartic.Out,n.Easing.Power4=n.Easing.Quintic.Out,n.Time=function(t){this.game=t,this.time=0,this.prevTime=0,this.now=0,this.elapsed=0,this.elapsedMS=0,this.physicsElapsed=1/60,this.physicsElapsedMS=1/60*1e3,this.desiredFpsMult=1/60,this._desiredFps=60,this.suggestedFps=this.desiredFps,this.slowMotion=1,this.advancedTiming=!1,this.frames=0,this.fps=0,this.fpsMin=1e3,this.fpsMax=0,this.msMin=1e3,this.msMax=0,this.pauseDuration=0,this.timeToCall=0,this.timeExpected=0,this.events=new n.Timer(this.game,!1),this._frameCount=0,this._elapsedAccumulator=0,this._started=0,this._timeLastSecond=0,this._pauseStarted=0,this._justResumed=!1,this._timers=[]},n.Time.prototype={boot:function(){this._started=Date.now(),this.time=Date.now(),this.events.start(),this.timeExpected=this.time},add:function(t){return this._timers.push(t),t},create:function(t){void 0===t&&(t=!0);var e=new n.Timer(this.game,t);return this._timers.push(e),e},removeAll:function(){for(var t=0;t<this._timers.length;t++)this._timers[t].destroy();this._timers=[],this.events.removeAll()},refresh:function(){var t=this.time;this.time=Date.now(),this.elapsedMS=this.time-t},update:function(t){var e=this.time;this.time=Date.now(),this.elapsedMS=this.time-e,this.prevTime=this.now,this.now=t,this.elapsed=this.now-this.prevTime,this.game.raf._isSetTimeOut&&(this.timeToCall=Math.floor(Math.max(0,1e3/this._desiredFps-(this.timeExpected-t))),this.timeExpected=t+this.timeToCall),this.advancedTiming&&this.updateAdvancedTiming(),this.game.paused||(this.events.update(this.time),this._timers.length&&this.updateTimers())},updateTimers:function(){for(var t=0,e=this._timers.length;t<e;)this._timers[t].update(this.time)?t++:(this._timers.splice(t,1),e--)},updateAdvancedTiming:function(){this._frameCount++,this._elapsedAccumulator+=this.elapsed,this._frameCount>=2*this._desiredFps&&(this.suggestedFps=5*Math.floor(200/(this._elapsedAccumulator/this._frameCount)),this._frameCount=0,this._elapsedAccumulator=0),this.msMin=Math.min(this.msMin,this.elapsed),this.msMax=Math.max(this.msMax,this.elapsed),this.frames++,this.now>this._timeLastSecond+1e3&&(this.fps=Math.round(1e3*this.frames/(this.now-this._timeLastSecond)),this.fpsMin=Math.min(this.fpsMin,this.fps),this.fpsMax=Math.max(this.fpsMax,this.fps),this._timeLastSecond=this.now,this.frames=0)},gamePaused:function(){this._pauseStarted=Date.now(),this.events.pause();for(var t=this._timers.length;t--;)this._timers[t]._pause()},gameResumed:function(){this.time=Date.now(),this.pauseDuration=this.time-this._pauseStarted,this.events.resume();for(var t=this._timers.length;t--;)this._timers[t]._resume()},totalElapsedSeconds:function(){return.001*(this.time-this._started)},elapsedSince:function(t){return this.time-t},elapsedSecondsSince:function(t){return.001*(this.time-t)},reset:function(){this._started=this.time,this.removeAll()}},Object.defineProperty(n.Time.prototype,"desiredFps",{get:function(){return this._desiredFps},set:function(t){this._desiredFps=t,this.physicsElapsed=1/t,this.physicsElapsedMS=1e3*this.physicsElapsed,this.desiredFpsMult=1/t}}),n.Time.prototype.constructor=n.Time,n.Timer=function(t,e){void 0===e&&(e=!0),this.game=t,this.running=!1,this.autoDestroy=e,this.expired=!1,this.elapsed=0,this.events=[],this.onComplete=new n.Signal,this.nextTick=0,this.timeCap=1e3,this.paused=!1,this._codePaused=!1,this._started=0,this._pauseStarted=0,this._pauseTotal=0,this._now=Date.now(),this._len=0,this._marked=0,this._i=0,this._diff=0,this._newTick=0},n.Timer.MINUTE=6e4,n.Timer.SECOND=1e3,n.Timer.HALF=500,n.Timer.QUARTER=250,n.Timer.prototype={create:function(t,e,i,s,r,o){t=Math.round(t);var a=t;0===this._now?a+=this.game.time.time:a+=this._now;var h=new n.TimerEvent(this,t,a,i,e,s,r,o);return this.events.push(h),this.order(),this.expired=!1,h},add:function(t,e,i){return this.create(t,!1,0,e,i,Array.prototype.slice.call(arguments,3))},repeat:function(t,e,i,s){return this.create(t,!1,e,i,s,Array.prototype.slice.call(arguments,4))},loop:function(t,e,i){return this.create(t,!0,0,e,i,Array.prototype.slice.call(arguments,3))},start:function(t){if(!this.running){this._started=this.game.time.time+(t||0),this.running=!0;for(var e=0;e<this.events.length;e++)this.events[e].tick=this.events[e].delay+this._started}},stop:function(t){this.running=!1,void 0===t&&(t=!0),t&&(this.events.length=0)},remove:function(t){for(var e=0;e<this.events.length;e++)if(this.events[e]===t)return this.events[e].pendingDelete=!0,!0;return!1},order:function(){this.events.length>0&&(this.events.sort(this.sortHandler),this.nextTick=this.events[0].tick)},sortHandler:function(t,e){return t.tick<e.tick?-1:t.tick>e.tick?1:0},clearPendingEvents:function(){for(this._i=this.events.length;this._i--;)this.events[this._i].pendingDelete&&this.events.splice(this._i,1);this._len=this.events.length,this._i=0},update:function(t){if(this.paused)return!0;if(this.elapsed=t-this._now,this._now=t,this.elapsed>this.timeCap&&this.adjustEvents(t-this.elapsed),this._marked=0,this.clearPendingEvents(),this.running&&this._now>=this.nextTick&&this._len>0){for(;this._i<this._len&&this.running&&this._now>=this.events[this._i].tick&&!this.events[this._i].pendingDelete;)this._newTick=this._now+this.events[this._i].delay-(this._now-this.events[this._i].tick),this._newTick<0&&(this._newTick=this._now+this.events[this._i].delay),!0===this.events[this._i].loop?(this.events[this._i].tick=this._newTick,this.events[this._i].callback.apply(this.events[this._i].callbackContext,this.events[this._i].args)):this.events[this._i].repeatCount>0?(this.events[this._i].repeatCount--,this.events[this._i].tick=this._newTick,this.events[this._i].callback.apply(this.events[this._i].callbackContext,this.events[this._i].args)):(this._marked++,this.events[this._i].pendingDelete=!0,this.events[this._i].callback.apply(this.events[this._i].callbackContext,this.events[this._i].args)),this._i++;this.events.length>this._marked?this.order():(this.expired=!0,this.onComplete.dispatch(this))}return!this.expired||!this.autoDestroy},pause:function(){this.running&&(this._codePaused=!0,this.paused||(this._pauseStarted=this.game.time.time,this.paused=!0))},_pause:function(){!this.paused&&this.running&&(this._pauseStarted=this.game.time.time,this.paused=!0)},adjustEvents:function(t){for(var e=0;e<this.events.length;e++)if(!this.events[e].pendingDelete){var i=this.events[e].tick-t;i<0&&(i=0),this.events[e].tick=this._now+i}var s=this.nextTick-t;this.nextTick=s<0?this._now:this._now+s},resume:function(){if(this.paused){var t=this.game.time.time;this._pauseTotal+=t-this._now,this._now=t,this.adjustEvents(this._pauseStarted),this.paused=!1,this._codePaused=!1}},_resume:function(){this._codePaused||this.resume()},removeAll:function(){this.onComplete.removeAll(),this.events.length=0,this._len=0,this._i=0},destroy:function(){this.onComplete.removeAll(),this.running=!1,this.events=[],this._len=0,this._i=0}},Object.defineProperty(n.Timer.prototype,"next",{get:function(){return this.nextTick}}),Object.defineProperty(n.Timer.prototype,"duration",{get:function(){return this.running&&this.nextTick>this._now?this.nextTick-this._now:0}}),Object.defineProperty(n.Timer.prototype,"length",{get:function(){return this.events.length}}),Object.defineProperty(n.Timer.prototype,"ms",{get:function(){return this.running?this._now-this._started-this._pauseTotal:0}}),Object.defineProperty(n.Timer.prototype,"seconds",{get:function(){return this.running?.001*this.ms:0}}),n.Timer.prototype.constructor=n.Timer,n.TimerEvent=function(t,e,i,s,n,r,o,a){this.timer=t,this.delay=e,this.tick=i,this.repeatCount=s-1,this.loop=n,this.callback=r,this.callbackContext=o,this.args=a,this.pendingDelete=!1},n.TimerEvent.prototype.constructor=n.TimerEvent,n.AnimationManager=function(t){this.sprite=t,this.game=t.game,this.currentFrame=null,this.currentAnim=null,this.updateIfVisible=!0,this.isLoaded=!1,this._frameData=null,this._anims={},this._outputFrames=[]},n.AnimationManager.prototype={loadFrameData:function(t,e){if(void 0===t)return!1;if(this.isLoaded)for(var i in this._anims)this._anims[i].updateFrameData(t);return this._frameData=t,void 0===e||null===e?this.frame=0:"string"==typeof e?this.frameName=e:this.frame=e,this.isLoaded=!0,!0},copyFrameData:function(t,e){if(this._frameData=t.clone(),this.isLoaded)for(var i in this._anims)this._anims[i].updateFrameData(this._frameData);return void 0===e||null===e?this.frame=0:"string"==typeof e?this.frameName=e:this.frame=e,this.isLoaded=!0,!0},add:function(t,e,i,s,r){return e=e||[],i=i||60,void 0===s&&(s=!1),void 0===r&&(r=!(!e||"number"!=typeof e[0])),this._outputFrames=[],this._frameData.getFrameIndexes(e,r,this._outputFrames),this._anims[t]=new n.Animation(this.game,this.sprite,t,this._frameData,this._outputFrames,i,s),this.currentAnim=this._anims[t],this.sprite.tilingTexture&&(this.sprite.refreshTexture=!0),this._anims[t]},validateFrames:function(t,e){void 0===e&&(e=!0);for(var i=0;i<t.length;i++)if(!0===e){if(t[i]>this._frameData.total)return!1}else if(!1===this._frameData.checkFrameName(t[i]))return!1;return!0},play:function(t,e,i,s){if(this._anims[t])return this.currentAnim===this._anims[t]?!1===this.currentAnim.isPlaying?(this.currentAnim.paused=!1,this.currentAnim.play(e,i,s)):this.currentAnim:(this.currentAnim&&this.currentAnim.isPlaying&&this.currentAnim.stop(),this.currentAnim=this._anims[t],this.currentAnim.paused=!1,this.currentFrame=this.currentAnim.currentFrame,this.currentAnim.play(e,i,s))},stop:function(t,e){void 0===e&&(e=!1),!this.currentAnim||"string"==typeof t&&t!==this.currentAnim.name||this.currentAnim.stop(e)},update:function(){return!(this.updateIfVisible&&!this.sprite.visible)&&(!(!this.currentAnim||!this.currentAnim.update())&&(this.currentFrame=this.currentAnim.currentFrame,!0))},next:function(t){this.currentAnim&&(this.currentAnim.next(t),this.currentFrame=this.currentAnim.currentFrame)},previous:function(t){this.currentAnim&&(this.currentAnim.previous(t),this.currentFrame=this.currentAnim.currentFrame)},getAnimation:function(t){return"string"==typeof t&&this._anims[t]?this._anims[t]:null},refreshFrame:function(){},destroy:function(){var t=null;for(var t in this._anims)this._anims.hasOwnProperty(t)&&this._anims[t].destroy();this._anims={},this._outputFrames=[],this._frameData=null,this.currentAnim=null,this.currentFrame=null,this.sprite=null,this.game=null}},n.AnimationManager.prototype.constructor=n.AnimationManager,Object.defineProperty(n.AnimationManager.prototype,"frameData",{get:function(){return this._frameData}}),Object.defineProperty(n.AnimationManager.prototype,"frameTotal",{get:function(){return this._frameData.total}}),Object.defineProperty(n.AnimationManager.prototype,"paused",{get:function(){return this.currentAnim.isPaused},set:function(t){this.currentAnim.paused=t}}),Object.defineProperty(n.AnimationManager.prototype,"name",{get:function(){if(this.currentAnim)return this.currentAnim.name}}),Object.defineProperty(n.AnimationManager.prototype,"frame",{get:function(){if(this.currentFrame)return this.currentFrame.index},set:function(t){"number"==typeof t&&this._frameData&&null!==this._frameData.getFrame(t)&&(this.currentFrame=this._frameData.getFrame(t),this.currentFrame&&this.sprite.setFrame(this.currentFrame))}}),Object.defineProperty(n.AnimationManager.prototype,"frameName",{get:function(){if(this.currentFrame)return this.currentFrame.name},set:function(t){"string"==typeof t&&this._frameData&&null!==this._frameData.getFrameByName(t)?(this.currentFrame=this._frameData.getFrameByName(t),this.currentFrame&&(this._frameIndex=this.currentFrame.index,this.sprite.setFrame(this.currentFrame))):console.warn("Cannot set frameName: "+t)}}),n.Animation=function(t,e,i,s,r,o,a){void 0===a&&(a=!1),this.game=t,this._parent=e,this._frameData=s,this.name=i,this._frames=[],this._frames=this._frames.concat(r),this.delay=1e3/o,this.loop=a,this.loopCount=0,this.killOnComplete=!1,this.isFinished=!1,this.isPlaying=!1,this.isPaused=!1,this._pauseStartTime=0,this._frameIndex=0,this._frameDiff=0,this._frameSkip=1,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.onStart=new n.Signal,this.onUpdate=null,this.onComplete=new n.Signal,this.onLoop=new n.Signal,this.isReversed=!1,this.game.onPause.add(this.onPause,this),this.game.onResume.add(this.onResume,this)},n.Animation.prototype={play:function(t,e,i){return"number"==typeof t&&(this.delay=1e3/t),"boolean"==typeof e&&(this.loop=e),void 0!==i&&(this.killOnComplete=i),this.isPlaying=!0,this.isFinished=!1,this.paused=!1,this.loopCount=0,this._timeLastFrame=this.game.time.time,this._timeNextFrame=this.game.time.time+this.delay,this._frameIndex=this.isReversed?this._frames.length-1:0,this.updateCurrentFrame(!1,!0),this._parent.events.onAnimationStart$dispatch(this._parent,this),this.onStart.dispatch(this._parent,this),this._parent.animations.currentAnim=this,this._parent.animations.currentFrame=this.currentFrame,this},restart:function(){this.isPlaying=!0,this.isFinished=!1,this.paused=!1,this.loopCount=0,this._timeLastFrame=this.game.time.time,this._timeNextFrame=this.game.time.time+this.delay,this._frameIndex=0,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this._parent.setFrame(this.currentFrame),this._parent.animations.currentAnim=this,this._parent.animations.currentFrame=this.currentFrame,this.onStart.dispatch(this._parent,this)},reverse:function(){return this.reversed=!this.reversed,this},reverseOnce:function(){return this.onComplete.addOnce(this.reverse,this),this.reverse()},setFrame:function(t,e){var i;if(void 0===e&&(e=!1),"string"==typeof t)for(var s=0;s<this._frames.length;s++)this._frameData.getFrame(this._frames[s]).name===t&&(i=s);else if("number"==typeof t)if(e)i=t;else for(var s=0;s<this._frames.length;s++)this._frames[s]===t&&(i=s);i&&(this._frameIndex=i-1,this._timeNextFrame=this.game.time.time,this.update())},stop:function(t,e){void 0===t&&(t=!1),void 0===e&&(e=!1),this.isPlaying=!1,this.isFinished=!0,this.paused=!1,t&&(this.currentFrame=this._frameData.getFrame(this._frames[0]),this._parent.setFrame(this.currentFrame)),e&&(this._parent.events.onAnimationComplete$dispatch(this._parent,this),this.onComplete.dispatch(this._parent,this))},onPause:function(){this.isPlaying&&(this._frameDiff=this._timeNextFrame-this.game.time.time)},onResume:function(){this.isPlaying&&(this._timeNextFrame=this.game.time.time+this._frameDiff)},update:function(){return!this.isPaused&&(!!(this.isPlaying&&this.game.time.time>=this._timeNextFrame)&&(this._frameSkip=1,this._frameDiff=this.game.time.time-this._timeNextFrame,this._timeLastFrame=this.game.time.time,this._frameDiff>this.delay&&(this._frameSkip=Math.floor(this._frameDiff/this.delay),this._frameDiff-=this._frameSkip*this.delay),this._timeNextFrame=this.game.time.time+(this.delay-this._frameDiff),this.isReversed?this._frameIndex-=this._frameSkip:this._frameIndex+=this._frameSkip,!this.isReversed&&this._frameIndex>=this._frames.length||this.isReversed&&this._frameIndex<=-1?this.loop?(this._frameIndex=Math.abs(this._frameIndex)%this._frames.length,this.isReversed&&(this._frameIndex=this._frames.length-1-this._frameIndex),this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.currentFrame&&this._parent.setFrame(this.currentFrame),this.loopCount++,this._parent.events.onAnimationLoop$dispatch(this._parent,this),this.onLoop.dispatch(this._parent,this),!this.onUpdate||(this.onUpdate.dispatch(this,this.currentFrame),!!this._frameData)):(this.complete(),!1):this.updateCurrentFrame(!0)))},updateCurrentFrame:function(t,e){if(void 0===e&&(e=!1),!this._frameData)return!1;var i=this.currentFrame.index;return this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.currentFrame&&(e||!e&&i!==this.currentFrame.index)&&this._parent.setFrame(this.currentFrame),!this.onUpdate||!t||(this.onUpdate.dispatch(this,this.currentFrame),!!this._frameData)},next:function(t){void 0===t&&(t=1);var e=this._frameIndex+t;e>=this._frames.length&&(this.loop?e%=this._frames.length:e=this._frames.length-1),e!==this._frameIndex&&(this._frameIndex=e,this.updateCurrentFrame(!0))},previous:function(t){void 0===t&&(t=1);var e=this._frameIndex-t;e<0&&(this.loop?e=this._frames.length+e:e++),e!==this._frameIndex&&(this._frameIndex=e,this.updateCurrentFrame(!0))},updateFrameData:function(t){this._frameData=t,this.currentFrame=this._frameData?this._frameData.getFrame(this._frames[this._frameIndex%this._frames.length]):null},destroy:function(){this._frameData&&(this.game.onPause.remove(this.onPause,this),this.game.onResume.remove(this.onResume,this),this.game=null,this._parent=null,this._frames=null,this._frameData=null,this.currentFrame=null,this.isPlaying=!1,this.onStart.dispose(),this.onLoop.dispose(),this.onComplete.dispose(),this.onUpdate&&this.onUpdate.dispose())},complete:function(){this._frameIndex=this._frames.length-1,this.currentFrame=this._frameData.getFrame(this._frames[this._frameIndex]),this.isPlaying=!1,this.isFinished=!0,this.paused=!1,this._parent.events.onAnimationComplete$dispatch(this._parent,this),this.onComplete.dispatch(this._parent,this),this.killOnComplete&&this._parent.kill()}},n.Animation.prototype.constructor=n.Animation,Object.defineProperty(n.Animation.prototype,"paused",{get:function(){return this.isPaused},set:function(t){this.isPaused=t,t?this._pauseStartTime=this.game.time.time:this.isPlaying&&(this._timeNextFrame=this.game.time.time+this.delay)}}),Object.defineProperty(n.Animation.prototype,"reversed",{get:function(){return this.isReversed},set:function(t){this.isReversed=t}}),Object.defineProperty(n.Animation.prototype,"frameTotal",{get:function(){return this._frames.length}}),Object.defineProperty(n.Animation.prototype,"frame",{get:function(){return null!==this.currentFrame?this.currentFrame.index:this._frameIndex},set:function(t){this.currentFrame=this._frameData.getFrame(this._frames[t]),null!==this.currentFrame&&(this._frameIndex=t,this._parent.setFrame(this.currentFrame),this.onUpdate&&this.onUpdate.dispatch(this,this.currentFrame))}}),Object.defineProperty(n.Animation.prototype,"speed",{get:function(){return 1e3/this.delay},set:function(t){t>0&&(this.delay=1e3/t)}}),Object.defineProperty(n.Animation.prototype,"enableUpdate",{get:function(){return null!==this.onUpdate},set:function(t){t&&null===this.onUpdate?this.onUpdate=new n.Signal:t||null===this.onUpdate||(this.onUpdate.dispose(),this.onUpdate=null)}}),n.Animation.generateFrameNames=function(t,e,i,s,r){void 0===s&&(s="");var o=[],a="";if(e<i)for(var h=e;h<=i;h++)a="number"==typeof r?n.Utils.pad(h.toString(),r,"0",1):h.toString(),a=t+a+s,o.push(a);else for(var h=e;h>=i;h--)a="number"==typeof r?n.Utils.pad(h.toString(),r,"0",1):h.toString(),a=t+a+s,o.push(a);return o},n.Frame=function(t,e,i,s,r,o){this.index=t,this.x=e,this.y=i,this.width=s,this.height=r,this.name=o,this.centerX=Math.floor(s/2),this.centerY=Math.floor(r/2),this.distance=n.Math.distance(0,0,s,r),this.rotated=!1,this.rotationDirection="cw",this.trimmed=!1,this.sourceSizeW=s,this.sourceSizeH=r,this.spriteSourceSizeX=0,this.spriteSourceSizeY=0,this.spriteSourceSizeW=0,this.spriteSourceSizeH=0,this.right=this.x+this.width,this.bottom=this.y+this.height},n.Frame.prototype={resize:function(t,e){this.width=t,this.height=e,this.centerX=Math.floor(t/2),this.centerY=Math.floor(e/2),this.distance=n.Math.distance(0,0,t,e),this.sourceSizeW=t,this.sourceSizeH=e,this.right=this.x+t,this.bottom=this.y+e},setTrim:function(t,e,i,s,n,r,o){this.trimmed=t,t&&(this.sourceSizeW=e,this.sourceSizeH=i,this.centerX=Math.floor(e/2),this.centerY=Math.floor(i/2),this.spriteSourceSizeX=s,this.spriteSourceSizeY=n,this.spriteSourceSizeW=r,this.spriteSourceSizeH=o)},clone:function(){var t=new n.Frame(this.index,this.x,this.y,this.width,this.height,this.name);for(var e in this)this.hasOwnProperty(e)&&(t[e]=this[e]);return t},getRect:function(t){return void 0===t?t=new n.Rectangle(this.x,this.y,this.width,this.height):t.setTo(this.x,this.y,this.width,this.height),t}},n.Frame.prototype.constructor=n.Frame,n.FrameData=function(){this._frames=[],this._frameNames=[]},n.FrameData.prototype={addFrame:function(t){return t.index=this._frames.length,this._frames.push(t),""!==t.name&&(this._frameNames[t.name]=t.index),t},getFrame:function(t){return t>=this._frames.length&&(t=0),this._frames[t]},getFrameByName:function(t){return"number"==typeof this._frameNames[t]?this._frames[this._frameNames[t]]:null},checkFrameName:function(t){return null!=this._frameNames[t]},clone:function(){for(var t=new n.FrameData,e=0;e<this._frames.length;e++)t._frames.push(this._frames[e].clone());for(var i in this._frameNames)this._frameNames.hasOwnProperty(i)&&t._frameNames.push(this._frameNames[i]);return t},getFrameRange:function(t,e,i){void 0===i&&(i=[]);for(var s=t;s<=e;s++)i.push(this._frames[s]);return i},getFrames:function(t,e,i){if(void 0===e&&(e=!0),void 0===i&&(i=[]),void 0===t||0===t.length)for(var s=0;s<this._frames.length;s++)i.push(this._frames[s]);else for(var s=0;s<t.length;s++)e?i.push(this.getFrame(t[s])):i.push(this.getFrameByName(t[s]));return i},getFrameIndexes:function(t,e,i){if(void 0===e&&(e=!0),void 0===i&&(i=[]),void 0===t||0===t.length)for(var s=0;s<this._frames.length;s++)i.push(this._frames[s].index);else for(var s=0;s<t.length;s++)e&&this._frames[t[s]]?i.push(this._frames[t[s]].index):this.getFrameByName(t[s])&&i.push(this.getFrameByName(t[s]).index);return i},destroy:function(){this._frames=null,this._frameNames=null}},n.FrameData.prototype.constructor=n.FrameData,Object.defineProperty(n.FrameData.prototype,"total",{get:function(){return this._frames.length}}),n.AnimationParser={spriteSheet:function(t,e,i,s,r,o,a){var h=e;if("string"==typeof e&&(h=t.cache.getImage(e)),null===h)return null;var l=h.width,c=h.height;i<=0&&(i=Math.floor(-l/Math.min(-1,i))),s<=0&&(s=Math.floor(-c/Math.min(-1,s)));var u=Math.floor((l-o)/(i+a)),d=Math.floor((c-o)/(s+a)),p=u*d;if(-1!==r&&(p=r),0===l||0===c||l<i||c<s||0===p)return console.warn("Phaser.AnimationParser.spriteSheet: '"+e+"'s width/height zero or width/height < given frameWidth/frameHeight"),null;for(var f=new n.FrameData,g=o,m=o,y=0;y<p;y++)f.addFrame(new n.Frame(y,g,m,i,s,"")),(g+=i+a)+i>l&&(g=o,m+=s+a);return f},JSONData:function(t,e){if(!e.frames)return console.warn("Phaser.AnimationParser.JSONData: Invalid Texture Atlas JSON given, missing 'frames' array"),void console.log(e);for(var i,s=new n.FrameData,r=e.frames,o=0;o<r.length;o++)i=s.addFrame(new n.Frame(o,r[o].frame.x,r[o].frame.y,r[o].frame.w,r[o].frame.h,r[o].filename)),r[o].trimmed&&i.setTrim(r[o].trimmed,r[o].sourceSize.w,r[o].sourceSize.h,r[o].spriteSourceSize.x,r[o].spriteSourceSize.y,r[o].spriteSourceSize.w,r[o].spriteSourceSize.h);return s},JSONDataPyxel:function(t,e){if(["layers","tilewidth","tileheight","tileswide","tileshigh"].forEach(function(t){if(!e[t])return console.warn('Phaser.AnimationParser.JSONDataPyxel: Invalid Pyxel Tilemap JSON given, missing "'+t+'" key.'),void console.log(e)}),1!==e.layers.length)return console.warn("Phaser.AnimationParser.JSONDataPyxel: Too many layers, this parser only supports flat Tilemaps."),void console.log(e);for(var i,s=new n.FrameData,r=e.tileheight,o=e.tilewidth,a=e.layers[0].tiles,h=0;h<a.length;h++)i=s.addFrame(new n.Frame(h,a[h].x,a[h].y,o,r,"frame_"+h)),i.setTrim(!1);return s},JSONDataHash:function(t,e){if(!e.frames)return console.warn("Phaser.AnimationParser.JSONDataHash: Invalid Texture Atlas JSON given, missing 'frames' object"),void console.log(e);var i,s=new n.FrameData,r=e.frames,o=0;for(var a in r)i=s.addFrame(new n.Frame(o,r[a].frame.x,r[a].frame.y,r[a].frame.w,r[a].frame.h,a)),r[a].trimmed&&i.setTrim(r[a].trimmed,r[a].sourceSize.w,r[a].sourceSize.h,r[a].spriteSourceSize.x,r[a].spriteSourceSize.y,r[a].spriteSourceSize.w,r[a].spriteSourceSize.h),o++;return s},XMLData:function(t,e){if(!e.getElementsByTagName("TextureAtlas"))return void console.warn("Phaser.AnimationParser.XMLData: Invalid Texture Atlas XML given, missing <TextureAtlas> tag");for(var i,s,r,o,a,h,l,c,u,d,p,f=new n.FrameData,g=e.getElementsByTagName("SubTexture"),m=0;m<g.length;m++)r=g[m].attributes,s=r.name.value,o=parseInt(r.x.value,10),a=parseInt(r.y.value,10),h=parseInt(r.width.value,10),l=parseInt(r.height.value,10),c=null,u=null,r.frameX&&(c=Math.abs(parseInt(r.frameX.value,10)),u=Math.abs(parseInt(r.frameY.value,10)),d=parseInt(r.frameWidth.value,10),p=parseInt(r.frameHeight.value,10)),i=f.addFrame(new n.Frame(m,o,a,h,l,s)),null===c&&null===u||i.setTrim(!0,h,l,c,u,d,p);return f}},n.Cache=function(t){this.game=t,this.autoResolveURL=!1,this._cache={canvas:{},image:{},texture:{},sound:{},video:{},text:{},json:{},xml:{},physics:{},tilemap:{},binary:{},bitmapData:{},bitmapFont:{},shader:{},renderTexture:{}},this._urlMap={},this._urlResolver=new Image,this._urlTemp=null,this.onSoundUnlock=new n.Signal,this._cacheMap=[],this._cacheMap[n.Cache.CANVAS]=this._cache.canvas,this._cacheMap[n.Cache.IMAGE]=this._cache.image,this._cacheMap[n.Cache.TEXTURE]=this._cache.texture,this._cacheMap[n.Cache.SOUND]=this._cache.sound,this._cacheMap[n.Cache.TEXT]=this._cache.text,this._cacheMap[n.Cache.PHYSICS]=this._cache.physics,this._cacheMap[n.Cache.TILEMAP]=this._cache.tilemap,this._cacheMap[n.Cache.BINARY]=this._cache.binary,this._cacheMap[n.Cache.BITMAPDATA]=this._cache.bitmapData,this._cacheMap[n.Cache.BITMAPFONT]=this._cache.bitmapFont,this._cacheMap[n.Cache.JSON]=this._cache.json,this._cacheMap[n.Cache.XML]=this._cache.xml,this._cacheMap[n.Cache.VIDEO]=this._cache.video,this._cacheMap[n.Cache.SHADER]=this._cache.shader,this._cacheMap[n.Cache.RENDER_TEXTURE]=this._cache.renderTexture,this.addDefaultImage(),this.addMissingImage()},n.Cache.CANVAS=1,n.Cache.IMAGE=2,n.Cache.TEXTURE=3,n.Cache.SOUND=4,n.Cache.TEXT=5,n.Cache.PHYSICS=6,n.Cache.TILEMAP=7,n.Cache.BINARY=8,n.Cache.BITMAPDATA=9,n.Cache.BITMAPFONT=10,n.Cache.JSON=11,n.Cache.XML=12,n.Cache.VIDEO=13,n.Cache.SHADER=14,n.Cache.RENDER_TEXTURE=15,n.Cache.DEFAULT=null,n.Cache.MISSING=null,n.Cache.prototype={addCanvas:function(t,e,i){void 0===i&&(i=e.getContext("2d")),this._cache.canvas[t]={canvas:e,context:i}},addImage:function(t,e,i){this.checkImageKey(t)&&this.removeImage(t);var s={key:t,url:e,data:i,base:new PIXI.BaseTexture(i),frame:new n.Frame(0,0,0,i.width,i.height,t),frameData:new n.FrameData};return s.frameData.addFrame(new n.Frame(0,0,0,i.width,i.height,e)),this._cache.image[t]=s,this._resolveURL(e,s),"__default"===t?n.Cache.DEFAULT=new PIXI.Texture(s.base):"__missing"===t&&(n.Cache.MISSING=new PIXI.Texture(s.base)),s},addDefaultImage:function(){var t=new Image;t.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgAQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg==";var e=this.addImage("__default",null,t);e.base.skipRender=!0,n.Cache.DEFAULT=new PIXI.Texture(e.base)},addMissingImage:function(){var t=new Image;t.src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg==";var e=this.addImage("__missing",null,t);n.Cache.MISSING=new PIXI.Texture(e.base)},addSound:function(t,e,i,s,n){void 0===s&&(s=!0,n=!1),void 0===n&&(s=!1,n=!0);var r=!1;n&&(r=!0),this._cache.sound[t]={url:e,data:i,isDecoding:!1,decoded:r,webAudio:s,audioTag:n,locked:this.game.sound.touchLocked},this._resolveURL(e,this._cache.sound[t])},addText:function(t,e,i){this._cache.text[t]={url:e,data:i},this._resolveURL(e,this._cache.text[t])},addPhysicsData:function(t,e,i,s){this._cache.physics[t]={url:e,data:i,format:s},this._resolveURL(e,this._cache.physics[t])},addTilemap:function(t,e,i,s){this._cache.tilemap[t]={url:e,data:i,format:s},this._resolveURL(e,this._cache.tilemap[t])},addBinary:function(t,e){this._cache.binary[t]=e},addBitmapData:function(t,e,i){return e.key=t,void 0===i&&(i=new n.FrameData,i.addFrame(e.textureFrame)),this._cache.bitmapData[t]={data:e,frameData:i},e},addBitmapFont:function(t,e,i,s,r,o,a){var h={url:e,data:i,font:null,base:new PIXI.BaseTexture(i)};void 0===o&&(o=0),void 0===a&&(a=0),h.font="json"===r?n.LoaderParser.jsonBitmapFont(s,h.base,o,a):n.LoaderParser.xmlBitmapFont(s,h.base,o,a),this._cache.bitmapFont[t]=h,this._resolveURL(e,h)},addJSON:function(t,e,i){this._cache.json[t]={url:e,data:i},this._resolveURL(e,this._cache.json[t])},addXML:function(t,e,i){this._cache.xml[t]={url:e,data:i},this._resolveURL(e,this._cache.xml[t])},addVideo:function(t,e,i,s){this._cache.video[t]={url:e,data:i,isBlob:s,locked:!0},this._resolveURL(e,this._cache.video[t])},addShader:function(t,e,i){this._cache.shader[t]={url:e,data:i},this._resolveURL(e,this._cache.shader[t])},addRenderTexture:function(t,e){this._cache.renderTexture[t]={texture:e,frame:new n.Frame(0,0,0,e.width,e.height,"","")}},addSpriteSheet:function(t,e,i,s,r,o,a,h){void 0===o&&(o=-1),void 0===a&&(a=0),void 0===h&&(h=0);var l={key:t,url:e,data:i,frameWidth:s,frameHeight:r,margin:a,spacing:h,base:new PIXI.BaseTexture(i),frameData:n.AnimationParser.spriteSheet(this.game,i,s,r,o,a,h)};this._cache.image[t]=l,this._resolveURL(e,l)},addTextureAtlas:function(t,e,i,s,r){var o={key:t,url:e,data:i,base:new PIXI.BaseTexture(i)};r===n.Loader.TEXTURE_ATLAS_XML_STARLING?o.frameData=n.AnimationParser.XMLData(this.game,s,t):r===n.Loader.TEXTURE_ATLAS_JSON_PYXEL?o.frameData=n.AnimationParser.JSONDataPyxel(this.game,s,t):Array.isArray(s.frames)?o.frameData=n.AnimationParser.JSONData(this.game,s,t):o.frameData=n.AnimationParser.JSONDataHash(this.game,s,t),this._cache.image[t]=o,this._resolveURL(e,o)},reloadSound:function(t){var e=this,i=this.getSound(t);i&&(i.data.src=i.url,i.data.addEventListener("canplaythrough",function(){return e.reloadSoundComplete(t)},!1),i.data.load())},reloadSoundComplete:function(t){var e=this.getSound(t);e&&(e.locked=!1,this.onSoundUnlock.dispatch(t))},updateSound:function(t,e,i){var s=this.getSound(t);s&&(s[e]=i)},decodedSound:function(t,e){var i=this.getSound(t);i.data=e,i.decoded=!0,i.isDecoding=!1},isSoundDecoded:function(t){var e=this.getItem(t,n.Cache.SOUND,"isSoundDecoded");if(e)return e.decoded},isSoundReady:function(t){var e=this.getItem(t,n.Cache.SOUND,"isSoundDecoded");if(e)return e.decoded&&!this.game.sound.touchLocked},checkKey:function(t,e){return!!this._cacheMap[t][e]},checkURL:function(t){return!!this._urlMap[this._resolveURL(t)]},checkCanvasKey:function(t){return this.checkKey(n.Cache.CANVAS,t)},checkImageKey:function(t){return this.checkKey(n.Cache.IMAGE,t)},checkTextureKey:function(t){return this.checkKey(n.Cache.TEXTURE,t)},checkSoundKey:function(t){return this.checkKey(n.Cache.SOUND,t)},checkTextKey:function(t){return this.checkKey(n.Cache.TEXT,t)},checkPhysicsKey:function(t){return this.checkKey(n.Cache.PHYSICS,t)},checkTilemapKey:function(t){return this.checkKey(n.Cache.TILEMAP,t)},checkBinaryKey:function(t){return this.checkKey(n.Cache.BINARY,t)},checkBitmapDataKey:function(t){return this.checkKey(n.Cache.BITMAPDATA,t)},checkBitmapFontKey:function(t){return this.checkKey(n.Cache.BITMAPFONT,t)},checkJSONKey:function(t){return this.checkKey(n.Cache.JSON,t)},checkXMLKey:function(t){return this.checkKey(n.Cache.XML,t)},checkVideoKey:function(t){return this.checkKey(n.Cache.VIDEO,t)},checkShaderKey:function(t){return this.checkKey(n.Cache.SHADER,t)},checkRenderTextureKey:function(t){return this.checkKey(n.Cache.RENDER_TEXTURE,t)},getItem:function(t,e,i,s){return this.checkKey(e,t)?void 0===s?this._cacheMap[e][t]:this._cacheMap[e][t][s]:(i&&console.warn("Phaser.Cache."+i+': Key "'+t+'" not found in Cache.'),null)},getCanvas:function(t){return this.getItem(t,n.Cache.CANVAS,"getCanvas","canvas")},getImage:function(t,e){void 0!==t&&null!==t||(t="__default"),void 0===e&&(e=!1);var i=this.getItem(t,n.Cache.IMAGE,"getImage");return null===i&&(i=this.getItem("__missing",n.Cache.IMAGE,"getImage")),e?i:i.data},getTextureFrame:function(t){return this.getItem(t,n.Cache.TEXTURE,"getTextureFrame","frame")},getSound:function(t){return this.getItem(t,n.Cache.SOUND,"getSound")},getSoundData:function(t){return this.getItem(t,n.Cache.SOUND,"getSoundData","data")},getText:function(t){return this.getItem(t,n.Cache.TEXT,"getText","data")},getPhysicsData:function(t,e,i){var s=this.getItem(t,n.Cache.PHYSICS,"getPhysicsData","data");if(null===s||void 0===e||null===e)return s;if(s[e]){var r=s[e];if(!r||!i)return r;for(var o in r)if(o=r[o],o.fixtureKey===i)return o;console.warn('Phaser.Cache.getPhysicsData: Could not find given fixtureKey: "'+i+" in "+t+'"')}else console.warn('Phaser.Cache.getPhysicsData: Invalid key/object: "'+t+" / "+e+'"');return null},getTilemapData:function(t){return this.getItem(t,n.Cache.TILEMAP,"getTilemapData")},getBinary:function(t){return this.getItem(t,n.Cache.BINARY,"getBinary")},getBitmapData:function(t){return this.getItem(t,n.Cache.BITMAPDATA,"getBitmapData","data")},getBitmapFont:function(t){return this.getItem(t,n.Cache.BITMAPFONT,"getBitmapFont")},getJSON:function(t,e){var i=this.getItem(t,n.Cache.JSON,"getJSON","data");return i?e?n.Utils.extend(!0,Array.isArray(i)?[]:{},i):i:null},getXML:function(t){return this.getItem(t,n.Cache.XML,"getXML","data")},getVideo:function(t){return this.getItem(t,n.Cache.VIDEO,"getVideo")},getShader:function(t){return this.getItem(t,n.Cache.SHADER,"getShader","data")},getRenderTexture:function(t){return this.getItem(t,n.Cache.RENDER_TEXTURE,"getRenderTexture")},getBaseTexture:function(t,e){return void 0===e&&(e=n.Cache.IMAGE),this.getItem(t,e,"getBaseTexture","base")},getFrame:function(t,e){return void 0===e&&(e=n.Cache.IMAGE),this.getItem(t,e,"getFrame","frame")},getFrameCount:function(t,e){var i=this.getFrameData(t,e);return i?i.total:0},getFrameData:function(t,e){return void 0===e&&(e=n.Cache.IMAGE),this.getItem(t,e,"getFrameData","frameData")},hasFrameData:function(t,e){return void 0===e&&(e=n.Cache.IMAGE),null!==this.getItem(t,e,"","frameData")},updateFrameData:function(t,e,i){void 0===i&&(i=n.Cache.IMAGE),this._cacheMap[i][t]&&(this._cacheMap[i][t].frameData=e)},getFrameByIndex:function(t,e,i){var s=this.getFrameData(t,i);return s?s.getFrame(e):null},getFrameByName:function(t,e,i){var s=this.getFrameData(t,i);return s?s.getFrameByName(e):null},getURL:function(t){var t=this._resolveURL(t);return t?this._urlMap[t]:(console.warn('Phaser.Cache.getUrl: Invalid url: "'+t+'" or Cache.autoResolveURL was false'),null)},getKeys:function(t){void 0===t&&(t=n.Cache.IMAGE);var e=[];if(this._cacheMap[t])for(var i in this._cacheMap[t])"__default"!==i&&"__missing"!==i&&e.push(i);return e},removeCanvas:function(t){delete this._cache.canvas[t]},removeImage:function(t,e){void 0===e&&(e=!0);var i=this.getImage(t,!0);e&&i.base&&i.base.destroy(),delete this._cache.image[t]},removeSound:function(t){delete this._cache.sound[t]},removeText:function(t){delete this._cache.text[t]},removePhysics:function(t){delete this._cache.physics[t]},removeTilemap:function(t){delete this._cache.tilemap[t]},removeBinary:function(t){delete this._cache.binary[t]},removeBitmapData:function(t){delete this._cache.bitmapData[t]},removeBitmapFont:function(t){delete this._cache.bitmapFont[t]},removeJSON:function(t){delete this._cache.json[t]},removeXML:function(t){delete this._cache.xml[t]},removeVideo:function(t){delete this._cache.video[t]},removeShader:function(t){delete this._cache.shader[t]},removeRenderTexture:function(t){delete this._cache.renderTexture[t]},removeSpriteSheet:function(t){delete this._cache.spriteSheet[t]},removeTextureAtlas:function(t){delete this._cache.atlas[t]},clearGLTextures:function(){for(var t in this._cache.image)this._cache.image[t].base._glTextures=[]},_resolveURL:function(t,e){return this.autoResolveURL?(this._urlResolver.src=this.game.load.baseURL+t,this._urlTemp=this._urlResolver.src,this._urlResolver.src="",e&&(this._urlMap[this._urlTemp]=e),this._urlTemp):null},destroy:function(){for(var t=0;t<this._cacheMap.length;t++){var e=this._cacheMap[t];for(var i in e)"__default"!==i&&"__missing"!==i&&(e[i].destroy&&e[i].destroy(),delete e[i])}this._urlMap=null,this._urlResolver=null,this._urlTemp=null}},n.Cache.prototype.constructor=n.Cache,n.Loader=function(t){this.game=t,this.cache=t.cache,this.resetLocked=!1,this.isLoading=!1,this.hasLoaded=!1,this.preloadSprite=null,this.crossOrigin=!1,this.baseURL="",this.path="",this.headers={requestedWith:!1,json:"application/json",xml:"application/xml"},this.onLoadStart=new n.Signal,this.onLoadComplete=new n.Signal,this.onPackComplete=new n.Signal,this.onFileStart=new n.Signal,this.onFileComplete=new n.Signal,this.onFileError=new n.Signal,this.useXDomainRequest=!1,this._warnedAboutXDomainRequest=!1,this.enableParallel=!0,this.maxParallelDownloads=4,this._withSyncPointDepth=0,this._fileList=[],this._flightQueue=[],this._processingHead=0,this._fileLoadStarted=!1,this._totalPackCount=0,this._totalFileCount=0,this._loadedPackCount=0,this._loadedFileCount=0},n.Loader.TEXTURE_ATLAS_JSON_ARRAY=0,n.Loader.TEXTURE_ATLAS_JSON_HASH=1,n.Loader.TEXTURE_ATLAS_XML_STARLING=2,n.Loader.PHYSICS_LIME_CORONA_JSON=3,n.Loader.PHYSICS_PHASER_JSON=4,n.Loader.TEXTURE_ATLAS_JSON_PYXEL=5,n.Loader.prototype={setPreloadSprite:function(t,e){e=e||0,this.preloadSprite={sprite:t,direction:e,width:t.width,height:t.height,rect:null},this.preloadSprite.rect=0===e?new n.Rectangle(0,0,1,t.height):new n.Rectangle(0,0,t.width,1),t.crop(this.preloadSprite.rect),t.visible=!0},resize:function(){this.preloadSprite&&this.preloadSprite.height!==this.preloadSprite.sprite.height&&(this.preloadSprite.rect.height=this.preloadSprite.sprite.height)},checkKeyExists:function(t,e){return this.getAssetIndex(t,e)>-1},getAssetIndex:function(t,e){for(var i=-1,s=0;s<this._fileList.length;s++){var n=this._fileList[s];if(n.type===t&&n.key===e&&(i=s,!n.loaded&&!n.loading))break}return i},getAsset:function(t,e){var i=this.getAssetIndex(t,e);return i>-1&&{index:i,file:this._fileList[i]}},reset:function(t,e){void 0===e&&(e=!1),this.resetLocked||(t&&(this.preloadSprite=null),this.isLoading=!1,this._processingHead=0,this._fileList.length=0,this._flightQueue.length=0,this._fileLoadStarted=!1,this._totalFileCount=0,this._totalPackCount=0,this._loadedPackCount=0,this._loadedFileCount=0,e&&(this.onLoadStart.removeAll(),this.onLoadComplete.removeAll(),this.onPackComplete.removeAll(),this.onFileStart.removeAll(),this.onFileComplete.removeAll(),this.onFileError.removeAll()))},addToFileList:function(t,e,i,s,n,r){if(void 0===n&&(n=!1),void 0===e||""===e)return console.warn("Phaser.Loader: Invalid or no key given of type "+t),this;if(void 0===i||null===i){if(!r)return console.warn("Phaser.Loader: No URL given for file type: "+t+" key: "+e),this;i=e+r}var o={type:t,key:e,path:this.path,url:i,syncPoint:this._withSyncPointDepth>0,data:null,loading:!1,loaded:!1,error:!1};if(s)for(var a in s)o[a]=s[a];var h=this.getAssetIndex(t,e);if(n&&h>-1){var l=this._fileList[h];l.loading||l.loaded?(this._fileList.push(o),this._totalFileCount++):this._fileList[h]=o}else-1===h&&(this._fileList.push(o),this._totalFileCount++);return this},replaceInFileList:function(t,e,i,s){return this.addToFileList(t,e,i,s,!0)},pack:function(t,e,i,s){if(void 0===e&&(e=null),void 0===i&&(i=null),void 0===s&&(s=null),!e&&!i)return console.warn("Phaser.Loader.pack - Both url and data are null. One must be set."),this;var n={type:"packfile",key:t,url:e,path:this.path,syncPoint:!0,data:null,loading:!1,loaded:!1,error:!1,callbackContext:s};i&&("string"==typeof i&&(i=JSON.parse(i)),n.data=i||{},n.loaded=!0);for(var r=0;r<this._fileList.length+1;r++){var o=this._fileList[r];if(!o||!o.loaded&&!o.loading&&"packfile"!==o.type){this._fileList.splice(r,0,n),this._totalPackCount++;break}}return this},image:function(t,e,i){return this.addToFileList("image",t,e,void 0,i,".png")},images:function(t,e){if(Array.isArray(e))for(var i=0;i<t.length;i++)this.image(t[i],e[i]);else for(var i=0;i<t.length;i++)this.image(t[i]);return this},text:function(t,e,i){return this.addToFileList("text",t,e,void 0,i,".txt")},json:function(t,e,i){return this.addToFileList("json",t,e,void 0,i,".json")},shader:function(t,e,i){return this.addToFileList("shader",t,e,void 0,i,".frag")},xml:function(t,e,i){return this.addToFileList("xml",t,e,void 0,i,".xml")},script:function(t,e,i,s){return void 0===i&&(i=!1),!1!==i&&void 0===s&&(s=this),this.addToFileList("script",t,e,{syncPoint:!0,callback:i,callbackContext:s},!1,".js")},binary:function(t,e,i,s){return void 0===i&&(i=!1),!1!==i&&void 0===s&&(s=i),this.addToFileList("binary",t,e,{callback:i,callbackContext:s},!1,".bin")},spritesheet:function(t,e,i,s,n,r,o){return void 0===n&&(n=-1),void 0===r&&(r=0),void 0===o&&(o=0),this.addToFileList("spritesheet",t,e,{frameWidth:i,frameHeight:s,frameMax:n,margin:r,spacing:o},!1,".png")},audio:function(t,e,i){return this.game.sound.noAudio?this:(void 0===i&&(i=!0),"string"==typeof e&&(e=[e]),this.addToFileList("audio",t,e,{buffer:null,autoDecode:i}))},audioSprite:function(t,e,i,s,n){return this.game.sound.noAudio?this:(void 0===i&&(i=null),void 0===s&&(s=null),void 0===n&&(n=!0),this.audio(t,e,n),i?this.json(t+"-audioatlas",i):s?("string"==typeof s&&(s=JSON.parse(s)),this.cache.addJSON(t+"-audioatlas","",s)):console.warn("Phaser.Loader.audiosprite - You must specify either a jsonURL or provide a jsonData object"),this)},audiosprite:function(t,e,i,s,n){return this.audioSprite(t,e,i,s,n)},video:function(t,e,i,s){return void 0===i&&(i=this.game.device.firefox?"loadeddata":"canplaythrough"),void 0===s&&(s=!1),"string"==typeof e&&(e=[e]),this.addToFileList("video",t,e,{buffer:null,asBlob:s,loadEvent:i})},tilemap:function(t,e,i,s){if(void 0===e&&(e=null),void 0===i&&(i=null),void 0===s&&(s=n.Tilemap.CSV),e||i||(e=s===n.Tilemap.CSV?t+".csv":t+".json"),i){switch(s){case n.Tilemap.CSV:break;case n.Tilemap.TILED_JSON:"string"==typeof i&&(i=JSON.parse(i))}this.cache.addTilemap(t,null,i,s)}else this.addToFileList("tilemap",t,e,{format:s});return this},physics:function(t,e,i,s){return void 0===e&&(e=null),void 0===i&&(i=null),void 0===s&&(s=n.Physics.LIME_CORONA_JSON),e||i||(e=t+".json"),i?("string"==typeof i&&(i=JSON.parse(i)),this.cache.addPhysicsData(t,null,i,s)):this.addToFileList("physics",t,e,{format:s}),this},bitmapFont:function(t,e,i,s,n,r){if(void 0!==e&&null!==e||(e=t+".png"),void 0===i&&(i=null),void 0===s&&(s=null),null===i&&null===s&&(i=t+".xml"),void 0===n&&(n=0),void 0===r&&(r=0),i)this.addToFileList("bitmapfont",t,e,{atlasURL:i,xSpacing:n,ySpacing:r});else if("string"==typeof s){var o,a;try{o=JSON.parse(s)}catch(t){a=this.parseXml(s)}if(!a&&!o)throw new Error("Phaser.Loader. Invalid Bitmap Font atlas given");this.addToFileList("bitmapfont",t,e,{atlasURL:null,atlasData:o||a,atlasType:o?"json":"xml",xSpacing:n,ySpacing:r})}return this},atlasJSONArray:function(t,e,i,s){return this.atlas(t,e,i,s,n.Loader.TEXTURE_ATLAS_JSON_ARRAY)},atlasJSONHash:function(t,e,i,s){return this.atlas(t,e,i,s,n.Loader.TEXTURE_ATLAS_JSON_HASH)},atlasXML:function(t,e,i,s){return void 0===i&&(i=null),void 0===s&&(s=null),i||s||(i=t+".xml"),this.atlas(t,e,i,s,n.Loader.TEXTURE_ATLAS_XML_STARLING)},atlas:function(t,e,i,s,r){if(void 0!==e&&null!==e||(e=t+".png"),void 0===i&&(i=null),void 0===s&&(s=null),void 0===r&&(r=n.Loader.TEXTURE_ATLAS_JSON_ARRAY),i||s||(i=r===n.Loader.TEXTURE_ATLAS_XML_STARLING?t+".xml":t+".json"),i)this.addToFileList("textureatlas",t,e,{atlasURL:i,format:r});else{switch(r){case n.Loader.TEXTURE_ATLAS_JSON_ARRAY:"string"==typeof s&&(s=JSON.parse(s));break;case n.Loader.TEXTURE_ATLAS_XML_STARLING:if("string"==typeof s){var o=this.parseXml(s);if(!o)throw new Error("Phaser.Loader. Invalid Texture Atlas XML given");s=o}}this.addToFileList("textureatlas",t,e,{atlasURL:null,atlasData:s,format:r})}return this},withSyncPoint:function(t,e){this._withSyncPointDepth++;try{t.call(e||this,this)}finally{this._withSyncPointDepth--}return this},addSyncPoint:function(t,e){var i=this.getAsset(t,e);return i&&(i.file.syncPoint=!0),this},removeFile:function(t,e){var i=this.getAsset(t,e);i&&(i.loaded||i.loading||this._fileList.splice(i.index,1))},removeAll:function(){this._fileList.length=0,this._flightQueue.length=0},start:function(){this.isLoading||(this.hasLoaded=!1,this.isLoading=!0,this.updateProgress(),this.processLoadQueue())},processLoadQueue:function(){if(!this.isLoading)return console.warn("Phaser.Loader - active loading canceled / reset"),void this.finishedLoading(!0);for(var t=0;t<this._flightQueue.length;t++){var e=this._flightQueue[t];(e.loaded||e.error)&&(this._flightQueue.splice(t,1),t--,e.loading=!1,e.requestUrl=null,e.requestObject=null,e.error&&this.onFileError.dispatch(e.key,e),"packfile"!==e.type?(this._loadedFileCount++,this.onFileComplete.dispatch(this.progress,e.key,!e.error,this._loadedFileCount,this._totalFileCount)):"packfile"===e.type&&e.error&&(this._loadedPackCount++,this.onPackComplete.dispatch(e.key,!e.error,this._loadedPackCount,this._totalPackCount)))}for(var i=!1,s=this.enableParallel?n.Math.clamp(this.maxParallelDownloads,1,12):1,t=this._processingHead;t<this._fileList.length;t++){var e=this._fileList[t];if("packfile"===e.type&&!e.error&&e.loaded&&t===this._processingHead&&(this.processPack(e),this._loadedPackCount++,this.onPackComplete.dispatch(e.key,!e.error,this._loadedPackCount,this._totalPackCount)),e.loaded||e.error?t===this._processingHead&&(this._processingHead=t+1):!e.loading&&this._flightQueue.length<s&&("packfile"!==e.type||e.data?i||(this._fileLoadStarted||(this._fileLoadStarted=!0,this.onLoadStart.dispatch()),this._flightQueue.push(e),e.loading=!0,this.onFileStart.dispatch(this.progress,e.key,e.url),this.loadFile(e)):(this._flightQueue.push(e),e.loading=!0,this.loadFile(e))),!e.loaded&&e.syncPoint&&(i=!0),this._flightQueue.length>=s||i&&this._loadedPackCount===this._totalPackCount)break}if(this.updateProgress(),this._processingHead>=this._fileList.length)this.finishedLoading();else if(!this._flightQueue.length){console.warn("Phaser.Loader - aborting: processing queue empty, loading may have stalled");var r=this;setTimeout(function(){r.finishedLoading(!0)},2e3)}},finishedLoading:function(t){this.hasLoaded||(this.hasLoaded=!0,this.isLoading=!1,t||this._fileLoadStarted||(this._fileLoadStarted=!0,this.onLoadStart.dispatch()),this.onLoadComplete.dispatch(),this.game.state.loadComplete(),this.reset())},asyncComplete:function(t,e){void 0===e&&(e=""),t.loaded=!0,t.error=!!e,e&&(t.errorMessage=e,console.warn("Phaser.Loader - "+t.type+"["+t.key+"]: "+e)),this.processLoadQueue()},processPack:function(t){var e=t.data[t.key];if(!e)return void console.warn("Phaser.Loader - "+t.key+": pack has data, but not for pack key");for(var i=0;i<e.length;i++){var s=e[i];switch(s.type){case"image":this.image(s.key,s.url,s.overwrite);break;case"text":this.text(s.key,s.url,s.overwrite);break;case"json":this.json(s.key,s.url,s.overwrite);break;case"xml":this.xml(s.key,s.url,s.overwrite);break;case"script":this.script(s.key,s.url,s.callback,t.callbackContext||this);break;case"binary":this.binary(s.key,s.url,s.callback,t.callbackContext||this);break;case"spritesheet":this.spritesheet(s.key,s.url,s.frameWidth,s.frameHeight,s.frameMax,s.margin,s.spacing);break;case"video":this.video(s.key,s.urls);break;case"audio":this.audio(s.key,s.urls,s.autoDecode);break;case"audiosprite":this.audiosprite(s.key,s.urls,s.jsonURL,s.jsonData,s.autoDecode);break;case"tilemap":this.tilemap(s.key,s.url,s.data,n.Tilemap[s.format]);break;case"physics":this.physics(s.key,s.url,s.data,n.Loader[s.format]);break;case"bitmapFont":this.bitmapFont(s.key,s.textureURL,s.atlasURL,s.atlasData,s.xSpacing,s.ySpacing);break;case"atlasJSONArray":this.atlasJSONArray(s.key,s.textureURL,s.atlasURL,s.atlasData);break;case"atlasJSONHash":this.atlasJSONHash(s.key,s.textureURL,s.atlasURL,s.atlasData);break;case"atlasXML":this.atlasXML(s.key,s.textureURL,s.atlasURL,s.atlasData);break;case"atlas":this.atlas(s.key,s.textureURL,s.atlasURL,s.atlasData,n.Loader[s.format]);break;case"shader":this.shader(s.key,s.url,s.overwrite)}}},transformUrl:function(t,e){return!!t&&(t.match(/^(?:blob:|data:|http:\/\/|https:\/\/|\/\/)/)?t:this.baseURL+e.path+t)},loadFile:function(t){switch(t.type){case"packfile":this.xhrLoad(t,this.transformUrl(t.url,t),"text",this.fileComplete);break;case"image":case"spritesheet":case"textureatlas":case"bitmapfont":this.loadImageTag(t);break;case"audio":t.url=this.getAudioURL(t.url),t.url?this.game.sound.usingWebAudio?this.xhrLoad(t,this.transformUrl(t.url,t),"arraybuffer",this.fileComplete):this.game.sound.usingAudioTag&&this.loadAudioTag(t):this.fileError(t,null,"No supported audio URL specified or device does not have audio playback support");break;case"video":t.url=this.getVideoURL(t.url),t.url?t.asBlob?this.xhrLoad(t,this.transformUrl(t.url,t),"blob",this.fileComplete):this.loadVideoTag(t):this.fileError(t,null,"No supported video URL specified or device does not have video playback support");break;case"json":this.xhrLoad(t,this.transformUrl(t.url,t),"text",this.jsonLoadComplete);break;case"xml":this.xhrLoad(t,this.transformUrl(t.url,t),"text",this.xmlLoadComplete);break;case"tilemap":t.format===n.Tilemap.TILED_JSON?this.xhrLoad(t,this.transformUrl(t.url,t),"text",this.jsonLoadComplete):t.format===n.Tilemap.CSV?this.xhrLoad(t,this.transformUrl(t.url,t),"text",this.csvLoadComplete):this.asyncComplete(t,"invalid Tilemap format: "+t.format);break;case"text":case"script":case"shader":case"physics":this.xhrLoad(t,this.transformUrl(t.url,t),"text",this.fileComplete);break;case"binary":this.xhrLoad(t,this.transformUrl(t.url,t),"arraybuffer",this.fileComplete)}},loadImageTag:function(t){var e=this;t.data=new Image,t.data.name=t.key,this.crossOrigin&&(t.data.crossOrigin=this.crossOrigin),t.data.onload=function(){t.data.onload&&(t.data.onload=null,t.data.onerror=null,e.fileComplete(t))},t.data.onerror=function(){t.data.onload&&(t.data.onload=null,t.data.onerror=null,e.fileError(t))},t.data.src=this.transformUrl(t.url,t),t.data.complete&&t.data.width&&t.data.height&&(t.data.onload=null,t.data.onerror=null,this.fileComplete(t))},loadVideoTag:function(t){var e=this;t.data=document.createElement("video"),t.data.name=t.key,t.data.controls=!1,t.data.autoplay=!1;var i=function(){t.data.removeEventListener(t.loadEvent,i,!1),t.data.onerror=null,t.data.canplay=!0,n.GAMES[e.game.id].load.fileComplete(t)};t.data.onerror=function(){t.data.removeEventListener(t.loadEvent,i,!1),t.data.onerror=null,t.data.canplay=!1,e.fileError(t)},t.data.addEventListener(t.loadEvent,i,!1),t.data.src=this.transformUrl(t.url,t),t.data.load()},loadAudioTag:function(t){var e=this;if(this.game.sound.touchLocked)t.data=new Audio,t.data.name=t.key,t.data.preload="auto",t.data.src=this.transformUrl(t.url,t),this.fileComplete(t);else{t.data=new Audio,t.data.name=t.key;var i=function(){t.data.removeEventListener("canplaythrough",i,!1),t.data.onerror=null,e.fileComplete(t)};t.data.onerror=function(){t.data.removeEventListener("canplaythrough",i,!1),t.data.onerror=null,e.fileError(t)},t.data.preload="auto",t.data.src=this.transformUrl(t.url,t),t.data.addEventListener("canplaythrough",i,!1),t.data.load()}},xhrLoad:function(t,e,i,s,n){if(this.useXDomainRequest&&window.XDomainRequest)return void this.xhrLoadWithXDR(t,e,i,s,n);var r=new XMLHttpRequest;r.open("GET",e,!0),r.responseType=i,!1!==this.headers.requestedWith&&r.setRequestHeader("X-Requested-With",this.headers.requestedWith),this.headers[t.type]&&r.setRequestHeader("Accept",this.headers[t.type]),n=n||this.fileError;var o=this;r.onload=function(){try{return 4===r.readyState&&r.status>=400&&r.status<=599?n.call(o,t,r):s.call(o,t,r)}catch(e){o.hasLoaded?window.console&&console.error(e):o.asyncComplete(t,e.message||"Exception")}},r.onerror=function(){try{return n.call(o,t,r)}catch(e){o.hasLoaded?window.console&&console.error(e):o.asyncComplete(t,e.message||"Exception")}},t.requestObject=r,t.requestUrl=e,r.send()},xhrLoadWithXDR:function(t,e,i,s,n){this._warnedAboutXDomainRequest||this.game.device.ie&&!(this.game.device.ieVersion>=10)||(this._warnedAboutXDomainRequest=!0,console.warn("Phaser.Loader - using XDomainRequest outside of IE 9"));var r=new window.XDomainRequest;r.open("GET",e,!0),r.responseType=i,r.timeout=3e3,n=n||this.fileError;var o=this;r.onerror=function(){try{return n.call(o,t,r)}catch(e){o.asyncComplete(t,e.message||"Exception")}},r.ontimeout=function(){try{return n.call(o,t,r)}catch(e){o.asyncComplete(t,e.message||"Exception")}},r.onprogress=function(){},r.onload=function(){try{return 4===r.readyState&&r.status>=400&&r.status<=599?n.call(o,t,r):s.call(o,t,r)}catch(e){o.asyncComplete(t,e.message||"Exception")}},t.requestObject=r,t.requestUrl=e,setTimeout(function(){r.send()},0)},getVideoURL:function(t){for(var e=0;e<t.length;e++){var i,s=t[e];if(s.uri){if(i=s.type,s=s.uri,this.game.device.canPlayVideo(i))return s}else{if(0===s.indexOf("blob:")||0===s.indexOf("data:"))return s;s.indexOf("?")>=0&&(s=s.substr(0,s.indexOf("?")));if(i=s.substr((Math.max(0,s.lastIndexOf("."))||1/0)+1).toLowerCase(),this.game.device.canPlayVideo(i))return t[e]}}return null},getAudioURL:function(t){if(this.game.sound.noAudio)return null;for(var e=0;e<t.length;e++){var i,s=t[e];if(s.uri){if(i=s.type,s=s.uri,this.game.device.canPlayAudio(i))return s}else{if(0===s.indexOf("blob:")||0===s.indexOf("data:"))return s;s.indexOf("?")>=0&&(s=s.substr(0,s.indexOf("?")));if(i=s.substr((Math.max(0,s.lastIndexOf("."))||1/0)+1).toLowerCase(),this.game.device.canPlayAudio(i))return t[e]}}return null},fileError:function(t,e,i){var s=t.requestUrl||this.transformUrl(t.url,t),n="error loading asset from URL "+s;!i&&e&&(i=e.status),i&&(n=n+" ("+i+")"),this.asyncComplete(t,n)},fileComplete:function(t,e){var i=!0;switch(t.type){case"packfile":var s=JSON.parse(e.responseText);t.data=s||{};break;case"image":this.cache.addImage(t.key,t.url,t.data);break;case"spritesheet":this.cache.addSpriteSheet(t.key,t.url,t.data,t.frameWidth,t.frameHeight,t.frameMax,t.margin,t.spacing);break;case"textureatlas":if(null==t.atlasURL)this.cache.addTextureAtlas(t.key,t.url,t.data,t.atlasData,t.format);else if(i=!1,t.format===n.Loader.TEXTURE_ATLAS_JSON_ARRAY||t.format===n.Loader.TEXTURE_ATLAS_JSON_HASH||t.format===n.Loader.TEXTURE_ATLAS_JSON_PYXEL)this.xhrLoad(t,this.transformUrl(t.atlasURL,t),"text",this.jsonLoadComplete);else{if(t.format!==n.Loader.TEXTURE_ATLAS_XML_STARLING)throw new Error("Phaser.Loader. Invalid Texture Atlas format: "+t.format);this.xhrLoad(t,this.transformUrl(t.atlasURL,t),"text",this.xmlLoadComplete)}break;case"bitmapfont":t.atlasURL?(i=!1,this.xhrLoad(t,this.transformUrl(t.atlasURL,t),"text",function(t,e){var i;try{i=JSON.parse(e.responseText)}catch(t){}i?(t.atlasType="json",this.jsonLoadComplete(t,e)):(t.atlasType="xml",this.xmlLoadComplete(t,e))})):this.cache.addBitmapFont(t.key,t.url,t.data,t.atlasData,t.atlasType,t.xSpacing,t.ySpacing);break;case"video":if(t.asBlob)try{t.data=e.response}catch(e){throw new Error("Phaser.Loader. Unable to parse video file as Blob: "+t.key)}this.cache.addVideo(t.key,t.url,t.data,t.asBlob);break;case"audio":this.game.sound.usingWebAudio?(t.data=e.response,this.cache.addSound(t.key,t.url,t.data,!0,!1),t.autoDecode&&this.game.sound.decode(t.key)):this.cache.addSound(t.key,t.url,t.data,!1,!0);break;case"text":t.data=e.responseText,this.cache.addText(t.key,t.url,t.data);break;case"shader":t.data=e.responseText,this.cache.addShader(t.key,t.url,t.data);break;case"physics":var s=JSON.parse(e.responseText);this.cache.addPhysicsData(t.key,t.url,s,t.format);break;case"script":t.data=document.createElement("script"),t.data.language="javascript",t.data.type="text/javascript",t.data.defer=!1,t.data.text=e.responseText,document.head.appendChild(t.data),t.callback&&(t.data=t.callback.call(t.callbackContext,t.key,e.responseText));break;case"binary":t.callback?t.data=t.callback.call(t.callbackContext,t.key,e.response):t.data=e.response,this.cache.addBinary(t.key,t.data)}i&&this.asyncComplete(t)},jsonLoadComplete:function(t,e){var i=JSON.parse(e.responseText);"tilemap"===t.type?this.cache.addTilemap(t.key,t.url,i,t.format):"bitmapfont"===t.type?this.cache.addBitmapFont(t.key,t.url,t.data,i,t.atlasType,t.xSpacing,t.ySpacing):"json"===t.type?this.cache.addJSON(t.key,t.url,i):this.cache.addTextureAtlas(t.key,t.url,t.data,i,t.format),this.asyncComplete(t)},csvLoadComplete:function(t,e){var i=e.responseText;this.cache.addTilemap(t.key,t.url,i,t.format),this.asyncComplete(t)},xmlLoadComplete:function(t,e){var i=e.responseText,s=this.parseXml(i);if(!s){var n=e.responseType||e.contentType;return console.warn("Phaser.Loader - "+t.key+": invalid XML ("+n+")"),void this.asyncComplete(t,"invalid XML")}"bitmapfont"===t.type?this.cache.addBitmapFont(t.key,t.url,t.data,s,t.atlasType,t.xSpacing,t.ySpacing):"textureatlas"===t.type?this.cache.addTextureAtlas(t.key,t.url,t.data,s,t.format):"xml"===t.type&&this.cache.addXML(t.key,t.url,s),this.asyncComplete(t)},parseXml:function(t){var e;try{if(window.DOMParser){var i=new DOMParser;e=i.parseFromString(t,"text/xml")}else e=new ActiveXObject("Microsoft.XMLDOM"),e.async="false",e.loadXML(t)}catch(t){e=null}return e&&e.documentElement&&!e.getElementsByTagName("parsererror").length?e:null},updateProgress:function(){this.preloadSprite&&(0===this.preloadSprite.direction?this.preloadSprite.rect.width=Math.floor(this.preloadSprite.width/100*this.progress):this.preloadSprite.rect.height=Math.floor(this.preloadSprite.height/100*this.progress),this.preloadSprite.sprite?this.preloadSprite.sprite.updateCrop():this.preloadSprite=null)},totalLoadedFiles:function(){return this._loadedFileCount},totalQueuedFiles:function(){return this._totalFileCount-this._loadedFileCount},totalLoadedPacks:function(){return this._totalPackCount},totalQueuedPacks:function(){return this._totalPackCount-this._loadedPackCount}},Object.defineProperty(n.Loader.prototype,"progressFloat",{get:function(){var t=this._loadedFileCount/this._totalFileCount*100;return n.Math.clamp(t||0,0,100)}}),Object.defineProperty(n.Loader.prototype,"progress",{get:function(){return Math.round(this.progressFloat)}}),n.Loader.prototype.constructor=n.Loader,n.LoaderParser={bitmapFont:function(t,e,i,s){return this.xmlBitmapFont(t,e,i,s)},xmlBitmapFont:function(t,e,i,s){var n={},r=t.getElementsByTagName("info")[0],o=t.getElementsByTagName("common")[0];n.font=r.getAttribute("face"),n.size=parseInt(r.getAttribute("size"),10),n.lineHeight=parseInt(o.getAttribute("lineHeight"),10)+s,n.chars={};for(var a=t.getElementsByTagName("char"),h=0;h<a.length;h++){var l=parseInt(a[h].getAttribute("id"),10);n.chars[l]={x:parseInt(a[h].getAttribute("x"),10),y:parseInt(a[h].getAttribute("y"),10),width:parseInt(a[h].getAttribute("width"),10),height:parseInt(a[h].getAttribute("height"),10),xOffset:parseInt(a[h].getAttribute("xoffset"),10),yOffset:parseInt(a[h].getAttribute("yoffset"),10),xAdvance:parseInt(a[h].getAttribute("xadvance"),10)+i,kerning:{}}}var c=t.getElementsByTagName("kerning");for(h=0;h<c.length;h++){var u=parseInt(c[h].getAttribute("first"),10),d=parseInt(c[h].getAttribute("second"),10),p=parseInt(c[h].getAttribute("amount"),10);n.chars[d].kerning[u]=p}return this.finalizeBitmapFont(e,n)},jsonBitmapFont:function(t,e,i,s){var n={font:t.font.info._face,size:parseInt(t.font.info._size,10),lineHeight:parseInt(t.font.common._lineHeight,10)+s,chars:{}};return t.font.chars.char.forEach(function(t){var e=parseInt(t._id,10);n.chars[e]={x:parseInt(t._x,10),y:parseInt(t._y,10),width:parseInt(t._width,10),height:parseInt(t._height,10),xOffset:parseInt(t._xoffset,10),yOffset:parseInt(t._yoffset,10),xAdvance:parseInt(t._xadvance,10)+i,kerning:{}}}),t.font.kernings&&t.font.kernings.kerning&&t.font.kernings.kerning.forEach(function(t){n.chars[t._second].kerning[t._first]=parseInt(t._amount,10)}),this.finalizeBitmapFont(e,n)},finalizeBitmapFont:function(t,e){return Object.keys(e.chars).forEach(function(i){var s=e.chars[i];s.texture=new PIXI.Texture(t,new n.Rectangle(s.x,s.y,s.width,s.height))}),e}},n.AudioSprite=function(t,e){this.game=t,this.key=e,this.config=this.game.cache.getJSON(e+"-audioatlas"),this.autoplayKey=null,this.autoplay=!1,this.sounds={};for(var i in this.config.spritemap){var s=this.config.spritemap[i],n=this.game.add.sound(this.key);n.addMarker(i,s.start,s.end-s.start,null,s.loop),this.sounds[i]=n}this.config.autoplay&&(this.autoplayKey=this.config.autoplay,this.play(this.autoplayKey),this.autoplay=this.sounds[this.autoplayKey])},n.AudioSprite.prototype={play:function(t,e){return void 0===e&&(e=1),this.sounds[t].play(t,null,e)},stop:function(t){if(t)this.sounds[t].stop();else for(var e in this.sounds)this.sounds[e].stop()},get:function(t){return this.sounds[t]}},n.AudioSprite.prototype.constructor=n.AudioSprite,n.Sound=function(t,e,i,s,r){void 0===i&&(i=1),void 0===s&&(s=!1),void 0===r&&(r=t.sound.connectToMaster),this.game=t,this.name=e,this.key=e,this.loop=s,this.markers={},this.context=null,this.autoplay=!1,this.totalDuration=0,this.startTime=0,this.currentTime=0,this.duration=0,this.durationMS=0,this.position=0,this.stopTime=0,this.paused=!1,this.pausedPosition=0,this.pausedTime=0,this.isPlaying=!1,this.currentMarker="",this.fadeTween=null,this.pendingPlayback=!1,this.override=!1,this.allowMultiple=!1,this.usingWebAudio=this.game.sound.usingWebAudio,this.usingAudioTag=this.game.sound.usingAudioTag,this.externalNode=null,this.masterGainNode=null,this.gainNode=null,this._sound=null,this.usingWebAudio?(this.context=this.game.sound.context,this.masterGainNode=this.game.sound.masterGain,void 0===this.context.createGain?this.gainNode=this.context.createGainNode():this.gainNode=this.context.createGain(),this.gainNode.gain.value=i*this.game.sound.volume,r&&this.gainNode.connect(this.masterGainNode)):this.usingAudioTag&&(this.game.cache.getSound(e)&&this.game.cache.isSoundReady(e)?(this._sound=this.game.cache.getSoundData(e),this.totalDuration=0,this._sound.duration&&(this.totalDuration=this._sound.duration)):this.game.cache.onSoundUnlock.add(this.soundHasUnlocked,this)),this.onDecoded=new n.Signal,this.onPlay=new n.Signal,this.onPause=new n.Signal,this.onResume=new n.Signal,this.onLoop=new n.Signal,this.onStop=new n.Signal,this.onMute=new n.Signal,this.onMarkerComplete=new n.Signal,this.onFadeComplete=new n.Signal,this._volume=i,this._buffer=null,this._muted=!1,this._tempMarker=0,this._tempPosition=0,this._tempVolume=0,this._tempPause=0,this._muteVolume=0,this._tempLoop=0,this._paused=!1,this._onDecodedEventDispatched=!1},n.Sound.prototype={soundHasUnlocked:function(t){t===this.key&&(this._sound=this.game.cache.getSoundData(this.key),this.totalDuration=this._sound.duration)},addMarker:function(t,e,i,s,n){void 0!==i&&null!==i||(i=1),void 0!==s&&null!==s||(s=1),void 0===n&&(n=!1),this.markers[t]={name:t,start:e,stop:e+i,volume:s,duration:i,durationMS:1e3*i,loop:n}},removeMarker:function(t){delete this.markers[t]},onEndedHandler:function(){this._sound.onended=null,this.isPlaying=!1,this.currentTime=this.durationMS,this.stop()},update:function(){if(!this.game.cache.checkSoundKey(this.key))return void this.destroy();this.isDecoded&&!this._onDecodedEventDispatched&&(this.onDecoded.dispatch(this),this._onDecodedEventDispatched=!0),this.pendingPlayback&&this.game.cache.isSoundReady(this.key)&&(this.pendingPlayback=!1,this.play(this._tempMarker,this._tempPosition,this._tempVolume,this._tempLoop)),this.isPlaying&&(this.currentTime=this.game.time.time-this.startTime,this.currentTime>=this.durationMS&&(this.usingWebAudio?this.loop?(this.onLoop.dispatch(this),this.isPlaying=!1,""===this.currentMarker?(this.currentTime=0,this.startTime=this.game.time.time,this.isPlaying=!0):(this.onMarkerComplete.dispatch(this.currentMarker,this),this.play(this.currentMarker,0,this.volume,!0,!0))):""!==this.currentMarker&&this.stop():this.loop?(this.onLoop.dispatch(this),""===this.currentMarker&&(this.currentTime=0,this.startTime=this.game.time.time),this.isPlaying=!1,this.play(this.currentMarker,0,this.volume,!0,!0)):this.stop()))},loopFull:function(t){return this.play(null,0,t,!0)},play:function(t,e,i,s,n){if(void 0!==t&&!1!==t&&null!==t||(t=""),void 0===n&&(n=!0),this.isPlaying&&!this.allowMultiple&&!n&&!this.override)return this;if(this._sound&&this.isPlaying&&!this.allowMultiple&&(this.override||n)){if(this.usingWebAudio){if(void 0===this._sound.stop)this._sound.noteOff(0);else try{this._sound.stop(0)}catch(t){}this.externalNode?this._sound.disconnect(this.externalNode):this.gainNode&&this._sound.disconnect(this.gainNode)}else this.usingAudioTag&&(this._sound.pause(),this._sound.currentTime=0);this.isPlaying=!1}if(""===t&&Object.keys(this.markers).length>0)return this;if(""!==t){if(!this.markers[t])return console.warn("Phaser.Sound.play: audio marker "+t+" doesn't exist"),this;this.currentMarker=t,this.position=this.markers[t].start,this.volume=this.markers[t].volume,this.loop=this.markers[t].loop,this.duration=this.markers[t].duration,this.durationMS=this.markers[t].durationMS,void 0!==i&&(this.volume=i),void 0!==s&&(this.loop=s),this._tempMarker=t,this._tempPosition=this.position,this._tempVolume=this.volume,this._tempLoop=this.loop}else e=e||0,void 0===i&&(i=this._volume),void 0===s&&(s=this.loop),this.position=Math.max(0,e),this.volume=i,this.loop=s,this.duration=0,this.durationMS=0,this._tempMarker=t,this._tempPosition=e,this._tempVolume=i,this._tempLoop=s;return this.usingWebAudio?this.game.cache.isSoundDecoded(this.key)?(this._sound=this.context.createBufferSource(),this.externalNode?this._sound.connect(this.externalNode):this._sound.connect(this.gainNode),this._buffer=this.game.cache.getSoundData(this.key),this._sound.buffer=this._buffer,this.loop&&""===t&&(this._sound.loop=!0),this.loop||""!==t||(this._sound.onended=this.onEndedHandler.bind(this)),this.totalDuration=this._sound.buffer.duration,0===this.duration&&(this.duration=this.totalDuration,this.durationMS=Math.ceil(1e3*this.totalDuration)),void 0===this._sound.start?this._sound.noteGrainOn(0,this.position,this.duration):this.loop&&""===t?this._sound.start(0,0):this._sound.start(0,this.position,this.duration),this.isPlaying=!0,this.startTime=this.game.time.time,this.currentTime=0,this.stopTime=this.startTime+this.durationMS,this.onPlay.dispatch(this)):(this.pendingPlayback=!0,this.game.cache.getSound(this.key)&&!1===this.game.cache.getSound(this.key).isDecoding&&this.game.sound.decode(this.key,this)):this.game.cache.getSound(this.key)&&this.game.cache.getSound(this.key).locked?(this.game.cache.reloadSound(this.key),this.pendingPlayback=!0):this._sound&&(this.game.device.cocoonJS||4===this._sound.readyState)?(this._sound.play(),this.totalDuration=this._sound.duration,0===this.duration&&(this.duration=this.totalDuration,this.durationMS=1e3*this.totalDuration),this._sound.currentTime=this.position,this._sound.muted=this._muted,this._muted||this.game.sound.mute?this._sound.volume=0:this._sound.volume=this._volume,this.isPlaying=!0,this.startTime=this.game.time.time,this.currentTime=0,this.stopTime=this.startTime+this.durationMS,this.onPlay.dispatch(this)):this.pendingPlayback=!0,this},restart:function(t,e,i,s){t=t||"",e=e||0,i=i||1,void 0===s&&(s=!1),this.play(t,e,i,s,!0)},pause:function(){this.isPlaying&&this._sound&&(this.paused=!0,this.pausedPosition=this.currentTime,this.pausedTime=this.game.time.time,this._tempPause=this._sound.currentTime,this.onPause.dispatch(this),this.stop())},resume:function(){if(this.paused&&this._sound){if(this.usingWebAudio){var t=Math.max(0,this.position+this.pausedPosition/1e3);this._sound=this.context.createBufferSource(),this._sound.buffer=this._buffer,this.externalNode?this._sound.connect(this.externalNode):this._sound.connect(this.gainNode),this.loop&&(this._sound.loop=!0),this.loop||""!==this.currentMarker||(this._sound.onended=this.onEndedHandler.bind(this));var e=this.duration-this.pausedPosition/1e3;void 0===this._sound.start?this._sound.noteGrainOn(0,t,e):this.loop&&this.game.device.chrome?42===this.game.device.chromeVersion?this._sound.start(0):this._sound.start(0,t):this._sound.start(0,t,e)}else this._sound.currentTime=this._tempPause,this._sound.play();this.isPlaying=!0,this.paused=!1,this.startTime+=this.game.time.time-this.pausedTime,this.onResume.dispatch(this)}},stop:function(){if(this.isPlaying&&this._sound)if(this.usingWebAudio){if(void 0===this._sound.stop)this._sound.noteOff(0);else try{this._sound.stop(0)}catch(t){}this.externalNode?this._sound.disconnect(this.externalNode):this.gainNode&&this._sound.disconnect(this.gainNode)}else this.usingAudioTag&&(this._sound.pause(),this._sound.currentTime=0);if(this.pendingPlayback=!1,this.isPlaying=!1,!this.paused){var t=this.currentMarker;""!==this.currentMarker&&this.onMarkerComplete.dispatch(this.currentMarker,this),this.currentMarker="",null!==this.fadeTween&&this.fadeTween.stop(),this.onStop.dispatch(this,t)}},fadeIn:function(t,e,i){void 0===e&&(e=!1),void 0===i&&(i=this.currentMarker),this.paused||(this.play(i,0,0,e),this.fadeTo(t,1))},fadeOut:function(t){this.fadeTo(t,0)},fadeTo:function(t,e){if(this.isPlaying&&!this.paused&&e!==this.volume){if(void 0===t&&(t=1e3),void 0===e)return void console.warn("Phaser.Sound.fadeTo: No Volume Specified.");this.fadeTween=this.game.add.tween(this).to({volume:e},t,n.Easing.Linear.None,!0),this.fadeTween.onComplete.add(this.fadeComplete,this)}},fadeComplete:function(){this.onFadeComplete.dispatch(this,this.volume),0===this.volume&&this.stop()},updateGlobalVolume:function(t){this.usingAudioTag&&this._sound&&(this._sound.volume=t*this._volume)},destroy:function(t){void 0===t&&(t=!0),this.stop(),t?this.game.sound.remove(this):(this.markers={},this.context=null,this._buffer=null,this.externalNode=null,this.onDecoded.dispose(),this.onPlay.dispose(),this.onPause.dispose(),this.onResume.dispose(),this.onLoop.dispose(),this.onStop.dispose(),this.onMute.dispose(),this.onMarkerComplete.dispose())}},n.Sound.prototype.constructor=n.Sound,Object.defineProperty(n.Sound.prototype,"isDecoding",{get:function(){return this.game.cache.getSound(this.key).isDecoding}}),Object.defineProperty(n.Sound.prototype,"isDecoded",{get:function(){return this.game.cache.isSoundDecoded(this.key)}}),Object.defineProperty(n.Sound.prototype,"mute",{get:function(){return this._muted||this.game.sound.mute},set:function(t){(t=t||!1)!==this._muted&&(t?(this._muted=!0,this._muteVolume=this._tempVolume,this.usingWebAudio?this.gainNode.gain.value=0:this.usingAudioTag&&this._sound&&(this._sound.volume=0)):(this._muted=!1,this.usingWebAudio?this.gainNode.gain.value=this._muteVolume:this.usingAudioTag&&this._sound&&(this._sound.volume=this._muteVolume)),this.onMute.dispatch(this))}}),Object.defineProperty(n.Sound.prototype,"volume",{get:function(){return this._volume},set:function(t){if(this.game.device.firefox&&this.usingAudioTag&&(t=this.game.math.clamp(t,0,1)),this._muted)return void(this._muteVolume=t);this._tempVolume=t,this._volume=t,this.usingWebAudio?this.gainNode.gain.value=t:this.usingAudioTag&&this._sound&&(this._sound.volume=t)}}),n.SoundManager=function(t){this.game=t,this.onSoundDecode=new n.Signal,this.onVolumeChange=new n.Signal,this.onMute=new n.Signal,this.onUnMute=new n.Signal,this.context=null,this.usingWebAudio=!1,this.usingAudioTag=!1,this.noAudio=!1,this.connectToMaster=!0,this.touchLocked=!1,this.channels=32,this.muteOnPause=!0,this._codeMuted=!1,this._muted=!1,this._unlockSource=null,this._volume=1,this._sounds=[],this._watchList=new n.ArraySet,this._watching=!1,this._watchCallback=null,this._watchContext=null},n.SoundManager.prototype={boot:function(){if(this.game.device.iOS&&!1===this.game.device.webAudio&&(this.channels=1),window.PhaserGlobal){if(!0===window.PhaserGlobal.disableAudio)return this.noAudio=!0,void(this.touchLocked=!1);if(!0===window.PhaserGlobal.disableWebAudio)return this.usingAudioTag=!0,void(this.touchLocked=!1)}if(window.PhaserGlobal&&window.PhaserGlobal.audioContext)this.context=window.PhaserGlobal.audioContext;else if(window.AudioContext)try{this.context=new window.AudioContext}catch(t){this.context=null,this.usingWebAudio=!1,this.touchLocked=!1}else if(window.webkitAudioContext)try{this.context=new window.webkitAudioContext}catch(t){this.context=null,this.usingWebAudio=!1,this.touchLocked=!1}if(null===this.context){if(void 0===window.Audio)return void(this.noAudio=!0);this.usingAudioTag=!0}else this.usingWebAudio=!0,void 0===this.context.createGain?this.masterGain=this.context.createGainNode():this.masterGain=this.context.createGain(),this.masterGain.gain.value=1,this.masterGain.connect(this.context.destination);this.noAudio||(!this.game.device.cocoonJS&&this.game.device.iOS||window.PhaserGlobal&&window.PhaserGlobal.fakeiOSTouchLock)&&this.setTouchLock()},setTouchLock:function(){this.noAudio||window.PhaserGlobal&&!0===window.PhaserGlobal.disableAudio||(this.game.device.iOSVersion>8?this.game.input.touch.addTouchLockCallback(this.unlock,this,!0):this.game.input.touch.addTouchLockCallback(this.unlock,this),this.touchLocked=!0)},unlock:function(){if(this.noAudio||!this.touchLocked||null!==this._unlockSource)return!0;if(this.usingAudioTag)this.touchLocked=!1,this._unlockSource=null;else if(this.usingWebAudio){var t=this.context.createBuffer(1,1,22050);this._unlockSource=this.context.createBufferSource(),this._unlockSource.buffer=t,this._unlockSource.connect(this.context.destination),void 0===this._unlockSource.start?this._unlockSource.noteOn(0):this._unlockSource.start(0)}return!0},stopAll:function(){if(!this.noAudio)for(var t=0;t<this._sounds.length;t++)this._sounds[t]&&this._sounds[t].stop()},pauseAll:function(){if(!this.noAudio)for(var t=0;t<this._sounds.length;t++)this._sounds[t]&&this._sounds[t].pause()},resumeAll:function(){if(!this.noAudio)for(var t=0;t<this._sounds.length;t++)this._sounds[t]&&this._sounds[t].resume()},decode:function(t,e){e=e||null;var i=this.game.cache.getSoundData(t);if(i&&!1===this.game.cache.isSoundDecoded(t)){this.game.cache.updateSound(t,"isDecoding",!0);var s=this;try{this.context.decodeAudioData(i,function(i){i&&(s.game.cache.decodedSound(t,i),s.onSoundDecode.dispatch(t,e))})}catch(t){}}},setDecodedCallback:function(t,e,i){"string"==typeof t&&(t=[t]),this._watchList.reset();for(var s=0;s<t.length;s++)t[s]instanceof n.Sound?this.game.cache.isSoundDecoded(t[s].key)||this._watchList.add(t[s].key):this.game.cache.isSoundDecoded(t[s])||this._watchList.add(t[s]);0===this._watchList.total?(this._watching=!1,e.call(i)):(this._watching=!0,this._watchCallback=e,this._watchContext=i)},update:function(){if(!this.noAudio){!this.touchLocked||null===this._unlockSource||this._unlockSource.playbackState!==this._unlockSource.PLAYING_STATE&&this._unlockSource.playbackState!==this._unlockSource.FINISHED_STATE||(this.touchLocked=!1,this._unlockSource=null);for(var t=0;t<this._sounds.length;t++)this._sounds[t].update();if(this._watching){for(var e=this._watchList.first;e;)this.game.cache.isSoundDecoded(e)&&this._watchList.remove(e),e=this._watchList.next;0===this._watchList.total&&(this._watching=!1,this._watchCallback.call(this._watchContext))}}},add:function(t,e,i,s){void 0===e&&(e=1),void 0===i&&(i=!1),void 0===s&&(s=this.connectToMaster);var r=new n.Sound(this.game,t,e,i,s);return this._sounds.push(r),r},addSprite:function(t){return new n.AudioSprite(this.game,t)},remove:function(t){for(var e=this._sounds.length;e--;)if(this._sounds[e]===t)return this._sounds[e].destroy(!1),this._sounds.splice(e,1),!0;return!1},removeByKey:function(t){for(var e=this._sounds.length,i=0;e--;)this._sounds[e].key===t&&(this._sounds[e].destroy(!1),this._sounds.splice(e,1),i++);return i},play:function(t,e,i){if(!this.noAudio){var s=this.add(t,e,i);return s.play(),s}},setMute:function(){if(!this._muted){this._muted=!0,this.usingWebAudio&&(this._muteVolume=this.masterGain.gain.value,this.masterGain.gain.value=0);for(var t=0;t<this._sounds.length;t++)this._sounds[t].usingAudioTag&&(this._sounds[t].mute=!0);this.onMute.dispatch()}},unsetMute:function(){if(this._muted&&!this._codeMuted){this._muted=!1,this.usingWebAudio&&(this.masterGain.gain.value=this._muteVolume);for(var t=0;t<this._sounds.length;t++)this._sounds[t].usingAudioTag&&(this._sounds[t].mute=!1);this.onUnMute.dispatch()}},destroy:function(){this.stopAll();for(var t=0;t<this._sounds.length;t++)this._sounds[t]&&this._sounds[t].destroy();this._sounds=[],this.onSoundDecode.dispose(),this.context&&(window.PhaserGlobal?window.PhaserGlobal.audioContext=this.context:this.context.close&&this.context.close())}},n.SoundManager.prototype.constructor=n.SoundManager,Object.defineProperty(n.SoundManager.prototype,"mute",{get:function(){return this._muted},set:function(t){if(t=t||!1){if(this._muted)return;this._codeMuted=!0,this.setMute()}else{if(!this._muted)return;this._codeMuted=!1,this.unsetMute()}}}),Object.defineProperty(n.SoundManager.prototype,"volume",{get:function(){return this._volume},set:function(t){if(t<0?t=0:t>1&&(t=1),this._volume!==t){if(this._volume=t,this.usingWebAudio)this.masterGain.gain.value=t;else for(var e=0;e<this._sounds.length;e++)this._sounds[e].usingAudioTag&&this._sounds[e].updateGlobalVolume(t);this.onVolumeChange.dispatch(t)}}}),n.ScaleManager=function(t,e,i){this.game=t,this.dom=n.DOM,this.grid=null,this.width=0,this.height=0,this.minWidth=null,this.maxWidth=null,this.minHeight=null,this.maxHeight=null,this.offset=new n.Point,this.forceLandscape=!1,this.forcePortrait=!1,this.incorrectOrientation=!1,this._pageAlignHorizontally=!1,this._pageAlignVertically=!1,this.onOrientationChange=new n.Signal,this.enterIncorrectOrientation=new n.Signal,this.leaveIncorrectOrientation=new n.Signal,this.hasPhaserSetFullScreen=!1,this.fullScreenTarget=null,this._createdFullScreenTarget=null,this.onFullScreenInit=new n.Signal,this.onFullScreenChange=new n.Signal,this.onFullScreenError=new n.Signal,this.screenOrientation=this.dom.getScreenOrientation(),this.scaleFactor=new n.Point(1,1),this.scaleFactorInversed=new n.Point(1,1),this.margin={left:0,top:0,right:0,bottom:0,x:0,y:0},this.bounds=new n.Rectangle,this.aspectRatio=0,this.sourceAspectRatio=0,this.event=null,this.windowConstraints={right:"layout",bottom:""},this.compatibility={supportsFullScreen:!1,orientationFallback:null,noMargins:!1,scrollTo:null,forceMinimumDocumentHeight:!1,canExpandParent:!0,clickTrampoline:""},this._scaleMode=n.ScaleManager.NO_SCALE,this._fullScreenScaleMode=n.ScaleManager.NO_SCALE,this.parentIsWindow=!1,this.parentNode=null,this.parentScaleFactor=new n.Point(1,1),this.trackParentInterval=2e3,this.onSizeChange=new n.Signal,this.onResize=null,this.onResizeContext=null,this._pendingScaleMode=null,this._fullScreenRestore=null,this._gameSize=new n.Rectangle,this._userScaleFactor=new n.Point(1,1),this._userScaleTrim=new n.Point(0,0),this._lastUpdate=0,this._updateThrottle=0,this._updateThrottleReset=100,this._parentBounds=new n.Rectangle,this._tempBounds=new n.Rectangle,this._lastReportedCanvasSize=new n.Rectangle,this._lastReportedGameSize=new n.Rectangle,this._booted=!1,t.config&&this.parseConfig(t.config),this.setupScale(e,i)},n.ScaleManager.EXACT_FIT=0,n.ScaleManager.NO_SCALE=1,n.ScaleManager.SHOW_ALL=2,n.ScaleManager.RESIZE=3,n.ScaleManager.USER_SCALE=4,n.ScaleManager.prototype={boot:function(){var t=this.compatibility;t.supportsFullScreen=this.game.device.fullscreen&&!this.game.device.cocoonJS,this.game.device.iPad||this.game.device.webApp||this.game.device.desktop||(this.game.device.android&&!this.game.device.chrome?t.scrollTo=new n.Point(0,1):t.scrollTo=new n.Point(0,0)),this.game.device.desktop?(t.orientationFallback="screen",t.clickTrampoline="when-not-mouse"):(t.orientationFallback="",t.clickTrampoline="");var e=this;this._orientationChange=function(t){return e.orientationChange(t)},this._windowResize=function(t){return e.windowResize(t)},window.addEventListener("orientationchange",this._orientationChange,!1),window.addEventListener("resize",this._windowResize,!1),this.compatibility.supportsFullScreen&&(this._fullScreenChange=function(t){return e.fullScreenChange(t)},this._fullScreenError=function(t){return e.fullScreenError(t)},document.addEventListener("webkitfullscreenchange",this._fullScreenChange,!1),document.addEventListener("mozfullscreenchange",this._fullScreenChange,!1),document.addEventListener("MSFullscreenChange",this._fullScreenChange,!1),document.addEventListener("fullscreenchange",this._fullScreenChange,!1),document.addEventListener("webkitfullscreenerror",this._fullScreenError,!1),document.addEventListener("mozfullscreenerror",this._fullScreenError,!1),document.addEventListener("MSFullscreenError",this._fullScreenError,!1),document.addEventListener("fullscreenerror",this._fullScreenError,!1)),this.game.onResume.add(this._gameResumed,this),this.dom.getOffset(this.game.canvas,this.offset),this.bounds.setTo(this.offset.x,this.offset.y,this.width,this.height),this.setGameSize(this.game.width,this.game.height),this.screenOrientation=this.dom.getScreenOrientation(this.compatibility.orientationFallback),n.FlexGrid&&(this.grid=new n.FlexGrid(this,this.width,this.height)),this._booted=!0,null!==this._pendingScaleMode&&(this.scaleMode=this._pendingScaleMode,this._pendingScaleMode=null)},parseConfig:function(t){void 0!==t.scaleMode&&(this._booted?this.scaleMode=t.scaleMode:this._pendingScaleMode=t.scaleMode),void 0!==t.fullScreenScaleMode&&(this.fullScreenScaleMode=t.fullScreenScaleMode),t.fullScreenTarget&&(this.fullScreenTarget=t.fullScreenTarget)},setupScale:function(t,e){var i,s=new n.Rectangle;""!==this.game.parent&&("string"==typeof this.game.parent?i=document.getElementById(this.game.parent):this.game.parent&&1===this.game.parent.nodeType&&(i=this.game.parent)),i?(this.parentNode=i,this.parentIsWindow=!1,this.getParentBounds(this._parentBounds),s.width=this._parentBounds.width,s.height=this._parentBounds.height,this.offset.set(this._parentBounds.x,this._parentBounds.y)):(this.parentNode=null,this.parentIsWindow=!0,s.width=this.dom.visualBounds.width,s.height=this.dom.visualBounds.height,this.offset.set(0,0));var r=0,o=0;"number"==typeof t?r=t:(this.parentScaleFactor.x=parseInt(t,10)/100,r=s.width*this.parentScaleFactor.x),"number"==typeof e?o=e:(this.parentScaleFactor.y=parseInt(e,10)/100,o=s.height*this.parentScaleFactor.y),r=Math.floor(r),o=Math.floor(o),this._gameSize.setTo(0,0,r,o),this.updateDimensions(r,o,!1)},_gameResumed:function(){this.queueUpdate(!0)},setGameSize:function(t,e){this._gameSize.setTo(0,0,t,e),this.currentScaleMode!==n.ScaleManager.RESIZE&&this.updateDimensions(t,e,!0),this.queueUpdate(!0)},setUserScale:function(t,e,i,s){this._userScaleFactor.setTo(t,e),this._userScaleTrim.setTo(0|i,0|s),this.queueUpdate(!0)},setResizeCallback:function(t,e){this.onResize=t,this.onResizeContext=e},signalSizeChange:function(){if(!n.Rectangle.sameDimensions(this,this._lastReportedCanvasSize)||!n.Rectangle.sameDimensions(this.game,this._lastReportedGameSize)){var t=this.width,e=this.height;this._lastReportedCanvasSize.setTo(0,0,t,e),this._lastReportedGameSize.setTo(0,0,this.game.width,this.game.height),this.grid&&this.grid.onResize(t,e),this.onSizeChange.dispatch(this,t,e),this.currentScaleMode===n.ScaleManager.RESIZE&&(this.game.state.resize(t,e),this.game.load.resize(t,e))}},setMinMax:function(t,e,i,s){this.minWidth=t,this.minHeight=e,void 0!==i&&(this.maxWidth=i),void 0!==s&&(this.maxHeight=s)},preUpdate:function(){if(!(this.game.time.time<this._lastUpdate+this._updateThrottle)){var t=this._updateThrottle;this._updateThrottleReset=t>=400?0:100,this.dom.getOffset(this.game.canvas,this.offset);var e=this._parentBounds.width,i=this._parentBounds.height,s=this.getParentBounds(this._parentBounds),r=s.width!==e||s.height!==i,o=this.updateOrientationState();(r||o)&&(this.onResize&&this.onResize.call(this.onResizeContext,this,s),this.updateLayout(),this.signalSizeChange());var a=2*this._updateThrottle;this._updateThrottle<t&&(a=Math.min(t,this._updateThrottleReset)),this._updateThrottle=n.Math.clamp(a,25,this.trackParentInterval),this._lastUpdate=this.game.time.time}},pauseUpdate:function(){this.preUpdate(),this._updateThrottle=this.trackParentInterval},updateDimensions:function(t,e,i){this.width=t*this.parentScaleFactor.x,this.height=e*this.parentScaleFactor.y,this.game.width=this.width,this.game.height=this.height,this.sourceAspectRatio=this.width/this.height,this.updateScalingAndBounds(),i&&(this.game.renderer.resize(this.width,this.height),this.game.camera.setSize(this.width,this.height),this.game.world.resize(this.width,this.height))},updateScalingAndBounds:function(){this.scaleFactor.x=this.game.width/this.width,this.scaleFactor.y=this.game.height/this.height,this.scaleFactorInversed.x=this.width/this.game.width,this.scaleFactorInversed.y=this.height/this.game.height,this.aspectRatio=this.width/this.height,this.game.canvas&&this.dom.getOffset(this.game.canvas,this.offset),this.bounds.setTo(this.offset.x,this.offset.y,this.width,this.height),this.game.input&&this.game.input.scale&&this.game.input.scale.setTo(this.scaleFactor.x,this.scaleFactor.y)},forceOrientation:function(t,e){void 0===e&&(e=!1),this.forceLandscape=t,this.forcePortrait=e,this.queueUpdate(!0)},classifyOrientation:function(t){return"portrait-primary"===t||"portrait-secondary"===t?"portrait":"landscape-primary"===t||"landscape-secondary"===t?"landscape":null},updateOrientationState:function(){var t=this.screenOrientation,e=this.incorrectOrientation;this.screenOrientation=this.dom.getScreenOrientation(this.compatibility.orientationFallback),this.incorrectOrientation=this.forceLandscape&&!this.isLandscape||this.forcePortrait&&!this.isPortrait;var i=t!==this.screenOrientation,s=e!==this.incorrectOrientation;return s&&(this.incorrectOrientation?this.enterIncorrectOrientation.dispatch():this.leaveIncorrectOrientation.dispatch()),(i||s)&&this.onOrientationChange.dispatch(this,t,e),i||s},orientationChange:function(t){this.event=t,this.queueUpdate(!0)},windowResize:function(t){this.event=t,this.queueUpdate(!0)},scrollTop:function(){var t=this.compatibility.scrollTo;t&&window.scrollTo(t.x,t.y)},refresh:function(){this.scrollTop(),this.queueUpdate(!0)},updateLayout:function(){var t=this.currentScaleMode;if(t===n.ScaleManager.RESIZE)return void this.reflowGame();if(this.scrollTop(),this.compatibility.forceMinimumDocumentHeight&&(document.documentElement.style.minHeight=window.innerHeight+"px"),this.incorrectOrientation?this.setMaximum():t===n.ScaleManager.EXACT_FIT?this.setExactFit():t===n.ScaleManager.SHOW_ALL?!this.isFullScreen&&this.boundingParent&&this.compatibility.canExpandParent?(this.setShowAll(!0),this.resetCanvas(),this.setShowAll()):this.setShowAll():t===n.ScaleManager.NO_SCALE?(this.width=this.game.width,this.height=this.game.height):t===n.ScaleManager.USER_SCALE&&(this.width=this.game.width*this._userScaleFactor.x-this._userScaleTrim.x,this.height=this.game.height*this._userScaleFactor.y-this._userScaleTrim.y),!this.compatibility.canExpandParent&&(t===n.ScaleManager.SHOW_ALL||t===n.ScaleManager.USER_SCALE)){var e=this.getParentBounds(this._tempBounds);this.width=Math.min(this.width,e.width),this.height=Math.min(this.height,e.height)}this.width=0|this.width,this.height=0|this.height,this.reflowCanvas()},getParentBounds:function(t){var e=t||new n.Rectangle,i=this.boundingParent,s=this.dom.visualBounds,r=this.dom.layoutBounds;if(i){var o=i.getBoundingClientRect(),a=i.offsetParent?i.offsetParent.getBoundingClientRect():i.getBoundingClientRect();e.setTo(o.left-a.left,o.top-a.top,o.width,o.height);var h=this.windowConstraints;if(h.right){var l="layout"===h.right?r:s;e.right=Math.min(e.right,l.width)}if(h.bottom){var l="layout"===h.bottom?r:s;e.bottom=Math.min(e.bottom,l.height)}}else e.setTo(0,0,s.width,s.height);return e.setTo(Math.round(e.x),Math.round(e.y),Math.round(e.width),Math.round(e.height)),e},alignCanvas:function(t,e){var i=this.getParentBounds(this._tempBounds),s=this.game.canvas,n=this.margin;if(t){n.left=n.right=0;var r=s.getBoundingClientRect();if(this.width<i.width&&!this.incorrectOrientation){var o=r.left-i.x,a=i.width/2-this.width/2;a=Math.max(a,0);var h=a-o;n.left=Math.round(h)}s.style.marginLeft=n.left+"px",0!==n.left&&(n.right=-(i.width-r.width-n.left),s.style.marginRight=n.right+"px")}if(e){n.top=n.bottom=0;var r=s.getBoundingClientRect();if(this.height<i.height&&!this.incorrectOrientation){var o=r.top-i.y,a=i.height/2-this.height/2;a=Math.max(a,0);var h=a-o;n.top=Math.round(h)}s.style.marginTop=n.top+"px",0!==n.top&&(n.bottom=-(i.height-r.height-n.top),s.style.marginBottom=n.bottom+"px")}n.x=n.left,n.y=n.top},reflowGame:function(){this.resetCanvas("","");var t=this.getParentBounds(this._tempBounds);this.updateDimensions(t.width,t.height,!0)},reflowCanvas:function(){this.incorrectOrientation||(this.width=n.Math.clamp(this.width,this.minWidth||0,this.maxWidth||this.width),this.height=n.Math.clamp(this.height,this.minHeight||0,this.maxHeight||this.height)),this.resetCanvas(),this.compatibility.noMargins||(this.isFullScreen&&this._createdFullScreenTarget?this.alignCanvas(!0,!0):this.alignCanvas(this.pageAlignHorizontally,this.pageAlignVertically)),this.updateScalingAndBounds()},resetCanvas:function(t,e){void 0===t&&(t=this.width+"px"),void 0===e&&(e=this.height+"px");var i=this.game.canvas;this.compatibility.noMargins||(i.style.marginLeft="",i.style.marginTop="",i.style.marginRight="",i.style.marginBottom=""),i.style.width=t,i.style.height=e},queueUpdate:function(t){t&&(this._parentBounds.width=0,this._parentBounds.height=0),this._updateThrottle=this._updateThrottleReset},reset:function(t){t&&this.grid&&this.grid.reset()},setMaximum:function(){this.width=this.dom.visualBounds.width,this.height=this.dom.visualBounds.height},setShowAll:function(t){var e,i=this.getParentBounds(this._tempBounds),s=i.width,n=i.height;e=t?Math.max(n/this.game.height,s/this.game.width):Math.min(n/this.game.height,s/this.game.width),this.width=Math.round(this.game.width*e),this.height=Math.round(this.game.height*e)},setExactFit:function(){var t=this.getParentBounds(this._tempBounds);this.width=t.width,this.height=t.height,this.isFullScreen||(this.maxWidth&&(this.width=Math.min(this.width,this.maxWidth)),this.maxHeight&&(this.height=Math.min(this.height,this.maxHeight)))},createFullScreenTarget:function(){var t=document.createElement("div");return t.style.margin="0",t.style.padding="0",t.style.background="#000",t},startFullScreen:function(t,e){if(this.isFullScreen)return!1;if(!this.compatibility.supportsFullScreen){var i=this;return void setTimeout(function(){i.fullScreenError()},10)}if("when-not-mouse"===this.compatibility.clickTrampoline){var s=this.game.input;if(s.activePointer&&s.activePointer!==s.mousePointer&&(e||!1!==e))return void s.activePointer.addClickTrampoline("startFullScreen",this.startFullScreen,this,[t,!1])}void 0!==t&&this.game.renderType===n.CANVAS&&(this.game.stage.smoothed=t);var r=this.fullScreenTarget;r||(this.cleanupCreatedTarget(),this._createdFullScreenTarget=this.createFullScreenTarget(),r=this._createdFullScreenTarget);var o={targetElement:r};if(this.hasPhaserSetFullScreen=!0,this.onFullScreenInit.dispatch(this,o),this._createdFullScreenTarget){var a=this.game.canvas;a.parentNode.insertBefore(r,a),r.appendChild(a)}return this.game.device.fullscreenKeyboard?r[this.game.device.requestFullscreen](Element.ALLOW_KEYBOARD_INPUT):r[this.game.device.requestFullscreen](),!0},stopFullScreen:function(){return!(!this.isFullScreen||!this.compatibility.supportsFullScreen)&&(this.hasPhaserSetFullScreen=!1,document[this.game.device.cancelFullscreen](),!0)},cleanupCreatedTarget:function(){var t=this._createdFullScreenTarget;if(t&&t.parentNode){var e=t.parentNode;e.insertBefore(this.game.canvas,t),e.removeChild(t)}this._createdFullScreenTarget=null},prepScreenMode:function(t){var e=!!this._createdFullScreenTarget,i=this._createdFullScreenTarget||this.fullScreenTarget;t?(e||this.fullScreenScaleMode===n.ScaleManager.EXACT_FIT)&&i!==this.game.canvas&&(this._fullScreenRestore={targetWidth:i.style.width,targetHeight:i.style.height},i.style.width="100%",i.style.height="100%"):(this._fullScreenRestore&&(i.style.width=this._fullScreenRestore.targetWidth,i.style.height=this._fullScreenRestore.targetHeight,this._fullScreenRestore=null),this.updateDimensions(this._gameSize.width,this._gameSize.height,!0),this.resetCanvas())},fullScreenChange:function(t){this.event=t,this.isFullScreen?(this.prepScreenMode(!0),this.updateLayout(),this.queueUpdate(!0)):(this.prepScreenMode(!1),this.cleanupCreatedTarget(),this.updateLayout(),this.queueUpdate(!0)),this.onFullScreenChange.dispatch(this,this.width,this.height)},fullScreenError:function(t){this.event=t,this.cleanupCreatedTarget(),console.warn("Phaser.ScaleManager: requestFullscreen failed or device does not support the Fullscreen API"),this.onFullScreenError.dispatch(this)},scaleSprite:function(t,e,i,s){if(void 0===e&&(e=this.width),void 0===i&&(i=this.height),void 0===s&&(s=!1),!t||!t.scale)return t;if(t.scale.x=1,t.scale.y=1,t.width<=0||t.height<=0||e<=0||i<=0)return t;var n=e,r=t.height*e/t.width,o=t.width*i/t.height,a=i,h=o>e;return h=h?s:!s,h?(t.width=Math.floor(n),t.height=Math.floor(r)):(t.width=Math.floor(o),t.height=Math.floor(a)),t},destroy:function(){this.game.onResume.remove(this._gameResumed,this),window.removeEventListener("orientationchange",this._orientationChange,!1),window.removeEventListener("resize",this._windowResize,!1),this.compatibility.supportsFullScreen&&(document.removeEventListener("webkitfullscreenchange",this._fullScreenChange,!1),document.removeEventListener("mozfullscreenchange",this._fullScreenChange,!1),document.removeEventListener("MSFullscreenChange",this._fullScreenChange,!1),document.removeEventListener("fullscreenchange",this._fullScreenChange,!1),document.removeEventListener("webkitfullscreenerror",this._fullScreenError,!1),document.removeEventListener("mozfullscreenerror",this._fullScreenError,!1),document.removeEventListener("MSFullscreenError",this._fullScreenError,!1),document.removeEventListener("fullscreenerror",this._fullScreenError,!1))}},n.ScaleManager.prototype.constructor=n.ScaleManager,Object.defineProperty(n.ScaleManager.prototype,"boundingParent",{get:function(){return this.parentIsWindow||this.isFullScreen&&this.hasPhaserSetFullScreen&&!this._createdFullScreenTarget?null:this.game.canvas&&this.game.canvas.parentNode||null}}),Object.defineProperty(n.ScaleManager.prototype,"scaleMode",{get:function(){return this._scaleMode},set:function(t){return t!==this._scaleMode&&(this.isFullScreen||(this.updateDimensions(this._gameSize.width,this._gameSize.height,!0),this.queueUpdate(!0)),this._scaleMode=t),this._scaleMode}}),Object.defineProperty(n.ScaleManager.prototype,"fullScreenScaleMode",{get:function(){return this._fullScreenScaleMode},set:function(t){return t!==this._fullScreenScaleMode&&(this.isFullScreen?(this.prepScreenMode(!1),this._fullScreenScaleMode=t,this.prepScreenMode(!0),this.queueUpdate(!0)):this._fullScreenScaleMode=t),this._fullScreenScaleMode}}),Object.defineProperty(n.ScaleManager.prototype,"currentScaleMode",{get:function(){return this.isFullScreen?this._fullScreenScaleMode:this._scaleMode}}),Object.defineProperty(n.ScaleManager.prototype,"pageAlignHorizontally",{get:function(){return this._pageAlignHorizontally},set:function(t){t!==this._pageAlignHorizontally&&(this._pageAlignHorizontally=t,this.queueUpdate(!0))}}),Object.defineProperty(n.ScaleManager.prototype,"pageAlignVertically",{get:function(){return this._pageAlignVertically},set:function(t){t!==this._pageAlignVertically&&(this._pageAlignVertically=t,this.queueUpdate(!0))}}),Object.defineProperty(n.ScaleManager.prototype,"isFullScreen",{get:function(){return!!(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement)}}),Object.defineProperty(n.ScaleManager.prototype,"isPortrait",{get:function(){return"portrait"===this.classifyOrientation(this.screenOrientation)}}),Object.defineProperty(n.ScaleManager.prototype,"isLandscape",{get:function(){return"landscape"===this.classifyOrientation(this.screenOrientation)}}),Object.defineProperty(n.ScaleManager.prototype,"isGamePortrait",{get:function(){return this.height>this.width}}),Object.defineProperty(n.ScaleManager.prototype,"isGameLandscape",{get:function(){return this.width>this.height}}),n.Utils.Debug=function(t){this.game=t,this.sprite=null,this.bmd=null,this.canvas=null,this.context=null,this.font="14px Courier",this.columnWidth=100,this.lineHeight=16,this.renderShadow=!0,this.currentX=0,this.currentY=0,this.currentAlpha=1,this.dirty=!1},n.Utils.Debug.prototype={boot:function(){this.game.renderType===n.CANVAS?this.context=this.game.context:(this.bmd=new n.BitmapData(this.game,"__DEBUG",this.game.width,this.game.height,!0),this.sprite=this.game.make.image(0,0,this.bmd),this.game.stage.addChild(this.sprite),this.game.scale.onSizeChange.add(this.resize,this),this.canvas=PIXI.CanvasPool.create(this,this.game.width,this.game.height),this.context=this.canvas.getContext("2d"))},resize:function(t,e,i){this.bmd.resize(e,i),this.canvas.width=e,this.canvas.height=i},preUpdate:function(){this.dirty&&this.sprite&&(this.bmd.clear(),this.bmd.draw(this.canvas,0,0),this.context.clearRect(0,0,this.game.width,this.game.height),this.dirty=!1)},reset:function(){this.context&&this.context.clearRect(0,0,this.game.width,this.game.height),this.sprite&&this.bmd.clear()},start:function(t,e,i,s){"number"!=typeof t&&(t=0),"number"!=typeof e&&(e=0),i=i||"rgb(255,255,255)",void 0===s&&(s=0),this.currentX=t,this.currentY=e,this.currentColor=i,this.columnWidth=s,this.dirty=!0,this.context.save(),this.context.setTransform(1,0,0,1,0,0),this.context.strokeStyle=i,this.context.fillStyle=i,this.context.font=this.font,this.context.globalAlpha=this.currentAlpha},stop:function(){this.context.restore()},line:function(){for(var t=this.currentX,e=0;e<arguments.length;e++)this.renderShadow&&(this.context.fillStyle="rgb(0,0,0)",this.context.fillText(arguments[e],t+1,this.currentY+1),this.context.fillStyle=this.currentColor),this.context.fillText(arguments[e],t,this.currentY),t+=this.columnWidth;this.currentY+=this.lineHeight},soundInfo:function(t,e,i,s){this.start(e,i,s),this.line("Sound: "+t.key+" Locked: "+t.game.sound.touchLocked),this.line("Is Ready?: "+this.game.cache.isSoundReady(t.key)+" Pending Playback: "+t.pendingPlayback),this.line("Decoded: "+t.isDecoded+" Decoding: "+t.isDecoding),this.line("Total Duration: "+t.totalDuration+" Playing: "+t.isPlaying),this.line("Time: "+t.currentTime),this.line("Volume: "+t.volume+" Muted: "+t.mute),this.line("WebAudio: "+t.usingWebAudio+" Audio: "+t.usingAudioTag),""!==t.currentMarker&&(this.line("Marker: "+t.currentMarker+" Duration: "+t.duration+" (ms: "+t.durationMS+")"),this.line("Start: "+t.markers[t.currentMarker].start+" Stop: "+t.markers[t.currentMarker].stop),this.line("Position: "+t.position)),this.stop()},cameraInfo:function(t,e,i,s){this.start(e,i,s),this.line("Camera ("+t.width+" x "+t.height+")"),this.line("X: "+t.x+" Y: "+t.y),t.bounds&&this.line("Bounds x: "+t.bounds.x+" Y: "+t.bounds.y+" w: "+t.bounds.width+" h: "+t.bounds.height),this.line("View x: "+t.view.x+" Y: "+t.view.y+" w: "+t.view.width+" h: "+t.view.height),this.line("Total in view: "+t.totalInView),this.stop()},timer:function(t,e,i,s){this.start(e,i,s),this.line("Timer (running: "+t.running+" expired: "+t.expired+")"),this.line("Next Tick: "+t.next+" Duration: "+t.duration),this.line("Paused: "+t.paused+" Length: "+t.length),this.stop()},pointer:function(t,e,i,s,n){null!=t&&(void 0===e&&(e=!1),i=i||"rgba(0,255,0,0.5)",s=s||"rgba(255,0,0,0.5)",!0===e&&!0===t.isUp||(this.start(t.x,t.y-100,n),this.context.beginPath(),this.context.arc(t.x,t.y,t.circle.radius,0,2*Math.PI),t.active?this.context.fillStyle=i:this.context.fillStyle=s,this.context.fill(),this.context.closePath(),this.context.beginPath(),this.context.moveTo(t.positionDown.x,t.positionDown.y),this.context.lineTo(t.position.x,t.position.y),this.context.lineWidth=2,this.context.stroke(),this.context.closePath(),this.line("ID: "+t.id+" Active: "+t.active),this.line("World X: "+t.worldX+" World Y: "+t.worldY),this.line("Screen X: "+t.x+" Screen Y: "+t.y+" In: "+t.withinGame),this.line("Duration: "+t.duration+" ms"),this.line("is Down: "+t.isDown+" is Up: "+t.isUp),this.stop()))},spriteInputInfo:function(t,e,i,s){this.start(e,i,s),this.line("Sprite Input: ("+t.width+" x "+t.height+")"),this.line("x: "+t.input.pointerX().toFixed(1)+" y: "+t.input.pointerY().toFixed(1)),this.line("over: "+t.input.pointerOver()+" duration: "+t.input.overDuration().toFixed(0)),this.line("down: "+t.input.pointerDown()+" duration: "+t.input.downDuration().toFixed(0)),this.line("just over: "+t.input.justOver()+" just out: "+t.input.justOut()),this.stop()},key:function(t,e,i,s){this.start(e,i,s,150),this.line("Key:",t.keyCode,"isDown:",t.isDown),this.line("justDown:",t.justDown,"justUp:",t.justUp),this.line("Time Down:",t.timeDown.toFixed(0),"duration:",t.duration.toFixed(0)),this.stop()},inputInfo:function(t,e,i){this.start(t,e,i),this.line("Input"),this.line("X: "+this.game.input.x+" Y: "+this.game.input.y),this.line("World X: "+this.game.input.worldX+" World Y: "+this.game.input.worldY),this.line("Scale X: "+this.game.input.scale.x.toFixed(1)+" Scale Y: "+this.game.input.scale.x.toFixed(1)),this.line("Screen X: "+this.game.input.activePointer.screenX+" Screen Y: "+this.game.input.activePointer.screenY),this.stop()},spriteBounds:function(t,e,i){var s=t.getBounds();s.x+=this.game.camera.x,s.y+=this.game.camera.y,this.rectangle(s,e,i)},ropeSegments:function(t,e,i){var s=this;t.segments.forEach(function(t){s.rectangle(t,e,i)},this)},spriteInfo:function(t,e,i,s){this.start(e,i,s),this.line("Sprite: ("+t.width+" x "+t.height+") anchor: "+t.anchor.x+" x "+t.anchor.y),this.line("x: "+t.x.toFixed(1)+" y: "+t.y.toFixed(1)),this.line("angle: "+t.angle.toFixed(1)+" rotation: "+t.rotation.toFixed(1)),this.line("visible: "+t.visible+" in camera: "+t.inCamera),this.line("bounds x: "+t._bounds.x.toFixed(1)+" y: "+t._bounds.y.toFixed(1)+" w: "+t._bounds.width.toFixed(1)+" h: "+t._bounds.height.toFixed(1)),this.stop()},spriteCoords:function(t,e,i,s){this.start(e,i,s,100),t.name&&this.line(t.name),this.line("x:",t.x.toFixed(2),"y:",t.y.toFixed(2)),this.line("pos x:",t.position.x.toFixed(2),"pos y:",t.position.y.toFixed(2)),this.line("world x:",t.world.x.toFixed(2),"world y:",t.world.y.toFixed(2)),this.stop()},lineInfo:function(t,e,i,s){this.start(e,i,s,80),this.line("start.x:",t.start.x.toFixed(2),"start.y:",t.start.y.toFixed(2)),this.line("end.x:",t.end.x.toFixed(2),"end.y:",t.end.y.toFixed(2)),this.line("length:",t.length.toFixed(2),"angle:",t.angle),this.stop()},pixel:function(t,e,i,s){s=s||2,this.start(),this.context.fillStyle=i,this.context.fillRect(t,e,s,s),this.stop()},geom:function(t,e,i,s){void 0===i&&(i=!0),void 0===s&&(s=0),e=e||"rgba(0,255,0,0.4)",this.start(),this.context.fillStyle=e,this.context.strokeStyle=e,t instanceof n.Rectangle||1===s?i?this.context.fillRect(t.x-this.game.camera.x,t.y-this.game.camera.y,t.width,t.height):this.context.strokeRect(t.x-this.game.camera.x,t.y-this.game.camera.y,t.width,t.height):t instanceof n.Circle||2===s?(this.context.beginPath(),this.context.arc(t.x-this.game.camera.x,t.y-this.game.camera.y,t.radius,0,2*Math.PI,!1),this.context.closePath(),i?this.context.fill():this.context.stroke()):t instanceof n.Point||3===s?this.context.fillRect(t.x-this.game.camera.x,t.y-this.game.camera.y,4,4):(t instanceof n.Line||4===s)&&(this.context.lineWidth=1,this.context.beginPath(),this.context.moveTo(t.start.x+.5-this.game.camera.x,t.start.y+.5-this.game.camera.y),this.context.lineTo(t.end.x+.5-this.game.camera.x,t.end.y+.5-this.game.camera.y),this.context.closePath(),this.context.stroke()),this.stop()},rectangle:function(t,e,i){void 0===i&&(i=!0),e=e||"rgba(0, 255, 0, 0.4)",this.start(),i?(this.context.fillStyle=e,this.context.fillRect(t.x-this.game.camera.x,t.y-this.game.camera.y,t.width,t.height)):(this.context.strokeStyle=e,this.context.strokeRect(t.x-this.game.camera.x,t.y-this.game.camera.y,t.width,t.height)),this.stop()},text:function(t,e,i,s,n){s=s||"rgb(255,255,255)",n=n||"16px Courier",this.start(),this.context.font=n,this.renderShadow&&(this.context.fillStyle="rgb(0,0,0)",this.context.fillText(t,e+1,i+1)),this.context.fillStyle=s,this.context.fillText(t,e,i),this.stop()},quadTree:function(t,e){e=e||"rgba(255,0,0,0.3)",this.start();var i=t.bounds;if(0===t.nodes.length){this.context.strokeStyle=e,this.context.strokeRect(i.x,i.y,i.width,i.height),this.text("size: "+t.objects.length,i.x+4,i.y+16,"rgb(0,200,0)","12px Courier"),this.context.strokeStyle="rgb(0,255,0)";for(var s=0;s<t.objects.length;s++)this.context.strokeRect(t.objects[s].x,t.objects[s].y,t.objects[s].width,t.objects[s].height)}else for(var s=0;s<t.nodes.length;s++)this.quadTree(t.nodes[s]);this.stop()},body:function(t,e,i){t.body&&(this.start(),t.body.type===n.Physics.ARCADE?n.Physics.Arcade.Body.render(this.context,t.body,e,i):t.body.type===n.Physics.NINJA?n.Physics.Ninja.Body.render(this.context,t.body,e,i):t.body.type===n.Physics.BOX2D&&n.Physics.Box2D.renderBody(this.context,t.body,e),this.stop())},bodyInfo:function(t,e,i,s){t.body&&(this.start(e,i,s,210),t.body.type===n.Physics.ARCADE?n.Physics.Arcade.Body.renderBodyInfo(this,t.body):t.body.type===n.Physics.BOX2D&&this.game.physics.box2d.renderBodyInfo(this,t.body),this.stop())},box2dWorld:function(){this.start(),this.context.translate(-this.game.camera.view.x,-this.game.camera.view.y,0),this.game.physics.box2d.renderDebugDraw(this.context),this.stop()},box2dBody:function(t,e){this.start(),n.Physics.Box2D.renderBody(this.context,t,e),this.stop()},displayList:function(t){if(void 0===t&&(t=this.game.world),t.hasOwnProperty("renderOrderID")?console.log("["+t.renderOrderID+"]",t):console.log("[]",t),t.children&&t.children.length>0)for(var e=0;e<t.children.length;e++)this.game.debug.displayList(t.children[e])},destroy:function(){PIXI.CanvasPool.remove(this)}},n.Utils.Debug.prototype.constructor=n.Utils.Debug,n.DOM={getOffset:function(t,e){e=e||new n.Point;var i=t.getBoundingClientRect(),s=n.DOM.scrollY,r=n.DOM.scrollX,o=document.documentElement.clientTop,a=document.documentElement.clientLeft;return e.x=i.left+r-a,e.y=i.top+s-o,e},getBounds:function(t,e){return void 0===e&&(e=0),!(!(t=t&&!t.nodeType?t[0]:t)||1!==t.nodeType)&&this.calibrate(t.getBoundingClientRect(),e)},calibrate:function(t,e){e=+e||0;var i={width:0,height:0,left:0,right:0,top:0,bottom:0};return i.width=(i.right=t.right+e)-(i.left=t.left-e),i.height=(i.bottom=t.bottom+e)-(i.top=t.top-e),i},getAspectRatio:function(t){t=null==t?this.visualBounds:1===t.nodeType?this.getBounds(t):t;var e=t.width,i=t.height;return"function"==typeof e&&(e=e.call(t)),"function"==typeof i&&(i=i.call(t)),e/i},inLayoutViewport:function(t,e){var i=this.getBounds(t,e);return!!i&&i.bottom>=0&&i.right>=0&&i.top<=this.layoutBounds.width&&i.left<=this.layoutBounds.height},getScreenOrientation:function(t){var e=window.screen,i=e.orientation||e.mozOrientation||e.msOrientation;if(i&&"string"==typeof i.type)return i.type;if("string"==typeof i)return i;var s="portrait-primary",n="landscape-primary";if("screen"===t)return e.height>e.width?s:n;if("viewport"===t)return this.visualBounds.height>this.visualBounds.width?s:n;if("window.orientation"===t&&"number"==typeof window.orientation)return 0===window.orientation||180===window.orientation?s:n;if(window.matchMedia){if(window.matchMedia("(orientation: portrait)").matches)return s;if(window.matchMedia("(orientation: landscape)").matches)return n}return this.visualBounds.height>this.visualBounds.width?s:n},visualBounds:new n.Rectangle,layoutBounds:new n.Rectangle,documentBounds:new n.Rectangle},n.Device.whenReady(function(t){var e=window&&"pageXOffset"in window?function(){return window.pageXOffset}:function(){return document.documentElement.scrollLeft},i=window&&"pageYOffset"in window?function(){return window.pageYOffset}:function(){return document.documentElement.scrollTop};if(Object.defineProperty(n.DOM,"scrollX",{get:e}),Object.defineProperty(n.DOM,"scrollY",{get:i}),Object.defineProperty(n.DOM.visualBounds,"x",{get:e}),Object.defineProperty(n.DOM.visualBounds,"y",{get:i}),Object.defineProperty(n.DOM.layoutBounds,"x",{value:0}),Object.defineProperty(n.DOM.layoutBounds,"y",{value:0}),t.desktop&&document.documentElement.clientWidth<=window.innerWidth&&document.documentElement.clientHeight<=window.innerHeight){var s=function(){return Math.max(window.innerWidth,document.documentElement.clientWidth)},r=function(){return Math.max(window.innerHeight,document.documentElement.clientHeight)};Object.defineProperty(n.DOM.visualBounds,"width",{get:s}),Object.defineProperty(n.DOM.visualBounds,"height",{get:r}),Object.defineProperty(n.DOM.layoutBounds,"width",{get:s}),Object.defineProperty(n.DOM.layoutBounds,"height",{get:r})}else Object.defineProperty(n.DOM.visualBounds,"width",{get:function(){return window.innerWidth}}),Object.defineProperty(n.DOM.visualBounds,"height",{get:function(){return window.innerHeight}}),Object.defineProperty(n.DOM.layoutBounds,"width",{get:function(){var t=document.documentElement.clientWidth,e=window.innerWidth;return t<e?e:t}}),Object.defineProperty(n.DOM.layoutBounds,"height",{get:function(){var t=document.documentElement.clientHeight,e=window.innerHeight;return t<e?e:t}});Object.defineProperty(n.DOM.documentBounds,"x",{value:0}),Object.defineProperty(n.DOM.documentBounds,"y",{value:0}),Object.defineProperty(n.DOM.documentBounds,"width",{get:function(){var t=document.documentElement;return Math.max(t.clientWidth,t.offsetWidth,t.scrollWidth)}}),Object.defineProperty(n.DOM.documentBounds,"height",{get:function(){var t=document.documentElement;return Math.max(t.clientHeight,t.offsetHeight,t.scrollHeight)}})},null,!0),n.ArraySet=function(t){this.position=0,this.list=t||[]},n.ArraySet.prototype={add:function(t){return this.exists(t)||this.list.push(t),t},getIndex:function(t){return this.list.indexOf(t)},getByKey:function(t,e){for(var i=this.list.length;i--;)if(this.list[i][t]===e)return this.list[i];return null},exists:function(t){return this.list.indexOf(t)>-1},reset:function(){this.list.length=0},remove:function(t){var e=this.list.indexOf(t);if(e>-1)return this.list.splice(e,1),t},setAll:function(t,e){for(var i=this.list.length;i--;)this.list[i]&&(this.list[i][t]=e)},callAll:function(t){for(var e=Array.prototype.slice.call(arguments,1),i=this.list.length;i--;)this.list[i]&&this.list[i][t]&&this.list[i][t].apply(this.list[i],e)},removeAll:function(t){void 0===t&&(t=!1);for(var e=this.list.length;e--;)if(this.list[e]){var i=this.remove(this.list[e]);t&&i.destroy()}this.position=0,this.list=[]}},Object.defineProperty(n.ArraySet.prototype,"total",{get:function(){return this.list.length}}),Object.defineProperty(n.ArraySet.prototype,"first",{get:function(){return this.position=0,this.list.length>0?this.list[0]:null}}),Object.defineProperty(n.ArraySet.prototype,"next",{get:function(){return this.position<this.list.length?(this.position++,this.list[this.position]):null}}),n.ArraySet.prototype.constructor=n.ArraySet,n.ArrayUtils={getRandomItem:function(t,e,i){if(null===t)return null;void 0===e&&(e=0),void 0===i&&(i=t.length);var s=e+Math.floor(Math.random()*i);return void 0===t[s]?null:t[s]},removeRandomItem:function(t,e,i){if(null==t)return null;void 0===e&&(e=0),void 0===i&&(i=t.length);var s=e+Math.floor(Math.random()*i);if(s<t.length){var n=t.splice(s,1);return void 0===n[0]?null:n[0]}return null},shuffle:function(t){for(var e=t.length-1;e>0;e--){var i=Math.floor(Math.random()*(e+1)),s=t[e];t[e]=t[i],t[i]=s}return t},transposeMatrix:function(t){for(var e=t.length,i=t[0].length,s=new Array(i),n=0;n<i;n++){s[n]=new Array(e);for(var r=e-1;r>-1;r--)s[n][r]=t[r][n]}return s},rotateMatrix:function(t,e){if("string"!=typeof e&&(e=(e%360+360)%360),90===e||-270===e||"rotateLeft"===e)t=n.ArrayUtils.transposeMatrix(t),t=t.reverse();else if(-90===e||270===e||"rotateRight"===e)t=t.reverse(),t=n.ArrayUtils.transposeMatrix(t);else if(180===Math.abs(e)||"rotate180"===e){for(var i=0;i<t.length;i++)t[i].reverse();t=t.reverse()}return t},findClosest:function(t,e){if(!e.length)return NaN;if(1===e.length||t<e[0])return e[0];for(var i=1;e[i]<t;)i++;var s=e[i-1],n=i<e.length?e[i]:Number.POSITIVE_INFINITY;return n-t<=t-s?n:s},rotateRight:function(t){var e=t.pop();return t.unshift(e),e},rotateLeft:function(t){var e=t.shift();return t.push(e),e},rotate:function(t){var e=t.shift();return t.push(e),e},numberArray:function(t,e){for(var i=[],s=t;s<=e;s++)i.push(s);return i},numberArrayStep:function(t,e,i){void 0!==t&&null!==t||(t=0),void 0!==e&&null!==e||(e=t,t=0),void 0===i&&(i=1);for(var s=[],r=Math.max(n.Math.roundAwayFromZero((e-t)/(i||1)),0),o=0;o<r;o++)s.push(t),t+=i;return s}},n.LinkedList=function(){this.next=null,this.prev=null,this.first=null,this.last=null,this.total=0},n.LinkedList.prototype={add:function(t){return 0===this.total&&null===this.first&&null===this.last?(this.first=t,this.last=t,this.next=t,t.prev=this,this.total++,t):(this.last.next=t,t.prev=this.last,this.last=t,this.total++,t)},reset:function(){this.first=null,this.last=null,this.next=null,this.prev=null,this.total=0},remove:function(t){if(1===this.total)return this.reset(),void(t.next=t.prev=null);t===this.first?this.first=this.first.next:t===this.last&&(this.last=this.last.prev),t.prev&&(t.prev.next=t.next),t.next&&(t.next.prev=t.prev),t.next=t.prev=null,null===this.first&&(this.last=null),this.total--},callAll:function(t){if(this.first&&this.last){var e=this.first;do{e&&e[t]&&e[t].call(e),e=e.next}while(e!==this.last.next)}}},n.LinkedList.prototype.constructor=n.LinkedList,n.Create=function(t){this.game=t,this.bmd=null,this.canvas=null,this.ctx=null,this.palettes=[{0:"#000",1:"#9D9D9D",2:"#FFF",3:"#BE2633",4:"#E06F8B",5:"#493C2B",6:"#A46422",7:"#EB8931",8:"#F7E26B",9:"#2F484E",A:"#44891A",B:"#A3CE27",C:"#1B2632",D:"#005784",E:"#31A2F2",F:"#B2DCEF"},{0:"#000",1:"#191028",2:"#46af45",3:"#a1d685",4:"#453e78",5:"#7664fe",6:"#833129",7:"#9ec2e8",8:"#dc534b",9:"#e18d79",A:"#d6b97b",B:"#e9d8a1",C:"#216c4b",D:"#d365c8",E:"#afaab9",F:"#f5f4eb"},{0:"#000",1:"#2234d1",2:"#0c7e45",3:"#44aacc",4:"#8a3622",5:"#5c2e78",6:"#aa5c3d",7:"#b5b5b5",8:"#5e606e",9:"#4c81fb",A:"#6cd947",B:"#7be2f9",C:"#eb8a60",D:"#e23d69",E:"#ffd93f",F:"#fff"},{0:"#000",1:"#fff",2:"#8b4131",3:"#7bbdc5",4:"#8b41ac",5:"#6aac41",6:"#3931a4",7:"#d5de73",8:"#945a20",9:"#5a4100",A:"#bd736a",B:"#525252",C:"#838383",D:"#acee8b",E:"#7b73de",F:"#acacac"},{0:"#000",1:"#191028",2:"#46af45",3:"#a1d685",4:"#453e78",5:"#7664fe",6:"#833129",7:"#9ec2e8",8:"#dc534b",9:"#e18d79",A:"#d6b97b",B:"#e9d8a1",C:"#216c4b",D:"#d365c8",E:"#afaab9",F:"#fff"}]},n.Create.PALETTE_ARNE=0,n.Create.PALETTE_JMP=1,n.Create.PALETTE_CGA=2,n.Create.PALETTE_C64=3,n.Create.PALETTE_JAPANESE_MACHINE=4,n.Create.prototype={texture:function(t,e,i,s,n){void 0===i&&(i=8),void 0===s&&(s=i),void 0===n&&(n=0);var r=e[0].length*i,o=e.length*s;null===this.bmd&&(this.bmd=this.game.make.bitmapData(),this.canvas=this.bmd.canvas,this.ctx=this.bmd.context),this.bmd.resize(r,o),this.bmd.clear();for(var a=0;a<e.length;a++)for(var h=e[a],l=0;l<h.length;l++){var c=h[l];"."!==c&&" "!==c&&(this.ctx.fillStyle=this.palettes[n][c],this.ctx.fillRect(l*i,a*s,i,s))}return this.bmd.generateTexture(t)},grid:function(t,e,i,s,n,r){null===this.bmd&&(this.bmd=this.game.make.bitmapData(),this.canvas=this.bmd.canvas,this.ctx=this.bmd.context),this.bmd.resize(e,i),this.ctx.fillStyle=r;for(var o=0;o<i;o+=n)this.ctx.fillRect(0,o,e,1);for(var a=0;a<e;a+=s)this.ctx.fillRect(a,0,1,i);return this.bmd.generateTexture(t)}},n.Create.prototype.constructor=n.Create,n.FlexGrid=function(t,e,i){this.game=t.game,this.manager=t,this.width=e,this.height=i,this.boundsCustom=new n.Rectangle(0,0,e,i),this.boundsFluid=new n.Rectangle(0,0,e,i),this.boundsFull=new n.Rectangle(0,0,e,i),this.boundsNone=new n.Rectangle(0,0,e,i),this.positionCustom=new n.Point(0,0),this.positionFluid=new n.Point(0,0),this.positionFull=new n.Point(0,0),this.positionNone=new n.Point(0,0),this.scaleCustom=new n.Point(1,1),this.scaleFluid=new n.Point(1,1),this.scaleFluidInversed=new n.Point(1,1),this.scaleFull=new n.Point(1,1),this.scaleNone=new n.Point(1,1),this.customWidth=0,this.customHeight=0,this.customOffsetX=0,this.customOffsetY=0,this.ratioH=e/i,this.ratioV=i/e,this.multiplier=0,this.layers=[]},n.FlexGrid.prototype={setSize:function(t,e){this.width=t,this.height=e,this.ratioH=t/e,this.ratioV=e/t,this.scaleNone=new n.Point(1,1),this.boundsNone.width=this.width,this.boundsNone.height=this.height,this.refresh()},createCustomLayer:function(t,e,i,s){void 0===s&&(s=!0),this.customWidth=t,this.customHeight=e,this.boundsCustom.width=t,this.boundsCustom.height=e;var r=new n.FlexLayer(this,this.positionCustom,this.boundsCustom,this.scaleCustom);return s&&this.game.world.add(r),this.layers.push(r),void 0!==i&&null!==typeof i&&r.addMultiple(i),r},createFluidLayer:function(t,e){void 0===e&&(e=!0);var i=new n.FlexLayer(this,this.positionFluid,this.boundsFluid,this.scaleFluid);return e&&this.game.world.add(i),this.layers.push(i),void 0!==t&&null!==typeof t&&i.addMultiple(t),i},createFullLayer:function(t){var e=new n.FlexLayer(this,this.positionFull,this.boundsFull,this.scaleFluid);return this.game.world.add(e),this.layers.push(e),void 0!==t&&e.addMultiple(t),e},createFixedLayer:function(t){var e=new n.FlexLayer(this,this.positionNone,this.boundsNone,this.scaleNone);return this.game.world.add(e),this.layers.push(e),void 0!==t&&e.addMultiple(t),e},reset:function(){for(var t=this.layers.length;t--;)this.layers[t].persist||(this.layers[t].position=null,this.layers[t].scale=null,this.layers.slice(t,1))},onResize:function(t,e){this.ratioH=t/e,this.ratioV=e/t,this.refresh(t,e)},refresh:function(){this.multiplier=Math.min(this.manager.height/this.height,this.manager.width/this.width),this.boundsFluid.width=Math.round(this.width*this.multiplier),this.boundsFluid.height=Math.round(this.height*this.multiplier),this.scaleFluid.set(this.boundsFluid.width/this.width,this.boundsFluid.height/this.height),this.scaleFluidInversed.set(this.width/this.boundsFluid.width,this.height/this.boundsFluid.height),this.scaleFull.set(this.boundsFull.width/this.width,this.boundsFull.height/this.height),this.boundsFull.width=Math.round(this.manager.width*this.scaleFluidInversed.x),this.boundsFull.height=Math.round(this.manager.height*this.scaleFluidInversed.y),this.boundsFluid.centerOn(this.manager.bounds.centerX,this.manager.bounds.centerY),this.boundsNone.centerOn(this.manager.bounds.centerX,this.manager.bounds.centerY),this.positionFluid.set(this.boundsFluid.x,this.boundsFluid.y),this.positionNone.set(this.boundsNone.x,this.boundsNone.y)},fitSprite:function(t){this.manager.scaleSprite(t),t.x=this.manager.bounds.centerX,t.y=this.manager.bounds.centerY},debug:function(){this.game.debug.text(this.boundsFluid.width+" x "+this.boundsFluid.height,this.boundsFluid.x+4,this.boundsFluid.y+16),this.game.debug.geom(this.boundsFluid,"rgba(255,0,0,0.9",!1)}},n.FlexGrid.prototype.constructor=n.FlexGrid,n.FlexLayer=function(t,e,i,s){n.Group.call(this,t.game,null,"__flexLayer"+t.game.rnd.uuid(),!1),this.manager=t.manager,this.grid=t,this.persist=!1,this.position=e,this.bounds=i,this.scale=s,this.topLeft=i.topLeft,this.topMiddle=new n.Point(i.halfWidth,0),this.topRight=i.topRight,this.bottomLeft=i.bottomLeft,this.bottomMiddle=new n.Point(i.halfWidth,i.bottom),this.bottomRight=i.bottomRight},n.FlexLayer.prototype=Object.create(n.Group.prototype),n.FlexLayer.prototype.constructor=n.FlexLayer,n.FlexLayer.prototype.resize=function(){},n.FlexLayer.prototype.debug=function(){this.game.debug.text(this.bounds.width+" x "+this.bounds.height,this.bounds.x+4,this.bounds.y+16),this.game.debug.geom(this.bounds,"rgba(0,0,255,0.9",!1),this.game.debug.geom(this.topLeft,"rgba(255,255,255,0.9"),this.game.debug.geom(this.topMiddle,"rgba(255,255,255,0.9"),this.game.debug.geom(this.topRight,"rgba(255,255,255,0.9")},n.Color={packPixel:function(t,e,i,s){return n.Device.LITTLE_ENDIAN?(s<<24|i<<16|e<<8|t)>>>0:(t<<24|e<<16|i<<8|s)>>>0},unpackPixel:function(t,e,i,s){return void 0!==e&&null!==e||(e=n.Color.createColor()),void 0!==i&&null!==i||(i=!1),void 0!==s&&null!==s||(s=!1),n.Device.LITTLE_ENDIAN?(e.a=(4278190080&t)>>>24,e.b=(16711680&t)>>>16,e.g=(65280&t)>>>8,e.r=255&t):(e.r=(4278190080&t)>>>24,e.g=(16711680&t)>>>16,e.b=(65280&t)>>>8,e.a=255&t),e.color=t,e.rgba="rgba("+e.r+","+e.g+","+e.b+","+e.a/255+")",i&&n.Color.RGBtoHSL(e.r,e.g,e.b,e),s&&n.Color.RGBtoHSV(e.r,e.g,e.b,e),e},fromRGBA:function(t,e){return e||(e=n.Color.createColor()),e.r=(4278190080&t)>>>24,e.g=(16711680&t)>>>16,e.b=(65280&t)>>>8,e.a=255&t,e.rgba="rgba("+e.r+","+e.g+","+e.b+","+e.a+")",e},toRGBA:function(t,e,i,s){return t<<24|e<<16|i<<8|s},toABGR:function(t,e,i,s){return(s<<24|i<<16|e<<8|t)>>>0},RGBtoHSL:function(t,e,i,s){s||(s=n.Color.createColor(t,e,i,1)),t/=255,e/=255,i/=255;var r=Math.min(t,e,i),o=Math.max(t,e,i);if(s.h=0,s.s=0,s.l=(o+r)/2,o!==r){var a=o-r;s.s=s.l>.5?a/(2-o-r):a/(o+r),o===t?s.h=(e-i)/a+(e<i?6:0):o===e?s.h=(i-t)/a+2:o===i&&(s.h=(t-e)/a+4),s.h/=6}return s},HSLtoRGB:function(t,e,i,s){if(s?(s.r=i,s.g=i,s.b=i):s=n.Color.createColor(i,i,i),0!==e){var r=i<.5?i*(1+e):i+e-i*e,o=2*i-r;s.r=n.Color.hueToColor(o,r,t+1/3),s.g=n.Color.hueToColor(o,r,t),s.b=n.Color.hueToColor(o,r,t-1/3)}return s.r=Math.floor(255*s.r|0),s.g=Math.floor(255*s.g|0),s.b=Math.floor(255*s.b|0),n.Color.updateColor(s),s},RGBtoHSV:function(t,e,i,s){s||(s=n.Color.createColor(t,e,i,255)),t/=255,e/=255,i/=255;var r=Math.min(t,e,i),o=Math.max(t,e,i),a=o-r;return s.h=0,s.s=0===o?0:a/o,s.v=o,o!==r&&(o===t?s.h=(e-i)/a+(e<i?6:0):o===e?s.h=(i-t)/a+2:o===i&&(s.h=(t-e)/a+4),s.h/=6),s},HSVtoRGB:function(t,e,i,s){void 0===s&&(s=n.Color.createColor(0,0,0,1,t,e,0,i));var r,o,a,h=Math.floor(6*t),l=6*t-h,c=i*(1-e),u=i*(1-l*e),d=i*(1-(1-l)*e);switch(h%6){case 0:r=i,o=d,a=c;break;case 1:r=u,o=i,a=c;break;case 2:r=c,o=i,a=d;break;case 3:r=c,o=u,a=i;break;case 4:r=d,o=c,a=i;break;case 5:r=i,o=c,a=u}return s.r=Math.floor(255*r),s.g=Math.floor(255*o),s.b=Math.floor(255*a),n.Color.updateColor(s),s},hueToColor:function(t,e,i){return i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t},createColor:function(t,e,i,s,r,o,a,h){var l={r:t||0,g:e||0,b:i||0,a:s||1,h:r||0,s:o||0,l:a||0,v:h||0,color:0,color32:0,rgba:""};return n.Color.updateColor(l)},updateColor:function(t){return t.rgba="rgba("+t.r.toString()+","+t.g.toString()+","+t.b.toString()+","+t.a.toString()+")",t.color=n.Color.getColor(t.r,t.g,t.b),t.color32=n.Color.getColor32(255*t.a,t.r,t.g,t.b),t},getColor32:function(t,e,i,s){return t<<24|e<<16|i<<8|s},getColor:function(t,e,i){return t<<16|e<<8|i},RGBtoString:function(t,e,i,s,r){return void 0===s&&(s=255),void 0===r&&(r="#"),"#"===r?"#"+((1<<24)+(t<<16)+(e<<8)+i).toString(16).slice(1):"0x"+n.Color.componentToHex(s)+n.Color.componentToHex(t)+n.Color.componentToHex(e)+n.Color.componentToHex(i)},hexToRGB:function(t){var e=n.Color.hexToColor(t);if(e)return n.Color.getColor32(e.a,e.r,e.g,e.b)},hexToColor:function(t,e){t=t.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i,function(t,e,i,s){return e+e+i+i+s+s});var i=/^(?:#|0x)?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);if(i){var s=parseInt(i[1],16),r=parseInt(i[2],16),o=parseInt(i[3],16);e?(e.r=s,e.g=r,e.b=o):e=n.Color.createColor(s,r,o)}return e},webToColor:function(t,e){e||(e=n.Color.createColor());var i=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?))?\s*\)$/.exec(t);return i&&(e.r=parseInt(i[1],10),e.g=parseInt(i[2],10),e.b=parseInt(i[3],10),e.a=void 0!==i[4]?parseFloat(i[4]):1,n.Color.updateColor(e)),e},valueToColor:function(t,e){if(e||(e=n.Color.createColor()),"string"==typeof t)return 0===t.indexOf("rgb")?n.Color.webToColor(t,e):(e.a=1,n.Color.hexToColor(t,e));if("number"==typeof t){var i=n.Color.getRGB(t);return e.r=i.r,e.g=i.g,e.b=i.b,e.a=i.a/255,e}return e},componentToHex:function(t){var e=t.toString(16);return 1===e.length?"0"+e:e},HSVColorWheel:function(t,e){void 0===t&&(t=1),void 0===e&&(e=1);for(var i=[],s=0;s<=359;s++)i.push(n.Color.HSVtoRGB(s/359,t,e));return i},HSLColorWheel:function(t,e){void 0===t&&(t=.5),void 0===e&&(e=.5);for(var i=[],s=0;s<=359;s++)i.push(n.Color.HSLtoRGB(s/359,t,e));return i},interpolateColor:function(t,e,i,s,r){void 0===r&&(r=255);var o=n.Color.getRGB(t),a=n.Color.getRGB(e),h=(a.red-o.red)*s/i+o.red,l=(a.green-o.green)*s/i+o.green,c=(a.blue-o.blue)*s/i+o.blue;return n.Color.getColor32(r,h,l,c)},interpolateColorWithRGB:function(t,e,i,s,r,o){var a=n.Color.getRGB(t),h=(e-a.red)*o/r+a.red,l=(i-a.green)*o/r+a.green,c=(s-a.blue)*o/r+a.blue;return n.Color.getColor(h,l,c)},interpolateRGB:function(t,e,i,s,r,o,a,h){var l=(s-t)*h/a+t,c=(r-e)*h/a+e,u=(o-i)*h/a+i;return n.Color.getColor(l,c,u)},getRandomColor:function(t,e,i){if(void 0===t&&(t=0),void 0===e&&(e=255),void 0===i&&(i=255),e>255||t>e)return n.Color.getColor(255,255,255);var s=t+Math.round(Math.random()*(e-t)),r=t+Math.round(Math.random()*(e-t)),o=t+Math.round(Math.random()*(e-t));return n.Color.getColor32(i,s,r,o)},getRGB:function(t){return t>16777215?{alpha:t>>>24,red:t>>16&255,green:t>>8&255,blue:255&t,a:t>>>24,r:t>>16&255,g:t>>8&255,b:255&t}:{alpha:255,red:t>>16&255,green:t>>8&255,blue:255&t,a:255,r:t>>16&255,g:t>>8&255,b:255&t}},getWebRGB:function(t){if("object"==typeof t)return"rgba("+t.r.toString()+","+t.g.toString()+","+t.b.toString()+","+(t.a/255).toString()+")";var e=n.Color.getRGB(t);return"rgba("+e.r.toString()+","+e.g.toString()+","+e.b.toString()+","+(e.a/255).toString()+")"},getAlpha:function(t){return t>>>24},getAlphaFloat:function(t){return(t>>>24)/255},getRed:function(t){return t>>16&255},getGreen:function(t){return t>>8&255},getBlue:function(t){return 255&t},blendNormal:function(t){return t},blendLighten:function(t,e){return e>t?e:t},blendDarken:function(t,e){return e>t?t:e},blendMultiply:function(t,e){return t*e/255},blendAverage:function(t,e){return(t+e)/2},blendAdd:function(t,e){return Math.min(255,t+e)},blendSubtract:function(t,e){return Math.max(0,t+e-255)},blendDifference:function(t,e){return Math.abs(t-e)},blendNegation:function(t,e){return 255-Math.abs(255-t-e)},blendScreen:function(t,e){return 255-((255-t)*(255-e)>>8)},blendExclusion:function(t,e){return t+e-2*t*e/255},blendOverlay:function(t,e){return e<128?2*t*e/255:255-2*(255-t)*(255-e)/255},blendSoftLight:function(t,e){return e<128?2*(64+(t>>1))*(e/255):255-2*(255-(64+(t>>1)))*(255-e)/255},blendHardLight:function(t,e){return n.Color.blendOverlay(e,t)},blendColorDodge:function(t,e){return 255===e?e:Math.min(255,(t<<8)/(255-e))},blendColorBurn:function(t,e){return 0===e?e:Math.max(0,255-(255-t<<8)/e)},blendLinearDodge:function(t,e){return n.Color.blendAdd(t,e)},blendLinearBurn:function(t,e){return n.Color.blendSubtract(t,e)},blendLinearLight:function(t,e){return e<128?n.Color.blendLinearBurn(t,2*e):n.Color.blendLinearDodge(t,2*(e-128))},blendVividLight:function(t,e){return e<128?n.Color.blendColorBurn(t,2*e):n.Color.blendColorDodge(t,2*(e-128))},blendPinLight:function(t,e){return e<128?n.Color.blendDarken(t,2*e):n.Color.blendLighten(t,2*(e-128))},blendHardMix:function(t,e){return n.Color.blendVividLight(t,e)<128?0:255},blendReflect:function(t,e){return 255===e?e:Math.min(255,t*t/(255-e))},blendGlow:function(t,e){return n.Color.blendReflect(e,t)},blendPhoenix:function(t,e){return Math.min(t,e)-Math.max(t,e)+255}},n.Physics=function(t,e){e=e||{},this.game=t,this.config=e,this.arcade=null,this.p2=null,this.ninja=null,this.box2d=null,this.chipmunk=null,this.matter=null,this.parseConfig()},n.Physics.ARCADE=0,n.Physics.P2JS=1,n.Physics.NINJA=2,n.Physics.BOX2D=3,n.Physics.CHIPMUNK=4,n.Physics.MATTERJS=5,n.Physics.prototype={parseConfig:function(){this.config.hasOwnProperty("arcade")&&!0!==this.config.arcade||!n.Physics.hasOwnProperty("Arcade")||(this.arcade=new n.Physics.Arcade(this.game)),this.config.hasOwnProperty("ninja")&&!0===this.config.ninja&&n.Physics.hasOwnProperty("Ninja")&&(this.ninja=new n.Physics.Ninja(this.game)),this.config.hasOwnProperty("p2")&&!0===this.config.p2&&n.Physics.hasOwnProperty("P2")&&(this.p2=new n.Physics.P2(this.game,this.config)),this.config.hasOwnProperty("box2d")&&!0===this.config.box2d&&n.Physics.hasOwnProperty("BOX2D")&&(this.box2d=new n.Physics.BOX2D(this.game,this.config)),this.config.hasOwnProperty("matter")&&!0===this.config.matter&&n.Physics.hasOwnProperty("Matter")&&(this.matter=new n.Physics.Matter(this.game,this.config))},startSystem:function(t){t===n.Physics.ARCADE?this.arcade=new n.Physics.Arcade(this.game):t===n.Physics.P2JS?null===this.p2?this.p2=new n.Physics.P2(this.game,this.config):this.p2.reset():t===n.Physics.NINJA?this.ninja=new n.Physics.Ninja(this.game):t===n.Physics.BOX2D?null===this.box2d?this.box2d=new n.Physics.Box2D(this.game,this.config):this.box2d.reset():t===n.Physics.MATTERJS&&(null===this.matter?this.matter=new n.Physics.Matter(this.game,this.config):this.matter.reset())},enable:function(t,e,i){void 0===e&&(e=n.Physics.ARCADE),void 0===i&&(i=!1),e===n.Physics.ARCADE?this.arcade.enable(t):e===n.Physics.P2JS&&this.p2?this.p2.enable(t,i):e===n.Physics.NINJA&&this.ninja?this.ninja.enableAABB(t):e===n.Physics.BOX2D&&this.box2d?this.box2d.enable(t):e===n.Physics.MATTERJS&&this.matter?this.matter.enable(t):console.warn(t.key+" is attempting to enable a physics body using an unknown physics system.")},preUpdate:function(){this.p2&&this.p2.preUpdate(),this.box2d&&this.box2d.preUpdate(),this.matter&&this.matter.preUpdate()},update:function(){this.p2&&this.p2.update(),this.box2d&&this.box2d.update(),this.matter&&this.matter.update()},setBoundsToWorld:function(){this.arcade&&this.arcade.setBoundsToWorld(),this.ninja&&this.ninja.setBoundsToWorld(),this.p2&&this.p2.setBoundsToWorld(),this.box2d&&this.box2d.setBoundsToWorld(),this.matter&&this.matter.setBoundsToWorld()},clear:function(){this.p2&&this.p2.clear(),this.box2d&&this.box2d.clear(),this.matter&&this.matter.clear()},reset:function(){this.p2&&this.p2.reset(),this.box2d&&this.box2d.reset(),this.matter&&this.matter.reset()},destroy:function(){this.p2&&this.p2.destroy(),this.box2d&&this.box2d.destroy(),this.matter&&this.matter.destroy(),this.arcade=null,this.ninja=null,this.p2=null,this.box2d=null,this.matter=null}},n.Physics.prototype.constructor=n.Physics,n.Physics.Arcade=function(t){this.game=t,this.gravity=new n.Point,this.bounds=new n.Rectangle(0,0,t.world.width,t.world.height),this.checkCollision={up:!0,down:!0,left:!0,right:!0},this.maxObjects=10,this.maxLevels=4,this.OVERLAP_BIAS=4,this.forceX=!1,this.sortDirection=n.Physics.Arcade.LEFT_RIGHT,this.skipQuadTree=!0,this.isPaused=!1,this.quadTree=new n.QuadTree(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height,this.maxObjects,this.maxLevels),this._total=0,this.setBoundsToWorld()},n.Physics.Arcade.prototype.constructor=n.Physics.Arcade,n.Physics.Arcade.SORT_NONE=0,n.Physics.Arcade.LEFT_RIGHT=1,n.Physics.Arcade.RIGHT_LEFT=2,n.Physics.Arcade.TOP_BOTTOM=3,n.Physics.Arcade.BOTTOM_TOP=4,n.Physics.Arcade.prototype={setBounds:function(t,e,i,s){this.bounds.setTo(t,e,i,s)},setBoundsToWorld:function(){this.bounds.copyFrom(this.game.world.bounds)},enable:function(t,e){void 0===e&&(e=!0);var i=1;if(Array.isArray(t))for(i=t.length;i--;)t[i]instanceof n.Group?this.enable(t[i].children,e):(this.enableBody(t[i]),e&&t[i].hasOwnProperty("children")&&t[i].children.length>0&&this.enable(t[i],!0));else t instanceof n.Group?this.enable(t.children,e):(this.enableBody(t),e&&t.hasOwnProperty("children")&&t.children.length>0&&this.enable(t.children,!0))},enableBody:function(t){t.hasOwnProperty("body")&&null===t.body&&(t.body=new n.Physics.Arcade.Body(t),t.parent&&t.parent instanceof n.Group&&t.parent.addToHash(t))},updateMotion:function(t){var e=this.computeVelocity(0,t,t.angularVelocity,t.angularAcceleration,t.angularDrag,t.maxAngular)-t.angularVelocity;t.angularVelocity+=e,t.rotation+=t.angularVelocity*this.game.time.physicsElapsed,t.velocity.x=this.computeVelocity(1,t,t.velocity.x,t.acceleration.x,t.drag.x,t.maxVelocity.x),t.velocity.y=this.computeVelocity(2,t,t.velocity.y,t.acceleration.y,t.drag.y,t.maxVelocity.y)},computeVelocity:function(t,e,i,s,n,r){return void 0===r&&(r=1e4),1===t&&e.allowGravity?i+=(this.gravity.x+e.gravity.x)*this.game.time.physicsElapsed:2===t&&e.allowGravity&&(i+=(this.gravity.y+e.gravity.y)*this.game.time.physicsElapsed),s?i+=s*this.game.time.physicsElapsed:n&&(n*=this.game.time.physicsElapsed,i-n>0?i-=n:i+n<0?i+=n:i=0),i>r?i=r:i<-r&&(i=-r),i},overlap:function(t,e,i,s,n){if(i=i||null,s=s||null,n=n||i,this._total=0,!Array.isArray(t)&&Array.isArray(e))for(var r=0;r<e.length;r++)this.collideHandler(t,e[r],i,s,n,!0);else if(Array.isArray(t)&&!Array.isArray(e))for(var r=0;r<t.length;r++)this.collideHandler(t[r],e,i,s,n,!0);else if(Array.isArray(t)&&Array.isArray(e))for(var r=0;r<t.length;r++)for(var o=0;o<e.length;o++)this.collideHandler(t[r],e[o],i,s,n,!0);else this.collideHandler(t,e,i,s,n,!0);return this._total>0},collide:function(t,e,i,s,n){if(i=i||null,s=s||null,n=n||i,this._total=0,!Array.isArray(t)&&Array.isArray(e))for(var r=0;r<e.length;r++)this.collideHandler(t,e[r],i,s,n,!1);else if(Array.isArray(t)&&!Array.isArray(e))for(var r=0;r<t.length;r++)this.collideHandler(t[r],e,i,s,n,!1);else if(Array.isArray(t)&&Array.isArray(e))for(var r=0;r<t.length;r++)for(var o=0;o<e.length;o++)this.collideHandler(t[r],e[o],i,s,n,!1);else this.collideHandler(t,e,i,s,n,!1);return this._total>0},sortLeftRight:function(t,e){return t.body&&e.body?t.body.x-e.body.x:0},sortRightLeft:function(t,e){return t.body&&e.body?e.body.x-t.body.x:0},sortTopBottom:function(t,e){return t.body&&e.body?t.body.y-e.body.y:0},sortBottomTop:function(t,e){return t.body&&e.body?e.body.y-t.body.y:0},sort:function(t,e){null!==t.physicsSortDirection?e=t.physicsSortDirection:void 0===e&&(e=this.sortDirection),e===n.Physics.Arcade.LEFT_RIGHT?t.hash.sort(this.sortLeftRight):e===n.Physics.Arcade.RIGHT_LEFT?t.hash.sort(this.sortRightLeft):e===n.Physics.Arcade.TOP_BOTTOM?t.hash.sort(this.sortTopBottom):e===n.Physics.Arcade.BOTTOM_TOP&&t.hash.sort(this.sortBottomTop)},collideHandler:function(t,e,i,s,r,o){if(void 0===e&&t.physicsType===n.GROUP)return this.sort(t),void this.collideGroupVsSelf(t,i,s,r,o);t&&e&&t.exists&&e.exists&&(this.sortDirection!==n.Physics.Arcade.SORT_NONE&&(t.physicsType===n.GROUP&&this.sort(t),e.physicsType===n.GROUP&&this.sort(e)),t.physicsType===n.SPRITE?e.physicsType===n.SPRITE?this.collideSpriteVsSprite(t,e,i,s,r,o):e.physicsType===n.GROUP?this.collideSpriteVsGroup(t,e,i,s,r,o):e.physicsType===n.TILEMAPLAYER&&this.collideSpriteVsTilemapLayer(t,e,i,s,r,o):t.physicsType===n.GROUP?e.physicsType===n.SPRITE?this.collideSpriteVsGroup(e,t,i,s,r,o):e.physicsType===n.GROUP?this.collideGroupVsGroup(t,e,i,s,r,o):e.physicsType===n.TILEMAPLAYER&&this.collideGroupVsTilemapLayer(t,e,i,s,r,o):t.physicsType===n.TILEMAPLAYER&&(e.physicsType===n.SPRITE?this.collideSpriteVsTilemapLayer(e,t,i,s,r,o):e.physicsType===n.GROUP&&this.collideGroupVsTilemapLayer(e,t,i,s,r,o)))},collideSpriteVsSprite:function(t,e,i,s,n,r){return!(!t.body||!e.body)&&(this.separate(t.body,e.body,s,n,r)&&(i&&i.call(n,t,e),this._total++),!0)},collideSpriteVsGroup:function(t,e,i,s,r,o){if(0!==e.length&&t.body)if(this.skipQuadTree||t.body.skipQuadTree)for(var a={},h=0;h<e.hash.length;h++){var l=e.hash[h];if(l&&l.exists&&l.body){if(a=l.body.getBounds(a),this.sortDirection===n.Physics.Arcade.LEFT_RIGHT){if(t.body.right<a.x)break;if(a.right<t.body.x)continue}else if(this.sortDirection===n.Physics.Arcade.RIGHT_LEFT){if(t.body.x>a.right)break;if(a.x>t.body.right)continue}else if(this.sortDirection===n.Physics.Arcade.TOP_BOTTOM){if(t.body.bottom<a.y)break;if(a.bottom<t.body.y)continue}else if(this.sortDirection===n.Physics.Arcade.BOTTOM_TOP){if(t.body.y>a.bottom)break;if(a.y>t.body.bottom)continue}this.collideSpriteVsSprite(t,l,i,s,r,o)}}else{this.quadTree.clear(),this.quadTree.reset(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height,this.maxObjects,this.maxLevels),this.quadTree.populate(e);for(var c=this.quadTree.retrieve(t),h=0;h<c.length;h++)this.separate(t.body,c[h],s,r,o)&&(i&&i.call(r,t,c[h].sprite),this._total++)}},collideGroupVsSelf:function(t,e,i,s,r){if(0!==t.length)for(var o=0;o<t.hash.length;o++){var a={},h=t.hash[o];if(h&&h.exists&&h.body){a=h.body.getBounds(a);for(var l=o+1;l<t.hash.length;l++){var c={},u=t.hash[l];if(u&&u.exists&&u.body){if(c=u.body.getBounds(c),this.sortDirection===n.Physics.Arcade.LEFT_RIGHT){if(a.right<c.x)break;if(c.right<a.x)continue}else if(this.sortDirection===n.Physics.Arcade.RIGHT_LEFT){if(a.x>c.right)continue;if(c.x>a.right)break}else if(this.sortDirection===n.Physics.Arcade.TOP_BOTTOM){if(a.bottom<c.y)continue;if(c.bottom<a.y)break}else if(this.sortDirection===n.Physics.Arcade.BOTTOM_TOP){if(a.y>c.bottom)continue;if(c.y>h.body.bottom)break}this.collideSpriteVsSprite(h,u,e,i,s,r)}}}}},collideGroupVsGroup:function(t,e,i,s,r,o){if(0!==t.length&&0!==e.length)for(var a=0;a<t.children.length;a++)t.children[a].exists&&(t.children[a].physicsType===n.GROUP?this.collideGroupVsGroup(t.children[a],e,i,s,r,o):this.collideSpriteVsGroup(t.children[a],e,i,s,r,o))},separate:function(t,e,i,s,n){if(!t.enable||!e.enable||t.checkCollision.none||e.checkCollision.none||!this.intersects(t,e))return!1;if(i&&!1===i.call(s,t.sprite,e.sprite))return!1;if(t.isCircle&&e.isCircle)return this.separateCircle(t,e,n);if(t.isCircle!==e.isCircle){var r=t.isCircle?e:t,o=t.isCircle?t:e,a={x:r.x,y:r.y,right:r.right,bottom:r.bottom},h={x:o.x+o.radius,y:o.y+o.radius};if((h.y<a.y||h.y>a.bottom)&&(h.x<a.x||h.x>a.right))return this.separateCircle(t,e,n)}var l=!1,c=!1;this.forceX||Math.abs(this.gravity.y+t.gravity.y)<Math.abs(this.gravity.x+t.gravity.x)?(l=this.separateX(t,e,n),this.intersects(t,e)&&(c=this.separateY(t,e,n))):(c=this.separateY(t,e,n),this.intersects(t,e)&&(l=this.separateX(t,e,n)));var u=l||c;return u&&(n?(t.onOverlap&&t.onOverlap.dispatch(t.sprite,e.sprite),e.onOverlap&&e.onOverlap.dispatch(e.sprite,t.sprite)):(t.onCollide&&t.onCollide.dispatch(t.sprite,e.sprite),e.onCollide&&e.onCollide.dispatch(e.sprite,t.sprite))),u},intersects:function(t,e){return t!==e&&(t.isCircle?e.isCircle?n.Math.distance(t.center.x,t.center.y,e.center.x,e.center.y)<=t.radius+e.radius:this.circleBodyIntersects(t,e):e.isCircle?this.circleBodyIntersects(e,t):!(t.right<=e.position.x)&&(!(t.bottom<=e.position.y)&&(!(t.position.x>=e.right)&&!(t.position.y>=e.bottom))))},circleBodyIntersects:function(t,e){var i=n.Math.clamp(t.center.x,e.left,e.right),s=n.Math.clamp(t.center.y,e.top,e.bottom);return(t.center.x-i)*(t.center.x-i)+(t.center.y-s)*(t.center.y-s)<=t.radius*t.radius},separateCircle:function(t,e,i){this.getOverlapX(t,e),this.getOverlapY(t,e);var s=e.center.x-t.center.x,r=e.center.y-t.center.y,o=Math.atan2(r,s),a=0;if(t.isCircle!==e.isCircle){var h={x:e.isCircle?t.position.x:e.position.x,y:e.isCircle?t.position.y:e.position.y,right:e.isCircle?t.right:e.right,bottom:e.isCircle?t.bottom:e.bottom},l={x:t.isCircle?t.position.x+t.radius:e.position.x+e.radius,y:t.isCircle?t.position.y+t.radius:e.position.y+e.radius,radius:t.isCircle?t.radius:e.radius};l.y<h.y?l.x<h.x?a=n.Math.distance(l.x,l.y,h.x,h.y)-l.radius:l.x>h.right&&(a=n.Math.distance(l.x,l.y,h.right,h.y)-l.radius):l.y>h.bottom&&(l.x<h.x?a=n.Math.distance(l.x,l.y,h.x,h.bottom)-l.radius:l.x>h.right&&(a=n.Math.distance(l.x,l.y,h.right,h.bottom)-l.radius)),a*=-1}else a=t.radius+e.radius-n.Math.distance(t.center.x,t.center.y,e.center.x,e.center.y);if(i||0===a||t.immovable&&e.immovable||t.customSeparateX||e.customSeparateX)return 0!==a&&(t.onOverlap&&t.onOverlap.dispatch(t.sprite,e.sprite),e.onOverlap&&e.onOverlap.dispatch(e.sprite,t.sprite)),0!==a;var c={x:t.velocity.x*Math.cos(o)+t.velocity.y*Math.sin(o),y:t.velocity.x*Math.sin(o)-t.velocity.y*Math.cos(o)},u={x:e.velocity.x*Math.cos(o)+e.velocity.y*Math.sin(o),y:e.velocity.x*Math.sin(o)-e.velocity.y*Math.cos(o)},d=((t.mass-e.mass)*c.x+2*e.mass*u.x)/(t.mass+e.mass),p=(2*t.mass*c.x+(e.mass-t.mass)*u.x)/(t.mass+e.mass);return t.immovable||(t.velocity.x=(d*Math.cos(o)-c.y*Math.sin(o))*t.bounce.x,t.velocity.y=(c.y*Math.cos(o)+d*Math.sin(o))*t.bounce.y),e.immovable||(e.velocity.x=(p*Math.cos(o)-u.y*Math.sin(o))*e.bounce.x,e.velocity.y=(u.y*Math.cos(o)+p*Math.sin(o))*e.bounce.y),Math.abs(o)<Math.PI/2?t.velocity.x>0&&!t.immovable&&e.velocity.x>t.velocity.x?t.velocity.x*=-1:e.velocity.x<0&&!e.immovable&&t.velocity.x<e.velocity.x?e.velocity.x*=-1:t.velocity.y>0&&!t.immovable&&e.velocity.y>t.velocity.y?t.velocity.y*=-1:e.velocity.y<0&&!e.immovable&&t.velocity.y<e.velocity.y&&(e.velocity.y*=-1):Math.abs(o)>Math.PI/2&&(t.velocity.x<0&&!t.immovable&&e.velocity.x<t.velocity.x?t.velocity.x*=-1:e.velocity.x>0&&!e.immovable&&t.velocity.x>e.velocity.x?e.velocity.x*=-1:t.velocity.y<0&&!t.immovable&&e.velocity.y<t.velocity.y?t.velocity.y*=-1:e.velocity.y>0&&!e.immovable&&t.velocity.x>e.velocity.y&&(e.velocity.y*=-1)),t.immovable||(t.x+=t.velocity.x*this.game.time.physicsElapsed-a*Math.cos(o),t.y+=t.velocity.y*this.game.time.physicsElapsed-a*Math.sin(o)),e.immovable||(e.x+=e.velocity.x*this.game.time.physicsElapsed+a*Math.cos(o),e.y+=e.velocity.y*this.game.time.physicsElapsed+a*Math.sin(o)),t.onCollide&&t.onCollide.dispatch(t.sprite,e.sprite),e.onCollide&&e.onCollide.dispatch(e.sprite,t.sprite),!0},getOverlapX:function(t,e,i){var s=0,n=t.deltaAbsX()+e.deltaAbsX()+this.OVERLAP_BIAS;return 0===t.deltaX()&&0===e.deltaX()?(t.embedded=!0,e.embedded=!0):t.deltaX()>e.deltaX()?(s=t.right-e.x,s>n&&!i||!1===t.checkCollision.right||!1===e.checkCollision.left?s=0:(t.touching.none=!1,t.touching.right=!0,e.touching.none=!1,e.touching.left=!0)):t.deltaX()<e.deltaX()&&(s=t.x-e.width-e.x,-s>n&&!i||!1===t.checkCollision.left||!1===e.checkCollision.right?s=0:(t.touching.none=!1,t.touching.left=!0,e.touching.none=!1,e.touching.right=!0)),t.overlapX=s,e.overlapX=s,s},getOverlapY:function(t,e,i){var s=0,n=t.deltaAbsY()+e.deltaAbsY()+this.OVERLAP_BIAS;return 0===t.deltaY()&&0===e.deltaY()?(t.embedded=!0,e.embedded=!0):t.deltaY()>e.deltaY()?(s=t.bottom-e.y,s>n&&!i||!1===t.checkCollision.down||!1===e.checkCollision.up?s=0:(t.touching.none=!1,t.touching.down=!0,e.touching.none=!1,e.touching.up=!0)):t.deltaY()<e.deltaY()&&(s=t.y-e.bottom,-s>n&&!i||!1===t.checkCollision.up||!1===e.checkCollision.down?s=0:(t.touching.none=!1,t.touching.up=!0,e.touching.none=!1,e.touching.down=!0)),t.overlapY=s,e.overlapY=s,s},separateX:function(t,e,i){var s=this.getOverlapX(t,e,i);if(i||0===s||t.immovable&&e.immovable||t.customSeparateX||e.customSeparateX)return 0!==s||t.embedded&&e.embedded;var n=t.velocity.x,r=e.velocity.x;if(t.immovable||e.immovable)t.immovable?(e.x+=s,e.velocity.x=n-r*e.bounce.x,t.moves&&(e.y+=(t.y-t.prev.y)*t.friction.y)):(t.x-=s,t.velocity.x=r-n*t.bounce.x,e.moves&&(t.y+=(e.y-e.prev.y)*e.friction.y));else{s*=.5,t.x-=s,e.x+=s;var o=Math.sqrt(r*r*e.mass/t.mass)*(r>0?1:-1),a=Math.sqrt(n*n*t.mass/e.mass)*(n>0?1:-1),h=.5*(o+a);o-=h,a-=h,t.velocity.x=h+o*t.bounce.x,e.velocity.x=h+a*e.bounce.x}return!0},separateY:function(t,e,i){var s=this.getOverlapY(t,e,i);if(i||0===s||t.immovable&&e.immovable||t.customSeparateY||e.customSeparateY)return 0!==s||t.embedded&&e.embedded;var n=t.velocity.y,r=e.velocity.y;if(t.immovable||e.immovable)t.immovable?(e.y+=s,e.velocity.y=n-r*e.bounce.y,t.moves&&(e.x+=(t.x-t.prev.x)*t.friction.x)):(t.y-=s,t.velocity.y=r-n*t.bounce.y,e.moves&&(t.x+=(e.x-e.prev.x)*e.friction.x));else{s*=.5,t.y-=s,e.y+=s;var o=Math.sqrt(r*r*e.mass/t.mass)*(r>0?1:-1),a=Math.sqrt(n*n*t.mass/e.mass)*(n>0?1:-1),h=.5*(o+a);o-=h,a-=h,t.velocity.y=h+o*t.bounce.y,e.velocity.y=h+a*e.bounce.y}return!0},getObjectsUnderPointer:function(t,e,i,s){if(0!==e.length&&t.exists)return this.getObjectsAtLocation(t.x,t.y,e,i,s,t)},getObjectsAtLocation:function(t,e,i,s,r,o){this.quadTree.clear(),this.quadTree.reset(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height,this.maxObjects,this.maxLevels),this.quadTree.populate(i);for(var a=new n.Rectangle(t,e,1,1),h=[],l=this.quadTree.retrieve(a),c=0;c<l.length;c++)l[c].hitTest(t,e)&&(s&&s.call(r,o,l[c].sprite),h.push(l[c].sprite));return h},moveToObject:function(t,e,i,s){void 0===i&&(i=60),void 0===s&&(s=0);var n=Math.atan2(e.y-t.y,e.x-t.x);return s>0&&(i=this.distanceBetween(t,e)/(s/1e3)),t.body.velocity.x=Math.cos(n)*i,t.body.velocity.y=Math.sin(n)*i,n},moveToPointer:function(t,e,i,s){void 0===e&&(e=60),i=i||this.game.input.activePointer,void 0===s&&(s=0);var n=this.angleToPointer(t,i);return s>0&&(e=this.distanceToPointer(t,i)/(s/1e3)),t.body.velocity.x=Math.cos(n)*e,t.body.velocity.y=Math.sin(n)*e,n},moveToXY:function(t,e,i,s,n){void 0===s&&(s=60),void 0===n&&(n=0);var r=Math.atan2(i-t.y,e-t.x);return n>0&&(s=this.distanceToXY(t,e,i)/(n/1e3)),t.body.velocity.x=Math.cos(r)*s,t.body.velocity.y=Math.sin(r)*s,r},velocityFromAngle:function(t,e,i){return void 0===e&&(e=60),i=i||new n.Point,i.setTo(Math.cos(this.game.math.degToRad(t))*e,Math.sin(this.game.math.degToRad(t))*e)},velocityFromRotation:function(t,e,i){return void 0===e&&(e=60),i=i||new n.Point,i.setTo(Math.cos(t)*e,Math.sin(t)*e)},accelerationFromRotation:function(t,e,i){return void 0===e&&(e=60),i=i||new n.Point,i.setTo(Math.cos(t)*e,Math.sin(t)*e)},accelerateToObject:function(t,e,i,s,n){void 0===i&&(i=60),void 0===s&&(s=1e3),void 0===n&&(n=1e3);var r=this.angleBetween(t,e);return t.body.acceleration.setTo(Math.cos(r)*i,Math.sin(r)*i),t.body.maxVelocity.setTo(s,n),r},accelerateToPointer:function(t,e,i,s,n){void 0===i&&(i=60),void 0===e&&(e=this.game.input.activePointer),void 0===s&&(s=1e3),void 0===n&&(n=1e3);var r=this.angleToPointer(t,e);return t.body.acceleration.setTo(Math.cos(r)*i,Math.sin(r)*i),t.body.maxVelocity.setTo(s,n),r},accelerateToXY:function(t,e,i,s,n,r){void 0===s&&(s=60),void 0===n&&(n=1e3),void 0===r&&(r=1e3);var o=this.angleToXY(t,e,i);return t.body.acceleration.setTo(Math.cos(o)*s,Math.sin(o)*s),t.body.maxVelocity.setTo(n,r),o},distanceBetween:function(t,e,i){void 0===i&&(i=!1);var s=i?t.world.x-e.world.x:t.x-e.x,n=i?t.world.y-e.world.y:t.y-e.y;return Math.sqrt(s*s+n*n)},distanceToXY:function(t,e,i,s){void 0===s&&(s=!1);var n=s?t.world.x-e:t.x-e,r=s?t.world.y-i:t.y-i;return Math.sqrt(n*n+r*r)},distanceToPointer:function(t,e,i){void 0===e&&(e=this.game.input.activePointer),void 0===i&&(i=!1);var s=i?t.world.x-e.worldX:t.x-e.worldX,n=i?t.world.y-e.worldY:t.y-e.worldY;return Math.sqrt(s*s+n*n)},angleBetween:function(t,e,i){return void 0===i&&(i=!1),i?Math.atan2(e.world.y-t.world.y,e.world.x-t.world.x):Math.atan2(e.y-t.y,e.x-t.x)},angleBetweenCenters:function(t,e){var i=e.centerX-t.centerX,s=e.centerY-t.centerY;return Math.atan2(s,i)},angleToXY:function(t,e,i,s){return void 0===s&&(s=!1),s?Math.atan2(i-t.world.y,e-t.world.x):Math.atan2(i-t.y,e-t.x)},angleToPointer:function(t,e,i){return void 0===e&&(e=this.game.input.activePointer),void 0===i&&(i=!1),i?Math.atan2(e.worldY-t.world.y,e.worldX-t.world.x):Math.atan2(e.worldY-t.y,e.worldX-t.x)},worldAngleToPointer:function(t,e){return this.angleToPointer(t,e,!0)}},n.Physics.Arcade.Body=function(t){this.sprite=t,this.game=t.game,this.type=n.Physics.ARCADE,this.enable=!0,this.isCircle=!1,this.radius=0,this.offset=new n.Point,this.position=new n.Point(t.x,t.y),this.prev=new n.Point(this.position.x,this.position.y),this.allowRotation=!0,this.rotation=t.angle,this.preRotation=t.angle,this.width=t.width,this.height=t.height,this.sourceWidth=t.width,this.sourceHeight=t.height,t.texture&&(this.sourceWidth=t.texture.frame.width,this.sourceHeight=t.texture.frame.height),this.halfWidth=Math.abs(t.width/2),this.halfHeight=Math.abs(t.height/2),this.center=new n.Point(t.x+this.halfWidth,t.y+this.halfHeight),this.velocity=new n.Point,this.newVelocity=new n.Point,this.deltaMax=new n.Point,this.acceleration=new n.Point,this.drag=new n.Point,this.allowGravity=!0,this.gravity=new n.Point,this.bounce=new n.Point,this.worldBounce=null,this.onWorldBounds=null,this.onCollide=null,this.onOverlap=null,this.maxVelocity=new n.Point(1e4,1e4),this.friction=new n.Point(1,0),this.angularVelocity=0,this.angularAcceleration=0,this.angularDrag=0,this.maxAngular=1e3,this.mass=1,this.angle=0,this.speed=0,this.facing=n.NONE,this.immovable=!1,this.moves=!0,this.customSeparateX=!1,this.customSeparateY=!1,this.overlapX=0,this.overlapY=0,this.overlapR=0,this.embedded=!1,this.collideWorldBounds=!1,this.checkCollision={none:!1,any:!0,up:!0,down:!0,left:!0,right:!0},this.touching={none:!0,up:!1,down:!1,left:!1,right:!1},this.wasTouching={none:!0,up:!1,down:!1,left:!1,right:!1},this.blocked={up:!1,down:!1,left:!1,right:!1},this.tilePadding=new n.Point,this.dirty=!1,this.skipQuadTree=!1,this.syncBounds=!1,this.isMoving=!1,this.stopVelocityOnCollide=!0,this.moveTimer=0,this.moveDistance=0,this.moveDuration=0,this.moveTarget=null,this.moveEnd=null,this.onMoveComplete=new n.Signal,this.movementCallback=null,this.movementCallbackContext=null,this._reset=!0,this._sx=t.scale.x,this._sy=t.scale.y,this._dx=0,this._dy=0},n.Physics.Arcade.Body.prototype={updateBounds:function(){if(this.syncBounds){var t=this.sprite.getBounds();t.ceilAll(),t.width===this.width&&t.height===this.height||(this.width=t.width,this.height=t.height,this._reset=!0)}else{var e=Math.abs(this.sprite.scale.x),i=Math.abs(this.sprite.scale.y);e===this._sx&&i===this._sy||(this.width=this.sourceWidth*e,this.height=this.sourceHeight*i,this._sx=e,this._sy=i,this._reset=!0)}this._reset&&(this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight))},preUpdate:function(){this.enable&&!this.game.physics.arcade.isPaused&&(this.dirty=!0,this.wasTouching.none=this.touching.none,this.wasTouching.up=this.touching.up,this.wasTouching.down=this.touching.down,this.wasTouching.left=this.touching.left,this.wasTouching.right=this.touching.right,this.touching.none=!0,this.touching.up=!1,this.touching.down=!1,this.touching.left=!1,this.touching.right=!1,this.blocked.up=!1,this.blocked.down=!1,this.blocked.left=!1,this.blocked.right=!1,this.embedded=!1,this.updateBounds(),this.position.x=this.sprite.world.x-this.sprite.anchor.x*this.sprite.width+this.sprite.scale.x*this.offset.x,this.position.x-=this.sprite.scale.x<0?this.width:0,this.position.y=this.sprite.world.y-this.sprite.anchor.y*this.sprite.height+this.sprite.scale.y*this.offset.y,this.position.y-=this.sprite.scale.y<0?this.height:0,this.rotation=this.sprite.angle,this.preRotation=this.rotation,(this._reset||this.sprite.fresh)&&(this.prev.x=this.position.x,this.prev.y=this.position.y),this.moves&&(this.game.physics.arcade.updateMotion(this),this.newVelocity.set(this.velocity.x*this.game.time.physicsElapsed,this.velocity.y*this.game.time.physicsElapsed),this.position.x+=this.newVelocity.x,this.position.y+=this.newVelocity.y,this.position.x===this.prev.x&&this.position.y===this.prev.y||(this.angle=Math.atan2(this.velocity.y,this.velocity.x)),this.speed=Math.sqrt(this.velocity.x*this.velocity.x+this.velocity.y*this.velocity.y),this.collideWorldBounds&&this.checkWorldBounds()&&this.onWorldBounds&&this.onWorldBounds.dispatch(this.sprite,this.blocked.up,this.blocked.down,this.blocked.left,this.blocked.right)),this._dx=this.deltaX(),this._dy=this.deltaY(),this._reset=!1)},updateMovement:function(){var t=0,e=0!==this.overlapX||0!==this.overlapY;if(this.moveDuration>0?(this.moveTimer+=this.game.time.elapsedMS,t=this.moveTimer/this.moveDuration):(this.moveTarget.end.set(this.position.x,this.position.y),t=this.moveTarget.length/this.moveDistance),this.movementCallback)var i=this.movementCallback.call(this.movementCallbackContext,this,this.velocity,t);return!(e||t>=1||void 0!==i&&!0!==i)||(this.stopMovement(t>=1||this.stopVelocityOnCollide&&e),!1)},stopMovement:function(t){this.isMoving&&(this.isMoving=!1,t&&this.velocity.set(0),this.onMoveComplete.dispatch(this.sprite,0!==this.overlapX||0!==this.overlapY))},postUpdate:function(){this.enable&&this.dirty&&(this.isMoving&&this.updateMovement(),this.dirty=!1,this.deltaX()<0?this.facing=n.LEFT:this.deltaX()>0&&(this.facing=n.RIGHT),this.deltaY()<0?this.facing=n.UP:this.deltaY()>0&&(this.facing=n.DOWN),this.moves&&(this._dx=this.deltaX(),this._dy=this.deltaY(),0!==this.deltaMax.x&&0!==this._dx&&(this._dx<0&&this._dx<-this.deltaMax.x?this._dx=-this.deltaMax.x:this._dx>0&&this._dx>this.deltaMax.x&&(this._dx=this.deltaMax.x)),0!==this.deltaMax.y&&0!==this._dy&&(this._dy<0&&this._dy<-this.deltaMax.y?this._dy=-this.deltaMax.y:this._dy>0&&this._dy>this.deltaMax.y&&(this._dy=this.deltaMax.y)),this.sprite.position.x+=this._dx,this.sprite.position.y+=this._dy,this._reset=!0),this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight),this.allowRotation&&(this.sprite.angle+=this.deltaZ()),this.prev.x=this.position.x,this.prev.y=this.position.y)},checkWorldBounds:function(){var t=this.position,e=this.game.physics.arcade.bounds,i=this.game.physics.arcade.checkCollision,s=this.worldBounce?-this.worldBounce.x:-this.bounce.x,n=this.worldBounce?-this.worldBounce.y:-this.bounce.y;if(this.isCircle){var r={x:this.center.x-this.radius,y:this.center.y-this.radius,right:this.center.x+this.radius,bottom:this.center.y+this.radius};r.x<e.x&&i.left?(t.x=e.x-this.halfWidth+this.radius,this.velocity.x*=s,this.blocked.left=!0):r.right>e.right&&i.right&&(t.x=e.right-this.halfWidth-this.radius,this.velocity.x*=s,this.blocked.right=!0),r.y<e.y&&i.up?(t.y=e.y-this.halfHeight+this.radius,this.velocity.y*=n,this.blocked.up=!0):r.bottom>e.bottom&&i.down&&(t.y=e.bottom-this.halfHeight-this.radius,this.velocity.y*=n,this.blocked.down=!0)}else t.x<e.x&&i.left?(t.x=e.x,this.velocity.x*=s,this.blocked.left=!0):this.right>e.right&&i.right&&(t.x=e.right-this.width,this.velocity.x*=s,this.blocked.right=!0),t.y<e.y&&i.up?(t.y=e.y,this.velocity.y*=n,this.blocked.up=!0):this.bottom>e.bottom&&i.down&&(t.y=e.bottom-this.height,this.velocity.y*=n,this.blocked.down=!0);return this.blocked.up||this.blocked.down||this.blocked.left||this.blocked.right},moveFrom:function(t,e,i){if(void 0===e&&(e=this.speed),0===e)return!1;var s;return void 0===i?(s=this.angle,i=this.game.math.radToDeg(s)):s=this.game.math.degToRad(i),this.moveTimer=0,this.moveDuration=t,0===i||180===i?this.velocity.set(Math.cos(s)*e,0):90===i||270===i?this.velocity.set(0,Math.sin(s)*e):this.velocity.set(Math.cos(s)*e,Math.sin(s)*e),this.isMoving=!0,!0},moveTo:function(t,e,i){var s=e/(t/1e3);if(0===s)return!1;var r;return void 0===i?(r=this.angle,i=this.game.math.radToDeg(r)):r=this.game.math.degToRad(i),e=Math.abs(e),this.moveDuration=0,this.moveDistance=e,null===this.moveTarget&&(this.moveTarget=new n.Line,this.moveEnd=new n.Point),this.moveTarget.fromAngle(this.x,this.y,r,e),this.moveEnd.set(this.moveTarget.end.x,this.moveTarget.end.y),this.moveTarget.setTo(this.x,this.y,this.x,this.y),0===i||180===i?this.velocity.set(Math.cos(r)*s,0):90===i||270===i?this.velocity.set(0,Math.sin(r)*s):this.velocity.set(Math.cos(r)*s,Math.sin(r)*s),this.isMoving=!0,!0},setSize:function(t,e,i,s){void 0===i&&(i=this.offset.x),void 0===s&&(s=this.offset.y),this.sourceWidth=t,this.sourceHeight=e,this.width=this.sourceWidth*this._sx,this.height=this.sourceHeight*this._sy,this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.offset.setTo(i,s),this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight),this.isCircle=!1,this.radius=0},setCircle:function(t,e,i){void 0===e&&(e=this.offset.x),void 0===i&&(i=this.offset.y),t>0?(this.isCircle=!0,this.radius=t,this.sourceWidth=2*t,this.sourceHeight=2*t,this.width=this.sourceWidth*this._sx,this.height=this.sourceHeight*this._sy,this.halfWidth=Math.floor(this.width/2),this.halfHeight=Math.floor(this.height/2),this.offset.setTo(e,i),this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight)):this.isCircle=!1},reset:function(t,e){this.velocity.set(0),this.acceleration.set(0),this.speed=0,this.angularVelocity=0,this.angularAcceleration=0,this.position.x=t-this.sprite.anchor.x*this.sprite.width+this.sprite.scale.x*this.offset.x,this.position.x-=this.sprite.scale.x<0?this.width:0,this.position.y=e-this.sprite.anchor.y*this.sprite.height+this.sprite.scale.y*this.offset.y,this.position.y-=this.sprite.scale.y<0?this.height:0,this.prev.x=this.position.x,this.prev.y=this.position.y,this.rotation=this.sprite.angle,this.preRotation=this.rotation,this._sx=this.sprite.scale.x,this._sy=this.sprite.scale.y,this.center.setTo(this.position.x+this.halfWidth,this.position.y+this.halfHeight)},getBounds:function(t){return this.isCircle?(t.x=this.center.x-this.radius,t.y=this.center.y-this.radius,t.right=this.center.x+this.radius,t.bottom=this.center.y+this.radius):(t.x=this.x,t.y=this.y,t.right=this.right,t.bottom=this.bottom),t},hitTest:function(t,e){return this.isCircle?n.Circle.contains(this,t,e):n.Rectangle.contains(this,t,e)},onFloor:function(){return this.blocked.down},onCeiling:function(){return this.blocked.up},onWall:function(){return this.blocked.left||this.blocked.right},deltaAbsX:function(){return this.deltaX()>0?this.deltaX():-this.deltaX()},deltaAbsY:function(){return this.deltaY()>0?this.deltaY():-this.deltaY()},deltaX:function(){return this.position.x-this.prev.x},deltaY:function(){return this.position.y-this.prev.y},deltaZ:function(){return this.rotation-this.preRotation},destroy:function(){this.sprite.parent&&this.sprite.parent instanceof n.Group&&this.sprite.parent.removeFromHash(this.sprite),this.sprite.body=null,this.sprite=null}},Object.defineProperty(n.Physics.Arcade.Body.prototype,"left",{get:function(){return this.position.x}}),Object.defineProperty(n.Physics.Arcade.Body.prototype,"right",{get:function(){return this.position.x+this.width}}),Object.defineProperty(n.Physics.Arcade.Body.prototype,"top",{get:function(){return this.position.y}}),Object.defineProperty(n.Physics.Arcade.Body.prototype,"bottom",{get:function(){return this.position.y+this.height}}),Object.defineProperty(n.Physics.Arcade.Body.prototype,"x",{get:function(){return this.position.x},set:function(t){this.position.x=t}}),Object.defineProperty(n.Physics.Arcade.Body.prototype,"y",{get:function(){return this.position.y},set:function(t){this.position.y=t}}),n.Physics.Arcade.Body.render=function(t,e,i,s){void 0===s&&(s=!0),i=i||"rgba(0,255,0,0.4)",t.fillStyle=i,t.strokeStyle=i,e.isCircle?(t.beginPath(),t.arc(e.center.x-e.game.camera.x,e.center.y-e.game.camera.y,e.radius,0,2*Math.PI),s?t.fill():t.stroke()):s?t.fillRect(e.position.x-e.game.camera.x,e.position.y-e.game.camera.y,e.width,e.height):t.strokeRect(e.position.x-e.game.camera.x,e.position.y-e.game.camera.y,e.width,e.height)},n.Physics.Arcade.Body.renderBodyInfo=function(t,e){t.line("x: "+e.x.toFixed(2),"y: "+e.y.toFixed(2),"width: "+e.width,"height: "+e.height),t.line("velocity x: "+e.velocity.x.toFixed(2),"y: "+e.velocity.y.toFixed(2),"deltaX: "+e._dx.toFixed(2),"deltaY: "+e._dy.toFixed(2)),t.line("acceleration x: "+e.acceleration.x.toFixed(2),"y: "+e.acceleration.y.toFixed(2),"speed: "+e.speed.toFixed(2),"angle: "+e.angle.toFixed(2)),t.line("gravity x: "+e.gravity.x,"y: "+e.gravity.y,"bounce x: "+e.bounce.x.toFixed(2),"y: "+e.bounce.y.toFixed(2)),t.line("touching left: "+e.touching.left,"right: "+e.touching.right,"up: "+e.touching.up,"down: "+e.touching.down),t.line("blocked left: "+e.blocked.left,"right: "+e.blocked.right,"up: "+e.blocked.up,"down: "+e.blocked.down)},n.Physics.Arcade.Body.prototype.constructor=n.Physics.Arcade.Body,n.Physics.Arcade.TilemapCollision=function(){},n.Physics.Arcade.TilemapCollision.prototype={TILE_BIAS:16,collideSpriteVsTilemapLayer:function(t,e,i,s,n,r){if(t.body){var o=e.getTiles(t.body.position.x-t.body.tilePadding.x,t.body.position.y-t.body.tilePadding.y,t.body.width+t.body.tilePadding.x,t.body.height+t.body.tilePadding.y,!1,!1);if(0!==o.length)for(var a=0;a<o.length;a++)s?s.call(n,t,o[a])&&this.separateTile(a,t.body,o[a],e,r)&&(this._total++,i&&i.call(n,t,o[a])):this.separateTile(a,t.body,o[a],e,r)&&(this._total++,i&&i.call(n,t,o[a]))}},collideGroupVsTilemapLayer:function(t,e,i,s,n,r){if(0!==t.length)for(var o=0;o<t.children.length;o++)t.children[o].exists&&this.collideSpriteVsTilemapLayer(t.children[o],e,i,s,n,r)},separateTile:function(t,e,i,s,n){if(!e.enable)return!1;var r=s.fixedToCamera?0:s.position.x,o=s.fixedToCamera?0:s.position.y;if(!i.intersects(e.position.x-r,e.position.y-o,e.right-r,e.bottom-o))return!1;if(n)return!0;if(i.collisionCallback&&!i.collisionCallback.call(i.collisionCallbackContext,e.sprite,i))return!1;if(void 0!==i.layer.callbacks&&i.layer.callbacks[i.index]&&!i.layer.callbacks[i.index].callback.call(i.layer.callbacks[i.index].callbackContext,e.sprite,i))return!1;if(!(i.faceLeft||i.faceRight||i.faceTop||i.faceBottom))return!1;var a=0,h=0,l=0,c=1;if(e.deltaAbsX()>e.deltaAbsY()?l=-1:e.deltaAbsX()<e.deltaAbsY()&&(c=-1),0!==e.deltaX()&&0!==e.deltaY()&&(i.faceLeft||i.faceRight)&&(i.faceTop||i.faceBottom)&&(l=Math.min(Math.abs(e.position.x-r-i.right),Math.abs(e.right-r-i.left)),c=Math.min(Math.abs(e.position.y-o-i.bottom),Math.abs(e.bottom-o-i.top))),l<c){if((i.faceLeft||i.faceRight)&&0!==(a=this.tileCheckX(e,i,s))&&!i.intersects(e.position.x-r,e.position.y-o,e.right-r,e.bottom-o))return!0;(i.faceTop||i.faceBottom)&&(h=this.tileCheckY(e,i,s))}else{if((i.faceTop||i.faceBottom)&&0!==(h=this.tileCheckY(e,i,s))&&!i.intersects(e.position.x-r,e.position.y-o,e.right-r,e.bottom-o))return!0;(i.faceLeft||i.faceRight)&&(a=this.tileCheckX(e,i,s))}return 0!==a||0!==h},tileCheckX:function(t,e,i){var s=0,n=i.fixedToCamera?0:i.position.x;return t.deltaX()<0&&!t.blocked.left&&e.collideRight&&t.checkCollision.left?e.faceRight&&t.x-n<e.right&&(s=t.x-n-e.right)<-this.TILE_BIAS&&(s=0):t.deltaX()>0&&!t.blocked.right&&e.collideLeft&&t.checkCollision.right&&e.faceLeft&&t.right-n>e.left&&(s=t.right-n-e.left)>this.TILE_BIAS&&(s=0),0!==s&&(t.customSeparateX?t.overlapX=s:this.processTileSeparationX(t,s)),s},tileCheckY:function(t,e,i){var s=0,n=i.fixedToCamera?0:i.position.y;return t.deltaY()<0&&!t.blocked.up&&e.collideDown&&t.checkCollision.up?e.faceBottom&&t.y-n<e.bottom&&(s=t.y-n-e.bottom)<-this.TILE_BIAS&&(s=0):t.deltaY()>0&&!t.blocked.down&&e.collideUp&&t.checkCollision.down&&e.faceTop&&t.bottom-n>e.top&&(s=t.bottom-n-e.top)>this.TILE_BIAS&&(s=0),0!==s&&(t.customSeparateY?t.overlapY=s:this.processTileSeparationY(t,s)),s},processTileSeparationX:function(t,e){e<0?t.blocked.left=!0:e>0&&(t.blocked.right=!0),t.position.x-=e,0===t.bounce.x?t.velocity.x=0:t.velocity.x=-t.velocity.x*t.bounce.x},processTileSeparationY:function(t,e){e<0?t.blocked.up=!0:e>0&&(t.blocked.down=!0),t.position.y-=e,0===t.bounce.y?t.velocity.y=0:t.velocity.y=-t.velocity.y*t.bounce.y}},n.Utils.mixinPrototype(n.Physics.Arcade.prototype,n.Physics.Arcade.TilemapCollision.prototype),p2.Body.prototype.parent=null,p2.Spring.prototype.parent=null,n.Physics.P2=function(t,e){this.game=t,void 0===e?e={gravity:[0,0],broadphase:new p2.SAPBroadphase}:(e.hasOwnProperty("gravity")||(e.gravity=[0,0]),e.hasOwnProperty("broadphase")||(e.broadphase=new p2.SAPBroadphase)),this.config=e,this.world=new p2.World(this.config),this.frameRate=1/60,this.useElapsedTime=!1,this.paused=!1,this.materials=[],this.gravity=new n.Physics.P2.InversePointProxy(this,this.world.gravity),this.walls={left:null,right:null,top:null,bottom:null},this.onBodyAdded=new n.Signal,this.onBodyRemoved=new n.Signal,this.onSpringAdded=new n.Signal,this.onSpringRemoved=new n.Signal,this.onConstraintAdded=new n.Signal,this.onConstraintRemoved=new n.Signal,this.onContactMaterialAdded=new n.Signal,this.onContactMaterialRemoved=new n.Signal,this.postBroadphaseCallback=null,this.callbackContext=null,this.onBeginContact=new n.Signal,this.onEndContact=new n.Signal,e.hasOwnProperty("mpx")&&e.hasOwnProperty("pxm")&&e.hasOwnProperty("mpxi")&&e.hasOwnProperty("pxmi")&&(this.mpx=e.mpx,this.mpxi=e.mpxi,this.pxm=e.pxm,this.pxmi=e.pxmi),this.world.on("beginContact",this.beginContactHandler,this),this.world.on("endContact",this.endContactHandler,this),this.collisionGroups=[],this.nothingCollisionGroup=new n.Physics.P2.CollisionGroup(1),this.boundsCollisionGroup=new n.Physics.P2.CollisionGroup(2),this.everythingCollisionGroup=new n.Physics.P2.CollisionGroup(2147483648),this.boundsCollidesWith=[],this._toRemove=[],this._collisionGroupID=2,this._boundsLeft=!0,this._boundsRight=!0,this._boundsTop=!0,this._boundsBottom=!0,this._boundsOwnGroup=!1,this.setBoundsToWorld(!0,!0,!0,!0,!1)},n.Physics.P2.prototype={removeBodyNextStep:function(t){this._toRemove.push(t)},preUpdate:function(){for(var t=this._toRemove.length;t--;)this.removeBody(this._toRemove[t]);this._toRemove.length=0},enable:function(t,e,i){void 0===e&&(e=!1),void 0===i&&(i=!0);var s=1;if(Array.isArray(t))for(s=t.length;s--;)t[s]instanceof n.Group?this.enable(t[s].children,e,i):(this.enableBody(t[s],e),i&&t[s].hasOwnProperty("children")&&t[s].children.length>0&&this.enable(t[s],e,!0));else t instanceof n.Group?this.enable(t.children,e,i):(this.enableBody(t,e),i&&t.hasOwnProperty("children")&&t.children.length>0&&this.enable(t.children,e,!0))},enableBody:function(t,e){t.hasOwnProperty("body")&&null===t.body&&(t.body=new n.Physics.P2.Body(this.game,t,t.x,t.y,1),t.body.debug=e,void 0!==t.anchor&&t.anchor.set(.5))},setImpactEvents:function(t){t?this.world.on("impact",this.impactHandler,this):this.world.off("impact",this.impactHandler,this)},setPostBroadphaseCallback:function(t,e){this.postBroadphaseCallback=t,this.callbackContext=e,null!==t?this.world.on("postBroadphase",this.postBroadphaseHandler,this):this.world.off("postBroadphase",this.postBroadphaseHandler,this)},postBroadphaseHandler:function(t){if(this.postBroadphaseCallback&&0!==t.pairs.length)for(var e=t.pairs.length-2;e>=0;e-=2)t.pairs[e].parent&&t.pairs[e+1].parent&&!this.postBroadphaseCallback.call(this.callbackContext,t.pairs[e].parent,t.pairs[e+1].parent)&&t.pairs.splice(e,2)},impactHandler:function(t){if(t.bodyA.parent&&t.bodyB.parent){var e=t.bodyA.parent,i=t.bodyB.parent;e._bodyCallbacks[t.bodyB.id]&&e._bodyCallbacks[t.bodyB.id].call(e._bodyCallbackContext[t.bodyB.id],e,i,t.shapeA,t.shapeB),i._bodyCallbacks[t.bodyA.id]&&i._bodyCallbacks[t.bodyA.id].call(i._bodyCallbackContext[t.bodyA.id],i,e,t.shapeB,t.shapeA),e._groupCallbacks[t.shapeB.collisionGroup]&&e._groupCallbacks[t.shapeB.collisionGroup].call(e._groupCallbackContext[t.shapeB.collisionGroup],e,i,t.shapeA,t.shapeB),i._groupCallbacks[t.shapeA.collisionGroup]&&i._groupCallbacks[t.shapeA.collisionGroup].call(i._groupCallbackContext[t.shapeA.collisionGroup],i,e,t.shapeB,t.shapeA)}},beginContactHandler:function(t){t.bodyA&&t.bodyB&&(this.onBeginContact.dispatch(t.bodyA,t.bodyB,t.shapeA,t.shapeB,t.contactEquations),t.bodyA.parent&&t.bodyA.parent.onBeginContact.dispatch(t.bodyB.parent,t.bodyB,t.shapeA,t.shapeB,t.contactEquations),t.bodyB.parent&&t.bodyB.parent.onBeginContact.dispatch(t.bodyA.parent,t.bodyA,t.shapeB,t.shapeA,t.contactEquations))},endContactHandler:function(t){t.bodyA&&t.bodyB&&(this.onEndContact.dispatch(t.bodyA,t.bodyB,t.shapeA,t.shapeB),t.bodyA.parent&&t.bodyA.parent.onEndContact.dispatch(t.bodyB.parent,t.bodyB,t.shapeA,t.shapeB),t.bodyB.parent&&t.bodyB.parent.onEndContact.dispatch(t.bodyA.parent,t.bodyA,t.shapeB,t.shapeA))},setBoundsToWorld:function(t,e,i,s,n){this.setBounds(this.game.world.bounds.x,this.game.world.bounds.y,this.game.world.bounds.width,this.game.world.bounds.height,t,e,i,s,n)},setWorldMaterial:function(t,e,i,s,n){void 0===e&&(e=!0),void 0===i&&(i=!0),void 0===s&&(s=!0),void 0===n&&(n=!0),e&&this.walls.left&&(this.walls.left.shapes[0].material=t),i&&this.walls.right&&(this.walls.right.shapes[0].material=t),s&&this.walls.top&&(this.walls.top.shapes[0].material=t),n&&this.walls.bottom&&(this.walls.bottom.shapes[0].material=t)},updateBoundsCollisionGroup:function(t){void 0===t&&(t=!0);var e=t?this.boundsCollisionGroup.mask:this.everythingCollisionGroup.mask;this.walls.left&&(this.walls.left.shapes[0].collisionGroup=e),this.walls.right&&(this.walls.right.shapes[0].collisionGroup=e),this.walls.top&&(this.walls.top.shapes[0].collisionGroup=e),this.walls.bottom&&(this.walls.bottom.shapes[0].collisionGroup=e),this._boundsOwnGroup=t},setBounds:function(t,e,i,s,n,r,o,a,h){void 0===n&&(n=this._boundsLeft),void 0===r&&(r=this._boundsRight),void 0===o&&(o=this._boundsTop),void 0===a&&(a=this._boundsBottom),void 0===h&&(h=this._boundsOwnGroup),this.setupWall(n,"left",t,e,1.5707963267948966,h),this.setupWall(r,"right",t+i,e,-1.5707963267948966,h),this.setupWall(o,"top",t,e,-3.141592653589793,h),this.setupWall(a,"bottom",t,e+s,0,h),this._boundsLeft=n,this._boundsRight=r,this._boundsTop=o,this._boundsBottom=a,this._boundsOwnGroup=h},setupWall:function(t,e,i,s,n,r){t?(this.walls[e]?this.walls[e].position=[this.pxmi(i),this.pxmi(s)]:(this.walls[e]=new p2.Body({mass:0,position:[this.pxmi(i),this.pxmi(s)],angle:n}),this.walls[e].addShape(new p2.Plane),this.world.addBody(this.walls[e])),r&&(this.walls[e].shapes[0].collisionGroup=this.boundsCollisionGroup.mask)):this.walls[e]&&(this.world.removeBody(this.walls[e]),this.walls[e]=null)},pause:function(){this.paused=!0},resume:function(){this.paused=!1},update:function(){this.paused||(this.useElapsedTime?this.world.step(this.game.time.physicsElapsed):this.world.step(this.frameRate))},reset:function(){this.world.on("beginContact",this.beginContactHandler,this),this.world.on("endContact",this.endContactHandler,this),this.nothingCollisionGroup=new n.Physics.P2.CollisionGroup(1),this.boundsCollisionGroup=new n.Physics.P2.CollisionGroup(2),this.everythingCollisionGroup=new n.Physics.P2.CollisionGroup(2147483648),this._collisionGroupID=2,this.setBoundsToWorld(!0,!0,!0,!0,!1)},clear:function(){this.world.time=0,this.world.fixedStepTime=0,this.world.solver&&this.world.solver.equations.length&&this.world.solver.removeAllEquations();for(var t=this.world.constraints,e=t.length-1;e>=0;e--)this.world.removeConstraint(t[e]);for(var i=this.world.bodies,e=i.length-1;e>=0;e--)this.world.removeBody(i[e]);for(var s=this.world.springs,e=s.length-1;e>=0;e--)this.world.removeSpring(s[e]);for(var n=this.world.contactMaterials,e=n.length-1;e>=0;e--)this.world.removeContactMaterial(n[e]);this.world.off("beginContact",this.beginContactHandler,this),this.world.off("endContact",this.endContactHandler,this),this.postBroadphaseCallback=null,this.callbackContext=null,this.impactCallback=null,this.collisionGroups=[],this._toRemove=[],this.boundsCollidesWith=[],this.walls={left:null,right:null,top:null,bottom:null}},destroy:function(){this.clear(),this.game=null},addBody:function(t){return!t.data.world&&(this.world.addBody(t.data),this.onBodyAdded.dispatch(t),!0)},removeBody:function(t){return t.data.world===this.world&&(this.world.removeBody(t.data),this.onBodyRemoved.dispatch(t)),t},addSpring:function(t){return t instanceof n.Physics.P2.Spring||t instanceof n.Physics.P2.RotationalSpring?this.world.addSpring(t.data):this.world.addSpring(t),this.onSpringAdded.dispatch(t),t},removeSpring:function(t){return t instanceof n.Physics.P2.Spring||t instanceof n.Physics.P2.RotationalSpring?this.world.removeSpring(t.data):this.world.removeSpring(t),this.onSpringRemoved.dispatch(t),t},createDistanceConstraint:function(t,e,i,s,r,o){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new n.Physics.P2.DistanceConstraint(this,t,e,i,s,r,o));console.warn("Cannot create Constraint, invalid body objects given")},createGearConstraint:function(t,e,i,s){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new n.Physics.P2.GearConstraint(this,t,e,i,s));console.warn("Cannot create Constraint, invalid body objects given")},createRevoluteConstraint:function(t,e,i,s,r,o){if(t=this.getBody(t),i=this.getBody(i),t&&i)return this.addConstraint(new n.Physics.P2.RevoluteConstraint(this,t,e,i,s,r,o));console.warn("Cannot create Constraint, invalid body objects given")},createLockConstraint:function(t,e,i,s,r){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new n.Physics.P2.LockConstraint(this,t,e,i,s,r));console.warn("Cannot create Constraint, invalid body objects given")},createPrismaticConstraint:function(t,e,i,s,r,o,a){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addConstraint(new n.Physics.P2.PrismaticConstraint(this,t,e,i,s,r,o,a));console.warn("Cannot create Constraint, invalid body objects given")},addConstraint:function(t){return this.world.addConstraint(t),this.onConstraintAdded.dispatch(t),t},removeConstraint:function(t){return this.world.removeConstraint(t),this.onConstraintRemoved.dispatch(t),t},addContactMaterial:function(t){return this.world.addContactMaterial(t),this.onContactMaterialAdded.dispatch(t),t},removeContactMaterial:function(t){return this.world.removeContactMaterial(t),this.onContactMaterialRemoved.dispatch(t),t},getContactMaterial:function(t,e){return this.world.getContactMaterial(t,e)},setMaterial:function(t,e){for(var i=e.length;i--;)e[i].setMaterial(t)},createMaterial:function(t,e){t=t||"";var i=new n.Physics.P2.Material(t);return this.materials.push(i),void 0!==e&&e.setMaterial(i),i},createContactMaterial:function(t,e,i){void 0===t&&(t=this.createMaterial()),void 0===e&&(e=this.createMaterial());var s=new n.Physics.P2.ContactMaterial(t,e,i);return this.addContactMaterial(s)},getBodies:function(){for(var t=[],e=this.world.bodies.length;e--;)t.push(this.world.bodies[e].parent);return t},getBody:function(t){return t instanceof p2.Body?t:t instanceof n.Physics.P2.Body?t.data:t.body&&t.body.type===n.Physics.P2JS?t.body.data:null},getSprings:function(){for(var t=[],e=this.world.springs.length;e--;)t.push(this.world.springs[e].parent);return t},getConstraints:function(){for(var t=[],e=this.world.constraints.length;e--;)t.push(this.world.constraints[e]);return t},hitTest:function(t,e,i,s){void 0===e&&(e=this.world.bodies),void 0===i&&(i=5),void 0===s&&(s=!1);for(var r=[this.pxmi(t.x),this.pxmi(t.y)],o=[],a=e.length;a--;)e[a]instanceof n.Physics.P2.Body&&(!s||e[a].data.type!==p2.Body.STATIC)?o.push(e[a].data):e[a]instanceof p2.Body&&e[a].parent&&(!s||e[a].type!==p2.Body.STATIC)?o.push(e[a]):e[a]instanceof n.Sprite&&e[a].hasOwnProperty("body")&&(!s||e[a].body.data.type!==p2.Body.STATIC)&&o.push(e[a].body.data);return this.world.hitTest(r,o,i)},toJSON:function(){return this.world.toJSON()},createCollisionGroup:function(t){var e=Math.pow(2,this._collisionGroupID);this.walls.left&&(this.walls.left.shapes[0].collisionMask=this.walls.left.shapes[0].collisionMask|e),this.walls.right&&(this.walls.right.shapes[0].collisionMask=this.walls.right.shapes[0].collisionMask|e),this.walls.top&&(this.walls.top.shapes[0].collisionMask=this.walls.top.shapes[0].collisionMask|e),this.walls.bottom&&(this.walls.bottom.shapes[0].collisionMask=this.walls.bottom.shapes[0].collisionMask|e),this._collisionGroupID++;var i=new n.Physics.P2.CollisionGroup(e);return this.collisionGroups.push(i),t&&this.setCollisionGroup(t,i),i},setCollisionGroup:function(t,e){if(t instanceof n.Group)for(var i=0;i<t.total;i++)t.children[i].body&&t.children[i].body.type===n.Physics.P2JS&&t.children[i].body.setCollisionGroup(e);else t.body.setCollisionGroup(e)},createSpring:function(t,e,i,s,r,o,a,h,l){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addSpring(new n.Physics.P2.Spring(this,t,e,i,s,r,o,a,h,l));console.warn("Cannot create Spring, invalid body objects given")},createRotationalSpring:function(t,e,i,s,r){if(t=this.getBody(t),e=this.getBody(e),t&&e)return this.addSpring(new n.Physics.P2.RotationalSpring(this,t,e,i,s,r));console.warn("Cannot create Rotational Spring, invalid body objects given")},createBody:function(t,e,i,s,r,o){void 0===s&&(s=!1);var a=new n.Physics.P2.Body(this.game,null,t,e,i);if(o){if(!a.addPolygon(r,o))return!1}return s&&this.world.addBody(a.data),a},createParticle:function(t,e,i,s,r,o){void 0===s&&(s=!1);var a=new n.Physics.P2.Body(this.game,null,t,e,i);if(o){if(!a.addPolygon(r,o))return!1}return s&&this.world.addBody(a.data),a},convertCollisionObjects:function(t,e,i){void 0===i&&(i=!0);for(var s=[],n=0,r=t.collision[e].length;n<r;n++){var o=t.collision[e][n],a=this.createBody(o.x,o.y,0,i,{},o.polyline);a&&s.push(a)}return s},clearTilemapLayerBodies:function(t,e){e=t.getLayer(e);for(var i=t.layers[e].bodies.length;i--;)t.layers[e].bodies[i].destroy();t.layers[e].bodies.length=0},convertTilemap:function(t,e,i,s){e=t.getLayer(e),void 0===i&&(i=!0),void 0===s&&(s=!0),this.clearTilemapLayerBodies(t,e);for(var n=0,r=0,o=0,a=0,h=t.layers[e].height;a<h;a++){n=0;for(var l=0,c=t.layers[e].width;l<c;l++){var u=t.layers[e].data[a][l];if(u&&u.index>-1&&u.collides)if(s){var d=t.getTileRight(e,l,a);if(0===n&&(r=u.x*u.width,o=u.y*u.height,n=u.width),d&&d.collides)n+=u.width;else{var p=this.createBody(r,o,0,!1);p.addRectangle(n,u.height,n/2,u.height/2,0),i&&this.addBody(p),t.layers[e].bodies.push(p),n=0}}else{var p=this.createBody(u.x*u.width,u.y*u.height,0,!1);p.addRectangle(u.width,u.height,u.width/2,u.height/2,0),i&&this.addBody(p),t.layers[e].bodies.push(p)}}}return t.layers[e].bodies},mpx:function(t){return t*=20},pxm:function(t){return.05*t},mpxi:function(t){return t*=-20},pxmi:function(t){return-.05*t}},Object.defineProperty(n.Physics.P2.prototype,"friction",{get:function(){return this.world.defaultContactMaterial.friction},set:function(t){this.world.defaultContactMaterial.friction=t}}),Object.defineProperty(n.Physics.P2.prototype,"restitution",{get:function(){return this.world.defaultContactMaterial.restitution},set:function(t){this.world.defaultContactMaterial.restitution=t}}),Object.defineProperty(n.Physics.P2.prototype,"contactMaterial",{get:function(){return this.world.defaultContactMaterial},set:function(t){this.world.defaultContactMaterial=t}}),Object.defineProperty(n.Physics.P2.prototype,"applySpringForces",{get:function(){return this.world.applySpringForces},set:function(t){this.world.applySpringForces=t}}),Object.defineProperty(n.Physics.P2.prototype,"applyDamping",{get:function(){return this.world.applyDamping},set:function(t){this.world.applyDamping=t}}),Object.defineProperty(n.Physics.P2.prototype,"applyGravity",{get:function(){return this.world.applyGravity},set:function(t){this.world.applyGravity=t}}),Object.defineProperty(n.Physics.P2.prototype,"solveConstraints",{get:function(){return this.world.solveConstraints},set:function(t){this.world.solveConstraints=t}}),Object.defineProperty(n.Physics.P2.prototype,"time",{get:function(){return this.world.time}}),Object.defineProperty(n.Physics.P2.prototype,"emitImpactEvent",{get:function(){return this.world.emitImpactEvent},set:function(t){this.world.emitImpactEvent=t}}),Object.defineProperty(n.Physics.P2.prototype,"sleepMode",{get:function(){return this.world.sleepMode},set:function(t){this.world.sleepMode=t}}),Object.defineProperty(n.Physics.P2.prototype,"total",{get:function(){return this.world.bodies.length}}),n.Physics.P2.FixtureList=function(t){Array.isArray(t)||(t=[t]),this.rawList=t,this.init(),this.parse(this.rawList)},n.Physics.P2.FixtureList.prototype={init:function(){this.namedFixtures={},this.groupedFixtures=[],this.allFixtures=[]},setCategory:function(t,e){var i=function(e){e.collisionGroup=t};this.getFixtures(e).forEach(i)},setMask:function(t,e){var i=function(e){e.collisionMask=t};this.getFixtures(e).forEach(i)},setSensor:function(t,e){var i=function(e){e.sensor=t};this.getFixtures(e).forEach(i)},setMaterial:function(t,e){var i=function(e){e.material=t};this.getFixtures(e).forEach(i)},getFixtures:function(t){var e=[];if(t){t instanceof Array||(t=[t]);var i=this;return t.forEach(function(t){i.namedFixtures[t]&&e.push(i.namedFixtures[t])}),this.flatten(e)}return this.allFixtures},getFixtureByKey:function(t){return this.namedFixtures[t]},getGroup:function(t){return this.groupedFixtures[t]},parse:function(){var t,e,i,s;i=this.rawList,s=[];for(t in i)e=i[t],isNaN(t-0)?this.namedFixtures[t]=this.flatten(e):(this.groupedFixtures[t]=this.groupedFixtures[t]||[],this.groupedFixtures[t]=this.groupedFixtures[t].concat(e)),s.push(this.allFixtures=this.flatten(this.groupedFixtures))},flatten:function(t){var e,i;return e=[],i=arguments.callee,t.forEach(function(t){return Array.prototype.push.apply(e,Array.isArray(t)?i(t):[t])}),e}},n.Physics.P2.PointProxy=function(t,e){this.world=t,this.destination=e},n.Physics.P2.PointProxy.prototype.constructor=n.Physics.P2.PointProxy,Object.defineProperty(n.Physics.P2.PointProxy.prototype,"x",{get:function(){return this.world.mpx(this.destination[0])},set:function(t){this.destination[0]=this.world.pxm(t)}}),Object.defineProperty(n.Physics.P2.PointProxy.prototype,"y",{get:function(){return this.world.mpx(this.destination[1])},set:function(t){this.destination[1]=this.world.pxm(t)}}),Object.defineProperty(n.Physics.P2.PointProxy.prototype,"mx",{get:function(){return this.destination[0]},set:function(t){this.destination[0]=t}}),Object.defineProperty(n.Physics.P2.PointProxy.prototype,"my",{get:function(){return this.destination[1]},set:function(t){this.destination[1]=t}}),n.Physics.P2.InversePointProxy=function(t,e){this.world=t,this.destination=e},n.Physics.P2.InversePointProxy.prototype.constructor=n.Physics.P2.InversePointProxy,Object.defineProperty(n.Physics.P2.InversePointProxy.prototype,"x",{get:function(){return this.world.mpxi(this.destination[0])},set:function(t){this.destination[0]=this.world.pxmi(t)}}),Object.defineProperty(n.Physics.P2.InversePointProxy.prototype,"y",{get:function(){return this.world.mpxi(this.destination[1])},set:function(t){this.destination[1]=this.world.pxmi(t)}}),Object.defineProperty(n.Physics.P2.InversePointProxy.prototype,"mx",{get:function(){return this.destination[0]},set:function(t){this.destination[0]=-t}}),Object.defineProperty(n.Physics.P2.InversePointProxy.prototype,"my",{get:function(){return this.destination[1]},set:function(t){this.destination[1]=-t}}),n.Physics.P2.Body=function(t,e,i,s,r){e=e||null,i=i||0,s=s||0,void 0===r&&(r=1),this.game=t,this.world=t.physics.p2,this.sprite=e,this.type=n.Physics.P2JS,this.offset=new n.Point,this.data=new p2.Body({position:[this.world.pxmi(i),this.world.pxmi(s)],mass:r}),this.data.parent=this,this.velocity=new n.Physics.P2.InversePointProxy(this.world,this.data.velocity),this.force=new n.Physics.P2.InversePointProxy(this.world,this.data.force),this.gravity=new n.Point,this.onBeginContact=new n.Signal,this.onEndContact=new n.Signal,this.collidesWith=[],this.removeNextStep=!1,this.debugBody=null,this.dirty=!1,this._collideWorldBounds=!0,this._bodyCallbacks={},this._bodyCallbackContext={},this._groupCallbacks={},this._groupCallbackContext={},this._reset=!1,e&&(this.setRectangleFromSprite(e),e.exists&&this.game.physics.p2.addBody(this))},n.Physics.P2.Body.prototype={createBodyCallback:function(t,e,i){var s=-1;t.id?s=t.id:t.body&&(s=t.body.id),s>-1&&(null===e?(delete this._bodyCallbacks[s],delete this._bodyCallbackContext[s]):(this._bodyCallbacks[s]=e,this._bodyCallbackContext[s]=i))},createGroupCallback:function(t,e,i){null===e?(delete this._groupCallbacks[t.mask],delete this._groupCallbackContext[t.mask]):(this._groupCallbacks[t.mask]=e,this._groupCallbackContext[t.mask]=i)},getCollisionMask:function(){var t=0;this._collideWorldBounds&&(t=this.game.physics.p2.boundsCollisionGroup.mask);for(var e=0;e<this.collidesWith.length;e++)t|=this.collidesWith[e].mask;return t},updateCollisionMask:function(t){var e=this.getCollisionMask();if(void 0===t)for(var i=this.data.shapes.length-1;i>=0;i--)this.data.shapes[i].collisionMask=e;else t.collisionMask=e},setCollisionGroup:function(t,e){var i=this.getCollisionMask();if(void 0===e)for(var s=this.data.shapes.length-1;s>=0;s--)this.data.shapes[s].collisionGroup=t.mask,this.data.shapes[s].collisionMask=i;else e.collisionGroup=t.mask,e.collisionMask=i},clearCollision:function(t,e,i){if(void 0===t&&(t=!0),void 0===e&&(e=!0),void 0===i)for(var s=this.data.shapes.length-1;s>=0;s--)t&&(this.data.shapes[s].collisionGroup=null),e&&(this.data.shapes[s].collisionMask=null);else t&&(i.collisionGroup=null),e&&(i.collisionMask=null);t&&(this.collidesWith.length=0)},removeCollisionGroup:function(t,e,i){void 0===e&&(e=!0);var s;if(Array.isArray(t))for(var n=0;n<t.length;n++)(s=this.collidesWith.indexOf(t[n]))>-1&&(this.collidesWith.splice(s,1),e&&(delete this._groupCallbacks[t.mask],delete this._groupCallbackContext[t.mask]));else(s=this.collidesWith.indexOf(t))>-1&&(this.collidesWith.splice(s,1),e&&(delete this._groupCallbacks[t.mask],delete this._groupCallbackContext[t.mask]));var r=this.getCollisionMask();if(void 0===i)for(var n=this.data.shapes.length-1;n>=0;n--)this.data.shapes[n].collisionMask=r;else i.collisionMask=r},collides:function(t,e,i,s){if(Array.isArray(t))for(var n=0;n<t.length;n++)-1===this.collidesWith.indexOf(t[n])&&(this.collidesWith.push(t[n]),e&&this.createGroupCallback(t[n],e,i));else-1===this.collidesWith.indexOf(t)&&(this.collidesWith.push(t),e&&this.createGroupCallback(t,e,i));var r=this.getCollisionMask();if(void 0===s)for(var n=this.data.shapes.length-1;n>=0;n--)this.data.shapes[n].collisionMask=r;else s.collisionMask=r},adjustCenterOfMass:function(){this.data.adjustCenterOfMass(),this.shapeChanged()},getVelocityAtPoint:function(t,e){return this.data.getVelocityAtPoint(t,e)},applyDamping:function(t){this.data.applyDamping(t)},applyImpulse:function(t,e,i){this.data.applyImpulse(t,[this.world.pxmi(e),this.world.pxmi(i)])},applyImpulseLocal:function(t,e,i){this.data.applyImpulseLocal(t,[this.world.pxmi(e),this.world.pxmi(i)])},applyForce:function(t,e,i){this.data.applyForce(t,[this.world.pxmi(e),this.world.pxmi(i)])},setZeroForce:function(){this.data.setZeroForce()},setZeroRotation:function(){this.data.angularVelocity=0},setZeroVelocity:function(){this.data.velocity[0]=0,this.data.velocity[1]=0},setZeroDamping:function(){this.data.damping=0,this.data.angularDamping=0},toLocalFrame:function(t,e){return this.data.toLocalFrame(t,e)},toWorldFrame:function(t,e){return this.data.toWorldFrame(t,e)},rotateLeft:function(t){this.data.angularVelocity=this.world.pxm(-t)},rotateRight:function(t){this.data.angularVelocity=this.world.pxm(t)},moveForward:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.velocity[0]=e*Math.cos(i),this.data.velocity[1]=e*Math.sin(i)},moveBackward:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.velocity[0]=-e*Math.cos(i),this.data.velocity[1]=-e*Math.sin(i)},thrust:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.force[0]+=e*Math.cos(i),this.data.force[1]+=e*Math.sin(i)},thrustLeft:function(t){var e=this.world.pxmi(-t),i=this.data.angle;this.data.force[0]+=e*Math.cos(i),this.data.force[1]+=e*Math.sin(i)},thrustRight:function(t){var e=this.world.pxmi(-t),i=this.data.angle;this.data.force[0]-=e*Math.cos(i),this.data.force[1]-=e*Math.sin(i)},reverse:function(t){var e=this.world.pxmi(-t),i=this.data.angle+Math.PI/2;this.data.force[0]-=e*Math.cos(i),this.data.force[1]-=e*Math.sin(i)},moveLeft:function(t){this.data.velocity[0]=this.world.pxmi(-t)},moveRight:function(t){this.data.velocity[0]=this.world.pxmi(t)},moveUp:function(t){this.data.velocity[1]=this.world.pxmi(-t)},moveDown:function(t){this.data.velocity[1]=this.world.pxmi(t)},preUpdate:function(){this.dirty=!0,this.removeNextStep&&(this.removeFromWorld(),this.removeNextStep=!1)},postUpdate:function(){this.sprite.x=this.world.mpxi(this.data.position[0])+this.offset.x,this.sprite.y=this.world.mpxi(this.data.position[1])+this.offset.y,this.fixedRotation||(this.sprite.rotation=this.data.angle),this.debugBody&&this.debugBody.updateSpriteTransform(),this.dirty=!1},reset:function(t,e,i,s){void 0===i&&(i=!1),void 0===s&&(s=!1),this.setZeroForce(),this.setZeroVelocity(),this.setZeroRotation(),i&&this.setZeroDamping(),s&&(this.mass=1),this.x=t,this.y=e},addToWorld:function(){if(this.game.physics.p2._toRemove)for(var t=0;t<this.game.physics.p2._toRemove.length;t++)this.game.physics.p2._toRemove[t]===this&&this.game.physics.p2._toRemove.splice(t,1);this.data.world!==this.game.physics.p2.world&&this.game.physics.p2.addBody(this)},removeFromWorld:function(){this.data.world===this.game.physics.p2.world&&this.game.physics.p2.removeBodyNextStep(this)},destroy:function(){this.removeFromWorld(),this.clearShapes(),this._bodyCallbacks={},this._bodyCallbackContext={},this._groupCallbacks={},this._groupCallbackContext={},this.debugBody&&this.debugBody.destroy(!0,!0),this.debugBody=null,this.sprite&&(this.sprite.body=null,this.sprite=null)},clearShapes:function(){for(var t=this.data.shapes.length;t--;)this.data.removeShape(this.data.shapes[t]);this.shapeChanged()},addShape:function(t,e,i,s){return void 0===e&&(e=0),void 0===i&&(i=0),void 0===s&&(s=0),this.data.addShape(t,[this.world.pxmi(e),this.world.pxmi(i)],s),this.shapeChanged(),t},addCircle:function(t,e,i,s){var n=new p2.Circle({radius:this.world.pxm(t)});return this.addShape(n,e,i,s)},addRectangle:function(t,e,i,s,n){var r=new p2.Box({width:this.world.pxm(t),height:this.world.pxm(e)});return this.addShape(r,i,s,n)},addPlane:function(t,e,i){var s=new p2.Plane;return this.addShape(s,t,e,i)},addParticle:function(t,e,i){var s=new p2.Particle;return this.addShape(s,t,e,i)},addLine:function(t,e,i,s){var n=new p2.Line({length:this.world.pxm(t)});return this.addShape(n,e,i,s)},addCapsule:function(t,e,i,s,n){var r=new p2.Capsule({length:this.world.pxm(t),radius:this.world.pxm(e)});return this.addShape(r,i,s,n)},addPolygon:function(t,e){t=t||{},Array.isArray(e)||(e=Array.prototype.slice.call(arguments,1));var i=[];if(1===e.length&&Array.isArray(e[0]))i=e[0].slice(0);else if(Array.isArray(e[0]))i=e.slice();else if("number"==typeof e[0])for(var s=0,n=e.length;s<n;s+=2)i.push([e[s],e[s+1]]);var r=i.length-1;i[r][0]===i[0][0]&&i[r][1]===i[0][1]&&i.pop();for(var o=0;o<i.length;o++)i[o][0]=this.world.pxmi(i[o][0]),i[o][1]=this.world.pxmi(i[o][1]);var a=this.data.fromPolygon(i,t);return this.shapeChanged(),a},removeShape:function(t){var e=this.data.removeShape(t);return this.shapeChanged(),e},setCircle:function(t,e,i,s){return this.clearShapes(),this.addCircle(t,e,i,s)},setRectangle:function(t,e,i,s,n){return void 0===t&&(t=16),void 0===e&&(e=16),this.clearShapes(),this.addRectangle(t,e,i,s,n)},setRectangleFromSprite:function(t){return void 0===t&&(t=this.sprite),this.clearShapes(),this.addRectangle(t.width,t.height,0,0,t.rotation)},setMaterial:function(t,e){if(void 0===e)for(var i=this.data.shapes.length-1;i>=0;i--)this.data.shapes[i].material=t;else e.material=t},shapeChanged:function(){this.debugBody&&this.debugBody.draw()},addPhaserPolygon:function(t,e){for(var i=this.game.cache.getPhysicsData(t,e),s=[],n=0;n<i.length;n++){var r=i[n],o=this.addFixture(r);s[r.filter.group]=s[r.filter.group]||[],s[r.filter.group]=s[r.filter.group].concat(o),r.fixtureKey&&(s[r.fixtureKey]=o)}return this.data.aabbNeedsUpdate=!0,this.shapeChanged(),s},addFixture:function(t){var e=[];if(t.circle){var i=new p2.Circle({radius:this.world.pxm(t.circle.radius)});i.collisionGroup=t.filter.categoryBits,i.collisionMask=t.filter.maskBits,i.sensor=t.isSensor;var s=p2.vec2.create();s[0]=this.world.pxmi(t.circle.position[0]-this.sprite.width/2),s[1]=this.world.pxmi(t.circle.position[1]-this.sprite.height/2),this.data.addShape(i,s),e.push(i)}else for(var n=t.polygons,r=p2.vec2.create(),o=0;o<n.length;o++){for(var a=n[o],h=[],l=0;l<a.length;l+=2)h.push([this.world.pxmi(a[l]),this.world.pxmi(a[l+1])]);for(var i=new p2.Convex({vertices:h}),c=0;c!==i.vertices.length;c++){var u=i.vertices[c];p2.vec2.sub(u,u,i.centerOfMass)}p2.vec2.scale(r,i.centerOfMass,1),r[0]-=this.world.pxmi(this.sprite.width/2),r[1]-=this.world.pxmi(this.sprite.height/2),i.updateTriangles(),i.updateCenterOfMass(),i.updateBoundingRadius(),i.collisionGroup=t.filter.categoryBits,i.collisionMask=t.filter.maskBits,i.sensor=t.isSensor,this.data.addShape(i,r),e.push(i)}return e},loadPolygon:function(t,e){if(null===t)var i=e;else var i=this.game.cache.getPhysicsData(t,e);for(var s=p2.vec2.create(),n=0;n<i.length;n++){for(var r=[],o=0;o<i[n].shape.length;o+=2)r.push([this.world.pxmi(i[n].shape[o]),this.world.pxmi(i[n].shape[o+1])]);for(var a=new p2.Convex({vertices:r}),h=0;h!==a.vertices.length;h++){var l=a.vertices[h];p2.vec2.sub(l,l,a.centerOfMass)}p2.vec2.scale(s,a.centerOfMass,1),s[0]-=this.world.pxmi(this.sprite.width/2),s[1]-=this.world.pxmi(this.sprite.height/2),a.updateTriangles(),a.updateCenterOfMass(),a.updateBoundingRadius(),this.data.addShape(a,s)}return this.data.aabbNeedsUpdate=!0,this.shapeChanged(),!0}},n.Physics.P2.Body.prototype.constructor=n.Physics.P2.Body,n.Physics.P2.Body.DYNAMIC=1,n.Physics.P2.Body.STATIC=2,n.Physics.P2.Body.KINEMATIC=4,Object.defineProperty(n.Physics.P2.Body.prototype,"static",{get:function(){return this.data.type===n.Physics.P2.Body.STATIC},set:function(t){t&&this.data.type!==n.Physics.P2.Body.STATIC?(this.data.type=n.Physics.P2.Body.STATIC,this.mass=0):t||this.data.type!==n.Physics.P2.Body.STATIC||(this.data.type=n.Physics.P2.Body.DYNAMIC,this.mass=1)}}),Object.defineProperty(n.Physics.P2.Body.prototype,"dynamic",{get:function(){return this.data.type===n.Physics.P2.Body.DYNAMIC},set:function(t){t&&this.data.type!==n.Physics.P2.Body.DYNAMIC?(this.data.type=n.Physics.P2.Body.DYNAMIC,this.mass=1):t||this.data.type!==n.Physics.P2.Body.DYNAMIC||(this.data.type=n.Physics.P2.Body.STATIC,this.mass=0)}}),Object.defineProperty(n.Physics.P2.Body.prototype,"kinematic",{get:function(){return this.data.type===n.Physics.P2.Body.KINEMATIC},set:function(t){t&&this.data.type!==n.Physics.P2.Body.KINEMATIC?(this.data.type=n.Physics.P2.Body.KINEMATIC,this.mass=4):t||this.data.type!==n.Physics.P2.Body.KINEMATIC||(this.data.type=n.Physics.P2.Body.STATIC,this.mass=0)}}),Object.defineProperty(n.Physics.P2.Body.prototype,"allowSleep",{get:function(){return this.data.allowSleep},set:function(t){t!==this.data.allowSleep&&(this.data.allowSleep=t)}}),Object.defineProperty(n.Physics.P2.Body.prototype,"angle",{get:function(){return n.Math.wrapAngle(n.Math.radToDeg(this.data.angle))},set:function(t){this.data.angle=n.Math.degToRad(n.Math.wrapAngle(t))}}),Object.defineProperty(n.Physics.P2.Body.prototype,"angularDamping",{get:function(){return this.data.angularDamping},set:function(t){this.data.angularDamping=t}}),Object.defineProperty(n.Physics.P2.Body.prototype,"angularForce",{get:function(){return this.data.angularForce},set:function(t){this.data.angularForce=t}}),Object.defineProperty(n.Physics.P2.Body.prototype,"angularVelocity",{get:function(){return this.data.angularVelocity},set:function(t){this.data.angularVelocity=t}}),Object.defineProperty(n.Physics.P2.Body.prototype,"damping",{get:function(){return this.data.damping},set:function(t){this.data.damping=t}}),Object.defineProperty(n.Physics.P2.Body.prototype,"fixedRotation",{get:function(){return this.data.fixedRotation},set:function(t){t!==this.data.fixedRotation&&(this.data.fixedRotation=t)}}),Object.defineProperty(n.Physics.P2.Body.prototype,"inertia",{get:function(){return this.data.inertia},set:function(t){this.data.inertia=t}}),Object.defineProperty(n.Physics.P2.Body.prototype,"mass",{get:function(){return this.data.mass},set:function(t){t!==this.data.mass&&(this.data.mass=t,this.data.updateMassProperties())}}),Object.defineProperty(n.Physics.P2.Body.prototype,"motionState",{get:function(){return this.data.type},set:function(t){t!==this.data.type&&(this.data.type=t)}}),Object.defineProperty(n.Physics.P2.Body.prototype,"rotation",{get:function(){return this.data.angle},set:function(t){this.data.angle=t}}),Object.defineProperty(n.Physics.P2.Body.prototype,"sleepSpeedLimit",{get:function(){return this.data.sleepSpeedLimit},set:function(t){this.data.sleepSpeedLimit=t}}),Object.defineProperty(n.Physics.P2.Body.prototype,"x",{get:function(){return this.world.mpxi(this.data.position[0])},set:function(t){this.data.position[0]=this.world.pxmi(t)}}),Object.defineProperty(n.Physics.P2.Body.prototype,"y",{get:function(){return this.world.mpxi(this.data.position[1])},set:function(t){this.data.position[1]=this.world.pxmi(t)}}),Object.defineProperty(n.Physics.P2.Body.prototype,"id",{get:function(){return this.data.id}}),Object.defineProperty(n.Physics.P2.Body.prototype,"debug",{get:function(){return null!==this.debugBody},set:function(t){t&&!this.debugBody?this.debugBody=new n.Physics.P2.BodyDebug(this.game,this.data):!t&&this.debugBody&&(this.debugBody.destroy(),this.debugBody=null)}}),Object.defineProperty(n.Physics.P2.Body.prototype,"collideWorldBounds",{get:function(){return this._collideWorldBounds},set:function(t){t&&!this._collideWorldBounds?(this._collideWorldBounds=!0,this.updateCollisionMask()):!t&&this._collideWorldBounds&&(this._collideWorldBounds=!1,this.updateCollisionMask())}}),n.Physics.P2.BodyDebug=function(t,e,i){n.Group.call(this,t);var s={pixelsPerLengthUnit:t.physics.p2.mpx(1),debugPolygons:!1,lineWidth:1,alpha:.5};this.settings=n.Utils.extend(s,i),this.ppu=this.settings.pixelsPerLengthUnit,this.ppu=-1*this.ppu,this.body=e,this.canvas=new n.Graphics(t),this.canvas.alpha=this.settings.alpha,this.add(this.canvas),this.draw(),this.updateSpriteTransform()},n.Physics.P2.BodyDebug.prototype=Object.create(n.Group.prototype),n.Physics.P2.BodyDebug.prototype.constructor=n.Physics.P2.BodyDebug,n.Utils.extend(n.Physics.P2.BodyDebug.prototype,{updateSpriteTransform:function(){this.position.x=this.body.position[0]*this.ppu,this.position.y=this.body.position[1]*this.ppu,this.rotation=this.body.angle},draw:function(){var t,e,i,s,n,r,o,a,h,l,c,u,d,p,f;if(a=this.body,l=this.canvas,l.clear(),i=parseInt(this.randomPastelHex(),16),r=16711680,o=this.lineWidth,a instanceof p2.Body&&a.shapes.length){var g=a.shapes.length;for(s=0;s!==g;){if(e=a.shapes[s],h=e.position||0,t=e.angle||0,e instanceof p2.Circle)this.drawCircle(l,h[0]*this.ppu,h[1]*this.ppu,t,e.radius*this.ppu,i,o);else if(e instanceof p2.Capsule)this.drawCapsule(l,h[0]*this.ppu,h[1]*this.ppu,t,e.length*this.ppu,e.radius*this.ppu,r,i,o);else if(e instanceof p2.Plane)this.drawPlane(l,h[0]*this.ppu,-h[1]*this.ppu,i,r,5*o,10*o,10*o,100*this.ppu,t);else if(e instanceof p2.Line)this.drawLine(l,e.length*this.ppu,r,o);else if(e instanceof p2.Box)this.drawRectangle(l,h[0]*this.ppu,h[1]*this.ppu,t,e.width*this.ppu,e.height*this.ppu,r,i,o);else if(e instanceof p2.Convex){for(u=[],d=p2.vec2.create(),n=p=0,f=e.vertices.length;0<=f?p<f:p>f;n=0<=f?++p:--p)c=e.vertices[n],p2.vec2.rotate(d,c,t),u.push([(d[0]+h[0])*this.ppu,-(d[1]+h[1])*this.ppu]);this.drawConvex(l,u,e.triangles,r,i,o,this.settings.debugPolygons,[h[0]*this.ppu,-h[1]*this.ppu])}s++}}},drawRectangle:function(t,e,i,s,n,r,o,a,h){void 0===h&&(h=1),void 0===o&&(o=0),t.lineStyle(h,o,1),t.beginFill(a),t.drawRect(e-n/2,i-r/2,n,r)},drawCircle:function(t,e,i,s,n,r,o){void 0===o&&(o=1),void 0===r&&(r=16777215),t.lineStyle(o,0,1),t.beginFill(r,1),t.drawCircle(e,i,2*-n),t.endFill(),t.moveTo(e,i),t.lineTo(e+n*Math.cos(-s),i+n*Math.sin(-s))},drawLine:function(t,e,i,s){void 0===s&&(s=1),void 0===i&&(i=0),t.lineStyle(5*s,i,1),t.moveTo(-e/2,0),t.lineTo(e/2,0)},drawConvex:function(t,e,i,s,n,r,o,a){var h,l,c,u,d,p,f,g,m,y,v;if(void 0===r&&(r=1),void 0===s&&(s=0),o){for(h=[16711680,65280,255],l=0;l!==e.length+1;)u=e[l%e.length],d=e[(l+1)%e.length],f=u[0],y=u[1],g=d[0],v=d[1],t.lineStyle(r,h[l%h.length],1),t.moveTo(f,-y),t.lineTo(g,-v),t.drawCircle(f,-y,2*r),l++;return t.lineStyle(r,0,1),t.drawCircle(a[0],a[1],2*r)}for(t.lineStyle(r,s,1),t.beginFill(n),l=0;l!==e.length;)c=e[l],p=c[0],m=c[1],0===l?t.moveTo(p,-m):t.lineTo(p,-m),l++;if(t.endFill(),e.length>2)return t.moveTo(e[e.length-1][0],-e[e.length-1][1]),t.lineTo(e[0][0],-e[0][1])},drawPath:function(t,e,i,s,n){var r,o,a,h,l,c,u,d,p,f,g,m;for(void 0===n&&(n=1),void 0===i&&(i=0),t.lineStyle(n,i,1),"number"==typeof s&&t.beginFill(s),o=null,a=null,r=0;r<e.length;)f=e[r],g=f[0],m=f[1],g===o&&m===a||(0===r?t.moveTo(g,m):(h=o,l=a,c=g,u=m,d=e[(r+1)%e.length][0],p=e[(r+1)%e.length][1],0!==(c-h)*(p-l)-(d-h)*(u-l)&&t.lineTo(g,m)),o=g,a=m),r++;"number"==typeof s&&t.endFill(),e.length>2&&"number"==typeof s&&(t.moveTo(e[e.length-1][0],e[e.length-1][1]),t.lineTo(e[0][0],e[0][1]))},drawPlane:function(t,e,i,s,n,r,o,a,h,l){var c,u;void 0===r&&(r=1),void 0===s&&(s=16777215),t.lineStyle(r,n,11),t.beginFill(s),t.moveTo(e,-i),c=e+Math.cos(l)*this.game.width,u=i+Math.sin(l)*this.game.height,t.lineTo(c,-u),t.moveTo(e,-i),c=e+Math.cos(l)*-this.game.width,u=i+Math.sin(l)*-this.game.height,t.lineTo(c,-u)},drawCapsule:function(t,e,i,s,n,r,o,a,h){void 0===h&&(h=1),void 0===o&&(o=0),t.lineStyle(h,o,1);var l=Math.cos(s),c=Math.sin(s);t.beginFill(a,1),t.drawCircle(-n/2*l+e,-n/2*c+i,2*-r),t.drawCircle(n/2*l+e,n/2*c+i,2*-r),t.endFill(),t.lineStyle(h,o,0),t.beginFill(a,1),t.moveTo(-n/2*l+r*c+e,-n/2*c+r*l+i),t.lineTo(n/2*l+r*c+e,n/2*c+r*l+i),t.lineTo(n/2*l-r*c+e,n/2*c-r*l+i),t.lineTo(-n/2*l-r*c+e,-n/2*c-r*l+i),t.endFill(),t.lineStyle(h,o,1),t.moveTo(-n/2*l+r*c+e,-n/2*c+r*l+i),t.lineTo(n/2*l+r*c+e,n/2*c+r*l+i),t.moveTo(-n/2*l-r*c+e,-n/2*c-r*l+i),t.lineTo(n/2*l-r*c+e,n/2*c-r*l+i)},randomPastelHex:function(){var t,e,i,s;return i=[255,255,255],s=Math.floor(256*Math.random()),e=Math.floor(256*Math.random()),t=Math.floor(256*Math.random()),s=Math.floor((s+3*i[0])/4),e=Math.floor((e+3*i[1])/4),t=Math.floor((t+3*i[2])/4),this.rgbToHex(s,e,t)},rgbToHex:function(t,e,i){return this.componentToHex(t)+this.componentToHex(e)+this.componentToHex(i)},componentToHex:function(t){var e;return e=t.toString(16),2===e.length?e:e+"0"}}),n.Physics.P2.Spring=function(t,e,i,s,n,r,o,a,h,l){this.game=t.game,this.world=t,void 0===s&&(s=1),void 0===n&&(n=100),void 0===r&&(r=1),s=t.pxm(s);var c={restLength:s,stiffness:n,damping:r};void 0!==o&&null!==o&&(c.worldAnchorA=[t.pxm(o[0]),t.pxm(o[1])]),void 0!==a&&null!==a&&(c.worldAnchorB=[t.pxm(a[0]),t.pxm(a[1])]),void 0!==h&&null!==h&&(c.localAnchorA=[t.pxm(h[0]),t.pxm(h[1])]),void 0!==l&&null!==l&&(c.localAnchorB=[t.pxm(l[0]),t.pxm(l[1])]),this.data=new p2.LinearSpring(e,i,c),this.data.parent=this},n.Physics.P2.Spring.prototype.constructor=n.Physics.P2.Spring,n.Physics.P2.RotationalSpring=function(t,e,i,s,n,r){this.game=t.game,this.world=t,void 0===s&&(s=null),void 0===n&&(n=100),void 0===r&&(r=1),s&&(s=t.pxm(s));var o={restAngle:s,stiffness:n,damping:r};this.data=new p2.RotationalSpring(e,i,o),this.data.parent=this},n.Physics.P2.Spring.prototype.constructor=n.Physics.P2.Spring,n.Physics.P2.Material=function(t){this.name=t,p2.Material.call(this)},n.Physics.P2.Material.prototype=Object.create(p2.Material.prototype),n.Physics.P2.Material.prototype.constructor=n.Physics.P2.Material,n.Physics.P2.ContactMaterial=function(t,e,i){p2.ContactMaterial.call(this,t,e,i)},n.Physics.P2.ContactMaterial.prototype=Object.create(p2.ContactMaterial.prototype),n.Physics.P2.ContactMaterial.prototype.constructor=n.Physics.P2.ContactMaterial,n.Physics.P2.CollisionGroup=function(t){this.mask=t},n.Physics.P2.DistanceConstraint=function(t,e,i,s,n,r,o){void 0===s&&(s=100),void 0===n&&(n=[0,0]),void 0===r&&(r=[0,0]),void 0===o&&(o=Number.MAX_VALUE),this.game=t.game,this.world=t,s=t.pxm(s),n=[t.pxmi(n[0]),t.pxmi(n[1])],r=[t.pxmi(r[0]),t.pxmi(r[1])];var a={distance:s,localAnchorA:n,localAnchorB:r,maxForce:o};p2.DistanceConstraint.call(this,e,i,a)},n.Physics.P2.DistanceConstraint.prototype=Object.create(p2.DistanceConstraint.prototype),n.Physics.P2.DistanceConstraint.prototype.constructor=n.Physics.P2.DistanceConstraint,n.Physics.P2.GearConstraint=function(t,e,i,s,n){void 0===s&&(s=0),void 0===n&&(n=1),this.game=t.game,this.world=t;var r={angle:s,ratio:n};p2.GearConstraint.call(this,e,i,r)},n.Physics.P2.GearConstraint.prototype=Object.create(p2.GearConstraint.prototype),n.Physics.P2.GearConstraint.prototype.constructor=n.Physics.P2.GearConstraint,n.Physics.P2.LockConstraint=function(t,e,i,s,n,r){void 0===s&&(s=[0,0]),void 0===n&&(n=0),void 0===r&&(r=Number.MAX_VALUE),this.game=t.game,this.world=t,s=[t.pxm(s[0]),t.pxm(s[1])];var o={localOffsetB:s,localAngleB:n,maxForce:r};p2.LockConstraint.call(this,e,i,o)},n.Physics.P2.LockConstraint.prototype=Object.create(p2.LockConstraint.prototype),n.Physics.P2.LockConstraint.prototype.constructor=n.Physics.P2.LockConstraint,n.Physics.P2.PrismaticConstraint=function(t,e,i,s,n,r,o,a){void 0===s&&(s=!0),void 0===n&&(n=[0,0]),void 0===r&&(r=[0,0]),void 0===o&&(o=[0,0]),void 0===a&&(a=Number.MAX_VALUE),this.game=t.game,this.world=t,n=[t.pxmi(n[0]),t.pxmi(n[1])],r=[t.pxmi(r[0]),t.pxmi(r[1])];var h={localAnchorA:n,localAnchorB:r,localAxisA:o,maxForce:a,disableRotationalLock:!s};p2.PrismaticConstraint.call(this,e,i,h)},n.Physics.P2.PrismaticConstraint.prototype=Object.create(p2.PrismaticConstraint.prototype),n.Physics.P2.PrismaticConstraint.prototype.constructor=n.Physics.P2.PrismaticConstraint,n.Physics.P2.RevoluteConstraint=function(t,e,i,s,n,r,o){void 0===r&&(r=Number.MAX_VALUE),void 0===o&&(o=null),this.game=t.game,this.world=t,i=[t.pxmi(i[0]),t.pxmi(i[1])],n=[t.pxmi(n[0]),t.pxmi(n[1])],o&&(o=[t.pxmi(o[0]),t.pxmi(o[1])]);var a={worldPivot:o,localPivotA:i,localPivotB:n,maxForce:r};p2.RevoluteConstraint.call(this,e,s,a)},n.Physics.P2.RevoluteConstraint.prototype=Object.create(p2.RevoluteConstraint.prototype),n.Physics.P2.RevoluteConstraint.prototype.constructor=n.Physics.P2.RevoluteConstraint,n.ImageCollection=function(t,e,i,s,n,r,o){(void 0===i||i<=0)&&(i=32),(void 0===s||s<=0)&&(s=32),void 0===n&&(n=0),void 0===r&&(r=0),this.name=t,this.firstgid=0|e,this.imageWidth=0|i,this.imageHeight=0|s,this.imageMargin=0|n,this.imageSpacing=0|r,this.properties=o||{},this.images=[],this.total=0},n.ImageCollection.prototype={containsImageIndex:function(t){return t>=this.firstgid&&t<this.firstgid+this.total},addImage:function(t,e){this.images.push({gid:t,image:e}),this.total++}},n.ImageCollection.prototype.constructor=n.ImageCollection,n.Tile=function(t,e,i,s,n,r){this.layer=t,this.index=e,this.x=i,this.y=s,this.rotation=0,this.flipped=!1,this.worldX=i*n,this.worldY=s*r,this.width=n,this.height=r,this.centerX=Math.abs(n/2),this.centerY=Math.abs(r/2),this.alpha=1,this.properties={},this.scanned=!1,this.faceTop=!1,this.faceBottom=!1,this.faceLeft=!1,this.faceRight=!1,this.collideLeft=!1,this.collideRight=!1,this.collideUp=!1,this.collideDown=!1,this.collisionCallback=null,this.collisionCallbackContext=this},n.Tile.prototype={containsPoint:function(t,e){return!(t<this.worldX||e<this.worldY||t>this.right||e>this.bottom)},intersects:function(t,e,i,s){return!(i<=this.worldX)&&(!(s<=this.worldY)&&(!(t>=this.worldX+this.width)&&!(e>=this.worldY+this.height)))},setCollisionCallback:function(t,e){this.collisionCallback=t,this.collisionCallbackContext=e},destroy:function(){this.collisionCallback=null,this.collisionCallbackContext=null,this.properties=null},setCollision:function(t,e,i,s){this.collideLeft=t,this.collideRight=e,this.collideUp=i,this.collideDown=s,this.faceLeft=t,this.faceRight=e,this.faceTop=i,this.faceBottom=s},resetCollision:function(){this.collideLeft=!1,this.collideRight=!1,this.collideUp=!1,this.collideDown=!1,this.faceTop=!1,this.faceBottom=!1,this.faceLeft=!1,this.faceRight=!1},isInteresting:function(t,e){return t&&e?this.collideLeft||this.collideRight||this.collideUp||this.collideDown||this.faceTop||this.faceBottom||this.faceLeft||this.faceRight||this.collisionCallback:t?this.collideLeft||this.collideRight||this.collideUp||this.collideDown:!!e&&(this.faceTop||this.faceBottom||this.faceLeft||this.faceRight)},copy:function(t){this.index=t.index,this.alpha=t.alpha,this.properties=t.properties,this.collideUp=t.collideUp,this.collideDown=t.collideDown,this.collideLeft=t.collideLeft,this.collideRight=t.collideRight,this.collisionCallback=t.collisionCallback,this.collisionCallbackContext=t.collisionCallbackContext}},n.Tile.prototype.constructor=n.Tile,Object.defineProperty(n.Tile.prototype,"collides",{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown}}),Object.defineProperty(n.Tile.prototype,"canCollide",{get:function(){return this.collideLeft||this.collideRight||this.collideUp||this.collideDown||this.collisionCallback}}),Object.defineProperty(n.Tile.prototype,"left",{get:function(){return this.worldX}}),Object.defineProperty(n.Tile.prototype,"right",{get:function(){return this.worldX+this.width}}),Object.defineProperty(n.Tile.prototype,"top",{get:function(){return this.worldY}}),Object.defineProperty(n.Tile.prototype,"bottom",{get:function(){return this.worldY+this.height}}),n.Tilemap=function(t,e,i,s,r,o){this.game=t,this.key=e;var a=n.TilemapParser.parse(this.game,e,i,s,r,o);null!==a&&(this.width=a.width,this.height=a.height,this.tileWidth=a.tileWidth,this.tileHeight=a.tileHeight,this.orientation=a.orientation,this.format=a.format,this.version=a.version,this.properties=a.properties,this.widthInPixels=a.widthInPixels,this.heightInPixels=a.heightInPixels,this.layers=a.layers,this.tilesets=a.tilesets,this.imagecollections=a.imagecollections,this.tiles=a.tiles,this.objects=a.objects,this.collideIndexes=[],this.collision=a.collision,this.images=a.images,this.enableDebug=!1,this.currentLayer=0,this.debugMap=[],this._results=[],this._tempA=0,this._tempB=0)},n.Tilemap.CSV=0,n.Tilemap.TILED_JSON=1,n.Tilemap.NORTH=0,n.Tilemap.EAST=1,n.Tilemap.SOUTH=2,n.Tilemap.WEST=3,n.Tilemap.prototype={create:function(t,e,i,s,n,r){return void 0===r&&(r=this.game.world),this.width=e,this.height=i,this.setTileSize(s,n),this.layers.length=0,this.createBlankLayer(t,e,i,s,n,r)},setTileSize:function(t,e){this.tileWidth=t,this.tileHeight=e,this.widthInPixels=this.width*t,this.heightInPixels=this.height*e},addTilesetImage:function(t,e,i,s,r,o,a){if(void 0===t)return null;void 0===i&&(i=this.tileWidth),void 0===s&&(s=this.tileHeight),void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=0),0===i&&(i=32),0===s&&(s=32);var h=null;if(void 0!==e&&null!==e||(e=t),e instanceof n.BitmapData)h=e.canvas;else{if(!this.game.cache.checkImageKey(e))return console.warn('Phaser.Tilemap.addTilesetImage: Invalid image key given: "'+e+'"'),null;h=this.game.cache.getImage(e)}var l=this.getTilesetIndex(t);if(null===l&&this.format===n.Tilemap.TILED_JSON)return console.warn('Phaser.Tilemap.addTilesetImage: No data found in the JSON matching the tileset name: "'+t+'"'),null;if(this.tilesets[l])return this.tilesets[l].setImage(h),this.tilesets[l];var c=new n.Tileset(t,a,i,s,r,o,{});c.setImage(h),this.tilesets.push(c);for(var u=this.tilesets.length-1,d=r,p=r,f=0,g=0,m=0,y=a;y<a+c.total&&(this.tiles[y]=[d,p,u],d+=i+o,++f!==c.total)&&(++g!==c.columns||(d=r,p+=s+o,g=0,++m!==c.rows));y++);return c},createFromObjects:function(t,e,i,s,r,o,a,h,l){if(void 0===r&&(r=!0),void 0===o&&(o=!1),void 0===a&&(a=this.game.world),void 0===h&&(h=n.Sprite),void 0===l&&(l=!0),!this.objects[t])return void console.warn("Tilemap.createFromObjects: Invalid objectgroup name given: "+t);for(var c=0;c<this.objects[t].length;c++){var u=!1,d=this.objects[t][c];if(void 0!==d.gid&&"number"==typeof e&&d.gid===e?u=!0:void 0!==d.id&&"number"==typeof e&&d.id===e?u=!0:void 0!==d.name&&"string"==typeof e&&d.name===e&&(u=!0),u){var p=new h(this.game,parseFloat(d.x,10),parseFloat(d.y,10),i,s);p.name=d.name,p.visible=d.visible,p.autoCull=o,p.exists=r,d.width&&(p.width=d.width),d.height&&(p.height=d.height),d.rotation&&(p.angle=d.rotation),l&&(p.y-=p.height),a.add(p);for(var f in d.properties)a.set(p,f,d.properties[f],!1,!1,0,!0)}}},createFromTiles:function(t,e,i,s,r,o){"number"==typeof t&&(t=[t]),void 0===e||null===e?e=[]:"number"==typeof e&&(e=[e]),s=this.getLayer(s),void 0===r&&(r=this.game.world),void 0===o&&(o={}),void 0===o.customClass&&(o.customClass=n.Sprite),void 0===o.adjustY&&(o.adjustY=!0);var a=this.layers[s].width,h=this.layers[s].height;if(this.copy(0,0,a,h,s),this._results.length<2)return 0;for(var l,c=0,u=1,d=this._results.length;u<d;u++)if(-1!==t.indexOf(this._results[u].index)){l=new o.customClass(this.game,this._results[u].worldX,this._results[u].worldY,i);for(var p in o)l[p]=o[p];r.add(l),c++}if(1===e.length)for(u=0;u<t.length;u++)this.replace(t[u],e[0],0,0,a,h,s);else if(e.length>1)for(u=0;u<t.length;u++)this.replace(t[u],e[u],0,0,a,h,s);return c},createLayer:function(t,e,i,s){void 0===e&&(e=this.game.width),void 0===i&&(i=this.game.height),void 0===s&&(s=this.game.world);var r=t;if("string"==typeof t&&(r=this.getLayerIndex(t)),null===r||r>this.layers.length)return void console.warn("Tilemap.createLayer: Invalid layer ID given: "+r);void 0===e||e<=0?e=Math.min(this.game.width,this.layers[r].widthInPixels):e>this.game.width&&(e=this.game.width),void 0===i||i<=0?i=Math.min(this.game.height,this.layers[r].heightInPixels):i>this.game.height&&(i=this.game.height),this.enableDebug&&(console.group("Tilemap.createLayer"),console.log("Name:",this.layers[r].name),console.log("Size:",e,"x",i),console.log("Tileset:",this.tilesets[0].name,"index:",r));var o=s.add(new n.TilemapLayer(this.game,this,r,e,i));return this.enableDebug&&console.groupEnd(),o},createBlankLayer:function(t,e,i,s,r,o){if(void 0===o&&(o=this.game.world),null!==this.getLayerIndex(t))return void console.warn("Tilemap.createBlankLayer: Layer with matching name already exists: "+t);for(var a,h={name:t,x:0,y:0,width:e,height:i,widthInPixels:e*s,heightInPixels:i*r,alpha:1,visible:!0,properties:{},indexes:[],callbacks:[],bodies:[],data:null},l=[],c=0;c<i;c++){a=[];for(var u=0;u<e;u++)a.push(new n.Tile(h,-1,u,c,s,r));l.push(a)}h.data=l,this.layers.push(h),this.currentLayer=this.layers.length-1;var d=h.widthInPixels,p=h.heightInPixels;d>this.game.width&&(d=this.game.width),p>this.game.height&&(p=this.game.height);var l=new n.TilemapLayer(this.game,this,this.layers.length-1,d,p);return l.name=t,o.add(l)},getIndex:function(t,e){for(var i=0;i<t.length;i++)if(t[i].name===e)return i;return null},getLayerIndex:function(t){return this.getIndex(this.layers,t)},getTilesetIndex:function(t){return this.getIndex(this.tilesets,t)},getImageIndex:function(t){return this.getIndex(this.images,t)},setTileIndexCallback:function(t,e,i,s){if(s=this.getLayer(s),"number"==typeof t)this.layers[s].callbacks[t]={callback:e,callbackContext:i};else for(var n=0,r=t.length;n<r;n++)this.layers[s].callbacks[t[n]]={callback:e,callbackContext:i}},setTileLocationCallback:function(t,e,i,s,n,r,o){if(o=this.getLayer(o),this.copy(t,e,i,s,o),!(this._results.length<2))for(var a=1;a<this._results.length;a++)this._results[a].setCollisionCallback(n,r)},setCollision:function(t,e,i,s){if(void 0===e&&(e=!0),void 0===s&&(s=!0),i=this.getLayer(i),"number"==typeof t)return this.setCollisionByIndex(t,e,i,!0);if(Array.isArray(t)){for(var n=0;n<t.length;n++)this.setCollisionByIndex(t[n],e,i,!1);s&&this.calculateFaces(i)}},setCollisionBetween:function(t,e,i,s,n){if(void 0===i&&(i=!0),void 0===n&&(n=!0),s=this.getLayer(s),!(t>e)){for(var r=t;r<=e;r++)this.setCollisionByIndex(r,i,s,!1);n&&this.calculateFaces(s)}},setCollisionByExclusion:function(t,e,i,s){void 0===e&&(e=!0),void 0===s&&(s=!0),i=this.getLayer(i);for(var n=0,r=this.tiles.length;n<r;n++)-1===t.indexOf(n)&&this.setCollisionByIndex(n,e,i,!1);s&&this.calculateFaces(i)},setCollisionByIndex:function(t,e,i,s){if(void 0===e&&(e=!0),void 0===i&&(i=this.currentLayer),void 0===s&&(s=!0),e)this.collideIndexes.push(t);else{var n=this.collideIndexes.indexOf(t);n>-1&&this.collideIndexes.splice(n,1)}for(var r=0;r<this.layers[i].height;r++)for(var o=0;o<this.layers[i].width;o++){var a=this.layers[i].data[r][o];a&&a.index===t&&(e?a.setCollision(!0,!0,!0,!0):a.resetCollision(),a.faceTop=e,a.faceBottom=e,a.faceLeft=e,a.faceRight=e)}return s&&this.calculateFaces(i),i},getLayer:function(t){return void 0===t?t=this.currentLayer:"string"==typeof t?t=this.getLayerIndex(t):t instanceof n.TilemapLayer&&(t=t.index),t},setPreventRecalculate:function(t){if(!0===t&&!0!==this.preventingRecalculate&&(this.preventingRecalculate=!0,this.needToRecalculate={}),!1===t&&!0===this.preventingRecalculate){this.preventingRecalculate=!1;for(var e in this.needToRecalculate)this.calculateFaces(e);this.needToRecalculate=!1}},calculateFaces:function(t){if(this.preventingRecalculate)return void(this.needToRecalculate[t]=!0);for(var e=null,i=null,s=null,n=null,r=0,o=this.layers[t].height;r<o;r++)for(var a=0,h=this.layers[t].width;a<h;a++){var l=this.layers[t].data[r][a];l&&(e=this.getTileAbove(t,a,r),i=this.getTileBelow(t,a,r),s=this.getTileLeft(t,a,r),n=this.getTileRight(t,a,r),l.collides&&(l.faceTop=!0,l.faceBottom=!0,l.faceLeft=!0,l.faceRight=!0),e&&e.collides&&(l.faceTop=!1),i&&i.collides&&(l.faceBottom=!1),s&&s.collides&&(l.faceLeft=!1),n&&n.collides&&(l.faceRight=!1))}},getTileAbove:function(t,e,i){return i>0?this.layers[t].data[i-1][e]:null},getTileBelow:function(t,e,i){return i<this.layers[t].height-1?this.layers[t].data[i+1][e]:null},getTileLeft:function(t,e,i){return e>0?this.layers[t].data[i][e-1]:null},getTileRight:function(t,e,i){return e<this.layers[t].width-1?this.layers[t].data[i][e+1]:null},setLayer:function(t){t=this.getLayer(t),this.layers[t]&&(this.currentLayer=t)},hasTile:function(t,e,i){return i=this.getLayer(i),void 0!==this.layers[i].data[e]&&void 0!==this.layers[i].data[e][t]&&this.layers[i].data[e][t].index>-1},removeTile:function(t,e,i){if(i=this.getLayer(i),t>=0&&t<this.layers[i].width&&e>=0&&e<this.layers[i].height&&this.hasTile(t,e,i)){var s=this.layers[i].data[e][t];return this.layers[i].data[e][t]=new n.Tile(this.layers[i],-1,t,e,this.tileWidth,this.tileHeight),this.layers[i].dirty=!0,this.calculateFaces(i),s}},removeTileWorldXY:function(t,e,i,s,n){return n=this.getLayer(n),t=this.game.math.snapToFloor(t,i)/i,e=this.game.math.snapToFloor(e,s)/s,this.removeTile(t,e,n)},putTile:function(t,e,i,s){if(null===t)return this.removeTile(e,i,s);if(s=this.getLayer(s),e>=0&&e<this.layers[s].width&&i>=0&&i<this.layers[s].height){var r;return t instanceof n.Tile?(r=t.index,this.hasTile(e,i,s)?this.layers[s].data[i][e].copy(t):this.layers[s].data[i][e]=new n.Tile(s,r,e,i,t.width,t.height)):(r=t,this.hasTile(e,i,s)?this.layers[s].data[i][e].index=r:this.layers[s].data[i][e]=new n.Tile(this.layers[s],r,e,i,this.tileWidth,this.tileHeight)),this.collideIndexes.indexOf(r)>-1?this.layers[s].data[i][e].setCollision(!0,!0,!0,!0):this.layers[s].data[i][e].resetCollision(),this.layers[s].dirty=!0,this.calculateFaces(s),this.layers[s].data[i][e]}return null},putTileWorldXY:function(t,e,i,s,n,r){return r=this.getLayer(r),e=this.game.math.snapToFloor(e,s)/s,i=this.game.math.snapToFloor(i,n)/n,this.putTile(t,e,i,r)},searchTileIndex:function(t,e,i,s){void 0===e&&(e=0),void 0===i&&(i=!1),s=this.getLayer(s);var n=0;if(i){for(var r=this.layers[s].height-1;r>=0;r--)for(var o=this.layers[s].width-1;o>=0;o--)if(this.layers[s].data[r][o].index===t){if(n===e)return this.layers[s].data[r][o];n++}}else for(var r=0;r<this.layers[s].height;r++)for(var o=0;o<this.layers[s].width;o++)if(this.layers[s].data[r][o].index===t){if(n===e)return this.layers[s].data[r][o];n++}return null},getTile:function(t,e,i,s){return void 0===s&&(s=!1),i=this.getLayer(i),t>=0&&t<this.layers[i].width&&e>=0&&e<this.layers[i].height?-1===this.layers[i].data[e][t].index?s?this.layers[i].data[e][t]:null:this.layers[i].data[e][t]:null},getTileWorldXY:function(t,e,i,s,n,r){return void 0===i&&(i=this.tileWidth),void 0===s&&(s=this.tileHeight),n=this.getLayer(n),t=this.game.math.snapToFloor(t,i)/i,e=this.game.math.snapToFloor(e,s)/s,this.getTile(t,e,n,r)},copy:function(t,e,i,s,n){if(n=this.getLayer(n),!this.layers[n])return void(this._results.length=0);void 0===t&&(t=0),void 0===e&&(e=0),void 0===i&&(i=this.layers[n].width),void 0===s&&(s=this.layers[n].height),t<0&&(t=0),e<0&&(e=0),i>this.layers[n].width&&(i=this.layers[n].width),s>this.layers[n].height&&(s=this.layers[n].height),this._results.length=0,this._results.push({x:t,y:e,width:i,height:s,layer:n});for(var r=e;r<e+s;r++)for(var o=t;o<t+i;o++)this._results.push(this.layers[n].data[r][o]);return this._results},paste:function(t,e,i,s){if(void 0===t&&(t=0),void 0===e&&(e=0),s=this.getLayer(s),i&&!(i.length<2)){for(var n=t-i[1].x,r=e-i[1].y,o=1;o<i.length;o++)this.layers[s].data[r+i[o].y][n+i[o].x].copy(i[o]);this.layers[s].dirty=!0,this.calculateFaces(s)}},swap:function(t,e,i,s,n,r,o){o=this.getLayer(o),this.copy(i,s,n,r,o),this._results.length<2||(this._tempA=t,this._tempB=e,this._results.forEach(this.swapHandler,this),this.paste(i,s,this._results,o))},swapHandler:function(t){t.index===this._tempA?t.index=this._tempB:t.index===this._tempB&&(t.index=this._tempA)},forEach:function(t,e,i,s,n,r,o){o=this.getLayer(o),this.copy(i,s,n,r,o),this._results.length<2||(this._results.forEach(t,e),this.paste(i,s,this._results,o))},replace:function(t,e,i,s,n,r,o){if(o=this.getLayer(o),this.copy(i,s,n,r,o),!(this._results.length<2)){for(var a=1;a<this._results.length;a++)this._results[a].index===t&&(this._results[a].index=e);this.paste(i,s,this._results,o)}},random:function(t,e,i,s,n){if(n=this.getLayer(n),this.copy(t,e,i,s,n),!(this._results.length<2)){for(var r=[],o=1;o<this._results.length;o++)if(this._results[o].index){var a=this._results[o].index;-1===r.indexOf(a)&&r.push(a)}for(var h=1;h<this._results.length;h++)this._results[h].index=this.game.rnd.pick(r);this.paste(t,e,this._results,n)}},shuffle:function(t,e,i,s,r){if(r=this.getLayer(r),this.copy(t,e,i,s,r),!(this._results.length<2)){for(var o=[],a=1;a<this._results.length;a++)this._results[a].index&&o.push(this._results[a].index);n.ArrayUtils.shuffle(o);for(var h=1;h<this._results.length;h++)this._results[h].index=o[h-1];this.paste(t,e,this._results,r)}},fill:function(t,e,i,s,n,r){if(r=this.getLayer(r),this.copy(e,i,s,n,r),!(this._results.length<2)){for(var o=1;o<this._results.length;o++)this._results[o].index=t;this.paste(e,i,this._results,r)}},removeAllLayers:function(){this.layers.length=0,this.currentLayer=0},dump:function(){for(var t="",e=[""],i=0;i<this.layers[this.currentLayer].height;i++){for(var s=0;s<this.layers[this.currentLayer].width;s++)t+="%c ",this.layers[this.currentLayer].data[i][s]>1?this.debugMap[this.layers[this.currentLayer].data[i][s]]?e.push("background: "+this.debugMap[this.layers[this.currentLayer].data[i][s]]):e.push("background: #ffffff"):e.push("background: rgb(0, 0, 0)");t+="\n"}e[0]=t,console.log.apply(console,e)},destroy:function(){this.removeAllLayers(),this.data=[],this.game=null}},n.Tilemap.prototype.constructor=n.Tilemap,Object.defineProperty(n.Tilemap.prototype,"layer",{get:function(){return this.layers[this.currentLayer]},set:function(t){t!==this.currentLayer&&this.setLayer(t)}}),n.TilemapLayer=function(t,e,i,s,r){s|=0,r|=0,n.Sprite.call(this,t,0,0),this.map=e,this.index=i,this.layer=e.layers[i],this.canvas=PIXI.CanvasPool.create(this,s,r),this.context=this.canvas.getContext("2d"),this.setTexture(new PIXI.Texture(new PIXI.BaseTexture(this.canvas))),this.type=n.TILEMAPLAYER,this.physicsType=n.TILEMAPLAYER,this.renderSettings={enableScrollDelta:!1,overdrawRatio:.2,copyCanvas:null},this.debug=!1,this.exists=!0,this.debugSettings={missingImageFill:"rgb(255,255,255)",debuggedTileOverfill:"rgba(0,255,0,0.4)",forceFullRedraw:!0,debugAlpha:.5,facingEdgeStroke:"rgba(0,255,0,1)",collidingTileOverfill:"rgba(0,255,0,0.2)"},this.scrollFactorX=1,this.scrollFactorY=1,this.dirty=!0,this.rayStepRate=4,this._wrap=!1,this._mc={scrollX:0,scrollY:0,renderWidth:0,renderHeight:0,tileWidth:e.tileWidth,tileHeight:e.tileHeight,cw:e.tileWidth,ch:e.tileHeight,tilesets:[]},this._scrollX=0,this._scrollY=0,this._results=[],t.device.canvasBitBltShift||(this.renderSettings.copyCanvas=n.TilemapLayer.ensureSharedCopyCanvas()),this.fixedToCamera=!0},n.TilemapLayer.prototype=Object.create(n.Sprite.prototype),n.TilemapLayer.prototype.constructor=n.TilemapLayer,n.TilemapLayer.prototype.preUpdateCore=n.Component.Core.preUpdate,n.TilemapLayer.sharedCopyCanvas=null,n.TilemapLayer.ensureSharedCopyCanvas=function(){return this.sharedCopyCanvas||(this.sharedCopyCanvas=PIXI.CanvasPool.create(this,2,2)),this.sharedCopyCanvas},n.TilemapLayer.prototype.preUpdate=function(){return this.preUpdateCore()},n.TilemapLayer.prototype.postUpdate=function(){this.fixedToCamera&&(this.position.x=(this.game.camera.view.x+this.cameraOffset.x)/this.game.camera.scale.x,this.position.y=(this.game.camera.view.y+this.cameraOffset.y)/this.game.camera.scale.y),this._scrollX=this.game.camera.view.x*this.scrollFactorX/this.scale.x,this._scrollY=this.game.camera.view.y*this.scrollFactorY/this.scale.y},n.TilemapLayer.prototype._renderCanvas=function(t){this.fixedToCamera&&(this.position.x=(this.game.camera.view.x+this.cameraOffset.x)/this.game.camera.scale.x,this.position.y=(this.game.camera.view.y+this.cameraOffset.y)/this.game.camera.scale.y),this._scrollX=this.game.camera.view.x*this.scrollFactorX/this.scale.x,this._scrollY=this.game.camera.view.y*this.scrollFactorY/this.scale.y,this.render(),PIXI.Sprite.prototype._renderCanvas.call(this,t)},n.TilemapLayer.prototype._renderWebGL=function(t){this.fixedToCamera&&(this.position.x=(this.game.camera.view.x+this.cameraOffset.x)/this.game.camera.scale.x,this.position.y=(this.game.camera.view.y+this.cameraOffset.y)/this.game.camera.scale.y),this._scrollX=this.game.camera.view.x*this.scrollFactorX/this.scale.x,this._scrollY=this.game.camera.view.y*this.scrollFactorY/this.scale.y,this.render(),PIXI.Sprite.prototype._renderWebGL.call(this,t)},n.TilemapLayer.prototype.destroy=function(){PIXI.CanvasPool.remove(this),n.Component.Destroy.prototype.destroy.call(this)},n.TilemapLayer.prototype.resize=function(t,e){this.canvas.width=t,this.canvas.height=e,this.texture.frame.resize(t,e),this.texture.width=t,this.texture.height=e,this.texture.crop.width=t,this.texture.crop.height=e,this.texture.baseTexture.width=t,this.texture.baseTexture.height=e,this.texture.baseTexture.dirty(),this.texture.requiresUpdate=!0,this.texture._updateUvs(),this.dirty=!0},n.TilemapLayer.prototype.resizeWorld=function(){this.game.world.setBounds(0,0,this.layer.widthInPixels*this.scale.x,this.layer.heightInPixels*this.scale.y)},n.TilemapLayer.prototype._fixX=function(t){return 1===this.scrollFactorX||0===this.scrollFactorX&&0===this.position.x?t:0===this.scrollFactorX&&0!==this.position.x?t-this.position.x:this._scrollX+(t-this._scrollX/this.scrollFactorX)},n.TilemapLayer.prototype._unfixX=function(t){return 1===this.scrollFactorX?t:this._scrollX/this.scrollFactorX+(t-this._scrollX)},n.TilemapLayer.prototype._fixY=function(t){return 1===this.scrollFactorY||0===this.scrollFactorY&&0===this.position.y?t:0===this.scrollFactorY&&0!==this.position.y?t-this.position.y:this._scrollY+(t-this._scrollY/this.scrollFactorY)},n.TilemapLayer.prototype._unfixY=function(t){return 1===this.scrollFactorY?t:this._scrollY/this.scrollFactorY+(t-this._scrollY)},n.TilemapLayer.prototype.getTileX=function(t){return Math.floor(this._fixX(t)/this._mc.tileWidth)},n.TilemapLayer.prototype.getTileY=function(t){return Math.floor(this._fixY(t)/this._mc.tileHeight)},n.TilemapLayer.prototype.getTileXY=function(t,e,i){return i.x=this.getTileX(t),i.y=this.getTileY(e),i},n.TilemapLayer.prototype.getRayCastTiles=function(t,e,i,s){e||(e=this.rayStepRate),void 0===i&&(i=!1),void 0===s&&(s=!1);var n=this.getTiles(t.x,t.y,t.width,t.height,i,s);if(0===n.length)return[];for(var r=t.coordinatesOnLine(e),o=[],a=0;a<n.length;a++)for(var h=0;h<r.length;h++){var l=n[a],c=r[h];if(l.containsPoint(c[0],c[1])){o.push(l);break}}return o},n.TilemapLayer.prototype.getTiles=function(t,e,i,s,n,r){void 0===n&&(n=!1),void 0===r&&(r=!1);var o=!(n||r);t=this._fixX(t),e=this._fixY(e);for(var a=Math.floor(t/(this._mc.cw*this.scale.x)),h=Math.floor(e/(this._mc.ch*this.scale.y)),l=Math.ceil((t+i)/(this._mc.cw*this.scale.x))-a,c=Math.ceil((e+s)/(this._mc.ch*this.scale.y))-h;this._results.length;)this._results.pop();for(var u=h;u<h+c;u++)for(var d=a;d<a+l;d++){var p=this.layer.data[u];p&&p[d]&&(o||p[d].isInteresting(n,r))&&this._results.push(p[d])}return this._results.slice()},n.TilemapLayer.prototype.resolveTileset=function(t){var e=this._mc.tilesets;if(t<2e3)for(;e.length<t;)e.push(void 0);var i=this.map.tiles[t]&&this.map.tiles[t][2];if(null!==i){var s=this.map.tilesets[i];if(s&&s.containsTileIndex(t))return e[t]=s}return e[t]=null},n.TilemapLayer.prototype.resetTilesetCache=function(){for(var t=this._mc.tilesets;t.length;)t.pop()},n.TilemapLayer.prototype.setScale=function(t,e){t=t||1,e=e||t;for(var i=0;i<this.layer.data.length;i++)for(var s=this.layer.data[i],n=0;n<s.length;n++){var r=s[n];r.width=this.map.tileWidth*t,r.height=this.map.tileHeight*e,r.worldX=r.x*r.width,r.worldY=r.y*r.height}this.scale.setTo(t,e)},n.TilemapLayer.prototype.shiftCanvas=function(t,e,i){var s=t.canvas,n=s.width-Math.abs(e),r=s.height-Math.abs(i),o=0,a=0,h=e,l=i;e<0&&(o=-e,h=0),i<0&&(a=-i,l=0);var c=this.renderSettings.copyCanvas;if(c){(c.width<n||c.height<r)&&(c.width=n,c.height=r);var u=c.getContext("2d");u.clearRect(0,0,n,r),u.drawImage(s,o,a,n,r,0,0,n,r),t.clearRect(h,l,n,r),t.drawImage(c,0,0,n,r,h,l,n,r)}else t.save(),t.globalCompositeOperation="copy",t.drawImage(s,o,a,n,r,h,l,n,r),t.restore()},n.TilemapLayer.prototype.renderRegion=function(t,e,i,s,n,r){var o=this.context,a=this.layer.width,h=this.layer.height,l=this._mc.tileWidth,c=this._mc.tileHeight,u=this._mc.tilesets,d=NaN;this._wrap||(i<=n&&(i=Math.max(0,i),n=Math.min(a-1,n)),s<=r&&(s=Math.max(0,s),r=Math.min(h-1,r)));var p,f,g,m,y,v,b=i*l-t,x=s*c-e,w=(i+(1<<20)*a)%a,_=(s+(1<<20)*h)%h;for(m=_,v=r-s,f=x;v>=0;m++,v--,f+=c){m>=h&&(m-=h);var P=this.layer.data[m];for(g=w,y=n-i,p=b;y>=0;g++,y--,p+=l){g>=a&&(g-=a);var T=P[g];if(T&&!(T.index<0)){var C=T.index,S=u[C];void 0===S&&(S=this.resolveTileset(C)),T.alpha===d||this.debug||(o.globalAlpha=T.alpha,d=T.alpha),S?T.rotation||T.flipped?(o.save(),o.translate(p+T.centerX,f+T.centerY),o.rotate(T.rotation),T.flipped&&o.scale(-1,1),S.draw(o,-T.centerX,-T.centerY,C),o.restore()):S.draw(o,p,f,C):this.debugSettings.missingImageFill&&(o.fillStyle=this.debugSettings.missingImageFill,o.fillRect(p,f,l,c)),T.debug&&this.debugSettings.debuggedTileOverfill&&(o.fillStyle=this.debugSettings.debuggedTileOverfill,o.fillRect(p,f,l,c))}}}},n.TilemapLayer.prototype.renderDeltaScroll=function(t,e){var i=this._mc.scrollX,s=this._mc.scrollY,n=this.canvas.width,r=this.canvas.height,o=this._mc.tileWidth,a=this._mc.tileHeight,h=0,l=-o,c=0,u=-a;if(t<0?(h=n+t,l=n-1):t>0&&(l=t),e<0?(c=r+e,u=r-1):e>0&&(u=e),this.shiftCanvas(this.context,t,e),h=Math.floor((h+i)/o),l=Math.floor((l+i)/o),c=Math.floor((c+s)/a),u=Math.floor((u+s)/a),h<=l){this.context.clearRect(h*o-i,0,(l-h+1)*o,r);var d=Math.floor((0+s)/a),p=Math.floor((r-1+s)/a);this.renderRegion(i,s,h,d,l,p)}if(c<=u){this.context.clearRect(0,c*a-s,n,(u-c+1)*a);var f=Math.floor((0+i)/o),g=Math.floor((n-1+i)/o);this.renderRegion(i,s,f,c,g,u)}},n.TilemapLayer.prototype.renderFull=function(){var t=this._mc.scrollX,e=this._mc.scrollY,i=this.canvas.width,s=this.canvas.height,n=this._mc.tileWidth,r=this._mc.tileHeight,o=Math.floor(t/n),a=Math.floor((i-1+t)/n),h=Math.floor(e/r),l=Math.floor((s-1+e)/r);this.context.clearRect(0,0,i,s),this.renderRegion(t,e,o,h,a,l)},n.TilemapLayer.prototype.render=function(){var t=!1;if(this.visible){(this.dirty||this.layer.dirty)&&(this.layer.dirty=!1,t=!0);var e=this.canvas.width,i=this.canvas.height,s=0|this._scrollX,n=0|this._scrollY,r=this._mc,o=r.scrollX-s,a=r.scrollY-n;if(t||0!==o||0!==a||r.renderWidth!==e||r.renderHeight!==i)return this.context.save(),r.scrollX=s,r.scrollY=n,r.renderWidth===e&&r.renderHeight===i||(r.renderWidth=e,r.renderHeight=i),this.debug&&(this.context.globalAlpha=this.debugSettings.debugAlpha,this.debugSettings.forceFullRedraw&&(t=!0)),!t&&this.renderSettings.enableScrollDelta&&Math.abs(o)+Math.abs(a)<Math.min(e,i)?this.renderDeltaScroll(o,a):this.renderFull(),this.debug&&(this.context.globalAlpha=1,this.renderDebug()),this.texture.baseTexture.dirty(),this.dirty=!1,this.context.restore(),!0}},n.TilemapLayer.prototype.renderDebug=function(){var t,e,i,s,n,r,o=this._mc.scrollX,a=this._mc.scrollY,h=this.context,l=this.canvas.width,c=this.canvas.height,u=this.layer.width,d=this.layer.height,p=this._mc.tileWidth,f=this._mc.tileHeight,g=Math.floor(o/p),m=Math.floor((l-1+o)/p),y=Math.floor(a/f),v=Math.floor((c-1+a)/f),b=g*p-o,x=y*f-a,w=(g+(1<<20)*u)%u,_=(y+(1<<20)*d)%d;for(h.strokeStyle=this.debugSettings.facingEdgeStroke,s=_,r=v-y,e=x;r>=0;s++,r--,e+=f){s>=d&&(s-=d);var P=this.layer.data[s];for(i=w,n=m-g,t=b;n>=0;i++,n--,t+=p){i>=u&&(i-=u);var T=P[i];!T||T.index<0||!T.collides||(this.debugSettings.collidingTileOverfill&&(h.fillStyle=this.debugSettings.collidingTileOverfill,h.fillRect(t,e,this._mc.cw,this._mc.ch)),this.debugSettings.facingEdgeStroke&&(h.beginPath(),T.faceTop&&(h.moveTo(t,e),h.lineTo(t+this._mc.cw,e)),T.faceBottom&&(h.moveTo(t,e+this._mc.ch),h.lineTo(t+this._mc.cw,e+this._mc.ch)),T.faceLeft&&(h.moveTo(t,e),h.lineTo(t,e+this._mc.ch)),T.faceRight&&(h.moveTo(t+this._mc.cw,e),h.lineTo(t+this._mc.cw,e+this._mc.ch)),h.closePath(),h.stroke()))}}},Object.defineProperty(n.TilemapLayer.prototype,"wrap",{get:function(){return this._wrap},set:function(t){this._wrap=t,this.dirty=!0}}),Object.defineProperty(n.TilemapLayer.prototype,"scrollX",{get:function(){return this._scrollX},set:function(t){this._scrollX=t}}),Object.defineProperty(n.TilemapLayer.prototype,"scrollY",{get:function(){return this._scrollY},set:function(t){this._scrollY=t}}),Object.defineProperty(n.TilemapLayer.prototype,"collisionWidth",{get:function(){return this._mc.cw},set:function(t){this._mc.cw=0|t,this.dirty=!0}}),Object.defineProperty(n.TilemapLayer.prototype,"collisionHeight",{get:function(){return this._mc.ch},set:function(t){this._mc.ch=0|t,this.dirty=!0}}),n.TilemapParser={INSERT_NULL:!1,parse:function(t,e,i,s,r,o){if(void 0===i&&(i=32),void 0===s&&(s=32),void 0===r&&(r=10),void 0===o&&(o=10),void 0===e)return this.getEmptyData();if(null===e)return this.getEmptyData(i,s,r,o);var a=t.cache.getTilemapData(e);if(a){if(a.format===n.Tilemap.CSV)return this.parseCSV(e,a.data,i,s);if(!a.format||a.format===n.Tilemap.TILED_JSON)return this.parseTiledJSON(a.data)}else console.warn("Phaser.TilemapParser.parse - No map data found for key "+e)},parseCSV:function(t,e,i,s){var r=this.getEmptyData();e=e.trim();for(var o=[],a=e.split("\n"),h=a.length,l=0,c=0;c<a.length;c++){o[c]=[];for(var u=a[c].split(","),d=0;d<u.length;d++)o[c][d]=new n.Tile(r.layers[0],parseInt(u[d],10),d,c,i,s);0===l&&(l=u.length)}return r.format=n.Tilemap.CSV,r.name=t,r.width=l,r.height=h,r.tileWidth=i,r.tileHeight=s,r.widthInPixels=l*i,r.heightInPixels=h*s,r.layers[0].width=l,r.layers[0].height=h,r.layers[0].widthInPixels=r.widthInPixels,r.layers[0].heightInPixels=r.heightInPixels,r.layers[0].data=o,r},getEmptyData:function(t,e,i,s){return{width:void 0!==i&&null!==i?i:0,height:void 0!==s&&null!==s?s:0,tileWidth:void 0!==t&&null!==t?t:0,tileHeight:void 0!==e&&null!==e?e:0,orientation:"orthogonal",version:"1",properties:{},widthInPixels:0,heightInPixels:0,layers:[{name:"layer",x:0,y:0,width:0,height:0,widthInPixels:0,heightInPixels:0,alpha:1,visible:!0,properties:{},indexes:[],callbacks:[],bodies:[],data:[]}],images:[],objects:{},collision:{},tilesets:[],tiles:[]}},parseTiledJSON:function(t){function e(t,e){var i={};for(var s in e){var n=e[s];void 0!==t[n]&&(i[n]=t[n])}return i}if("orthogonal"!==t.orientation)return console.warn("TilemapParser.parseTiledJSON - Only orthogonal map types are supported in this version of Phaser"),null;for(var i={width:t.width,height:t.height,tileWidth:t.tilewidth,tileHeight:t.tileheight,orientation:t.orientation,format:n.Tilemap.TILED_JSON,version:t.version,properties:t.properties,widthInPixels:t.width*t.tilewidth,heightInPixels:t.height*t.tileheight},s=[],r=0;r<t.layers.length;r++)if("tilelayer"===t.layers[r].type){var o=t.layers[r];if(!o.compression&&o.encoding&&"base64"===o.encoding){for(var a=window.atob(o.data),h=a.length,l=new Array(h),c=0;c<h;c+=4)l[c/4]=(a.charCodeAt(c)|a.charCodeAt(c+1)<<8|a.charCodeAt(c+2)<<16|a.charCodeAt(c+3)<<24)>>>0;o.data=l,delete o.encoding}else if(o.compression){console.warn("TilemapParser.parseTiledJSON - Layer compression is unsupported, skipping layer '"+o.name+"'");continue}var u={name:o.name,x:o.x,y:o.y,width:o.width,height:o.height,widthInPixels:o.width*t.tilewidth,heightInPixels:o.height*t.tileheight,alpha:o.opacity,visible:o.visible,properties:{},indexes:[],callbacks:[],bodies:[]};o.properties&&(u.properties=o.properties);for(var d,p,f,g,m=0,y=[],v=[],b=0,h=o.data.length;b<h;b++){if(d=0,p=!1,g=o.data[b],f=0,g>536870912)switch(g>2147483648&&(g-=2147483648,f+=4),g>1073741824&&(g-=1073741824,f+=2),g>536870912&&(g-=536870912,f+=1),f){case 5:d=Math.PI/2;break;case 6:d=Math.PI;break;case 3:d=3*Math.PI/2;break;case 4:d=0,p=!0;break;case 7:d=Math.PI/2,p=!0;break;case 2:d=Math.PI,p=!0;break;case 1:d=3*Math.PI/2,p=!0}if(g>0){var x=new n.Tile(u,g,m,v.length,t.tilewidth,t.tileheight);x.rotation=d,x.flipped=p,0!==f&&(x.flippedVal=f),y.push(x)}else n.TilemapParser.INSERT_NULL?y.push(null):y.push(new n.Tile(u,-1,m,v.length,t.tilewidth,t.tileheight));m++,m===o.width&&(v.push(y),m=0,y=[])}u.data=v,s.push(u)}i.layers=s;for(var w=[],r=0;r<t.layers.length;r++)if("imagelayer"===t.layers[r].type){var _=t.layers[r],P={name:_.name,image:_.image,x:_.x,y:_.y,alpha:_.opacity,visible:_.visible,properties:{}};_.properties&&(P.properties=_.properties),w.push(P)}i.images=w;for(var T=[],C=[],S=null,r=0;r<t.tilesets.length;r++){var A=t.tilesets[r];if(A.image){var E=new n.Tileset(A.name,A.firstgid,A.tilewidth,A.tileheight,A.margin,A.spacing,A.properties);A.tileproperties&&(E.tileProperties=A.tileproperties),E.updateTileData(A.imagewidth,A.imageheight),T.push(E)}else{var I=new n.ImageCollection(A.name,A.firstgid,A.tilewidth,A.tileheight,A.margin,A.spacing,A.properties);for(var M in A.tiles){var P=A.tiles[M].image,g=A.firstgid+parseInt(M,10);I.addImage(g,P)}C.push(I)}S&&(S.lastgid=A.firstgid-1),S=A}i.tilesets=T,i.imagecollections=C;for(var R={},B={},r=0;r<t.layers.length;r++)if("objectgroup"===t.layers[r].type){var L=t.layers[r];R[L.name]=[],B[L.name]=[];for(var k=0,h=L.objects.length;k<h;k++)if(L.objects[k].gid){var O={gid:L.objects[k].gid,name:L.objects[k].name,type:L.objects[k].hasOwnProperty("type")?L.objects[k].type:"",x:L.objects[k].x,y:L.objects[k].y,visible:L.objects[k].visible,properties:L.objects[k].properties};L.objects[k].rotation&&(O.rotation=L.objects[k].rotation),R[L.name].push(O)}else if(L.objects[k].polyline){var O={name:L.objects[k].name,type:L.objects[k].type,x:L.objects[k].x,y:L.objects[k].y,width:L.objects[k].width,height:L.objects[k].height,visible:L.objects[k].visible,properties:L.objects[k].properties};L.objects[k].rotation&&(O.rotation=L.objects[k].rotation),O.polyline=[];for(var F=0;F<L.objects[k].polyline.length;F++)O.polyline.push([L.objects[k].polyline[F].x,L.objects[k].polyline[F].y]);B[L.name].push(O),R[L.name].push(O)}else if(L.objects[k].polygon){var O=e(L.objects[k],["name","type","x","y","visible","rotation","properties"]);O.polygon=[];for(var F=0;F<L.objects[k].polygon.length;F++)O.polygon.push([L.objects[k].polygon[F].x,L.objects[k].polygon[F].y]);R[L.name].push(O)}else if(L.objects[k].ellipse){var O=e(L.objects[k],["name","type","ellipse","x","y","width","height","visible","rotation","properties"]);R[L.name].push(O)}else{var O=e(L.objects[k],["name","type","x","y","width","height","visible","rotation","properties"]);O.rectangle=!0,R[L.name].push(O)}}i.objects=R,i.collision=B,i.tiles=[];for(var r=0;r<i.tilesets.length;r++)for(var A=i.tilesets[r],m=A.tileMargin,D=A.tileMargin,U=0,G=0,N=0,b=A.firstgid;b<A.firstgid+A.total&&(i.tiles[b]=[m,D,r],m+=A.tileWidth+A.tileSpacing,++U!==A.total)&&(++G!==A.columns||(m=A.tileMargin,D+=A.tileHeight+A.tileSpacing,G=0,++N!==A.rows));b++);for(var u,x,X,A,r=0;r<i.layers.length;r++){u=i.layers[r],A=null;for(var c=0;c<u.data.length;c++){y=u.data[c];for(var W=0;W<y.length;W++)null===(x=y[W])||x.index<0||(X=i.tiles[x.index][2],A=i.tilesets[X],A.tileProperties&&A.tileProperties[x.index-A.firstgid]&&(x.properties=n.Utils.mixin(A.tileProperties[x.index-A.firstgid],x.properties)))}}return i}},n.Tileset=function(t,e,i,s,n,r,o){(void 0===i||i<=0)&&(i=32),(void 0===s||s<=0)&&(s=32),void 0===n&&(n=0),void 0===r&&(r=0),this.name=t,this.firstgid=0|e,this.tileWidth=0|i,this.tileHeight=0|s,this.tileMargin=0|n,this.tileSpacing=0|r,this.properties=o||{},this.image=null,this.rows=0,this.columns=0,this.total=0,this.drawCoords=[]},n.Tileset.prototype={draw:function(t,e,i,s){var n=s-this.firstgid<<1;n>=0&&n+1<this.drawCoords.length&&t.drawImage(this.image,this.drawCoords[n],this.drawCoords[n+1],this.tileWidth,this.tileHeight,e,i,this.tileWidth,this.tileHeight)},containsTileIndex:function(t){return t>=this.firstgid&&t<this.firstgid+this.total},setImage:function(t){this.image=t,this.updateTileData(t.width,t.height)},setSpacing:function(t,e){this.tileMargin=0|t,this.tileSpacing=0|e,this.image&&this.updateTileData(this.image.width,this.image.height)},updateTileData:function(t,e){var i=(e-2*this.tileMargin+this.tileSpacing)/(this.tileHeight+this.tileSpacing),s=(t-2*this.tileMargin+this.tileSpacing)/(this.tileWidth+this.tileSpacing);i%1==0&&s%1==0||console.warn("Phaser.Tileset - "+this.name+" image tile area is not an even multiple of tile size"),i=Math.floor(i),s=Math.floor(s),(this.rows&&this.rows!==i||this.columns&&this.columns!==s)&&console.warn("Phaser.Tileset - actual and expected number of tile rows and columns differ"),this.rows=i,this.columns=s,this.total=i*s,this.drawCoords.length=0;for(var n=this.tileMargin,r=this.tileMargin,o=0;o<this.rows;o++){for(var a=0;a<this.columns;a++)this.drawCoords.push(n),this.drawCoords.push(r),n+=this.tileWidth+this.tileSpacing;n=this.tileMargin,r+=this.tileHeight+this.tileSpacing}}},n.Tileset.prototype.constructor=n.Tileset,n.Particle=function(t,e,i,s,r){n.Sprite.call(this,t,e,i,s,r),this.autoScale=!1,this.scaleData=null,this._s=0,this.autoAlpha=!1,this.alphaData=null,this._a=0},n.Particle.prototype=Object.create(n.Sprite.prototype),n.Particle.prototype.constructor=n.Particle,n.Particle.prototype.update=function(){this.autoScale&&(this._s--,this._s?this.scale.set(this.scaleData[this._s].x,this.scaleData[this._s].y):this.autoScale=!1),this.autoAlpha&&(this._a--,this._a?this.alpha=this.alphaData[this._a].v:this.autoAlpha=!1)},n.Particle.prototype.onEmit=function(){},n.Particle.prototype.setAlphaData=function(t){this.alphaData=t,this._a=t.length-1,this.alpha=this.alphaData[this._a].v,this.autoAlpha=!0},n.Particle.prototype.setScaleData=function(t){this.scaleData=t,this._s=t.length-1,this.scale.set(this.scaleData[this._s].x,this.scaleData[this._s].y),this.autoScale=!0},n.Particle.prototype.reset=function(t,e,i){return n.Component.Reset.prototype.reset.call(this,t,e,i),this.alpha=1,this.scale.set(1),this.autoScale=!1,this.autoAlpha=!1,this},n.Particles=function(t){this.game=t,this.emitters={},this.ID=0},n.Particles.prototype={add:function(t){return this.emitters[t.name]=t,t},remove:function(t){delete this.emitters[t.name]},update:function(){for(var t in this.emitters)this.emitters[t].exists&&this.emitters[t].update()}},n.Particles.prototype.constructor=n.Particles,n.Particles.Arcade={},n.Particles.Arcade.Emitter=function(t,e,i,s){this.maxParticles=s||50,n.Group.call(this,t),this.name="emitter"+this.game.particles.ID++,this.type=n.EMITTER,this.physicsType=n.GROUP,this.area=new n.Rectangle(e,i,1,1),this.minParticleSpeed=new n.Point(-100,-100),this.maxParticleSpeed=new n.Point(100,100),this.minParticleScale=1,this.maxParticleScale=1,this.scaleData=null,this.minRotation=-360,this.maxRotation=360,this.minParticleAlpha=1,this.maxParticleAlpha=1,this.alphaData=null,this.gravity=100,this.particleClass=n.Particle,this.particleDrag=new n.Point,this.angularDrag=0,this.frequency=100,this.lifespan=2e3,this.bounce=new n.Point,this.on=!1,this.particleAnchor=new n.Point(.5,.5),this.blendMode=n.blendModes.NORMAL,this.emitX=e,this.emitY=i,this.autoScale=!1,this.autoAlpha=!1,this.particleBringToTop=!1,this.particleSendToBack=!1,this._minParticleScale=new n.Point(1,1),this._maxParticleScale=new n.Point(1,1),this._quantity=0,this._timer=0,this._counter=0,this._flowQuantity=0,this._flowTotal=0,this._explode=!0,this._frames=null},n.Particles.Arcade.Emitter.prototype=Object.create(n.Group.prototype),n.Particles.Arcade.Emitter.prototype.constructor=n.Particles.Arcade.Emitter,n.Particles.Arcade.Emitter.prototype.update=function(){if(this.on&&this.game.time.time>=this._timer)if(this._timer=this.game.time.time+this.frequency*this.game.time.slowMotion,0!==this._flowTotal)if(this._flowQuantity>0){for(var t=0;t<this._flowQuantity;t++)if(this.emitParticle()&&(this._counter++,-1!==this._flowTotal&&this._counter>=this._flowTotal)){this.on=!1;break}}else this.emitParticle()&&(this._counter++,-1!==this._flowTotal&&this._counter>=this._flowTotal&&(this.on=!1));else this.emitParticle()&&(this._counter++,this._quantity>0&&this._counter>=this._quantity&&(this.on=!1));for(var t=this.children.length;t--;)this.children[t].exists&&this.children[t].update()},n.Particles.Arcade.Emitter.prototype.makeParticles=function(t,e,i,s,n){void 0===e&&(e=0),void 0===i&&(i=this.maxParticles),void 0===s&&(s=!1),void 0===n&&(n=!1);var r,o=0,a=t,h=e;for(this._frames=e,i>this.maxParticles&&(this.maxParticles=i);o<i;)Array.isArray(t)&&(a=this.game.rnd.pick(t)),Array.isArray(e)&&(h=this.game.rnd.pick(e)),r=new this.particleClass(this.game,0,0,a,h),this.game.physics.arcade.enable(r,!1),s?(r.body.checkCollision.any=!0,r.body.checkCollision.none=!1):r.body.checkCollision.none=!0,r.body.collideWorldBounds=n,r.body.skipQuadTree=!0,r.exists=!1,r.visible=!1,r.anchor.copyFrom(this.particleAnchor),this.add(r),o++;return this},n.Particles.Arcade.Emitter.prototype.kill=function(){return this.on=!1,this.alive=!1,this.exists=!1,this},n.Particles.Arcade.Emitter.prototype.revive=function(){return this.alive=!0,this.exists=!0,this},n.Particles.Arcade.Emitter.prototype.explode=function(t,e){return this._flowTotal=0,this.start(!0,t,0,e,!1),this},n.Particles.Arcade.Emitter.prototype.flow=function(t,e,i,s,n){return void 0!==i&&0!==i||(i=1),void 0===s&&(s=-1),void 0===n&&(n=!0),i>this.maxParticles&&(i=this.maxParticles),this._counter=0,this._flowQuantity=i,this._flowTotal=s,n?(this.start(!0,t,e,i),this._counter+=i,this.on=!0,this._timer=this.game.time.time+e*this.game.time.slowMotion):this.start(!1,t,e,i),this},n.Particles.Arcade.Emitter.prototype.start=function(t,e,i,s,n){if(void 0===t&&(t=!0),void 0===e&&(e=0),void 0!==i&&null!==i||(i=250),void 0===s&&(s=0),void 0===n&&(n=!1),s>this.maxParticles&&(s=this.maxParticles),this.revive(),this.visible=!0,this.lifespan=e,this.frequency=i,t||n)for(var r=0;r<s;r++)this.emitParticle();else this.on=!0,this._quantity=s,this._counter=0,this._timer=this.game.time.time+i*this.game.time.slowMotion;return this},n.Particles.Arcade.Emitter.prototype.emitParticle=function(t,e,i,s){void 0===t&&(t=null),void 0===e&&(e=null);var n=this.getFirstExists(!1);if(null===n)return!1;var r=this.game.rnd;void 0!==i&&void 0!==s?n.loadTexture(i,s):void 0!==i&&n.loadTexture(i);var o=this.emitX,a=this.emitY;null!==t?o=t:this.width>1&&(o=r.between(this.left,this.right)),null!==e?a=e:this.height>1&&(a=r.between(this.top,this.bottom)),n.reset(o,a),n.angle=0,n.lifespan=this.lifespan,this.particleBringToTop?this.bringToTop(n):this.particleSendToBack&&this.sendToBack(n),this.autoScale?n.setScaleData(this.scaleData):1!==this.minParticleScale||1!==this.maxParticleScale?n.scale.set(r.realInRange(this.minParticleScale,this.maxParticleScale)):this._minParticleScale.x===this._maxParticleScale.x&&this._minParticleScale.y===this._maxParticleScale.y||n.scale.set(r.realInRange(this._minParticleScale.x,this._maxParticleScale.x),r.realInRange(this._minParticleScale.y,this._maxParticleScale.y)),void 0===s&&(Array.isArray(this._frames)?n.frame=this.game.rnd.pick(this._frames):n.frame=this._frames),this.autoAlpha?n.setAlphaData(this.alphaData):n.alpha=r.realInRange(this.minParticleAlpha,this.maxParticleAlpha),n.blendMode=this.blendMode;var h=n.body;return h.updateBounds(),h.bounce.copyFrom(this.bounce),h.drag.copyFrom(this.particleDrag),h.velocity.x=r.between(this.minParticleSpeed.x,this.maxParticleSpeed.x),h.velocity.y=r.between(this.minParticleSpeed.y,this.maxParticleSpeed.y),h.angularVelocity=r.between(this.minRotation,this.maxRotation),h.gravity.y=this.gravity,h.angularDrag=this.angularDrag,n.onEmit(),!0},n.Particles.Arcade.Emitter.prototype.destroy=function(){this.game.particles.remove(this),n.Group.prototype.destroy.call(this,!0,!1)},n.Particles.Arcade.Emitter.prototype.setSize=function(t,e){return this.area.width=t,this.area.height=e,this},n.Particles.Arcade.Emitter.prototype.setXSpeed=function(t,e){return t=t||0,e=e||0,this.minParticleSpeed.x=t,this.maxParticleSpeed.x=e,this},n.Particles.Arcade.Emitter.prototype.setYSpeed=function(t,e){return t=t||0,e=e||0,this.minParticleSpeed.y=t,this.maxParticleSpeed.y=e,this},n.Particles.Arcade.Emitter.prototype.setRotation=function(t,e){return t=t||0,e=e||0,this.minRotation=t,this.maxRotation=e,this},n.Particles.Arcade.Emitter.prototype.setAlpha=function(t,e,i,s,r){if(void 0===t&&(t=1),void 0===e&&(e=1),void 0===i&&(i=0),void 0===s&&(s=n.Easing.Linear.None),void 0===r&&(r=!1),this.minParticleAlpha=t,this.maxParticleAlpha=e,this.autoAlpha=!1,i>0&&t!==e){var o={v:t},a=this.game.make.tween(o).to({v:e},i,s);a.yoyo(r),this.alphaData=a.generateData(60),this.alphaData.reverse(),this.autoAlpha=!0}return this},n.Particles.Arcade.Emitter.prototype.setScale=function(t,e,i,s,r,o,a){if(void 0===t&&(t=1),void 0===e&&(e=1),void 0===i&&(i=1),void 0===s&&(s=1),void 0===r&&(r=0),void 0===o&&(o=n.Easing.Linear.None),void 0===a&&(a=!1),this.minParticleScale=1,this.maxParticleScale=1,this._minParticleScale.set(t,i),this._maxParticleScale.set(e,s),this.autoScale=!1,r>0&&(t!==e||i!==s)){var h={x:t,y:i},l=this.game.make.tween(h).to({x:e,y:s},r,o);l.yoyo(a),this.scaleData=l.generateData(60),this.scaleData.reverse(),this.autoScale=!0}return this},n.Particles.Arcade.Emitter.prototype.at=function(t){return t.center?(this.emitX=t.center.x,this.emitY=t.center.y):(this.emitX=t.world.x+t.anchor.x*t.width,this.emitY=t.world.y+t.anchor.y*t.height),this},Object.defineProperty(n.Particles.Arcade.Emitter.prototype,"width",{get:function(){return this.area.width},set:function(t){this.area.width=t}}),Object.defineProperty(n.Particles.Arcade.Emitter.prototype,"height",{get:function(){return this.area.height},set:function(t){this.area.height=t}}),Object.defineProperty(n.Particles.Arcade.Emitter.prototype,"x",{get:function(){return this.emitX},set:function(t){this.emitX=t}}),Object.defineProperty(n.Particles.Arcade.Emitter.prototype,"y",{get:function(){return this.emitY},set:function(t){this.emitY=t}}),Object.defineProperty(n.Particles.Arcade.Emitter.prototype,"left",{get:function(){return Math.floor(this.x-this.area.width/2)}}),Object.defineProperty(n.Particles.Arcade.Emitter.prototype,"right",{get:function(){return Math.floor(this.x+this.area.width/2)}}),Object.defineProperty(n.Particles.Arcade.Emitter.prototype,"top",{get:function(){return Math.floor(this.y-this.area.height/2)}}),Object.defineProperty(n.Particles.Arcade.Emitter.prototype,"bottom",{get:function(){return Math.floor(this.y+this.area.height/2)}}),n.Weapon=function(t,e){n.Plugin.call(this,t,e),this.bullets=null,this.autoExpandBulletsGroup=!1,this.autofire=!1,this.shots=0,this.fireLimit=0,this.fireRate=100,this.fireRateVariance=0,this.fireFrom=new n.Rectangle(0,0,1,1),this.fireAngle=n.ANGLE_UP,this.bulletInheritSpriteSpeed=!1,this.bulletAnimation="",this.bulletFrameRandom=!1,this.bulletFrameCycle=!1,this.bulletWorldWrap=!1,this.bulletWorldWrapPadding=0,this.bulletAngleOffset=0,this.bulletAngleVariance=0,this.bulletSpeed=200,this.bulletSpeedVariance=0,this.bulletLifespan=0,this.bulletKillDistance=0,this.bulletGravity=new n.Point(0,0),this.bulletRotateToVelocity=!1,this.bulletKey="",this.bulletFrame="",this._bulletClass=n.Bullet,this._bulletCollideWorldBounds=!1,this._bulletKillType=n.Weapon.KILL_WORLD_BOUNDS,this._data={customBody:!1,width:0,height:0,offsetX:0,offsetY:0},this.bounds=new n.Rectangle,this.bulletBounds=t.world.bounds,this.bulletFrames=[],this.bulletFrameIndex=0,this.anims={},this.onFire=new n.Signal,this.onKill=new n.Signal,this.onFireLimit=new n.Signal,this.trackedSprite=null,this.trackedPointer=null,this.trackRotation=!1,this.trackOffset=new n.Point,this._nextFire=0,this._rotatedPoint=new n.Point},n.Weapon.prototype=Object.create(n.Plugin.prototype),n.Weapon.prototype.constructor=n.Weapon,n.Weapon.KILL_NEVER=0,n.Weapon.KILL_LIFESPAN=1,n.Weapon.KILL_DISTANCE=2,n.Weapon.KILL_WEAPON_BOUNDS=3,n.Weapon.KILL_CAMERA_BOUNDS=4,n.Weapon.KILL_WORLD_BOUNDS=5,n.Weapon.KILL_STATIC_BOUNDS=6,n.Weapon.prototype.createBullets=function(t,e,i,s){return void 0===t&&(t=1),void 0===s&&(s=this.game.world),this.bullets||(this.bullets=this.game.add.physicsGroup(n.Physics.ARCADE,s),this.bullets.classType=this._bulletClass),0!==t&&(-1===t&&(this.autoExpandBulletsGroup=!0,t=1),this.bullets.createMultiple(t,e,i),this.bullets.setAll("data.bulletManager",this),this.bulletKey=e,this.bulletFrame=i),this},n.Weapon.prototype.forEach=function(t,e){return this.bullets.forEachExists(t,e,arguments),this},n.Weapon.prototype.pauseAll=function(){return this.bullets.setAll("body.enable",!1),this},n.Weapon.prototype.resumeAll=function(){return this.bullets.setAll("body.enable",!0),this},n.Weapon.prototype.killAll=function(){return this.bullets.callAllExists("kill",!0),this.bullets.setAll("body.enable",!0),this},n.Weapon.prototype.resetShots=function(t){return this.shots=0,void 0!==t&&(this.fireLimit=t),this},n.Weapon.prototype.destroy=function(){this.parent.remove(this,!1),this.bullets.destroy(),this.game=null,this.parent=null,this.active=!1,this.visible=!1},n.Weapon.prototype.update=function(){this._bulletKillType===n.Weapon.KILL_WEAPON_BOUNDS&&(this.trackedSprite?(this.trackedSprite.updateTransform(),this.bounds.centerOn(this.trackedSprite.worldPosition.x,this.trackedSprite.worldPosition.y)):this.trackedPointer&&this.bounds.centerOn(this.trackedPointer.worldX,this.trackedPointer.worldY)),this.autofire&&this.fire()},n.Weapon.prototype.trackSprite=function(t,e,i,s){return void 0===e&&(e=0),void 0===i&&(i=0),void 0===s&&(s=!1),this.trackedPointer=null,this.trackedSprite=t,this.trackRotation=s,this.trackOffset.set(e,i),this},n.Weapon.prototype.trackPointer=function(t,e,i){return void 0===t&&(t=this.game.input.activePointer),void 0===e&&(e=0),void 0===i&&(i=0),this.trackedPointer=t,this.trackedSprite=null,this.trackRotation=!1,this.trackOffset.set(e,i),this},n.Weapon.prototype.fire=function(t,e,i){if(this.game.time.now<this._nextFire||this.fireLimit>0&&this.shots===this.fireLimit)return!1;var s=this.bulletSpeed;0!==this.bulletSpeedVariance&&(s+=n.Math.between(-this.bulletSpeedVariance,this.bulletSpeedVariance)),t?this.fireFrom.width>1?this.fireFrom.centerOn(t.x,t.y):(this.fireFrom.x=t.x,this.fireFrom.y=t.y):this.trackedSprite?(this.trackRotation?(this._rotatedPoint.set(this.trackedSprite.world.x+this.trackOffset.x,this.trackedSprite.world.y+this.trackOffset.y),this._rotatedPoint.rotate(this.trackedSprite.world.x,this.trackedSprite.world.y,this.trackedSprite.rotation),this.fireFrom.width>1?this.fireFrom.centerOn(this._rotatedPoint.x,this._rotatedPoint.y):(this.fireFrom.x=this._rotatedPoint.x,this.fireFrom.y=this._rotatedPoint.y)):this.fireFrom.width>1?this.fireFrom.centerOn(this.trackedSprite.world.x+this.trackOffset.x,this.trackedSprite.world.y+this.trackOffset.y):(this.fireFrom.x=this.trackedSprite.world.x+this.trackOffset.x,this.fireFrom.y=this.trackedSprite.world.y+this.trackOffset.y),this.bulletInheritSpriteSpeed&&(s+=this.trackedSprite.body.speed)):this.trackedPointer&&(this.fireFrom.width>1?this.fireFrom.centerOn(this.trackedPointer.world.x+this.trackOffset.x,this.trackedPointer.world.y+this.trackOffset.y):(this.fireFrom.x=this.trackedPointer.world.x+this.trackOffset.x,this.fireFrom.y=this.trackedPointer.world.y+this.trackOffset.y));var r=this.fireFrom.width>1?this.fireFrom.randomX:this.fireFrom.x,o=this.fireFrom.height>1?this.fireFrom.randomY:this.fireFrom.y,a=this.trackRotation?this.trackedSprite.angle:this.fireAngle;void 0!==e&&void 0!==i&&(a=this.game.math.radToDeg(Math.atan2(i-o,e-r))),0!==this.bulletAngleVariance&&(a+=n.Math.between(-this.bulletAngleVariance,this.bulletAngleVariance));var h=0,l=0;0===a||180===a?h=Math.cos(this.game.math.degToRad(a))*s:90===a||270===a?l=Math.sin(this.game.math.degToRad(a))*s:(h=Math.cos(this.game.math.degToRad(a))*s,l=Math.sin(this.game.math.degToRad(a))*s);var c=null;if(this.autoExpandBulletsGroup?(c=this.bullets.getFirstExists(!1,!0,r,o,this.bulletKey,this.bulletFrame),c.data.bulletManager=this):c=this.bullets.getFirstExists(!1),c){if(c.reset(r,o),c.data.fromX=r,c.data.fromY=o,c.data.killType=this.bulletKillType,c.data.killDistance=this.bulletKillDistance,c.data.rotateToVelocity=this.bulletRotateToVelocity,this.bulletKillType===n.Weapon.KILL_LIFESPAN&&(c.lifespan=this.bulletLifespan),c.angle=a+this.bulletAngleOffset,""!==this.bulletAnimation){if(null===c.animations.getAnimation(this.bulletAnimation)){var u=this.anims[this.bulletAnimation];c.animations.add(u.name,u.frames,u.frameRate,u.loop,u.useNumericIndex)}c.animations.play(this.bulletAnimation)}else this.bulletFrameCycle?(c.frame=this.bulletFrames[this.bulletFrameIndex],++this.bulletFrameIndex>=this.bulletFrames.length&&(this.bulletFrameIndex=0)):this.bulletFrameRandom&&(c.frame=this.bulletFrames[Math.floor(Math.random()*this.bulletFrames.length)]);if(c.data.bodyDirty&&(this._data.customBody&&c.body.setSize(this._data.width,this._data.height,this._data.offsetX,this._data.offsetY),c.body.collideWorldBounds=this.bulletCollideWorldBounds,c.data.bodyDirty=!1),c.body.velocity.set(h,l),c.body.gravity.set(this.bulletGravity.x,this.bulletGravity.y),0!==this.bulletSpeedVariance){var d=this.fireRate;d+=n.Math.between(-this.fireRateVariance,this.fireRateVariance),d<0&&(d=0),this._nextFire=this.game.time.now+d}else this._nextFire=this.game.time.now+this.fireRate;this.shots++,this.onFire.dispatch(c,this,s),this.fireLimit>0&&this.shots===this.fireLimit&&this.onFireLimit.dispatch(this,this.fireLimit)}return c},n.Weapon.prototype.fireAtPointer=function(t){return void 0===t&&(t=this.game.input.activePointer),this.fire(null,t.worldX,t.worldY)},n.Weapon.prototype.fireAtSprite=function(t){return this.fire(null,t.world.x,t.world.y)},n.Weapon.prototype.fireAtXY=function(t,e){return this.fire(null,t,e)},n.Weapon.prototype.setBulletBodyOffset=function(t,e,i,s){return void 0===i&&(i=0),void 0===s&&(s=0),this._data.customBody=!0,this._data.width=t,this._data.height=e,this._data.offsetX=i,this._data.offsetY=s,this.bullets.callAll("body.setSize","body",t,e,i,s),this.bullets.setAll("data.bodyDirty",!1),this},n.Weapon.prototype.setBulletFrames=function(t,e,i,s){return void 0===i&&(i=!0),void 0===s&&(s=!1),this.bulletFrames=n.ArrayUtils.numberArray(t,e),this.bulletFrameIndex=0,this.bulletFrameCycle=i,this.bulletFrameRandom=s,this},n.Weapon.prototype.addBulletAnimation=function(t,e,i,s,n){return this.anims[t]={name:t,frames:e,frameRate:i,loop:s,useNumericIndex:n},this.bullets.callAll("animations.add","animations",t,e,i,s,n),this.bulletAnimation=t,this},n.Weapon.prototype.debug=function(t,e,i){void 0===t&&(t=16),void 0===e&&(e=32),void 0===i&&(i=!1),this.game.debug.text("Weapon Plugin",t,e),this.game.debug.text("Bullets Alive: "+this.bullets.total+" - Total: "+this.bullets.length,t,e+24),i&&this.bullets.forEachExists(this.game.debug.body,this.game.debug,"rgba(255, 0, 255, 0.8)")},Object.defineProperty(n.Weapon.prototype,"bulletClass",{get:function(){return this._bulletClass},set:function(t){this._bulletClass=t,this.bullets.classType=this._bulletClass}}),Object.defineProperty(n.Weapon.prototype,"bulletKillType",{get:function(){return this._bulletKillType},set:function(t){switch(t){case n.Weapon.KILL_STATIC_BOUNDS:case n.Weapon.KILL_WEAPON_BOUNDS:this.bulletBounds=this.bounds;break;case n.Weapon.KILL_CAMERA_BOUNDS:this.bulletBounds=this.game.camera.view;break;case n.Weapon.KILL_WORLD_BOUNDS:this.bulletBounds=this.game.world.bounds}this._bulletKillType=t}}),Object.defineProperty(n.Weapon.prototype,"bulletCollideWorldBounds",{get:function(){return this._bulletCollideWorldBounds},set:function(t){this._bulletCollideWorldBounds=t,this.bullets.setAll("body.collideWorldBounds",t),this.bullets.setAll("data.bodyDirty",!1)}}),Object.defineProperty(n.Weapon.prototype,"x",{get:function(){return this.fireFrom.x},set:function(t){this.fireFrom.x=t}}),Object.defineProperty(n.Weapon.prototype,"y",{get:function(){return this.fireFrom.y},set:function(t){this.fireFrom.y=t}}),n.Bullet=function(t,e,i,s,r){n.Sprite.call(this,t,e,i,s,r),this.anchor.set(.5),this.data={bulletManager:null,fromX:0,fromY:0,bodyDirty:!0,rotateToVelocity:!1,killType:0,killDistance:0}},n.Bullet.prototype=Object.create(n.Sprite.prototype),n.Bullet.prototype.constructor=n.Bullet,n.Bullet.prototype.kill=function(){return this.alive=!1,this.exists=!1,this.visible=!1,this.data.bulletManager.onKill.dispatch(this),this},n.Bullet.prototype.update=function(){this.exists&&(this.data.killType>n.Weapon.KILL_LIFESPAN&&(this.data.killType===n.Weapon.KILL_DISTANCE?this.game.physics.arcade.distanceToXY(this,this.data.fromX,this.data.fromY,!0)>this.data.killDistance&&this.kill():this.data.bulletManager.bulletBounds.intersects(this)||this.kill()),this.data.rotateToVelocity&&(this.rotation=Math.atan2(this.body.velocity.y,this.body.velocity.x)),this.data.bulletManager.bulletWorldWrap&&this.game.world.wrap(this,this.data.bulletManager.bulletWorldWrapPadding))},n.Video=function(t,e,i){if(void 0===e&&(e=null),void 0===i&&(i=null),this.game=t,this.key=e,this.width=0,this.height=0,this.type=n.VIDEO,this.disableTextureUpload=!1,this.touchLocked=!1,this.onPlay=new n.Signal,this.onChangeSource=new n.Signal,this.onComplete=new n.Signal,this.onAccess=new n.Signal,this.onError=new n.Signal,this.onTimeout=new n.Signal,this.timeout=15e3,this._timeOutID=null,this.video=null,this.videoStream=null,this.isStreaming=!1,this.retryLimit=20,this.retry=0,this.retryInterval=500,this._retryID=null,this._codeMuted=!1,this._muted=!1,this._codePaused=!1,this._paused=!1,this._pending=!1,this._autoplay=!1,this._endCallback=null,this._playCallback=null,e&&this.game.cache.checkVideoKey(e)){var s=this.game.cache.getVideo(e);s.isBlob?this.createVideoFromBlob(s.data):this.video=s.data,this.width=this.video.videoWidth,this.height=this.video.videoHeight}else i&&this.createVideoFromURL(i,!1);this.video&&!i?(this.baseTexture=new PIXI.BaseTexture(this.video),this.baseTexture.forceLoaded(this.width,this.height)):(this.baseTexture=new PIXI.BaseTexture(n.Cache.DEFAULT.baseTexture.source),this.baseTexture.forceLoaded(this.width,this.height)),this.texture=new PIXI.Texture(this.baseTexture),this.textureFrame=new n.Frame(0,0,0,this.width,this.height,"video"),this.texture.setFrame(this.textureFrame),this.texture.valid=!1,null!==e&&this.video&&(this.texture.valid=this.video.canplay),this.snapshot=null,n.BitmapData&&(this.snapshot=new n.BitmapData(this.game,"",this.width,this.height)),!this.game.device.cocoonJS&&(this.game.device.iOS||this.game.device.android)||window.PhaserGlobal&&window.PhaserGlobal.fakeiOSTouchLock?this.setTouchLock():s&&(s.locked=!1)},n.Video.prototype={connectToMediaStream:function(t,e){return t&&e&&(this.video=t,this.videoStream=e,this.isStreaming=!0,this.baseTexture.source=this.video,this.updateTexture(null,this.video.videoWidth,this.video.videoHeight),this.onAccess.dispatch(this)),this},startMediaStream:function(t,e,i){if(void 0===t&&(t=!1),void 0===e&&(e=null),void 0===i&&(i=null),!this.game.device.getUserMedia)return this.onError.dispatch(this,"No getUserMedia"),!1;null!==this.videoStream&&(this.videoStream.active?this.videoStream.active=!1:this.videoStream.stop()),this.removeVideoElement(),this.video=document.createElement("video"),this.video.setAttribute("autoplay","autoplay"),null!==e&&(this.video.width=e),null!==i&&(this.video.height=i),this._timeOutID=window.setTimeout(this.getUserMediaTimeout.bind(this),this.timeout);try{navigator.getUserMedia({audio:t,video:!0},this.getUserMediaSuccess.bind(this),this.getUserMediaError.bind(this))}catch(t){this.getUserMediaError(t)}return this},getUserMediaTimeout:function(){clearTimeout(this._timeOutID),this.onTimeout.dispatch(this)},getUserMediaError:function(t){clearTimeout(this._timeOutID),this.onError.dispatch(this,t)},getUserMediaSuccess:function(t){clearTimeout(this._timeOutID),this.videoStream=t,void 0!==this.video.mozSrcObject?this.video.mozSrcObject=t:this.video.src=window.URL&&window.URL.createObjectURL(t)||t;var e=this;this.video.onloadeddata=function(){function t(){if(i>0)if(e.video.videoWidth>0){var s=e.video.videoWidth,n=e.video.videoHeight;isNaN(e.video.videoHeight)&&(n=s/(4/3)),e.video.play(),e.isStreaming=!0,e.baseTexture.source=e.video,e.updateTexture(null,s,n),e.onAccess.dispatch(e)}else window.setTimeout(t,500);else console.warn("Unable to connect to video stream. Webcam error?");i--}var i=10;t()}},createVideoFromBlob:function(t){var e=this;return this.video=document.createElement("video"),this.video.controls=!1,this.video.setAttribute("autoplay","autoplay"),this.video.addEventListener("loadeddata",function(t){e.updateTexture(t)},!0),this.video.src=window.URL.createObjectURL(t),this.video.canplay=!0,this},createVideoFromURL:function(t,e){return void 0===e&&(e=!1),this.texture&&(this.texture.valid=!1),this.video=document.createElement("video"),this.video.controls=!1,e&&this.video.setAttribute("autoplay","autoplay"),this.video.src=t,this.video.canplay=!0,this.video.load(),this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval),this.key=t,this},updateTexture:function(t,e,i){var s=!1;void 0!==e&&null!==e||(e=this.video.videoWidth,s=!0),void 0!==i&&null!==i||(i=this.video.videoHeight),this.width=e,this.height=i,this.baseTexture.source!==this.video&&(this.baseTexture.source=this.video),this.baseTexture.forceLoaded(e,i),this.texture.frame.resize(e,i),this.texture.width=e,this.texture.height=i,this.texture.valid=!0,this.snapshot&&this.snapshot.resize(e,i),s&&null!==this.key&&(this.onChangeSource.dispatch(this,e,i),this._autoplay&&(this.video.play(),this.onPlay.dispatch(this,this.loop,this.playbackRate)))},complete:function(){this.onComplete.dispatch(this)},play:function(t,e){return void 0===t&&(t=!1),void 0===e&&(e=1),this.game.sound.onMute&&(this.game.sound.onMute.add(this.setMute,this),this.game.sound.onUnMute.add(this.unsetMute,this),this.game.sound.mute&&this.setMute()),this.game.onPause.add(this.setPause,this),this.game.onResume.add(this.setResume,this),this._endCallback=this.complete.bind(this),this.video.addEventListener("ended",this._endCallback,!0),this.video.addEventListener("webkitendfullscreen",this._endCallback,!0),this.video.loop=t?"loop":"",this.video.playbackRate=e,this.touchLocked?this._pending=!0:(this._pending=!1,null!==this.key&&(4!==this.video.readyState?(this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval)):(this._playCallback=this.playHandler.bind(this),this.video.addEventListener("playing",this._playCallback,!0))),this.video.play(),this.onPlay.dispatch(this,t,e)),this},playHandler:function(){this.video.removeEventListener("playing",this._playCallback,!0),this.updateTexture()},stop:function(){return this.game.sound.onMute&&(this.game.sound.onMute.remove(this.setMute,this),this.game.sound.onUnMute.remove(this.unsetMute,this)),this.game.onPause.remove(this.setPause,this),this.game.onResume.remove(this.setResume,this),this.isStreaming?(this.video.mozSrcObject?(this.video.mozSrcObject.stop(),this.video.src=null):(this.video.src="",this.videoStream.active?this.videoStream.active=!1:this.videoStream.getTracks?this.videoStream.getTracks().forEach(function(t){t.stop()}):this.videoStream.stop()),this.videoStream=null,this.isStreaming=!1):(this.video.removeEventListener("ended",this._endCallback,!0),this.video.removeEventListener("webkitendfullscreen",this._endCallback,!0),this.video.removeEventListener("playing",this._playCallback,!0),this.touchLocked?this._pending=!1:this.video.pause()),this},add:function(t){if(Array.isArray(t))for(var e=0;e<t.length;e++)t[e].loadTexture&&t[e].loadTexture(this);else t.loadTexture(this);return this},addToWorld:function(t,e,i,s,n,r){n=n||1,r=r||1;var o=this.game.add.image(t,e,this);return o.anchor.set(i,s),o.scale.set(n,r),o},render:function(){!this.disableTextureUpload&&this.playing&&this.baseTexture.dirty()},setMute:function(){this._muted||(this._muted=!0,this.video.muted=!0)},unsetMute:function(){this._muted&&!this._codeMuted&&(this._muted=!1,this.video.muted=!1)},setPause:function(){this._paused||this.touchLocked||(this._paused=!0,this.video.pause())},setResume:function(){!this._paused||this._codePaused||this.touchLocked||(this._paused=!1,this.video.ended||this.video.play())},changeSource:function(t,e){return void 0===e&&(e=!0),this.texture.valid=!1,this.video.pause(),this.retry=this.retryLimit,this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval),this.video.src=t,this.video.load(),this._autoplay=e,e||(this.paused=!0),this},checkVideoProgress:function(){4===this.video.readyState?this.updateTexture():(this.retry--,this.retry>0?this._retryID=window.setTimeout(this.checkVideoProgress.bind(this),this.retryInterval):console.warn("Phaser.Video: Unable to start downloading video in time",this.isStreaming))},setTouchLock:function(){this.game.input.touch.addTouchLockCallback(this.unlock,this),this.touchLocked=!0},unlock:function(){if(this.touchLocked=!1,this.video.play(),this.onPlay.dispatch(this,this.loop,this.playbackRate),this.key){var t=this.game.cache.getVideo(this.key);t&&!t.isBlob&&(t.locked=!1)}return!0},grab:function(t,e,i){return void 0===t&&(t=!1),void 0===e&&(e=1),void 0===i&&(i=null),null===this.snapshot?void console.warn("Video.grab cannot run because Phaser.BitmapData is unavailable"):(t&&this.snapshot.cls(),this.snapshot.copy(this.video,0,0,this.width,this.height,0,0,this.width,this.height,0,0,0,1,1,e,i),this.snapshot)},removeVideoElement:function(){if(this.video){for(this.video.parentNode&&this.video.parentNode.removeChild(this.video);this.video.hasChildNodes();)this.video.removeChild(this.video.firstChild);this.video.removeAttribute("autoplay"),this.video.removeAttribute("src"),this.video=null}},destroy:function(){this.stop(),this.removeVideoElement(),this.touchLocked&&this.game.input.touch.removeTouchLockCallback(this.unlock,this),this._retryID&&window.clearTimeout(this._retryID)}},Object.defineProperty(n.Video.prototype,"currentTime",{get:function(){return this.video?this.video.currentTime:0},set:function(t){this.video.currentTime=t}}),Object.defineProperty(n.Video.prototype,"duration",{get:function(){return this.video?this.video.duration:0}}),Object.defineProperty(n.Video.prototype,"progress",{get:function(){return this.video?this.video.currentTime/this.video.duration:0}}),Object.defineProperty(n.Video.prototype,"mute",{get:function(){return this._muted},set:function(t){if(t=t||null){if(this._muted)return;this._codeMuted=!0,this.setMute()}else{if(!this._muted)return;this._codeMuted=!1,this.unsetMute()}}}),Object.defineProperty(n.Video.prototype,"paused",{get:function(){return this._paused},set:function(t){if(t=t||null,!this.touchLocked)if(t){if(this._paused)return;this._codePaused=!0,this.setPause()}else{if(!this._paused)return;this._codePaused=!1,this.setResume()}}}),Object.defineProperty(n.Video.prototype,"volume",{get:function(){return this.video?this.video.volume:1},set:function(t){t<0?t=0:t>1&&(t=1),this.video&&(this.video.volume=t)}}),Object.defineProperty(n.Video.prototype,"playbackRate",{get:function(){return this.video?this.video.playbackRate:1},set:function(t){this.video&&(this.video.playbackRate=t)}}),Object.defineProperty(n.Video.prototype,"loop",{get:function(){return!!this.video&&this.video.loop},set:function(t){t&&this.video?this.video.loop="loop":this.video&&(this.video.loop="")}}),Object.defineProperty(n.Video.prototype,"playing",{get:function(){return!(this.video.paused&&this.video.ended)}}),n.Video.prototype.constructor=n.Video,void 0===PIXI.blendModes&&(PIXI.blendModes=n.blendModes),void 0===PIXI.scaleModes&&(PIXI.scaleModes=n.scaleModes),void 0===PIXI.Texture.emptyTexture&&(PIXI.Texture.emptyTexture=new PIXI.Texture(new PIXI.BaseTexture)),void 0===PIXI.DisplayObject._tempMatrix&&(PIXI.DisplayObject._tempMatrix=new PIXI.Matrix),void 0===PIXI.RenderTexture.tempMatrix&&(PIXI.RenderTexture.tempMatrix=new PIXI.Matrix),PIXI.Graphics&&void 0===PIXI.Graphics.POLY&&(PIXI.Graphics.POLY=n.POLYGON,PIXI.Graphics.RECT=n.RECTANGLE,PIXI.Graphics.CIRC=n.CIRCLE,PIXI.Graphics.ELIP=n.ELLIPSE,PIXI.Graphics.RREC=n.ROUNDEDRECTANGLE),PIXI.TextureSilentFail=!0,void 0!==t&&t.exports&&(e=t.exports=n),e.Phaser=n,n}).call(this)}).call(e,i(4))},function(t,e,i){/**
<ide> * @author Richard Davey <[email protected]>
<ide> * @copyright 2016 Photon Storm Ltd.
<ide> * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
<ide> * @copyright 2016 Photon Storm Ltd.
<ide> * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
<ide> */
<del>return i.game=null,i.WEBGL_RENDERER=0,i.CANVAS_RENDERER=1,i.VERSION="v2.2.9",i._UID=0,"undefined"!=typeof Float32Array?(i.Float32Array=Float32Array,i.Uint16Array=Uint16Array,i.Uint32Array=Uint32Array,i.ArrayBuffer=ArrayBuffer):(i.Float32Array=Array,i.Uint16Array=Array),i.PI_2=2*Math.PI,i.RAD_TO_DEG=180/Math.PI,i.DEG_TO_RAD=Math.PI/180,i.RETINA_PREFIX="@2x",i.DisplayObject=function(){this.position=new i.Point(0,0),this.scale=new i.Point(1,1),this.pivot=new i.Point(0,0),this.rotation=0,this.alpha=1,this.visible=!0,this.hitArea=null,this.renderable=!1,this.parent=null,this.worldAlpha=1,this.worldTransform=new i.Matrix,this.worldPosition=new i.Point(0,0),this.worldScale=new i.Point(1,1),this.worldRotation=0,this.filterArea=null,this._sr=0,this._cr=1,this._bounds=new i.Rectangle(0,0,0,0),this._currentBounds=null,this._mask=null,this._cacheAsBitmap=!1,this._cacheIsDirty=!1},i.DisplayObject.prototype.constructor=i.DisplayObject,i.DisplayObject.prototype={destroy:function(){if(this.children){for(var t=this.children.length;t--;)this.children[t].destroy();this.children=[]}this.hitArea=null,this.parent=null,this.worldTransform=null,this.filterArea=null,this.renderable=!1,this._bounds=null,this._currentBounds=null,this._mask=null,this._destroyCachedSprite()},updateTransform:function(t){if(!t&&!this.parent&&!this.game)return this;var e=this.parent;t?e=t:this.parent||(e=this.game.world);var s,n,r,o,a,h,l=e.worldTransform,c=this.worldTransform;return this.rotation%i.PI_2?(this.rotation!==this.rotationCache&&(this.rotationCache=this.rotation,this._sr=Math.sin(this.rotation),this._cr=Math.cos(this.rotation)),s=this._cr*this.scale.x,n=this._sr*this.scale.x,r=-this._sr*this.scale.y,o=this._cr*this.scale.y,a=this.position.x,h=this.position.y,(this.pivot.x||this.pivot.y)&&(a-=this.pivot.x*s+this.pivot.y*r,h-=this.pivot.x*n+this.pivot.y*o),c.a=s*l.a+n*l.c,c.b=s*l.b+n*l.d,c.c=r*l.a+o*l.c,c.d=r*l.b+o*l.d,c.tx=a*l.a+h*l.c+l.tx,c.ty=a*l.b+h*l.d+l.ty):(s=this.scale.x,o=this.scale.y,a=this.position.x-this.pivot.x*s,h=this.position.y-this.pivot.y*o,c.a=s*l.a,c.b=s*l.b,c.c=o*l.c,c.d=o*l.d,c.tx=a*l.a+h*l.c+l.tx,c.ty=a*l.b+h*l.d+l.ty),this.worldAlpha=this.alpha*e.worldAlpha,this.worldPosition.set(c.tx,c.ty),this.worldScale.set(this.scale.x*Math.sqrt(c.a*c.a+c.c*c.c),this.scale.y*Math.sqrt(c.b*c.b+c.d*c.d)),this.worldRotation=Math.atan2(-c.c,c.d),this._currentBounds=null,this.transformCallback&&this.transformCallback.call(this.transformCallbackContext,c,l),this},preUpdate:function(){},generateTexture:function(t,e,s){var n=this.getLocalBounds(),r=new i.RenderTexture(0|n.width,0|n.height,s,e,t);return i.DisplayObject._tempMatrix.tx=-n.x,i.DisplayObject._tempMatrix.ty=-n.y,r.render(this,i.DisplayObject._tempMatrix),r},updateCache:function(){return this._generateCachedSprite(),this},toGlobal:function(t){return this.updateTransform(),this.worldTransform.apply(t)},toLocal:function(t,e){return e&&(t=e.toGlobal(t)),this.updateTransform(),this.worldTransform.applyInverse(t)},_renderCachedSprite:function(t){this._cachedSprite.worldAlpha=this.worldAlpha,t.gl?i.Sprite.prototype._renderWebGL.call(this._cachedSprite,t):i.Sprite.prototype._renderCanvas.call(this._cachedSprite,t)},_generateCachedSprite:function(){this._cacheAsBitmap=!1;var t=this.getLocalBounds();if(t.width=Math.max(1,Math.ceil(t.width)),t.height=Math.max(1,Math.ceil(t.height)),this.updateTransform(),this._cachedSprite)this._cachedSprite.texture.resize(t.width,t.height);else{var e=new i.RenderTexture(t.width,t.height);this._cachedSprite=new i.Sprite(e),this._cachedSprite.worldTransform=this.worldTransform}var s=this._filters;this._filters=null,this._cachedSprite.filters=s,i.DisplayObject._tempMatrix.tx=-t.x,i.DisplayObject._tempMatrix.ty=-t.y,this._cachedSprite.texture.render(this,i.DisplayObject._tempMatrix,!0),this._cachedSprite.anchor.x=-t.x/t.width,this._cachedSprite.anchor.y=-t.y/t.height,this._filters=s,this._cacheAsBitmap=!0},_destroyCachedSprite:function(){this._cachedSprite&&(this._cachedSprite.texture.destroy(!0),this._cachedSprite=null)}},i.DisplayObject.prototype.displayObjectUpdateTransform=i.DisplayObject.prototype.updateTransform,Object.defineProperties(i.DisplayObject.prototype,{x:{get:function(){return this.position.x},set:function(t){this.position.x=t}},y:{get:function(){return this.position.y},set:function(t){this.position.y=t}},worldVisible:{get:function(){if(this.visible){var t=this.parent;if(!t)return this.visible;do{if(!t.visible)return!1;t=t.parent}while(t);return!0}return!1}},mask:{get:function(){return this._mask},set:function(t){this._mask&&(this._mask.isMask=!1),this._mask=t,t&&(this._mask.isMask=!0)}},filters:{get:function(){return this._filters},set:function(t){if(Array.isArray(t)){for(var e=[],s=0;s<t.length;s++)for(var n=t[s].passes,r=0;r<n.length;r++)e.push(n[r]);this._filterBlock={target:this,filterPasses:e}}this._filters=t,this.blendMode&&this.blendMode===i.blendModes.MULTIPLY&&(this.blendMode=i.blendModes.NORMAL)}},cacheAsBitmap:{get:function(){return this._cacheAsBitmap},set:function(t){this._cacheAsBitmap!==t&&(t?this._generateCachedSprite():this._destroyCachedSprite(),this._cacheAsBitmap=t)}}}),i.DisplayObjectContainer=function(){i.DisplayObject.call(this),this.children=[],this.ignoreChildInput=!1},i.DisplayObjectContainer.prototype=Object.create(i.DisplayObject.prototype),i.DisplayObjectContainer.prototype.constructor=i.DisplayObjectContainer,i.DisplayObjectContainer.prototype.addChild=function(t){return this.addChildAt(t,this.children.length)},i.DisplayObjectContainer.prototype.addChildAt=function(t,e){if(e>=0&&e<=this.children.length)return t.parent&&t.parent.removeChild(t),t.parent=this,this.children.splice(e,0,t),t;throw new Error(t+"addChildAt: The index "+e+" supplied is out of bounds "+this.children.length)},i.DisplayObjectContainer.prototype.swapChildren=function(t,e){if(t!==e){var i=this.getChildIndex(t),s=this.getChildIndex(e);if(i<0||s<0)throw new Error("swapChildren: Both the supplied DisplayObjects must be a child of the caller.");this.children[i]=e,this.children[s]=t}},i.DisplayObjectContainer.prototype.getChildIndex=function(t){var e=this.children.indexOf(t);if(-1===e)throw new Error("The supplied DisplayObject must be a child of the caller");return e},i.DisplayObjectContainer.prototype.setChildIndex=function(t,e){if(e<0||e>=this.children.length)throw new Error("The supplied index is out of bounds");var i=this.getChildIndex(t);this.children.splice(i,1),this.children.splice(e,0,t)},i.DisplayObjectContainer.prototype.getChildAt=function(t){if(t<0||t>=this.children.length)throw new Error("getChildAt: Supplied index "+t+" does not exist in the child list, or the supplied DisplayObject must be a child of the caller");return this.children[t]},i.DisplayObjectContainer.prototype.removeChild=function(t){var e=this.children.indexOf(t);if(-1!==e)return this.removeChildAt(e)},i.DisplayObjectContainer.prototype.removeChildAt=function(t){var e=this.getChildAt(t);return e&&(e.parent=void 0,this.children.splice(t,1)),e},i.DisplayObjectContainer.prototype.removeChildren=function(t,e){void 0===t&&(t=0),void 0===e&&(e=this.children.length);var i=e-t;if(i>0&&i<=e){for(var s=this.children.splice(begin,i),n=0;n<s.length;n++){s[n].parent=void 0}return s}if(0===i&&0===this.children.length)return[];throw new Error("removeChildren: Range Error, numeric values are outside the acceptable range")},i.DisplayObjectContainer.prototype.updateTransform=function(){if(this.visible&&(this.displayObjectUpdateTransform(),!this._cacheAsBitmap))for(var t=0;t<this.children.length;t++)this.children[t].updateTransform()},i.DisplayObjectContainer.prototype.displayObjectContainerUpdateTransform=i.DisplayObjectContainer.prototype.updateTransform,i.DisplayObjectContainer.prototype.getBounds=function(t){var e=t&&t instanceof i.DisplayObject,s=!0;e?s=t instanceof i.DisplayObjectContainer&&t.contains(this):t=this;var n;if(e){var r=t.worldTransform;for(t.worldTransform=i.identityMatrix,n=0;n<t.children.length;n++)t.children[n].updateTransform()}var o,a,h,l=1/0,c=1/0,u=-1/0,d=-1/0,p=!1;for(n=0;n<this.children.length;n++){this.children[n].visible&&(p=!0,o=this.children[n].getBounds(),l=l<o.x?l:o.x,c=c<o.y?c:o.y,a=o.width+o.x,h=o.height+o.y,u=u>a?u:a,d=d>h?d:h)}var f=this._bounds;if(!p){f=new i.Rectangle;var g=f.x,m=f.width+f.x,y=f.y,v=f.height+f.y,b=this.worldTransform,x=b.a,w=b.b,_=b.c,P=b.d,T=b.tx,C=b.ty,S=x*m+_*v+T,A=P*v+w*m+C,E=x*g+_*v+T,I=P*v+w*g+C,M=x*g+_*y+T,R=P*y+w*g+C,B=x*m+_*y+T,L=P*y+w*m+C;u=S,d=A,l=S,c=A,l=E<l?E:l,l=M<l?M:l,l=B<l?B:l,c=I<c?I:c,c=R<c?R:c,c=L<c?L:c,u=E>u?E:u,u=M>u?M:u,u=B>u?B:u,d=I>d?I:d,d=R>d?R:d,d=L>d?L:d}if(f.x=l,f.y=c,f.width=u-l,f.height=d-c,e)for(t.worldTransform=r,n=0;n<t.children.length;n++)t.children[n].updateTransform();if(!s){var O=t.getBounds();f.x-=O.x,f.y-=O.y}return f},i.DisplayObjectContainer.prototype.getLocalBounds=function(){return this.getBounds(this)},i.DisplayObjectContainer.prototype.contains=function(t){return!!t&&(t===this||this.contains(t.parent))},i.DisplayObjectContainer.prototype._renderWebGL=function(t){if(this.visible&&!(this.alpha<=0)){if(this._cacheAsBitmap)return void this._renderCachedSprite(t);var e;if(this._mask||this._filters){for(this._filters&&(t.spriteBatch.flush(),t.filterManager.pushFilter(this._filterBlock)),this._mask&&(t.spriteBatch.stop(),t.maskManager.pushMask(this.mask,t),t.spriteBatch.start()),e=0;e<this.children.length;e++)this.children[e]._renderWebGL(t);t.spriteBatch.stop(),this._mask&&t.maskManager.popMask(this._mask,t),this._filters&&t.filterManager.popFilter(),t.spriteBatch.start()}else for(e=0;e<this.children.length;e++)this.children[e]._renderWebGL(t)}},i.DisplayObjectContainer.prototype._renderCanvas=function(t){if(!1!==this.visible&&0!==this.alpha){if(this._cacheAsBitmap)return void this._renderCachedSprite(t);this._mask&&t.maskManager.pushMask(this._mask,t);for(var e=0;e<this.children.length;e++)this.children[e]._renderCanvas(t);this._mask&&t.maskManager.popMask(t)}},Object.defineProperty(i.DisplayObjectContainer.prototype,"width",{get:function(){return this.getLocalBounds().width*this.scale.x},set:function(t){var e=this.getLocalBounds().width;this.scale.x=0!==e?t/e:1,this._width=t}}),Object.defineProperty(i.DisplayObjectContainer.prototype,"height",{get:function(){return this.getLocalBounds().height*this.scale.y},set:function(t){var e=this.getLocalBounds().height;this.scale.y=0!==e?t/e:1,this._height=t}}),i.Sprite=function(t){i.DisplayObjectContainer.call(this),this.anchor=new i.Point,this.texture=t||i.Texture.emptyTexture,this._width=0,this._height=0,this.tint=16777215,this.cachedTint=-1,this.tintedTexture=null,this.blendMode=i.blendModes.NORMAL,this.shader=null,this.exists=!0,this.texture.baseTexture.hasLoaded&&this.onTextureUpdate(),this.renderable=!0},i.Sprite.prototype=Object.create(i.DisplayObjectContainer.prototype),i.Sprite.prototype.constructor=i.Sprite,Object.defineProperty(i.Sprite.prototype,"width",{get:function(){return this.scale.x*this.texture.frame.width},set:function(t){this.scale.x=t/this.texture.frame.width,this._width=t}}),Object.defineProperty(i.Sprite.prototype,"height",{get:function(){return this.scale.y*this.texture.frame.height},set:function(t){this.scale.y=t/this.texture.frame.height,this._height=t}}),i.Sprite.prototype.setTexture=function(t,e){void 0!==e&&this.texture.baseTexture.destroy(),this.texture.baseTexture.skipRender=!1,this.texture=t,this.texture.valid=!0,this.cachedTint=-1},i.Sprite.prototype.onTextureUpdate=function(){this._width&&(this.scale.x=this._width/this.texture.frame.width),this._height&&(this.scale.y=this._height/this.texture.frame.height)},i.Sprite.prototype.getBounds=function(t){var e=this.texture.frame.width,i=this.texture.frame.height,s=e*(1-this.anchor.x),n=e*-this.anchor.x,r=i*(1-this.anchor.y),o=i*-this.anchor.y,a=t||this.worldTransform,h=a.a,l=a.b,c=a.c,u=a.d,d=a.tx,p=a.ty,f=-1/0,g=-1/0,m=1/0,y=1/0;if(0===l&&0===c){if(h<0){h*=-1;var v=s;s=-n,n=-v}if(u<0){u*=-1;var v=r;r=-o,o=-v}m=h*n+d,f=h*s+d,y=u*o+p,g=u*r+p}else{var b=h*n+c*o+d,x=u*o+l*n+p,w=h*s+c*o+d,_=u*o+l*s+p,P=h*s+c*r+d,T=u*r+l*s+p,C=h*n+c*r+d,S=u*r+l*n+p;m=b<m?b:m,m=w<m?w:m,m=P<m?P:m,m=C<m?C:m,y=x<y?x:y,y=_<y?_:y,y=T<y?T:y,y=S<y?S:y,f=b>f?b:f,f=w>f?w:f,f=P>f?P:f,f=C>f?C:f,g=x>g?x:g,g=_>g?_:g,g=T>g?T:g,g=S>g?S:g}var A=this._bounds;return A.x=m,A.width=f-m,A.y=y,A.height=g-y,this._currentBounds=A,A},i.Sprite.prototype.getLocalBounds=function(){var t=this.worldTransform;this.worldTransform=i.identityMatrix;for(var e=0;e<this.children.length;e++)this.children[e].updateTransform();var s=this.getBounds();for(this.worldTransform=t,e=0;e<this.children.length;e++)this.children[e].updateTransform();return s},i.Sprite.prototype._renderWebGL=function(t,e){if(this.visible&&!(this.alpha<=0)&&this.renderable){var i=this.worldTransform;if(e&&(i=e),this._mask||this._filters){var s=t.spriteBatch;this._filters&&(s.flush(),t.filterManager.pushFilter(this._filterBlock)),this._mask&&(s.stop(),t.maskManager.pushMask(this.mask,t),s.start()),s.render(this);for(var n=0;n<this.children.length;n++)this.children[n]._renderWebGL(t);s.stop(),this._mask&&t.maskManager.popMask(this._mask,t),this._filters&&t.filterManager.popFilter(),s.start()}else{t.spriteBatch.render(this);for(var n=0;n<this.children.length;n++)this.children[n]._renderWebGL(t,i)}}},i.Sprite.prototype._renderCanvas=function(t,e){if(!(!this.visible||0===this.alpha||!this.renderable||this.texture.crop.width<=0||this.texture.crop.height<=0)){var s=this.worldTransform;if(e&&(s=e),this.blendMode!==t.currentBlendMode&&(t.currentBlendMode=this.blendMode,t.context.globalCompositeOperation=i.blendModesCanvas[t.currentBlendMode]),this._mask&&t.maskManager.pushMask(this._mask,t),this.texture.valid){var n=this.texture.baseTexture.resolution/t.resolution;t.context.globalAlpha=this.worldAlpha,t.smoothProperty&&t.scaleMode!==this.texture.baseTexture.scaleMode&&(t.scaleMode=this.texture.baseTexture.scaleMode,t.context[t.smoothProperty]=t.scaleMode===i.scaleModes.LINEAR);var r=this.texture.trim?this.texture.trim.x-this.anchor.x*this.texture.trim.width:this.anchor.x*-this.texture.frame.width,o=this.texture.trim?this.texture.trim.y-this.anchor.y*this.texture.trim.height:this.anchor.y*-this.texture.frame.height,a=s.tx*t.resolution+t.shakeX,h=s.ty*t.resolution+t.shakeY;t.roundPixels?(t.context.setTransform(s.a,s.b,s.c,s.d,0|a,0|h),r|=0,o|=0):t.context.setTransform(s.a,s.b,s.c,s.d,a,h);var l=this.texture.crop.width,c=this.texture.crop.height;if(r/=n,o/=n,16777215!==this.tint)(this.texture.requiresReTint||this.cachedTint!==this.tint)&&(this.tintedTexture=i.CanvasTinter.getTintedTexture(this,this.tint),this.cachedTint=this.tint,this.texture.requiresReTint=!1),t.context.drawImage(this.tintedTexture,0,0,l,c,r,o,l/n,c/n);else{var u=this.texture.crop.x,d=this.texture.crop.y;t.context.drawImage(this.texture.baseTexture.source,u,d,l,c,r,o,l/n,c/n)}}for(var p=0;p<this.children.length;p++)this.children[p]._renderCanvas(t);this._mask&&t.maskManager.popMask(t)}},i.SpriteBatch=function(t){i.DisplayObjectContainer.call(this),this.textureThing=t,this.ready=!1},i.SpriteBatch.prototype=Object.create(i.DisplayObjectContainer.prototype),i.SpriteBatch.prototype.constructor=i.SpriteBatch,i.SpriteBatch.prototype.initWebGL=function(t){this.fastSpriteBatch=new i.WebGLFastSpriteBatch(t),this.ready=!0},i.SpriteBatch.prototype.updateTransform=function(){this.displayObjectUpdateTransform()},i.SpriteBatch.prototype._renderWebGL=function(t){!this.visible||this.alpha<=0||!this.children.length||(this.ready||this.initWebGL(t.gl),this.fastSpriteBatch.gl!==t.gl&&this.fastSpriteBatch.setContext(t.gl),t.spriteBatch.stop(),t.shaderManager.setShader(t.shaderManager.fastShader),this.fastSpriteBatch.begin(this,t),this.fastSpriteBatch.render(this),t.spriteBatch.start())},i.SpriteBatch.prototype._renderCanvas=function(t){if(this.visible&&!(this.alpha<=0)&&this.children.length){var e=t.context;e.globalAlpha=this.worldAlpha,this.displayObjectUpdateTransform();for(var i=this.worldTransform,s=!0,n=0;n<this.children.length;n++){var r=this.children[n];if(r.visible){var o=r.texture,a=o.frame;if(e.globalAlpha=this.worldAlpha*r.alpha,r.rotation%(2*Math.PI)==0)s&&(e.setTransform(i.a,i.b,i.c,i.d,i.tx,i.ty),s=!1),e.drawImage(o.baseTexture.source,a.x,a.y,a.width,a.height,r.anchor.x*(-a.width*r.scale.x)+r.position.x+.5+t.shakeX|0,r.anchor.y*(-a.height*r.scale.y)+r.position.y+.5+t.shakeY|0,a.width*r.scale.x,a.height*r.scale.y);else{s||(s=!0),r.displayObjectUpdateTransform();var h=r.worldTransform,l=h.tx*t.resolution+t.shakeX,c=h.ty*t.resolution+t.shakeY;t.roundPixels?e.setTransform(h.a,h.b,h.c,h.d,0|l,0|c):e.setTransform(h.a,h.b,h.c,h.d,l,c),e.drawImage(o.baseTexture.source,a.x,a.y,a.width,a.height,r.anchor.x*-a.width+.5|0,r.anchor.y*-a.height+.5|0,a.width,a.height)}}}}},i.hex2rgb=function(t){return[(t>>16&255)/255,(t>>8&255)/255,(255&t)/255]},i.rgb2hex=function(t){return(255*t[0]<<16)+(255*t[1]<<8)+255*t[2]},i.canUseNewCanvasBlendModes=function(){if(void 0===document)return!1;var t="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAABAQMAAADD8p2OAAAAA1BMVEX/",e="AAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJggg==",s=new Image;s.src=t+"AP804Oa6"+e;var n=new Image;n.src=t+"/wCKxvRF"+e;var r=i.CanvasPool.create(this,6,1),o=r.getContext("2d");if(o.globalCompositeOperation="multiply",o.drawImage(s,0,0),o.drawImage(n,2,0),!o.getImageData(2,0,1,1))return!1;var a=o.getImageData(2,0,1,1).data;return i.CanvasPool.remove(this),255===a[0]&&0===a[1]&&0===a[2]},i.getNextPowerOfTwo=function(t){if(t>0&&0==(t&t-1))return t;for(var e=1;e<t;)e<<=1;return e},i.isPowerOfTwo=function(t,e){return t>0&&0==(t&t-1)&&e>0&&0==(e&e-1)},i.CanvasPool={create:function(t,e,s){var n,r=i.CanvasPool.getFirst();if(-1===r){var o={parent:t,canvas:document.createElement("canvas")};i.CanvasPool.pool.push(o),n=o.canvas}else i.CanvasPool.pool[r].parent=t,n=i.CanvasPool.pool[r].canvas;return void 0!==e&&(n.width=e,n.height=s),n},getFirst:function(){for(var t=i.CanvasPool.pool,e=0;e<t.length;e++)if(!t[e].parent)return e;return-1},remove:function(t){for(var e=i.CanvasPool.pool,s=0;s<e.length;s++)e[s].parent===t&&(e[s].parent=null,e[s].canvas.width=1,e[s].canvas.height=1)},removeByCanvas:function(t){for(var e=i.CanvasPool.pool,s=0;s<e.length;s++)e[s].canvas===t&&(e[s].parent=null,e[s].canvas.width=1,e[s].canvas.height=1)},getTotal:function(){for(var t=i.CanvasPool.pool,e=0,s=0;s<t.length;s++)t[s].parent&&e++;return e},getFree:function(){for(var t=i.CanvasPool.pool,e=0,s=0;s<t.length;s++)t[s].parent||e++;return e}},i.CanvasPool.pool=[],i.initDefaultShaders=function(){},i.CompileVertexShader=function(t,e){return i._CompileShader(t,e,t.VERTEX_SHADER)},i.CompileFragmentShader=function(t,e){return i._CompileShader(t,e,t.FRAGMENT_SHADER)},i._CompileShader=function(t,e,i){var s=e;Array.isArray(e)&&(s=e.join("\n"));var n=t.createShader(i);return t.shaderSource(n,s),t.compileShader(n),t.getShaderParameter(n,t.COMPILE_STATUS)?n:(window.console.log(t.getShaderInfoLog(n)),null)},i.compileProgram=function(t,e,s){var n=i.CompileFragmentShader(t,s),r=i.CompileVertexShader(t,e),o=t.createProgram();return t.attachShader(o,r),t.attachShader(o,n),t.linkProgram(o),t.getProgramParameter(o,t.LINK_STATUS)||(window.console.log(t.getProgramInfoLog(o)),window.console.log("Could not initialise shaders")),o},i.PixiShader=function(t){this._UID=i._UID++,this.gl=t,this.program=null,this.fragmentSrc=["precision lowp float;","varying vec2 vTextureCoord;","varying vec4 vColor;","uniform sampler2D uSampler;","void main(void) {"," gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;","}"],this.textureCount=0,this.firstRun=!0,this.dirty=!0,this.attributes=[],this.init()},i.PixiShader.prototype.constructor=i.PixiShader,i.PixiShader.prototype.init=function(){var t=this.gl,e=i.compileProgram(t,this.vertexSrc||i.PixiShader.defaultVertexSrc,this.fragmentSrc);t.useProgram(e),this.uSampler=t.getUniformLocation(e,"uSampler"),this.projectionVector=t.getUniformLocation(e,"projectionVector"),this.offsetVector=t.getUniformLocation(e,"offsetVector"),this.dimensions=t.getUniformLocation(e,"dimensions"),this.aVertexPosition=t.getAttribLocation(e,"aVertexPosition"),this.aTextureCoord=t.getAttribLocation(e,"aTextureCoord"),this.colorAttribute=t.getAttribLocation(e,"aColor"),-1===this.colorAttribute&&(this.colorAttribute=2),this.attributes=[this.aVertexPosition,this.aTextureCoord,this.colorAttribute];for(var s in this.uniforms)this.uniforms[s].uniformLocation=t.getUniformLocation(e,s);this.initUniforms(),this.program=e},i.PixiShader.prototype.initUniforms=function(){this.textureCount=1;var t,e=this.gl;for(var i in this.uniforms){t=this.uniforms[i];var s=t.type;"sampler2D"===s?(t._init=!1,null!==t.value&&this.initSampler2D(t)):"mat2"===s||"mat3"===s||"mat4"===s?(t.glMatrix=!0,t.glValueLength=1,"mat2"===s?t.glFunc=e.uniformMatrix2fv:"mat3"===s?t.glFunc=e.uniformMatrix3fv:"mat4"===s&&(t.glFunc=e.uniformMatrix4fv)):(t.glFunc=e["uniform"+s],t.glValueLength="2f"===s||"2i"===s?2:"3f"===s||"3i"===s?3:"4f"===s||"4i"===s?4:1)}},i.PixiShader.prototype.initSampler2D=function(t){if(t.value&&t.value.baseTexture&&t.value.baseTexture.hasLoaded){var e=this.gl;if(e.activeTexture(e["TEXTURE"+this.textureCount]),e.bindTexture(e.TEXTURE_2D,t.value.baseTexture._glTextures[e.id]),t.textureData){var i=t.textureData,s=i.magFilter?i.magFilter:e.LINEAR,n=i.minFilter?i.minFilter:e.LINEAR,r=i.wrapS?i.wrapS:e.CLAMP_TO_EDGE,o=i.wrapT?i.wrapT:e.CLAMP_TO_EDGE,a=i.luminance?e.LUMINANCE:e.RGBA;if(i.repeat&&(r=e.REPEAT,o=e.REPEAT),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!!i.flipY),i.width){var h=i.width?i.width:512,l=i.height?i.height:2,c=i.border?i.border:0;e.texImage2D(e.TEXTURE_2D,0,a,h,l,c,a,e.UNSIGNED_BYTE,null)}else e.texImage2D(e.TEXTURE_2D,0,a,e.RGBA,e.UNSIGNED_BYTE,t.value.baseTexture.source);e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,s),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,n),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,r),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,o)}e.uniform1i(t.uniformLocation,this.textureCount),t._init=!0,this.textureCount++}},i.PixiShader.prototype.syncUniforms=function(){this.textureCount=1;var t,e=this.gl;for(var s in this.uniforms)t=this.uniforms[s],1===t.glValueLength?!0===t.glMatrix?t.glFunc.call(e,t.uniformLocation,t.transpose,t.value):t.glFunc.call(e,t.uniformLocation,t.value):2===t.glValueLength?t.glFunc.call(e,t.uniformLocation,t.value.x,t.value.y):3===t.glValueLength?t.glFunc.call(e,t.uniformLocation,t.value.x,t.value.y,t.value.z):4===t.glValueLength?t.glFunc.call(e,t.uniformLocation,t.value.x,t.value.y,t.value.z,t.value.w):"sampler2D"===t.type&&(t._init?(e.activeTexture(e["TEXTURE"+this.textureCount]),t.value.baseTexture._dirty[e.id]?i.instances[e.id].updateTexture(t.value.baseTexture):e.bindTexture(e.TEXTURE_2D,t.value.baseTexture._glTextures[e.id]),e.uniform1i(t.uniformLocation,this.textureCount),this.textureCount++):this.initSampler2D(t))},i.PixiShader.prototype.destroy=function(){this.gl.deleteProgram(this.program),this.uniforms=null,this.gl=null,this.attributes=null},i.PixiShader.defaultVertexSrc=["attribute vec2 aVertexPosition;","attribute vec2 aTextureCoord;","attribute vec4 aColor;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","varying vec2 vTextureCoord;","varying vec4 vColor;","const vec2 center = vec2(-1.0, 1.0);","void main(void) {"," gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);"," vTextureCoord = aTextureCoord;"," vColor = vec4(aColor.rgb * aColor.a, aColor.a);","}"],i.PixiFastShader=function(t){this._UID=i._UID++,this.gl=t,this.program=null,this.fragmentSrc=["precision lowp float;","varying vec2 vTextureCoord;","varying float vColor;","uniform sampler2D uSampler;","void main(void) {"," gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;","}"],this.vertexSrc=["attribute vec2 aVertexPosition;","attribute vec2 aPositionCoord;","attribute vec2 aScale;","attribute float aRotation;","attribute vec2 aTextureCoord;","attribute float aColor;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","uniform mat3 uMatrix;","varying vec2 vTextureCoord;","varying float vColor;","const vec2 center = vec2(-1.0, 1.0);","void main(void) {"," vec2 v;"," vec2 sv = aVertexPosition * aScale;"," v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);"," v.y = (sv.x) * sin(aRotation) + (sv.y) * cos(aRotation);"," v = ( uMatrix * vec3(v + aPositionCoord , 1.0) ).xy ;"," gl_Position = vec4( ( v / projectionVector) + center , 0.0, 1.0);"," vTextureCoord = aTextureCoord;"," vColor = aColor;","}"],this.textureCount=0,this.init()},i.PixiFastShader.prototype.constructor=i.PixiFastShader,i.PixiFastShader.prototype.init=function(){var t=this.gl,e=i.compileProgram(t,this.vertexSrc,this.fragmentSrc);t.useProgram(e),this.uSampler=t.getUniformLocation(e,"uSampler"),this.projectionVector=t.getUniformLocation(e,"projectionVector"),this.offsetVector=t.getUniformLocation(e,"offsetVector"),this.dimensions=t.getUniformLocation(e,"dimensions"),this.uMatrix=t.getUniformLocation(e,"uMatrix"),this.aVertexPosition=t.getAttribLocation(e,"aVertexPosition"),this.aPositionCoord=t.getAttribLocation(e,"aPositionCoord"),this.aScale=t.getAttribLocation(e,"aScale"),this.aRotation=t.getAttribLocation(e,"aRotation"),this.aTextureCoord=t.getAttribLocation(e,"aTextureCoord"),this.colorAttribute=t.getAttribLocation(e,"aColor"),-1===this.colorAttribute&&(this.colorAttribute=2),this.attributes=[this.aVertexPosition,this.aPositionCoord,this.aScale,this.aRotation,this.aTextureCoord,this.colorAttribute],this.program=e},i.PixiFastShader.prototype.destroy=function(){this.gl.deleteProgram(this.program),this.uniforms=null,this.gl=null,this.attributes=null},i.StripShader=function(t){this._UID=i._UID++,this.gl=t,this.program=null,this.fragmentSrc=["precision mediump float;","varying vec2 vTextureCoord;","uniform float alpha;","uniform sampler2D uSampler;","void main(void) {"," gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;","}"],this.vertexSrc=["attribute vec2 aVertexPosition;","attribute vec2 aTextureCoord;","uniform mat3 translationMatrix;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","varying vec2 vTextureCoord;","void main(void) {"," vec3 v = translationMatrix * vec3(aVertexPosition , 1.0);"," v -= offsetVector.xyx;"," gl_Position = vec4( v.x / projectionVector.x -1.0, v.y / -projectionVector.y + 1.0 , 0.0, 1.0);"," vTextureCoord = aTextureCoord;","}"],this.init()},i.StripShader.prototype.constructor=i.StripShader,i.StripShader.prototype.init=function(){var t=this.gl,e=i.compileProgram(t,this.vertexSrc,this.fragmentSrc);t.useProgram(e),this.uSampler=t.getUniformLocation(e,"uSampler"),this.projectionVector=t.getUniformLocation(e,"projectionVector"),this.offsetVector=t.getUniformLocation(e,"offsetVector"),this.colorAttribute=t.getAttribLocation(e,"aColor"),this.aVertexPosition=t.getAttribLocation(e,"aVertexPosition"),this.aTextureCoord=t.getAttribLocation(e,"aTextureCoord"),this.attributes=[this.aVertexPosition,this.aTextureCoord],this.translationMatrix=t.getUniformLocation(e,"translationMatrix"),this.alpha=t.getUniformLocation(e,"alpha"),this.program=e},i.StripShader.prototype.destroy=function(){this.gl.deleteProgram(this.program),this.uniforms=null,this.gl=null,this.attribute=null},i.PrimitiveShader=function(t){this._UID=i._UID++,this.gl=t,this.program=null,this.fragmentSrc=["precision mediump float;","varying vec4 vColor;","void main(void) {"," gl_FragColor = vColor;","}"],this.vertexSrc=["attribute vec2 aVertexPosition;","attribute vec4 aColor;","uniform mat3 translationMatrix;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","uniform float alpha;","uniform float flipY;","uniform vec3 tint;","varying vec4 vColor;","void main(void) {"," vec3 v = translationMatrix * vec3(aVertexPosition , 1.0);"," v -= offsetVector.xyx;"," gl_Position = vec4( v.x / projectionVector.x -1.0, (v.y / projectionVector.y * -flipY) + flipY , 0.0, 1.0);"," vColor = aColor * vec4(tint * alpha, alpha);","}"],this.init()},i.PrimitiveShader.prototype.constructor=i.PrimitiveShader,i.PrimitiveShader.prototype.init=function(){var t=this.gl,e=i.compileProgram(t,this.vertexSrc,this.fragmentSrc);t.useProgram(e),this.projectionVector=t.getUniformLocation(e,"projectionVector"),this.offsetVector=t.getUniformLocation(e,"offsetVector"),this.tintColor=t.getUniformLocation(e,"tint"),this.flipY=t.getUniformLocation(e,"flipY"),this.aVertexPosition=t.getAttribLocation(e,"aVertexPosition"),this.colorAttribute=t.getAttribLocation(e,"aColor"),this.attributes=[this.aVertexPosition,this.colorAttribute],this.translationMatrix=t.getUniformLocation(e,"translationMatrix"),this.alpha=t.getUniformLocation(e,"alpha"),this.program=e},i.PrimitiveShader.prototype.destroy=function(){this.gl.deleteProgram(this.program),this.uniforms=null,this.gl=null,this.attributes=null},i.ComplexPrimitiveShader=function(t){this._UID=i._UID++,this.gl=t,this.program=null,this.fragmentSrc=["precision mediump float;","varying vec4 vColor;","void main(void) {"," gl_FragColor = vColor;","}"],this.vertexSrc=["attribute vec2 aVertexPosition;","uniform mat3 translationMatrix;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","uniform vec3 tint;","uniform float alpha;","uniform vec3 color;","uniform float flipY;","varying vec4 vColor;","void main(void) {"," vec3 v = translationMatrix * vec3(aVertexPosition , 1.0);"," v -= offsetVector.xyx;"," gl_Position = vec4( v.x / projectionVector.x -1.0, (v.y / projectionVector.y * -flipY) + flipY , 0.0, 1.0);"," vColor = vec4(color * alpha * tint, alpha);","}"],this.init()},i.ComplexPrimitiveShader.prototype.constructor=i.ComplexPrimitiveShader,i.ComplexPrimitiveShader.prototype.init=function(){var t=this.gl,e=i.compileProgram(t,this.vertexSrc,this.fragmentSrc);t.useProgram(e),this.projectionVector=t.getUniformLocation(e,"projectionVector"),this.offsetVector=t.getUniformLocation(e,"offsetVector"),this.tintColor=t.getUniformLocation(e,"tint"),this.color=t.getUniformLocation(e,"color"),this.flipY=t.getUniformLocation(e,"flipY"),this.aVertexPosition=t.getAttribLocation(e,"aVertexPosition"),this.attributes=[this.aVertexPosition,this.colorAttribute],this.translationMatrix=t.getUniformLocation(e,"translationMatrix"),this.alpha=t.getUniformLocation(e,"alpha"),this.program=e},i.ComplexPrimitiveShader.prototype.destroy=function(){this.gl.deleteProgram(this.program),this.uniforms=null,this.gl=null,this.attribute=null},i.glContexts=[],i.instances=[],i.WebGLRenderer=function(t){this.game=t,i.defaultRenderer||(i.defaultRenderer=this),this.type=i.WEBGL_RENDERER,this.resolution=t.resolution,this.transparent=t.transparent,this.autoResize=!1,this.preserveDrawingBuffer=t.preserveDrawingBuffer,this.clearBeforeRender=t.clearBeforeRender,this.width=t.width,this.height=t.height,this.view=t.canvas,this._contextOptions={alpha:this.transparent,antialias:t.antialias,premultipliedAlpha:this.transparent&&"notMultiplied"!==this.transparent,stencil:!0,preserveDrawingBuffer:this.preserveDrawingBuffer},this.projection=new i.Point,this.offset=new i.Point,this.shaderManager=new i.WebGLShaderManager,this.spriteBatch=new i.WebGLSpriteBatch,this.maskManager=new i.WebGLMaskManager,this.filterManager=new i.WebGLFilterManager,this.stencilManager=new i.WebGLStencilManager,this.blendModeManager=new i.WebGLBlendModeManager,this.renderSession={},this.renderSession.game=this.game,this.renderSession.gl=this.gl,this.renderSession.drawCount=0,this.renderSession.shaderManager=this.shaderManager,this.renderSession.maskManager=this.maskManager,this.renderSession.filterManager=this.filterManager,this.renderSession.blendModeManager=this.blendModeManager,this.renderSession.spriteBatch=this.spriteBatch,this.renderSession.stencilManager=this.stencilManager,this.renderSession.renderer=this,this.renderSession.resolution=this.resolution,this.initContext(),this.mapBlendModes()},i.WebGLRenderer.prototype.constructor=i.WebGLRenderer,i.WebGLRenderer.prototype.initContext=function(){var t=this.view.getContext("webgl",this._contextOptions)||this.view.getContext("experimental-webgl",this._contextOptions);if(this.gl=t,!t)throw new Error("This browser does not support webGL. Try using the canvas renderer");this.glContextId=t.id=i.WebGLRenderer.glContextId++,i.glContexts[this.glContextId]=t,i.instances[this.glContextId]=this,t.disable(t.DEPTH_TEST),t.disable(t.CULL_FACE),t.enable(t.BLEND),this.shaderManager.setContext(t),this.spriteBatch.setContext(t),this.maskManager.setContext(t),this.filterManager.setContext(t),this.blendModeManager.setContext(t),this.stencilManager.setContext(t),this.renderSession.gl=this.gl,this.resize(this.width,this.height)},i.WebGLRenderer.prototype.render=function(t){if(!this.contextLost){var e=this.gl;e.viewport(0,0,this.width,this.height),e.bindFramebuffer(e.FRAMEBUFFER,null),this.game.clearBeforeRender&&(e.clearColor(t._bgColor.r,t._bgColor.g,t._bgColor.b,t._bgColor.a),e.clear(e.COLOR_BUFFER_BIT)),this.offset.x=this.game.camera._shake.x,this.offset.y=this.game.camera._shake.y,this.renderDisplayObject(t,this.projection)}},i.WebGLRenderer.prototype.renderDisplayObject=function(t,e,s,n){this.renderSession.blendModeManager.setBlendMode(i.blendModes.NORMAL),this.renderSession.drawCount=0,this.renderSession.flipY=s?-1:1,this.renderSession.projection=e,this.renderSession.offset=this.offset,this.spriteBatch.begin(this.renderSession),this.filterManager.begin(this.renderSession,s),t._renderWebGL(this.renderSession,n),this.spriteBatch.end()},i.WebGLRenderer.prototype.resize=function(t,e){this.width=t*this.resolution,this.height=e*this.resolution,this.view.width=this.width,this.view.height=this.height,this.autoResize&&(this.view.style.width=this.width/this.resolution+"px",this.view.style.height=this.height/this.resolution+"px"),this.gl.viewport(0,0,this.width,this.height),this.projection.x=this.width/2/this.resolution,this.projection.y=-this.height/2/this.resolution},i.WebGLRenderer.prototype.updateTexture=function(t){if(!t.hasLoaded)return!1;var e=this.gl;return t._glTextures[e.id]||(t._glTextures[e.id]=e.createTexture()),e.bindTexture(e.TEXTURE_2D,t._glTextures[e.id]),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultipliedAlpha),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t.source),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t.scaleMode===i.scaleModes.LINEAR?e.LINEAR:e.NEAREST),t.mipmap&&i.isPowerOfTwo(t.width,t.height)?(e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t.scaleMode===i.scaleModes.LINEAR?e.LINEAR_MIPMAP_LINEAR:e.NEAREST_MIPMAP_NEAREST),e.generateMipmap(e.TEXTURE_2D)):e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t.scaleMode===i.scaleModes.LINEAR?e.LINEAR:e.NEAREST),t._powerOf2?(e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT)):(e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),t._dirty[e.id]=!1,!0},i.WebGLRenderer.prototype.destroy=function(){i.glContexts[this.glContextId]=null,this.projection=null,this.offset=null,this.shaderManager.destroy(),this.spriteBatch.destroy(),this.maskManager.destroy(),this.filterManager.destroy(),this.shaderManager=null,this.spriteBatch=null,this.maskManager=null,this.filterManager=null,this.gl=null,this.renderSession=null,i.CanvasPool.remove(this),i.instances[this.glContextId]=null,i.WebGLRenderer.glContextId--},i.WebGLRenderer.prototype.mapBlendModes=function(){var t=this.gl;if(!i.blendModesWebGL){var e=[],s=i.blendModes;e[s.NORMAL]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.ADD]=[t.SRC_ALPHA,t.DST_ALPHA],e[s.MULTIPLY]=[t.DST_COLOR,t.ONE_MINUS_SRC_ALPHA],e[s.SCREEN]=[t.SRC_ALPHA,t.ONE],e[s.OVERLAY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.DARKEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.LIGHTEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.COLOR_DODGE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.COLOR_BURN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.HARD_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.SOFT_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.DIFFERENCE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.EXCLUSION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.HUE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.SATURATION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.COLOR]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.LUMINOSITY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],i.blendModesWebGL=e}},i.WebGLRenderer.glContextId=0,i.WebGLBlendModeManager=function(){this.currentBlendMode=99999},i.WebGLBlendModeManager.prototype.constructor=i.WebGLBlendModeManager,i.WebGLBlendModeManager.prototype.setContext=function(t){this.gl=t},i.WebGLBlendModeManager.prototype.setBlendMode=function(t){if(this.currentBlendMode===t)return!1;this.currentBlendMode=t;var e=i.blendModesWebGL[this.currentBlendMode];return e&&this.gl.blendFunc(e[0],e[1]),!0},i.WebGLBlendModeManager.prototype.destroy=function(){this.gl=null},i.WebGLMaskManager=function(){},i.WebGLMaskManager.prototype.constructor=i.WebGLMaskManager,i.WebGLMaskManager.prototype.setContext=function(t){this.gl=t},i.WebGLMaskManager.prototype.pushMask=function(t,e){var s=e.gl;t.dirty&&i.WebGLGraphics.updateGraphics(t,s),void 0!==t._webGL[s.id]&&void 0!==t._webGL[s.id].data&&0!==t._webGL[s.id].data.length&&e.stencilManager.pushStencil(t,t._webGL[s.id].data[0],e)},i.WebGLMaskManager.prototype.popMask=function(t,e){var i=this.gl;void 0!==t._webGL[i.id]&&void 0!==t._webGL[i.id].data&&0!==t._webGL[i.id].data.length&&e.stencilManager.popStencil(t,t._webGL[i.id].data[0],e)},i.WebGLMaskManager.prototype.destroy=function(){this.gl=null},i.WebGLStencilManager=function(){this.stencilStack=[],this.reverse=!0,this.count=0},i.WebGLStencilManager.prototype.setContext=function(t){this.gl=t},i.WebGLStencilManager.prototype.pushStencil=function(t,e,i){var s=this.gl;this.bindGraphics(t,e,i),0===this.stencilStack.length&&(s.enable(s.STENCIL_TEST),s.clear(s.STENCIL_BUFFER_BIT),this.reverse=!0,this.count=0),this.stencilStack.push(e);var n=this.count;s.colorMask(!1,!1,!1,!1),s.stencilFunc(s.ALWAYS,0,255),s.stencilOp(s.KEEP,s.KEEP,s.INVERT),1===e.mode?(s.drawElements(s.TRIANGLE_FAN,e.indices.length-4,s.UNSIGNED_SHORT,0),this.reverse?(s.stencilFunc(s.EQUAL,255-n,255),s.stencilOp(s.KEEP,s.KEEP,s.DECR)):(s.stencilFunc(s.EQUAL,n,255),s.stencilOp(s.KEEP,s.KEEP,s.INCR)),s.drawElements(s.TRIANGLE_FAN,4,s.UNSIGNED_SHORT,2*(e.indices.length-4)),this.reverse?s.stencilFunc(s.EQUAL,255-(n+1),255):s.stencilFunc(s.EQUAL,n+1,255),this.reverse=!this.reverse):(this.reverse?(s.stencilFunc(s.EQUAL,n,255),s.stencilOp(s.KEEP,s.KEEP,s.INCR)):(s.stencilFunc(s.EQUAL,255-n,255),s.stencilOp(s.KEEP,s.KEEP,s.DECR)),s.drawElements(s.TRIANGLE_STRIP,e.indices.length,s.UNSIGNED_SHORT,0),this.reverse?s.stencilFunc(s.EQUAL,n+1,255):s.stencilFunc(s.EQUAL,255-(n+1),255)),s.colorMask(!0,!0,!0,!0),s.stencilOp(s.KEEP,s.KEEP,s.KEEP),this.count++},i.WebGLStencilManager.prototype.bindGraphics=function(t,e,s){this._currentGraphics=t;var n,r=this.gl,o=s.projection,a=s.offset;1===e.mode?(n=s.shaderManager.complexPrimitiveShader,s.shaderManager.setShader(n),r.uniform1f(n.flipY,s.flipY),r.uniformMatrix3fv(n.translationMatrix,!1,t.worldTransform.toArray(!0)),r.uniform2f(n.projectionVector,o.x,-o.y),r.uniform2f(n.offsetVector,-a.x,-a.y),r.uniform3fv(n.tintColor,i.hex2rgb(t.tint)),r.uniform3fv(n.color,e.color),r.uniform1f(n.alpha,t.worldAlpha*e.alpha),r.bindBuffer(r.ARRAY_BUFFER,e.buffer),r.vertexAttribPointer(n.aVertexPosition,2,r.FLOAT,!1,8,0),r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,e.indexBuffer)):(n=s.shaderManager.primitiveShader,s.shaderManager.setShader(n),r.uniformMatrix3fv(n.translationMatrix,!1,t.worldTransform.toArray(!0)),r.uniform1f(n.flipY,s.flipY),r.uniform2f(n.projectionVector,o.x,-o.y),r.uniform2f(n.offsetVector,-a.x,-a.y),r.uniform3fv(n.tintColor,i.hex2rgb(t.tint)),r.uniform1f(n.alpha,t.worldAlpha),r.bindBuffer(r.ARRAY_BUFFER,e.buffer),r.vertexAttribPointer(n.aVertexPosition,2,r.FLOAT,!1,24,0),r.vertexAttribPointer(n.colorAttribute,4,r.FLOAT,!1,24,8),r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,e.indexBuffer))},i.WebGLStencilManager.prototype.popStencil=function(t,e,i){var s=this.gl;if(this.stencilStack.pop(),this.count--,0===this.stencilStack.length)s.disable(s.STENCIL_TEST);else{var n=this.count;this.bindGraphics(t,e,i),s.colorMask(!1,!1,!1,!1),1===e.mode?(this.reverse=!this.reverse,this.reverse?(s.stencilFunc(s.EQUAL,255-(n+1),255),s.stencilOp(s.KEEP,s.KEEP,s.INCR)):(s.stencilFunc(s.EQUAL,n+1,255),s.stencilOp(s.KEEP,s.KEEP,s.DECR)),s.drawElements(s.TRIANGLE_FAN,4,s.UNSIGNED_SHORT,2*(e.indices.length-4)),s.stencilFunc(s.ALWAYS,0,255),s.stencilOp(s.KEEP,s.KEEP,s.INVERT),s.drawElements(s.TRIANGLE_FAN,e.indices.length-4,s.UNSIGNED_SHORT,0),this.reverse?s.stencilFunc(s.EQUAL,n,255):s.stencilFunc(s.EQUAL,255-n,255)):(this.reverse?(s.stencilFunc(s.EQUAL,n+1,255),s.stencilOp(s.KEEP,s.KEEP,s.DECR)):(s.stencilFunc(s.EQUAL,255-(n+1),255),s.stencilOp(s.KEEP,s.KEEP,s.INCR)),s.drawElements(s.TRIANGLE_STRIP,e.indices.length,s.UNSIGNED_SHORT,0),this.reverse?s.stencilFunc(s.EQUAL,n,255):s.stencilFunc(s.EQUAL,255-n,255)),s.colorMask(!0,!0,!0,!0),s.stencilOp(s.KEEP,s.KEEP,s.KEEP)}},i.WebGLStencilManager.prototype.destroy=function(){this.stencilStack=null,this.gl=null},i.WebGLShaderManager=function(){this.maxAttibs=10,this.attribState=[],this.tempAttribState=[];for(var t=0;t<this.maxAttibs;t++)this.attribState[t]=!1;this.stack=[]},i.WebGLShaderManager.prototype.constructor=i.WebGLShaderManager,i.WebGLShaderManager.prototype.setContext=function(t){this.gl=t,this.primitiveShader=new i.PrimitiveShader(t),this.complexPrimitiveShader=new i.ComplexPrimitiveShader(t),this.defaultShader=new i.PixiShader(t),this.fastShader=new i.PixiFastShader(t),this.stripShader=new i.StripShader(t),this.setShader(this.defaultShader)},i.WebGLShaderManager.prototype.setAttribs=function(t){var e;for(e=0;e<this.tempAttribState.length;e++)this.tempAttribState[e]=!1;for(e=0;e<t.length;e++){var i=t[e];this.tempAttribState[i]=!0}var s=this.gl;for(e=0;e<this.attribState.length;e++)this.attribState[e]!==this.tempAttribState[e]&&(this.attribState[e]=this.tempAttribState[e],this.tempAttribState[e]?s.enableVertexAttribArray(e):s.disableVertexAttribArray(e))},i.WebGLShaderManager.prototype.setShader=function(t){return this._currentId!==t._UID&&(this._currentId=t._UID,this.currentShader=t,this.gl.useProgram(t.program),this.setAttribs(t.attributes),!0)},i.WebGLShaderManager.prototype.destroy=function(){this.attribState=null,this.tempAttribState=null,this.primitiveShader.destroy(),this.complexPrimitiveShader.destroy(),this.defaultShader.destroy(),this.fastShader.destroy(),this.stripShader.destroy(),this.gl=null},i.WebGLSpriteBatch=function(){this.vertSize=5,this.size=2e3;var t=4*this.size*4*this.vertSize,e=6*this.size;this.vertices=new i.ArrayBuffer(t),this.positions=new i.Float32Array(this.vertices),this.colors=new i.Uint32Array(this.vertices),this.indices=new i.Uint16Array(e),this.lastIndexCount=0;for(var s=0,n=0;s<e;s+=6,n+=4)this.indices[s+0]=n+0,this.indices[s+1]=n+1,this.indices[s+2]=n+2,this.indices[s+3]=n+0,this.indices[s+4]=n+2,this.indices[s+5]=n+3;this.drawing=!1,this.currentBatchSize=0,this.currentBaseTexture=null,this.dirty=!0,this.textures=[],this.blendModes=[],this.shaders=[],this.sprites=[],this.defaultShader=new i.AbstractFilter(["precision lowp float;","varying vec2 vTextureCoord;","varying vec4 vColor;","uniform sampler2D uSampler;","void main(void) {"," gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;","}"])},i.WebGLSpriteBatch.prototype.setContext=function(t){this.gl=t,this.vertexBuffer=t.createBuffer(),this.indexBuffer=t.createBuffer(),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,this.indices,t.STATIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),t.bufferData(t.ARRAY_BUFFER,this.vertices,t.DYNAMIC_DRAW),this.currentBlendMode=99999;var e=new i.PixiShader(t);e.fragmentSrc=this.defaultShader.fragmentSrc,e.uniforms={},e.init(),this.defaultShader.shaders[t.id]=e},i.WebGLSpriteBatch.prototype.begin=function(t){this.renderSession=t,this.shader=this.renderSession.shaderManager.defaultShader,this.start()},i.WebGLSpriteBatch.prototype.end=function(){this.flush()},i.WebGLSpriteBatch.prototype.render=function(t,e){var i=t.texture,s=t.worldTransform;e&&(s=e),this.currentBatchSize>=this.size&&(this.flush(),this.currentBaseTexture=i.baseTexture);var n=i._uvs;if(n){var r,o,a,h,l=t.anchor.x,c=t.anchor.y;if(i.trim){var u=i.trim;o=u.x-l*u.width,r=o+i.crop.width,h=u.y-c*u.height,a=h+i.crop.height}else r=i.frame.width*(1-l),o=i.frame.width*-l,a=i.frame.height*(1-c),h=i.frame.height*-c;var d=4*this.currentBatchSize*this.vertSize,p=i.baseTexture.resolution,f=s.a/p,g=s.b/p,m=s.c/p,y=s.d/p,v=s.tx,b=s.ty,x=this.colors,w=this.positions;this.renderSession.roundPixels?(w[d]=f*o+m*h+v|0,w[d+1]=y*h+g*o+b|0,w[d+5]=f*r+m*h+v|0,w[d+6]=y*h+g*r+b|0,w[d+10]=f*r+m*a+v|0,w[d+11]=y*a+g*r+b|0,w[d+15]=f*o+m*a+v|0,w[d+16]=y*a+g*o+b|0):(w[d]=f*o+m*h+v,w[d+1]=y*h+g*o+b,w[d+5]=f*r+m*h+v,w[d+6]=y*h+g*r+b,w[d+10]=f*r+m*a+v,w[d+11]=y*a+g*r+b,w[d+15]=f*o+m*a+v,w[d+16]=y*a+g*o+b),w[d+2]=n.x0,w[d+3]=n.y0,w[d+7]=n.x1,w[d+8]=n.y1,w[d+12]=n.x2,w[d+13]=n.y2,w[d+17]=n.x3,w[d+18]=n.y3;var _=t.tint;x[d+4]=x[d+9]=x[d+14]=x[d+19]=(_>>16)+(65280&_)+((255&_)<<16)+(255*t.worldAlpha<<24),this.sprites[this.currentBatchSize++]=t}},i.WebGLSpriteBatch.prototype.renderTilingSprite=function(t){var e=t.tilingTexture;this.currentBatchSize>=this.size&&(this.flush(),this.currentBaseTexture=e.baseTexture),t._uvs||(t._uvs=new i.TextureUvs);var s=t._uvs,n=e.baseTexture.width,r=e.baseTexture.height;t.tilePosition.x%=n*t.tileScaleOffset.x,t.tilePosition.y%=r*t.tileScaleOffset.y;var o=t.tilePosition.x/(n*t.tileScaleOffset.x),a=t.tilePosition.y/(r*t.tileScaleOffset.y),h=t.width/n/(t.tileScale.x*t.tileScaleOffset.x),l=t.height/r/(t.tileScale.y*t.tileScaleOffset.y);s.x0=0-o,s.y0=0-a,s.x1=1*h-o,s.y1=0-a,s.x2=1*h-o,s.y2=1*l-a,s.x3=0-o,s.y3=1*l-a;var c=t.tint,u=(c>>16)+(65280&c)+((255&c)<<16)+(255*t.worldAlpha<<24),d=this.positions,p=this.colors,f=t.width,g=t.height,m=t.anchor.x,y=t.anchor.y,v=f*(1-m),b=f*-m,x=g*(1-y),w=g*-y,_=4*this.currentBatchSize*this.vertSize,P=e.baseTexture.resolution,T=t.worldTransform,C=T.a/P,S=T.b/P,A=T.c/P,E=T.d/P,I=T.tx,M=T.ty;d[_++]=C*b+A*w+I,d[_++]=E*w+S*b+M,d[_++]=s.x0,d[_++]=s.y0,p[_++]=u,d[_++]=C*v+A*w+I,d[_++]=E*w+S*v+M,d[_++]=s.x1,d[_++]=s.y1,p[_++]=u,d[_++]=C*v+A*x+I,d[_++]=E*x+S*v+M,d[_++]=s.x2,d[_++]=s.y2,p[_++]=u,d[_++]=C*b+A*x+I,d[_++]=E*x+S*b+M,d[_++]=s.x3,d[_++]=s.y3,p[_++]=u,this.sprites[this.currentBatchSize++]=t},i.WebGLSpriteBatch.prototype.flush=function(){if(0!==this.currentBatchSize){var t,e=this.gl;if(this.dirty){this.dirty=!1,e.activeTexture(e.TEXTURE0),e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer),t=this.defaultShader.shaders[e.id];var s=4*this.vertSize;e.vertexAttribPointer(t.aVertexPosition,2,e.FLOAT,!1,s,0),e.vertexAttribPointer(t.aTextureCoord,2,e.FLOAT,!1,s,8),e.vertexAttribPointer(t.colorAttribute,4,e.UNSIGNED_BYTE,!0,s,16)}if(this.currentBatchSize>.5*this.size)e.bufferSubData(e.ARRAY_BUFFER,0,this.vertices);else{var n=this.positions.subarray(0,4*this.currentBatchSize*this.vertSize);e.bufferSubData(e.ARRAY_BUFFER,0,n)}for(var r,o,a,h,l=0,c=0,u=null,d=this.renderSession.blendModeManager.currentBlendMode,p=null,f=!1,g=!1,m=0,y=this.currentBatchSize;m<y;m++){h=this.sprites[m],r=h.tilingTexture?h.tilingTexture.baseTexture:h.texture.baseTexture,o=h.blendMode,a=h.shader||this.defaultShader,f=d!==o,g=p!==a;var v=r.skipRender;if(v&&h.children.length>0&&(v=!1),(u!==r&&!v||f||g)&&(this.renderBatch(u,l,c),c=m,l=0,u=r,f&&(d=o,this.renderSession.blendModeManager.setBlendMode(d)),g)){p=a,t=p.shaders[e.id],t||(t=new i.PixiShader(e),t.fragmentSrc=p.fragmentSrc,t.uniforms=p.uniforms,t.init(),p.shaders[e.id]=t),this.renderSession.shaderManager.setShader(t),t.dirty&&t.syncUniforms();var b=this.renderSession.projection;e.uniform2f(t.projectionVector,b.x,b.y);var x=this.renderSession.offset;e.uniform2f(t.offsetVector,x.x,x.y)}l++}this.renderBatch(u,l,c),this.currentBatchSize=0}},i.WebGLSpriteBatch.prototype.renderBatch=function(t,e,i){if(0!==e){var s=this.gl;if(t._dirty[s.id]){if(!this.renderSession.renderer.updateTexture(t))return}else s.bindTexture(s.TEXTURE_2D,t._glTextures[s.id]);s.drawElements(s.TRIANGLES,6*e,s.UNSIGNED_SHORT,6*i*2),this.renderSession.drawCount++}},i.WebGLSpriteBatch.prototype.stop=function(){this.flush(),this.dirty=!0},i.WebGLSpriteBatch.prototype.start=function(){this.dirty=!0},i.WebGLSpriteBatch.prototype.destroy=function(){this.vertices=null,this.indices=null,this.gl.deleteBuffer(this.vertexBuffer),this.gl.deleteBuffer(this.indexBuffer),this.currentBaseTexture=null,this.gl=null},i.WebGLFastSpriteBatch=function(t){this.vertSize=10,this.maxSize=6e3,this.size=this.maxSize;var e=4*this.size*this.vertSize,s=6*this.maxSize;this.vertices=new i.Float32Array(e),this.indices=new i.Uint16Array(s),this.vertexBuffer=null,this.indexBuffer=null,this.lastIndexCount=0;for(var n=0,r=0;n<s;n+=6,r+=4)this.indices[n+0]=r+0,this.indices[n+1]=r+1,this.indices[n+2]=r+2,this.indices[n+3]=r+0,this.indices[n+4]=r+2,this.indices[n+5]=r+3;this.drawing=!1,this.currentBatchSize=0,this.currentBaseTexture=null,this.currentBlendMode=0,this.renderSession=null,this.shader=null,this.matrix=null,this.setContext(t)},i.WebGLFastSpriteBatch.prototype.constructor=i.WebGLFastSpriteBatch,i.WebGLFastSpriteBatch.prototype.setContext=function(t){this.gl=t,this.vertexBuffer=t.createBuffer(),this.indexBuffer=t.createBuffer(),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,this.indices,t.STATIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),t.bufferData(t.ARRAY_BUFFER,this.vertices,t.DYNAMIC_DRAW)},i.WebGLFastSpriteBatch.prototype.begin=function(t,e){this.renderSession=e,this.shader=this.renderSession.shaderManager.fastShader,this.matrix=t.worldTransform.toArray(!0),this.start()},i.WebGLFastSpriteBatch.prototype.end=function(){this.flush()},i.WebGLFastSpriteBatch.prototype.render=function(t){var e=t.children,i=e[0];if(i.texture._uvs){this.currentBaseTexture=i.texture.baseTexture,i.blendMode!==this.renderSession.blendModeManager.currentBlendMode&&(this.flush(),this.renderSession.blendModeManager.setBlendMode(i.blendMode));for(var s=0,n=e.length;s<n;s++)this.renderSprite(e[s]);this.flush()}},i.WebGLFastSpriteBatch.prototype.renderSprite=function(t){if(t.visible&&(t.texture.baseTexture===this.currentBaseTexture||t.texture.baseTexture.skipRender||(this.flush(),this.currentBaseTexture=t.texture.baseTexture,t.texture._uvs))){var e,i,s,n,r,o,a=this.vertices;if(e=t.texture._uvs,t.texture.frame.width,t.texture.frame.height,t.texture.trim){var h=t.texture.trim;s=h.x-t.anchor.x*h.width,i=s+t.texture.crop.width,r=h.y-t.anchor.y*h.height,n=r+t.texture.crop.height}else i=t.texture.frame.width*(1-t.anchor.x),s=t.texture.frame.width*-t.anchor.x,n=t.texture.frame.height*(1-t.anchor.y),r=t.texture.frame.height*-t.anchor.y;o=4*this.currentBatchSize*this.vertSize,a[o++]=s,a[o++]=r,a[o++]=t.position.x,a[o++]=t.position.y,a[o++]=t.scale.x,a[o++]=t.scale.y,a[o++]=t.rotation,a[o++]=e.x0,a[o++]=e.y1,a[o++]=t.alpha,a[o++]=i,a[o++]=r,a[o++]=t.position.x,a[o++]=t.position.y,a[o++]=t.scale.x,a[o++]=t.scale.y,a[o++]=t.rotation,a[o++]=e.x1,a[o++]=e.y1,a[o++]=t.alpha,a[o++]=i,a[o++]=n,a[o++]=t.position.x,a[o++]=t.position.y,a[o++]=t.scale.x,a[o++]=t.scale.y,a[o++]=t.rotation,a[o++]=e.x2,a[o++]=e.y2,a[o++]=t.alpha,a[o++]=s,a[o++]=n,a[o++]=t.position.x,a[o++]=t.position.y,a[o++]=t.scale.x,a[o++]=t.scale.y,a[o++]=t.rotation,a[o++]=e.x3,a[o++]=e.y3,a[o++]=t.alpha,this.currentBatchSize++,this.currentBatchSize>=this.size&&this.flush()}},i.WebGLFastSpriteBatch.prototype.flush=function(){if(0!==this.currentBatchSize){var t=this.gl;if(this.currentBaseTexture._glTextures[t.id]||this.renderSession.renderer.updateTexture(this.currentBaseTexture,t),t.bindTexture(t.TEXTURE_2D,this.currentBaseTexture._glTextures[t.id]),this.currentBatchSize>.5*this.size)t.bufferSubData(t.ARRAY_BUFFER,0,this.vertices);else{var e=this.vertices.subarray(0,4*this.currentBatchSize*this.vertSize);t.bufferSubData(t.ARRAY_BUFFER,0,e)}t.drawElements(t.TRIANGLES,6*this.currentBatchSize,t.UNSIGNED_SHORT,0),this.currentBatchSize=0,this.renderSession.drawCount++}},i.WebGLFastSpriteBatch.prototype.stop=function(){this.flush()},i.WebGLFastSpriteBatch.prototype.start=function(){var t=this.gl;t.activeTexture(t.TEXTURE0),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer);var e=this.renderSession.projection;t.uniform2f(this.shader.projectionVector,e.x,e.y),t.uniformMatrix3fv(this.shader.uMatrix,!1,this.matrix);var i=4*this.vertSize;t.vertexAttribPointer(this.shader.aVertexPosition,2,t.FLOAT,!1,i,0),t.vertexAttribPointer(this.shader.aPositionCoord,2,t.FLOAT,!1,i,8),t.vertexAttribPointer(this.shader.aScale,2,t.FLOAT,!1,i,16),t.vertexAttribPointer(this.shader.aRotation,1,t.FLOAT,!1,i,24),t.vertexAttribPointer(this.shader.aTextureCoord,2,t.FLOAT,!1,i,28),t.vertexAttribPointer(this.shader.colorAttribute,1,t.FLOAT,!1,i,36)},i.WebGLFilterManager=function(){this.filterStack=[],this.offsetX=0,this.offsetY=0},i.WebGLFilterManager.prototype.constructor=i.WebGLFilterManager,i.WebGLFilterManager.prototype.setContext=function(t){this.gl=t,this.texturePool=[],this.initShaderBuffers()},i.WebGLFilterManager.prototype.begin=function(t,e){this.renderSession=t,this.defaultShader=t.shaderManager.defaultShader;var i=this.renderSession.projection;this.width=2*i.x,this.height=2*-i.y,this.buffer=e},i.WebGLFilterManager.prototype.pushFilter=function(t){var e=this.gl,s=this.renderSession.projection,n=this.renderSession.offset;t._filterArea=t.target.filterArea||t.target.getBounds(),t._previous_stencil_mgr=this.renderSession.stencilManager,this.renderSession.stencilManager=new i.WebGLStencilManager,this.renderSession.stencilManager.setContext(e),e.disable(e.STENCIL_TEST),this.filterStack.push(t);var r=t.filterPasses[0];this.offsetX+=t._filterArea.x,this.offsetY+=t._filterArea.y;var o=this.texturePool.pop();o?o.resize(this.width*this.renderSession.resolution,this.height*this.renderSession.resolution):o=new i.FilterTexture(this.gl,this.width*this.renderSession.resolution,this.height*this.renderSession.resolution),e.bindTexture(e.TEXTURE_2D,o.texture);var a=t._filterArea,h=r.padding;a.x-=h,a.y-=h,a.width+=2*h,a.height+=2*h,a.x<0&&(a.x=0),a.width>this.width&&(a.width=this.width),a.y<0&&(a.y=0),a.height>this.height&&(a.height=this.height),e.bindFramebuffer(e.FRAMEBUFFER,o.frameBuffer),e.viewport(0,0,a.width*this.renderSession.resolution,a.height*this.renderSession.resolution),s.x=a.width/2,s.y=-a.height/2,n.x=-a.x,n.y=-a.y,e.colorMask(!0,!0,!0,!0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT),t._glFilterTexture=o},i.WebGLFilterManager.prototype.popFilter=function(){var t=this.gl,e=this.filterStack.pop(),s=e._filterArea,n=e._glFilterTexture,r=this.renderSession.projection,o=this.renderSession.offset;if(e.filterPasses.length>1){t.viewport(0,0,s.width*this.renderSession.resolution,s.height*this.renderSession.resolution),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),this.vertexArray[0]=0,this.vertexArray[1]=s.height,this.vertexArray[2]=s.width,this.vertexArray[3]=s.height,this.vertexArray[4]=0,this.vertexArray[5]=0,this.vertexArray[6]=s.width,this.vertexArray[7]=0,t.bufferSubData(t.ARRAY_BUFFER,0,this.vertexArray),t.bindBuffer(t.ARRAY_BUFFER,this.uvBuffer),this.uvArray[2]=s.width/this.width,this.uvArray[5]=s.height/this.height,this.uvArray[6]=s.width/this.width,this.uvArray[7]=s.height/this.height,t.bufferSubData(t.ARRAY_BUFFER,0,this.uvArray);var a=n,h=this.texturePool.pop();h||(h=new i.FilterTexture(this.gl,this.width*this.renderSession.resolution,this.height*this.renderSession.resolution)),h.resize(this.width*this.renderSession.resolution,this.height*this.renderSession.resolution),t.bindFramebuffer(t.FRAMEBUFFER,h.frameBuffer),t.clear(t.COLOR_BUFFER_BIT),t.disable(t.BLEND);for(var l=0;l<e.filterPasses.length-1;l++){var c=e.filterPasses[l];t.bindFramebuffer(t.FRAMEBUFFER,h.frameBuffer),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,a.texture),this.applyFilterPass(c,s,s.width,s.height);var u=a;a=h,h=u}t.enable(t.BLEND),n=a,this.texturePool.push(h)}var d=e.filterPasses[e.filterPasses.length-1];this.offsetX-=s.x,this.offsetY-=s.y;var p=this.width,f=this.height,g=0,m=0,y=this.buffer;if(0===this.filterStack.length)t.colorMask(!0,!0,!0,!0);else{var v=this.filterStack[this.filterStack.length-1];s=v._filterArea,p=s.width,f=s.height,g=s.x,m=s.y,y=v._glFilterTexture.frameBuffer}r.x=p/2,r.y=-f/2,o.x=g,o.y=m,s=e._filterArea;var b=s.x-g,x=s.y-m;t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),this.vertexArray[0]=b,this.vertexArray[1]=x+s.height,this.vertexArray[2]=b+s.width,this.vertexArray[3]=x+s.height,this.vertexArray[4]=b,this.vertexArray[5]=x,this.vertexArray[6]=b+s.width,this.vertexArray[7]=x,t.bufferSubData(t.ARRAY_BUFFER,0,this.vertexArray),t.bindBuffer(t.ARRAY_BUFFER,this.uvBuffer),this.uvArray[2]=s.width/this.width,this.uvArray[5]=s.height/this.height,this.uvArray[6]=s.width/this.width,this.uvArray[7]=s.height/this.height,t.bufferSubData(t.ARRAY_BUFFER,0,this.uvArray),t.viewport(0,0,p*this.renderSession.resolution,f*this.renderSession.resolution),t.bindFramebuffer(t.FRAMEBUFFER,y),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,n.texture),this.renderSession.stencilManager&&this.renderSession.stencilManager.destroy(),this.renderSession.stencilManager=e._previous_stencil_mgr,e._previous_stencil_mgr=null,this.renderSession.stencilManager.count>0?t.enable(t.STENCIL_TEST):t.disable(t.STENCIL_TEST),this.applyFilterPass(d,s,p,f),this.texturePool.push(n),e._glFilterTexture=null},i.WebGLFilterManager.prototype.applyFilterPass=function(t,e,s,n){var r=this.gl,o=t.shaders[r.id];o||(o=new i.PixiShader(r),o.fragmentSrc=t.fragmentSrc,o.uniforms=t.uniforms,o.init(),t.shaders[r.id]=o),this.renderSession.shaderManager.setShader(o),r.uniform2f(o.projectionVector,s/2,-n/2),r.uniform2f(o.offsetVector,0,0),t.uniforms.dimensions&&(t.uniforms.dimensions.value[0]=this.width,t.uniforms.dimensions.value[1]=this.height,t.uniforms.dimensions.value[2]=this.vertexArray[0],t.uniforms.dimensions.value[3]=this.vertexArray[5]),o.syncUniforms(),r.bindBuffer(r.ARRAY_BUFFER,this.vertexBuffer),r.vertexAttribPointer(o.aVertexPosition,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ARRAY_BUFFER,this.uvBuffer),r.vertexAttribPointer(o.aTextureCoord,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ARRAY_BUFFER,this.colorBuffer),r.vertexAttribPointer(o.colorAttribute,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,this.indexBuffer),r.drawElements(r.TRIANGLES,6,r.UNSIGNED_SHORT,0),this.renderSession.drawCount++},i.WebGLFilterManager.prototype.initShaderBuffers=function(){var t=this.gl;this.vertexBuffer=t.createBuffer(),this.uvBuffer=t.createBuffer(),this.colorBuffer=t.createBuffer(),this.indexBuffer=t.createBuffer(),this.vertexArray=new i.Float32Array([0,0,1,0,0,1,1,1]),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),t.bufferData(t.ARRAY_BUFFER,this.vertexArray,t.STATIC_DRAW),this.uvArray=new i.Float32Array([0,0,1,0,0,1,1,1]),t.bindBuffer(t.ARRAY_BUFFER,this.uvBuffer),t.bufferData(t.ARRAY_BUFFER,this.uvArray,t.STATIC_DRAW),this.colorArray=new i.Float32Array([1,16777215,1,16777215,1,16777215,1,16777215]),t.bindBuffer(t.ARRAY_BUFFER,this.colorBuffer),t.bufferData(t.ARRAY_BUFFER,this.colorArray,t.STATIC_DRAW),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,new Uint16Array([0,1,2,1,3,2]),t.STATIC_DRAW)},i.WebGLFilterManager.prototype.destroy=function(){var t=this.gl;this.filterStack=null,this.offsetX=0,this.offsetY=0;for(var e=0;e<this.texturePool.length;e++)this.texturePool[e].destroy();this.texturePool=null,t.deleteBuffer(this.vertexBuffer),t.deleteBuffer(this.uvBuffer),t.deleteBuffer(this.colorBuffer),t.deleteBuffer(this.indexBuffer)},i.FilterTexture=function(t,e,s,n){this.gl=t,this.frameBuffer=t.createFramebuffer(),this.texture=t.createTexture(),n=n||i.scaleModes.DEFAULT,t.bindTexture(t.TEXTURE_2D,this.texture),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,n===i.scaleModes.LINEAR?t.LINEAR:t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,n===i.scaleModes.LINEAR?t.LINEAR:t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.bindFramebuffer(t.FRAMEBUFFER,this.frameBuffer),t.bindFramebuffer(t.FRAMEBUFFER,this.frameBuffer),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,this.texture,0),this.renderBuffer=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,this.renderBuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,this.renderBuffer),this.resize(e,s)},i.FilterTexture.prototype.constructor=i.FilterTexture,i.FilterTexture.prototype.clear=function(){var t=this.gl;t.clearColor(0,0,0,0),t.clear(t.COLOR_BUFFER_BIT)},i.FilterTexture.prototype.resize=function(t,e){if(this.width!==t||this.height!==e){this.width=t,this.height=e;var i=this.gl;i.bindTexture(i.TEXTURE_2D,this.texture),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,t,e,0,i.RGBA,i.UNSIGNED_BYTE,null),i.bindRenderbuffer(i.RENDERBUFFER,this.renderBuffer),i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH_STENCIL,t,e)}},i.FilterTexture.prototype.destroy=function(){var t=this.gl;t.deleteFramebuffer(this.frameBuffer),t.deleteTexture(this.texture),this.frameBuffer=null,this.texture=null},i.CanvasBuffer=function(t,e){this.width=t,this.height=e,this.canvas=i.CanvasPool.create(this,this.width,this.height),this.context=this.canvas.getContext("2d"),this.canvas.width=t,this.canvas.height=e},i.CanvasBuffer.prototype.constructor=i.CanvasBuffer,i.CanvasBuffer.prototype.clear=function(){this.context.setTransform(1,0,0,1,0,0),this.context.clearRect(0,0,this.width,this.height)},i.CanvasBuffer.prototype.resize=function(t,e){this.width=this.canvas.width=t,this.height=this.canvas.height=e},i.CanvasBuffer.prototype.destroy=function(){i.CanvasPool.remove(this)},i.CanvasMaskManager=function(){},i.CanvasMaskManager.prototype.constructor=i.CanvasMaskManager,i.CanvasMaskManager.prototype.pushMask=function(t,e){var s=e.context;s.save();var n=t.alpha,r=t.worldTransform,o=e.resolution;s.setTransform(r.a*o,r.b*o,r.c*o,r.d*o,r.tx*o,r.ty*o),i.CanvasGraphics.renderGraphicsMask(t,s),s.clip(),t.worldAlpha=n},i.CanvasMaskManager.prototype.popMask=function(t){t.context.restore()},i.CanvasTinter=function(){},i.CanvasTinter.getTintedTexture=function(t,e){var s=t.tintedTexture||i.CanvasPool.create(this);return i.CanvasTinter.tintMethod(t.texture,e,s),s},i.CanvasTinter.tintWithMultiply=function(t,e,i){var s=i.getContext("2d"),n=t.crop;i.width===n.width&&i.height===n.height||(i.width=n.width,i.height=n.height),s.clearRect(0,0,n.width,n.height),s.fillStyle="#"+("00000"+(0|e).toString(16)).substr(-6),s.fillRect(0,0,n.width,n.height),s.globalCompositeOperation="multiply",s.drawImage(t.baseTexture.source,n.x,n.y,n.width,n.height,0,0,n.width,n.height),s.globalCompositeOperation="destination-atop",s.drawImage(t.baseTexture.source,n.x,n.y,n.width,n.height,0,0,n.width,n.height)},i.CanvasTinter.tintWithPerPixel=function(t,e,s){var n=s.getContext("2d"),r=t.crop;s.width=r.width,s.height=r.height,n.globalCompositeOperation="copy",n.drawImage(t.baseTexture.source,r.x,r.y,r.width,r.height,0,0,r.width,r.height);for(var o=i.hex2rgb(e),a=o[0],h=o[1],l=o[2],c=n.getImageData(0,0,r.width,r.height),u=c.data,d=0;d<u.length;d+=4)if(u[d+0]*=a,u[d+1]*=h,u[d+2]*=l,!i.CanvasTinter.canHandleAlpha){var p=u[d+3];u[d+0]/=255/p,u[d+1]/=255/p,u[d+2]/=255/p}n.putImageData(c,0,0)},i.CanvasTinter.checkInverseAlpha=function(){var t=new i.CanvasBuffer(2,1);t.context.fillStyle="rgba(10, 20, 30, 0.5)",t.context.fillRect(0,0,1,1);var e=t.context.getImageData(0,0,1,1);if(null===e)return!1;t.context.putImageData(e,1,0);var s=t.context.getImageData(1,0,1,1);return s.data[0]===e.data[0]&&s.data[1]===e.data[1]&&s.data[2]===e.data[2]&&s.data[3]===e.data[3]},i.CanvasTinter.canHandleAlpha=i.CanvasTinter.checkInverseAlpha(),i.CanvasTinter.canUseMultiply=i.canUseNewCanvasBlendModes(),i.CanvasTinter.tintMethod=i.CanvasTinter.canUseMultiply?i.CanvasTinter.tintWithMultiply:i.CanvasTinter.tintWithPerPixel,i.CanvasRenderer=function(t){this.game=t,i.defaultRenderer||(i.defaultRenderer=this),this.type=i.CANVAS_RENDERER,this.resolution=t.resolution,this.clearBeforeRender=t.clearBeforeRender,this.transparent=t.transparent,this.autoResize=!1,this.width=t.width*this.resolution,this.height=t.height*this.resolution,this.view=t.canvas,this.context=this.view.getContext("2d",{alpha:this.transparent}),this.refresh=!0,this.count=0,this.maskManager=new i.CanvasMaskManager,this.renderSession={context:this.context,maskManager:this.maskManager,scaleMode:null,smoothProperty:Phaser.Canvas.getSmoothingPrefix(this.context),roundPixels:!1},this.mapBlendModes(),this.resize(this.width,this.height)},i.CanvasRenderer.prototype.constructor=i.CanvasRenderer,i.CanvasRenderer.prototype.render=function(t){this.context.setTransform(1,0,0,1,0,0),this.context.globalAlpha=1,this.renderSession.currentBlendMode=0,this.renderSession.shakeX=this.game.camera._shake.x,this.renderSession.shakeY=this.game.camera._shake.y,this.context.globalCompositeOperation="source-over",navigator.isCocoonJS&&this.view.screencanvas&&(this.context.fillStyle="black",this.context.clear()),this.clearBeforeRender&&(this.transparent?this.context.clearRect(0,0,this.width,this.height):t._bgColor&&(this.context.fillStyle=t._bgColor.rgba,this.context.fillRect(0,0,this.width,this.height))),this.renderDisplayObject(t)},i.CanvasRenderer.prototype.destroy=function(t){void 0===t&&(t=!0),t&&this.view.parent&&this.view.parent.removeChild(this.view),this.view=null,this.context=null,this.maskManager=null,this.renderSession=null},i.CanvasRenderer.prototype.resize=function(t,e){this.width=t*this.resolution,this.height=e*this.resolution,this.view.width=this.width,this.view.height=this.height,this.autoResize&&(this.view.style.width=this.width/this.resolution+"px",this.view.style.height=this.height/this.resolution+"px"),this.renderSession.smoothProperty&&(this.context[this.renderSession.smoothProperty]=this.renderSession.scaleMode===i.scaleModes.LINEAR)},i.CanvasRenderer.prototype.renderDisplayObject=function(t,e,i){this.renderSession.context=e||this.context,this.renderSession.resolution=this.resolution,t._renderCanvas(this.renderSession,i)},i.CanvasRenderer.prototype.mapBlendModes=function(){if(!i.blendModesCanvas){var t=[],e=i.blendModes,s=i.canUseNewCanvasBlendModes();t[e.NORMAL]="source-over",t[e.ADD]="lighter",t[e.MULTIPLY]=s?"multiply":"source-over",t[e.SCREEN]=s?"screen":"source-over",t[e.OVERLAY]=s?"overlay":"source-over",t[e.DARKEN]=s?"darken":"source-over",t[e.LIGHTEN]=s?"lighten":"source-over",t[e.COLOR_DODGE]=s?"color-dodge":"source-over",t[e.COLOR_BURN]=s?"color-burn":"source-over",t[e.HARD_LIGHT]=s?"hard-light":"source-over",t[e.SOFT_LIGHT]=s?"soft-light":"source-over",t[e.DIFFERENCE]=s?"difference":"source-over",t[e.EXCLUSION]=s?"exclusion":"source-over",t[e.HUE]=s?"hue":"source-over",t[e.SATURATION]=s?"saturation":"source-over",t[e.COLOR]=s?"color":"source-over",t[e.LUMINOSITY]=s?"luminosity":"source-over",i.blendModesCanvas=t}},i.BaseTexture=function(t,e){this.resolution=1,this.width=100,this.height=100,this.scaleMode=e||i.scaleModes.DEFAULT,this.hasLoaded=!1,this.source=t,this.premultipliedAlpha=!0,this._glTextures=[],this.mipmap=!1,this._dirty=[!0,!0,!0,!0],t&&((this.source.complete||this.source.getContext)&&this.source.width&&this.source.height&&(this.hasLoaded=!0,this.width=this.source.naturalWidth||this.source.width,this.height=this.source.naturalHeight||this.source.height,this.dirty()),this.skipRender=!1,this._powerOf2=!1)},i.BaseTexture.prototype.constructor=i.BaseTexture,i.BaseTexture.prototype.forceLoaded=function(t,e){this.hasLoaded=!0,this.width=t,this.height=e,this.dirty()},i.BaseTexture.prototype.destroy=function(){this.source&&i.CanvasPool.removeByCanvas(this.source),this.source=null,this.unloadFromGPU()},i.BaseTexture.prototype.updateSourceImage=function(t){console.warn("PIXI.BaseTexture.updateSourceImage is deprecated. Use Phaser.Sprite.loadTexture instead.")},i.BaseTexture.prototype.dirty=function(){for(var t=0;t<this._glTextures.length;t++)this._dirty[t]=!0},i.BaseTexture.prototype.unloadFromGPU=function(){this.dirty();for(var t=this._glTextures.length-1;t>=0;t--){var e=this._glTextures[t],s=i.glContexts[t];s&&e&&s.deleteTexture(e)}this._glTextures.length=0,this.dirty()},i.BaseTexture.fromCanvas=function(t,e){return 0===t.width&&(t.width=1),0===t.height&&(t.height=1),new i.BaseTexture(t,e)},i.TextureSilentFail=!1,i.Texture=function(t,e,s,n){this.noFrame=!1,e||(this.noFrame=!0,e=new i.Rectangle(0,0,1,1)),t instanceof i.Texture&&(t=t.baseTexture),this.baseTexture=t,this.frame=e,this.trim=n,this.valid=!1,this.isTiling=!1,this.requiresUpdate=!1,this.requiresReTint=!1,this._uvs=null,this.width=0,this.height=0,this.crop=s||new i.Rectangle(0,0,1,1),t.hasLoaded&&(this.noFrame&&(e=new i.Rectangle(0,0,t.width,t.height)),this.setFrame(e))},i.Texture.prototype.constructor=i.Texture,i.Texture.prototype.onBaseTextureLoaded=function(){var t=this.baseTexture;this.noFrame&&(this.frame=new i.Rectangle(0,0,t.width,t.height)),this.setFrame(this.frame)},i.Texture.prototype.destroy=function(t){t&&this.baseTexture.destroy(),this.valid=!1},i.Texture.prototype.setFrame=function(t){if(this.noFrame=!1,this.frame=t,this.width=t.width,this.height=t.height,this.crop.x=t.x,this.crop.y=t.y,this.crop.width=t.width,this.crop.height=t.height,!this.trim&&(t.x+t.width>this.baseTexture.width||t.y+t.height>this.baseTexture.height)){if(!i.TextureSilentFail)throw new Error("Texture Error: frame does not fit inside the base Texture dimensions "+this);return void(this.valid=!1)}this.valid=t&&t.width&&t.height&&this.baseTexture.source&&this.baseTexture.hasLoaded,this.trim&&(this.width=this.trim.width,this.height=this.trim.height,this.frame.width=this.trim.width,this.frame.height=this.trim.height),this.valid&&this._updateUvs()},i.Texture.prototype._updateUvs=function(){this._uvs||(this._uvs=new i.TextureUvs);var t=this.crop,e=this.baseTexture.width,s=this.baseTexture.height;this._uvs.x0=t.x/e,this._uvs.y0=t.y/s,this._uvs.x1=(t.x+t.width)/e,this._uvs.y1=t.y/s,this._uvs.x2=(t.x+t.width)/e,this._uvs.y2=(t.y+t.height)/s,this._uvs.x3=t.x/e,this._uvs.y3=(t.y+t.height)/s},i.Texture.fromCanvas=function(t,e){var s=i.BaseTexture.fromCanvas(t,e);return new i.Texture(s)},i.TextureUvs=function(){this.x0=0,this.y0=0,this.x1=0,this.y1=0,this.x2=0,this.y2=0,this.x3=0,this.y3=0},i.RenderTexture=function(t,e,s,n,r){if(this.width=t||100,this.height=e||100,this.resolution=r||1,this.frame=new i.Rectangle(0,0,this.width*this.resolution,this.height*this.resolution),this.crop=new i.Rectangle(0,0,this.width*this.resolution,this.height*this.resolution),this.baseTexture=new i.BaseTexture,this.baseTexture.width=this.width*this.resolution,this.baseTexture.height=this.height*this.resolution,this.baseTexture._glTextures=[],this.baseTexture.resolution=this.resolution,this.baseTexture.scaleMode=n||i.scaleModes.DEFAULT,this.baseTexture.hasLoaded=!0,i.Texture.call(this,this.baseTexture,new i.Rectangle(0,0,this.width*this.resolution,this.height*this.resolution)),this.renderer=s||i.defaultRenderer,this.renderer.type===i.WEBGL_RENDERER){var o=this.renderer.gl;this.baseTexture._dirty[o.id]=!1,this.textureBuffer=new i.FilterTexture(o,this.width,this.height,this.baseTexture.scaleMode),this.baseTexture._glTextures[o.id]=this.textureBuffer.texture,this.render=this.renderWebGL,this.projection=new i.Point(.5*this.width,.5*-this.height)}else this.render=this.renderCanvas,this.textureBuffer=new i.CanvasBuffer(this.width*this.resolution,this.height*this.resolution),this.baseTexture.source=this.textureBuffer.canvas;this.valid=!0,this.tempMatrix=new Phaser.Matrix,this._updateUvs()},i.RenderTexture.prototype=Object.create(i.Texture.prototype),i.RenderTexture.prototype.constructor=i.RenderTexture,i.RenderTexture.prototype.resize=function(t,e,s){t===this.width&&e===this.height||(this.valid=t>0&&e>0,this.width=t,this.height=e,this.frame.width=this.crop.width=t*this.resolution,this.frame.height=this.crop.height=e*this.resolution,s&&(this.baseTexture.width=this.width*this.resolution,this.baseTexture.height=this.height*this.resolution),this.renderer.type===i.WEBGL_RENDERER&&(this.projection.x=this.width/2,this.projection.y=-this.height/2),this.valid&&this.textureBuffer.resize(this.width,this.height))},i.RenderTexture.prototype.clear=function(){this.valid&&(this.renderer.type===i.WEBGL_RENDERER&&this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER,this.textureBuffer.frameBuffer),this.textureBuffer.clear())},i.RenderTexture.prototype.renderWebGL=function(t,e,i){if(this.valid&&0!==t.alpha){var s=t.worldTransform;s.identity(),s.translate(0,2*this.projection.y),e&&s.append(e),s.scale(1,-1);for(var n=0;n<t.children.length;n++)t.children[n].updateTransform();var r=this.renderer.gl;r.viewport(0,0,this.width*this.resolution,this.height*this.resolution),r.bindFramebuffer(r.FRAMEBUFFER,this.textureBuffer.frameBuffer),i&&this.textureBuffer.clear(),this.renderer.spriteBatch.dirty=!0,this.renderer.renderDisplayObject(t,this.projection,this.textureBuffer.frameBuffer,e),this.renderer.spriteBatch.dirty=!0}},i.RenderTexture.prototype.renderCanvas=function(t,e,i){if(this.valid&&0!==t.alpha){var s=t.worldTransform;s.identity(),e&&s.append(e);for(var n=0;n<t.children.length;n++)t.children[n].updateTransform();i&&this.textureBuffer.clear();var r=this.renderer.resolution;this.renderer.resolution=this.resolution,this.renderer.renderDisplayObject(t,this.textureBuffer.context,e),this.renderer.resolution=r}},i.RenderTexture.prototype.getImage=function(){var t=new Image;return t.src=this.getBase64(),t},i.RenderTexture.prototype.getBase64=function(){return this.getCanvas().toDataURL()},i.RenderTexture.prototype.getCanvas=function(){if(this.renderer.type===i.WEBGL_RENDERER){var t=this.renderer.gl,e=this.textureBuffer.width,s=this.textureBuffer.height,n=new Uint8Array(4*e*s);t.bindFramebuffer(t.FRAMEBUFFER,this.textureBuffer.frameBuffer),t.readPixels(0,0,e,s,t.RGBA,t.UNSIGNED_BYTE,n),t.bindFramebuffer(t.FRAMEBUFFER,null);var r=new i.CanvasBuffer(e,s),o=r.context.getImageData(0,0,e,s);return o.data.set(n),r.context.putImageData(o,0,0),r.canvas}return this.textureBuffer.canvas},i.AbstractFilter=function(t,e){this.passes=[this],this.shaders=[],this.dirty=!0,this.padding=0,this.uniforms=e||{},this.fragmentSrc=t||[]},i.AbstractFilter.prototype.constructor=i.AbstractFilter,i.AbstractFilter.prototype.syncUniforms=function(){for(var t=0,e=this.shaders.length;t<e;t++)this.shaders[t].dirty=!0},i.Strip=function(t){i.DisplayObjectContainer.call(this),this.texture=t,this.uvs=new i.Float32Array([0,1,1,1,1,0,0,1]),this.vertices=new i.Float32Array([0,0,100,0,100,100,0,100]),this.colors=new i.Float32Array([1,1,1,1]),this.indices=new i.Uint16Array([0,1,2,3]),this.dirty=!0,this.blendMode=i.blendModes.NORMAL,this.canvasPadding=0,this.drawMode=i.Strip.DrawModes.TRIANGLE_STRIP},i.Strip.prototype=Object.create(i.DisplayObjectContainer.prototype),i.Strip.prototype.constructor=i.Strip,i.Strip.prototype._renderWebGL=function(t){!this.visible||this.alpha<=0||(t.spriteBatch.stop(),this._vertexBuffer||this._initWebGL(t),t.shaderManager.setShader(t.shaderManager.stripShader),this._renderStrip(t),t.spriteBatch.start())},i.Strip.prototype._initWebGL=function(t){var e=t.gl;this._vertexBuffer=e.createBuffer(),this._indexBuffer=e.createBuffer(),this._uvBuffer=e.createBuffer(),this._colorBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this._vertexBuffer),e.bufferData(e.ARRAY_BUFFER,this.vertices,e.DYNAMIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,this._uvBuffer),e.bufferData(e.ARRAY_BUFFER,this.uvs,e.STATIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,this._colorBuffer),e.bufferData(e.ARRAY_BUFFER,this.colors,e.STATIC_DRAW),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this._indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,this.indices,e.STATIC_DRAW)},i.Strip.prototype._renderStrip=function(t){var e=t.gl,s=t.projection,n=t.offset,r=t.shaderManager.stripShader,o=this.drawMode===i.Strip.DrawModes.TRIANGLE_STRIP?e.TRIANGLE_STRIP:e.TRIANGLES;t.blendModeManager.setBlendMode(this.blendMode),e.uniformMatrix3fv(r.translationMatrix,!1,this.worldTransform.toArray(!0)),e.uniform2f(r.projectionVector,s.x,-s.y),e.uniform2f(r.offsetVector,-n.x,-n.y),e.uniform1f(r.alpha,this.worldAlpha),this.dirty?(this.dirty=!1,e.bindBuffer(e.ARRAY_BUFFER,this._vertexBuffer),e.bufferData(e.ARRAY_BUFFER,this.vertices,e.STATIC_DRAW),e.vertexAttribPointer(r.aVertexPosition,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this._uvBuffer),e.bufferData(e.ARRAY_BUFFER,this.uvs,e.STATIC_DRAW),e.vertexAttribPointer(r.aTextureCoord,2,e.FLOAT,!1,0,0),e.activeTexture(e.TEXTURE0),this.texture.baseTexture._dirty[e.id]?t.renderer.updateTexture(this.texture.baseTexture):e.bindTexture(e.TEXTURE_2D,this.texture.baseTexture._glTextures[e.id]),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this._indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,this.indices,e.STATIC_DRAW)):(e.bindBuffer(e.ARRAY_BUFFER,this._vertexBuffer),e.bufferSubData(e.ARRAY_BUFFER,0,this.vertices),e.vertexAttribPointer(r.aVertexPosition,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this._uvBuffer),e.vertexAttribPointer(r.aTextureCoord,2,e.FLOAT,!1,0,0),e.activeTexture(e.TEXTURE0),this.texture.baseTexture._dirty[e.id]?t.renderer.updateTexture(this.texture.baseTexture):e.bindTexture(e.TEXTURE_2D,this.texture.baseTexture._glTextures[e.id]),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this._indexBuffer)),e.drawElements(o,this.indices.length,e.UNSIGNED_SHORT,0)},i.Strip.prototype._renderCanvas=function(t){var e=t.context,s=this.worldTransform,n=s.tx*t.resolution+t.shakeX,r=s.ty*t.resolution+t.shakeY;t.roundPixels?e.setTransform(s.a,s.b,s.c,s.d,0|n,0|r):e.setTransform(s.a,s.b,s.c,s.d,n,r),this.drawMode===i.Strip.DrawModes.TRIANGLE_STRIP?this._renderCanvasTriangleStrip(e):this._renderCanvasTriangles(e)},i.Strip.prototype._renderCanvasTriangleStrip=function(t){var e=this.vertices,i=this.uvs,s=e.length/2;this.count++;for(var n=0;n<s-2;n++){var r=2*n;this._renderCanvasDrawTriangle(t,e,i,r,r+2,r+4)}},i.Strip.prototype._renderCanvasTriangles=function(t){var e=this.vertices,i=this.uvs,s=this.indices,n=s.length;this.count++;for(var r=0;r<n;r+=3){var o=2*s[r],a=2*s[r+1],h=2*s[r+2];this._renderCanvasDrawTriangle(t,e,i,o,a,h)}},i.Strip.prototype._renderCanvasDrawTriangle=function(t,e,i,s,n,r){var o=this.texture.baseTexture.source,a=this.texture.width,h=this.texture.height,l=e[s],c=e[n],u=e[r],d=e[s+1],p=e[n+1],f=e[r+1],g=i[s]*a,m=i[n]*a,y=i[r]*a,v=i[s+1]*h,b=i[n+1]*h,x=i[r+1]*h;if(this.canvasPadding>0){var w=this.canvasPadding/this.worldTransform.a,_=this.canvasPadding/this.worldTransform.d,P=(l+c+u)/3,T=(d+p+f)/3,C=l-P,S=d-T,A=Math.sqrt(C*C+S*S);l=P+C/A*(A+w),d=T+S/A*(A+_),C=c-P,S=p-T,A=Math.sqrt(C*C+S*S),c=P+C/A*(A+w),p=T+S/A*(A+_),C=u-P,S=f-T,A=Math.sqrt(C*C+S*S),u=P+C/A*(A+w),f=T+S/A*(A+_)}t.save(),t.beginPath(),t.moveTo(l,d),t.lineTo(c,p),t.lineTo(u,f),t.closePath(),t.clip();var E=g*b+v*y+m*x-b*y-v*m-g*x,I=l*b+v*u+c*x-b*u-v*c-l*x,M=g*c+l*y+m*u-c*y-l*m-g*u,R=g*b*u+v*c*y+l*m*x-l*b*y-v*m*u-g*c*x,B=d*b+v*f+p*x-b*f-v*p-d*x,L=g*p+d*y+m*f-p*y-d*m-g*f,O=g*b*f+v*p*y+d*m*x-d*b*y-v*m*f-g*p*x;t.transform(I/E,B/E,M/E,L/E,R/E,O/E),t.drawImage(o,0,0),t.restore()},i.Strip.prototype.renderStripFlat=function(t){var e=this.context,i=t.vertices,s=i.length/2;this.count++,e.beginPath();for(var n=1;n<s-2;n++){var r=2*n,o=i[r],a=i[r+2],h=i[r+4],l=i[r+1],c=i[r+3],u=i[r+5];e.moveTo(o,l),e.lineTo(a,c),e.lineTo(h,u)}e.fillStyle="#FF0000",e.fill(),e.closePath()},i.Strip.prototype.onTextureUpdate=function(){this.updateFrame=!0},i.Strip.prototype.getBounds=function(t){for(var e=t||this.worldTransform,s=e.a,n=e.b,r=e.c,o=e.d,a=e.tx,h=e.ty,l=-1/0,c=-1/0,u=1/0,d=1/0,p=this.vertices,f=0,g=p.length;f<g;f+=2){var m=p[f],y=p[f+1],v=s*m+r*y+a,b=o*y+n*m+h;u=v<u?v:u,d=b<d?b:d,l=v>l?v:l,c=b>c?b:c}if(u===-1/0||c===1/0)return i.EmptyRectangle;var x=this._bounds;return x.x=u,x.width=l-u,x.y=d,x.height=c-d,this._currentBounds=x,x},i.Strip.DrawModes={TRIANGLE_STRIP:0,TRIANGLES:1},i.Rope=function(t,e){i.Strip.call(this,t),this.points=e,this.vertices=new i.Float32Array(4*e.length),this.uvs=new i.Float32Array(4*e.length),this.colors=new i.Float32Array(2*e.length),this.indices=new i.Uint16Array(2*e.length),this.refresh()},i.Rope.prototype=Object.create(i.Strip.prototype),i.Rope.prototype.constructor=i.Rope,i.Rope.prototype.refresh=function(){var t=this.points;if(!(t.length<1)){var e=this.uvs,i=(t[0],this.indices),s=this.colors;this.count-=.2,e[0]=0,e[1]=0,e[2]=0,e[3]=1,s[0]=1,s[1]=1,i[0]=0,i[1]=1;for(var n,r,o,a=t.length,h=1;h<a;h++)n=t[h],r=4*h,o=h/(a-1),e[r]=o,e[r+1]=0,e[r+2]=o,e[r+3]=1,r=2*h,s[r]=1,s[r+1]=1,r=2*h,i[r]=r,i[r+1]=r+1,n}},i.Rope.prototype.updateTransform=function(){var t=this.points;if(!(t.length<1)){var e,s=t[0],n={x:0,y:0};this.count-=.2;for(var r,o,a,h,l,c=this.vertices,u=t.length,d=0;d<u;d++)r=t[d],o=4*d,e=d<t.length-1?t[d+1]:r,n.y=-(e.x-s.x),n.x=e.y-s.y,a=10*(1-d/(u-1)),a>1&&(a=1),h=Math.sqrt(n.x*n.x+n.y*n.y),l=this.texture.height/2,n.x/=h,n.y/=h,n.x*=l,n.y*=l,c[o]=r.x+n.x,c[o+1]=r.y+n.y,c[o+2]=r.x-n.x,c[o+3]=r.y-n.y,s=r;i.DisplayObjectContainer.prototype.updateTransform.call(this)}},i.Rope.prototype.setTexture=function(t){this.texture=t},i.TilingSprite=function(t,e,s){i.Sprite.call(this,t),this._width=e||128,this._height=s||128,this.tileScale=new i.Point(1,1),this.tileScaleOffset=new i.Point(1,1),this.tilePosition=new i.Point,this.renderable=!0,this.tint=16777215,this.textureDebug=!1,this.blendMode=i.blendModes.NORMAL,this.canvasBuffer=null,this.tilingTexture=null,this.tilePattern=null,this.refreshTexture=!0,this.frameWidth=0,this.frameHeight=0},i.TilingSprite.prototype=Object.create(i.Sprite.prototype),i.TilingSprite.prototype.constructor=i.TilingSprite,i.TilingSprite.prototype.setTexture=function(t){this.texture!==t&&(this.texture=t,this.refreshTexture=!0,this.cachedTint=16777215)},i.TilingSprite.prototype._renderWebGL=function(t){if(this.visible&&this.renderable&&0!==this.alpha){if(this._mask&&(t.spriteBatch.stop(),t.maskManager.pushMask(this.mask,t),t.spriteBatch.start()),this._filters&&(t.spriteBatch.flush(),t.filterManager.pushFilter(this._filterBlock)),this.refreshTexture){if(this.generateTilingTexture(!0,t),!this.tilingTexture)return;this.tilingTexture.needsUpdate&&(t.renderer.updateTexture(this.tilingTexture.baseTexture),this.tilingTexture.needsUpdate=!1)}t.spriteBatch.renderTilingSprite(this);for(var e=0;e<this.children.length;e++)this.children[e]._renderWebGL(t);t.spriteBatch.stop(),this._filters&&t.filterManager.popFilter(),this._mask&&t.maskManager.popMask(this._mask,t),t.spriteBatch.start()}},i.TilingSprite.prototype._renderCanvas=function(t){if(this.visible&&this.renderable&&0!==this.alpha){var e=t.context;this._mask&&t.maskManager.pushMask(this._mask,t),e.globalAlpha=this.worldAlpha;var s=this.worldTransform,n=t.resolution,r=s.tx*n+t.shakeX,o=s.ty*n+t.shakeY;if(e.setTransform(s.a*n,s.b*n,s.c*n,s.d*n,r,o),this.refreshTexture){if(this.generateTilingTexture(!1,t),!this.tilingTexture)return;this.tilePattern=e.createPattern(this.tilingTexture.baseTexture.source,"repeat")}var a=t.currentBlendMode;this.blendMode!==t.currentBlendMode&&(t.currentBlendMode=this.blendMode,e.globalCompositeOperation=i.blendModesCanvas[t.currentBlendMode]);var h=this.tilePosition,l=this.tileScale;h.x%=this.tilingTexture.baseTexture.width,h.y%=this.tilingTexture.baseTexture.height,e.scale(l.x,l.y),e.translate(h.x+this.anchor.x*-this._width,h.y+this.anchor.y*-this._height),e.fillStyle=this.tilePattern;var r=-h.x,o=-h.y,c=this._width/l.x,u=this._height/l.y;t.roundPixels&&(r|=0,o|=0,c|=0,u|=0),e.fillRect(r,o,c,u),e.scale(1/l.x,1/l.y),e.translate(-h.x+this.anchor.x*this._width,-h.y+this.anchor.y*this._height),this._mask&&t.maskManager.popMask(t);for(var d=0;d<this.children.length;d++)this.children[d]._renderCanvas(t);a!==this.blendMode&&(t.currentBlendMode=a,e.globalCompositeOperation=i.blendModesCanvas[a])}},i.TilingSprite.prototype.onTextureUpdate=function(){},i.TilingSprite.prototype.generateTilingTexture=function(t,e){if(this.texture.baseTexture.hasLoaded){var s=this.texture,n=s.frame,r=this._frame.sourceSizeW||this._frame.width,o=this._frame.sourceSizeH||this._frame.height,a=0,h=0;this._frame.trimmed&&(a=this._frame.spriteSourceSizeX,h=this._frame.spriteSourceSizeY),t&&(r=i.getNextPowerOfTwo(r),o=i.getNextPowerOfTwo(o)),this.canvasBuffer?(this.canvasBuffer.resize(r,o),this.tilingTexture.baseTexture.width=r,this.tilingTexture.baseTexture.height=o,this.tilingTexture.needsUpdate=!0):(this.canvasBuffer=new i.CanvasBuffer(r,o),this.tilingTexture=i.Texture.fromCanvas(this.canvasBuffer.canvas),this.tilingTexture.isTiling=!0,this.tilingTexture.needsUpdate=!0),this.textureDebug&&(this.canvasBuffer.context.strokeStyle="#00ff00",this.canvasBuffer.context.strokeRect(0,0,r,o));var l=s.crop.width,c=s.crop.height;l===r&&c===o||(l=r,c=o),this.canvasBuffer.context.drawImage(s.baseTexture.source,s.crop.x,s.crop.y,s.crop.width,s.crop.height,a,h,l,c),this.tileScaleOffset.x=n.width/r,this.tileScaleOffset.y=n.height/o,this.refreshTexture=!1,this.tilingTexture.baseTexture._powerOf2=!0}},i.TilingSprite.prototype.getBounds=function(){var t=this._width,e=this._height,i=t*(1-this.anchor.x),s=t*-this.anchor.x,n=e*(1-this.anchor.y),r=e*-this.anchor.y,o=this.worldTransform,a=o.a,h=o.b,l=o.c,c=o.d,u=o.tx,d=o.ty,p=a*s+l*r+u,f=c*r+h*s+d,g=a*i+l*r+u,m=c*r+h*i+d,y=a*i+l*n+u,v=c*n+h*i+d,b=a*s+l*n+u,x=c*n+h*s+d,w=-1/0,_=-1/0,P=1/0,T=1/0;P=p<P?p:P,P=g<P?g:P,P=y<P?y:P,P=b<P?b:P,T=f<T?f:T,T=m<T?m:T,T=v<T?v:T,T=x<T?x:T,w=p>w?p:w,w=g>w?g:w,w=y>w?y:w,w=b>w?b:w,_=f>_?f:_,_=m>_?m:_,_=v>_?v:_,_=x>_?x:_;var C=this._bounds;return C.x=P,C.width=w-P,C.y=T,C.height=_-T,this._currentBounds=C,C},i.TilingSprite.prototype.destroy=function(){i.Sprite.prototype.destroy.call(this),this.canvasBuffer&&(this.canvasBuffer.destroy(),this.canvasBuffer=null),this.tileScale=null,this.tileScaleOffset=null,this.tilePosition=null,this.tilingTexture&&(this.tilingTexture.destroy(!0),this.tilingTexture=null)},Object.defineProperty(i.TilingSprite.prototype,"width",{get:function(){return this._width},set:function(t){this._width=t}}),Object.defineProperty(i.TilingSprite.prototype,"height",{get:function(){return this._height},set:function(t){this._height=t}}),void 0!==t&&t.exports&&(e=t.exports=i),e.PIXI=i,i}).call(this)},,,,,,,,,,function(t,e,i){t.exports=i(33)}],[102]);
<add>return i.game=null,i.WEBGL_RENDERER=0,i.CANVAS_RENDERER=1,i.VERSION="v2.2.9",i._UID=0,"undefined"!=typeof Float32Array?(i.Float32Array=Float32Array,i.Uint16Array=Uint16Array,i.Uint32Array=Uint32Array,i.ArrayBuffer=ArrayBuffer):(i.Float32Array=Array,i.Uint16Array=Array),i.PI_2=2*Math.PI,i.RAD_TO_DEG=180/Math.PI,i.DEG_TO_RAD=Math.PI/180,i.RETINA_PREFIX="@2x",i.DisplayObject=function(){this.position=new i.Point(0,0),this.scale=new i.Point(1,1),this.pivot=new i.Point(0,0),this.rotation=0,this.alpha=1,this.visible=!0,this.hitArea=null,this.renderable=!1,this.parent=null,this.worldAlpha=1,this.worldTransform=new i.Matrix,this.worldPosition=new i.Point(0,0),this.worldScale=new i.Point(1,1),this.worldRotation=0,this.filterArea=null,this._sr=0,this._cr=1,this._bounds=new i.Rectangle(0,0,0,0),this._currentBounds=null,this._mask=null,this._cacheAsBitmap=!1,this._cacheIsDirty=!1},i.DisplayObject.prototype.constructor=i.DisplayObject,i.DisplayObject.prototype={destroy:function(){if(this.children){for(var t=this.children.length;t--;)this.children[t].destroy();this.children=[]}this.hitArea=null,this.parent=null,this.worldTransform=null,this.filterArea=null,this.renderable=!1,this._bounds=null,this._currentBounds=null,this._mask=null,this._destroyCachedSprite()},updateTransform:function(t){if(!t&&!this.parent&&!this.game)return this;var e=this.parent;t?e=t:this.parent||(e=this.game.world);var s,n,r,o,a,h,l=e.worldTransform,c=this.worldTransform;return this.rotation%i.PI_2?(this.rotation!==this.rotationCache&&(this.rotationCache=this.rotation,this._sr=Math.sin(this.rotation),this._cr=Math.cos(this.rotation)),s=this._cr*this.scale.x,n=this._sr*this.scale.x,r=-this._sr*this.scale.y,o=this._cr*this.scale.y,a=this.position.x,h=this.position.y,(this.pivot.x||this.pivot.y)&&(a-=this.pivot.x*s+this.pivot.y*r,h-=this.pivot.x*n+this.pivot.y*o),c.a=s*l.a+n*l.c,c.b=s*l.b+n*l.d,c.c=r*l.a+o*l.c,c.d=r*l.b+o*l.d,c.tx=a*l.a+h*l.c+l.tx,c.ty=a*l.b+h*l.d+l.ty):(s=this.scale.x,o=this.scale.y,a=this.position.x-this.pivot.x*s,h=this.position.y-this.pivot.y*o,c.a=s*l.a,c.b=s*l.b,c.c=o*l.c,c.d=o*l.d,c.tx=a*l.a+h*l.c+l.tx,c.ty=a*l.b+h*l.d+l.ty),this.worldAlpha=this.alpha*e.worldAlpha,this.worldPosition.set(c.tx,c.ty),this.worldScale.set(this.scale.x*Math.sqrt(c.a*c.a+c.c*c.c),this.scale.y*Math.sqrt(c.b*c.b+c.d*c.d)),this.worldRotation=Math.atan2(-c.c,c.d),this._currentBounds=null,this.transformCallback&&this.transformCallback.call(this.transformCallbackContext,c,l),this},preUpdate:function(){},generateTexture:function(t,e,s){var n=this.getLocalBounds(),r=new i.RenderTexture(0|n.width,0|n.height,s,e,t);return i.DisplayObject._tempMatrix.tx=-n.x,i.DisplayObject._tempMatrix.ty=-n.y,r.render(this,i.DisplayObject._tempMatrix),r},updateCache:function(){return this._generateCachedSprite(),this},toGlobal:function(t){return this.updateTransform(),this.worldTransform.apply(t)},toLocal:function(t,e){return e&&(t=e.toGlobal(t)),this.updateTransform(),this.worldTransform.applyInverse(t)},_renderCachedSprite:function(t){this._cachedSprite.worldAlpha=this.worldAlpha,t.gl?i.Sprite.prototype._renderWebGL.call(this._cachedSprite,t):i.Sprite.prototype._renderCanvas.call(this._cachedSprite,t)},_generateCachedSprite:function(){this._cacheAsBitmap=!1;var t=this.getLocalBounds();if(t.width=Math.max(1,Math.ceil(t.width)),t.height=Math.max(1,Math.ceil(t.height)),this.updateTransform(),this._cachedSprite)this._cachedSprite.texture.resize(t.width,t.height);else{var e=new i.RenderTexture(t.width,t.height);this._cachedSprite=new i.Sprite(e),this._cachedSprite.worldTransform=this.worldTransform}var s=this._filters;this._filters=null,this._cachedSprite.filters=s,i.DisplayObject._tempMatrix.tx=-t.x,i.DisplayObject._tempMatrix.ty=-t.y,this._cachedSprite.texture.render(this,i.DisplayObject._tempMatrix,!0),this._cachedSprite.anchor.x=-t.x/t.width,this._cachedSprite.anchor.y=-t.y/t.height,this._filters=s,this._cacheAsBitmap=!0},_destroyCachedSprite:function(){this._cachedSprite&&(this._cachedSprite.texture.destroy(!0),this._cachedSprite=null)}},i.DisplayObject.prototype.displayObjectUpdateTransform=i.DisplayObject.prototype.updateTransform,Object.defineProperties(i.DisplayObject.prototype,{x:{get:function(){return this.position.x},set:function(t){this.position.x=t}},y:{get:function(){return this.position.y},set:function(t){this.position.y=t}},worldVisible:{get:function(){if(this.visible){var t=this.parent;if(!t)return this.visible;do{if(!t.visible)return!1;t=t.parent}while(t);return!0}return!1}},mask:{get:function(){return this._mask},set:function(t){this._mask&&(this._mask.isMask=!1),this._mask=t,t&&(this._mask.isMask=!0)}},filters:{get:function(){return this._filters},set:function(t){if(Array.isArray(t)){for(var e=[],s=0;s<t.length;s++)for(var n=t[s].passes,r=0;r<n.length;r++)e.push(n[r]);this._filterBlock={target:this,filterPasses:e}}this._filters=t,this.blendMode&&this.blendMode===i.blendModes.MULTIPLY&&(this.blendMode=i.blendModes.NORMAL)}},cacheAsBitmap:{get:function(){return this._cacheAsBitmap},set:function(t){this._cacheAsBitmap!==t&&(t?this._generateCachedSprite():this._destroyCachedSprite(),this._cacheAsBitmap=t)}}}),i.DisplayObjectContainer=function(){i.DisplayObject.call(this),this.children=[],this.ignoreChildInput=!1},i.DisplayObjectContainer.prototype=Object.create(i.DisplayObject.prototype),i.DisplayObjectContainer.prototype.constructor=i.DisplayObjectContainer,i.DisplayObjectContainer.prototype.addChild=function(t){return this.addChildAt(t,this.children.length)},i.DisplayObjectContainer.prototype.addChildAt=function(t,e){if(e>=0&&e<=this.children.length)return t.parent&&t.parent.removeChild(t),t.parent=this,this.children.splice(e,0,t),t;throw new Error(t+"addChildAt: The index "+e+" supplied is out of bounds "+this.children.length)},i.DisplayObjectContainer.prototype.swapChildren=function(t,e){if(t!==e){var i=this.getChildIndex(t),s=this.getChildIndex(e);if(i<0||s<0)throw new Error("swapChildren: Both the supplied DisplayObjects must be a child of the caller.");this.children[i]=e,this.children[s]=t}},i.DisplayObjectContainer.prototype.getChildIndex=function(t){var e=this.children.indexOf(t);if(-1===e)throw new Error("The supplied DisplayObject must be a child of the caller");return e},i.DisplayObjectContainer.prototype.setChildIndex=function(t,e){if(e<0||e>=this.children.length)throw new Error("The supplied index is out of bounds");var i=this.getChildIndex(t);this.children.splice(i,1),this.children.splice(e,0,t)},i.DisplayObjectContainer.prototype.getChildAt=function(t){if(t<0||t>=this.children.length)throw new Error("getChildAt: Supplied index "+t+" does not exist in the child list, or the supplied DisplayObject must be a child of the caller");return this.children[t]},i.DisplayObjectContainer.prototype.removeChild=function(t){var e=this.children.indexOf(t);if(-1!==e)return this.removeChildAt(e)},i.DisplayObjectContainer.prototype.removeChildAt=function(t){var e=this.getChildAt(t);return e&&(e.parent=void 0,this.children.splice(t,1)),e},i.DisplayObjectContainer.prototype.removeChildren=function(t,e){void 0===t&&(t=0),void 0===e&&(e=this.children.length);var i=e-t;if(i>0&&i<=e){for(var s=this.children.splice(begin,i),n=0;n<s.length;n++){s[n].parent=void 0}return s}if(0===i&&0===this.children.length)return[];throw new Error("removeChildren: Range Error, numeric values are outside the acceptable range")},i.DisplayObjectContainer.prototype.updateTransform=function(){if(this.visible&&(this.displayObjectUpdateTransform(),!this._cacheAsBitmap))for(var t=0;t<this.children.length;t++)this.children[t].updateTransform()},i.DisplayObjectContainer.prototype.displayObjectContainerUpdateTransform=i.DisplayObjectContainer.prototype.updateTransform,i.DisplayObjectContainer.prototype.getBounds=function(t){var e=t&&t instanceof i.DisplayObject,s=!0;e?s=t instanceof i.DisplayObjectContainer&&t.contains(this):t=this;var n;if(e){var r=t.worldTransform;for(t.worldTransform=i.identityMatrix,n=0;n<t.children.length;n++)t.children[n].updateTransform()}var o,a,h,l=1/0,c=1/0,u=-1/0,d=-1/0,p=!1;for(n=0;n<this.children.length;n++){this.children[n].visible&&(p=!0,o=this.children[n].getBounds(),l=l<o.x?l:o.x,c=c<o.y?c:o.y,a=o.width+o.x,h=o.height+o.y,u=u>a?u:a,d=d>h?d:h)}var f=this._bounds;if(!p){f=new i.Rectangle;var g=f.x,m=f.width+f.x,y=f.y,v=f.height+f.y,b=this.worldTransform,x=b.a,w=b.b,_=b.c,P=b.d,T=b.tx,C=b.ty,S=x*m+_*v+T,A=P*v+w*m+C,E=x*g+_*v+T,I=P*v+w*g+C,M=x*g+_*y+T,R=P*y+w*g+C,B=x*m+_*y+T,L=P*y+w*m+C;u=S,d=A,l=S,c=A,l=E<l?E:l,l=M<l?M:l,l=B<l?B:l,c=I<c?I:c,c=R<c?R:c,c=L<c?L:c,u=E>u?E:u,u=M>u?M:u,u=B>u?B:u,d=I>d?I:d,d=R>d?R:d,d=L>d?L:d}if(f.x=l,f.y=c,f.width=u-l,f.height=d-c,e)for(t.worldTransform=r,n=0;n<t.children.length;n++)t.children[n].updateTransform();if(!s){var k=t.getBounds();f.x-=k.x,f.y-=k.y}return f},i.DisplayObjectContainer.prototype.getLocalBounds=function(){return this.getBounds(this)},i.DisplayObjectContainer.prototype.contains=function(t){return!!t&&(t===this||this.contains(t.parent))},i.DisplayObjectContainer.prototype._renderWebGL=function(t){if(this.visible&&!(this.alpha<=0)){if(this._cacheAsBitmap)return void this._renderCachedSprite(t);var e;if(this._mask||this._filters){for(this._filters&&(t.spriteBatch.flush(),t.filterManager.pushFilter(this._filterBlock)),this._mask&&(t.spriteBatch.stop(),t.maskManager.pushMask(this.mask,t),t.spriteBatch.start()),e=0;e<this.children.length;e++)this.children[e]._renderWebGL(t);t.spriteBatch.stop(),this._mask&&t.maskManager.popMask(this._mask,t),this._filters&&t.filterManager.popFilter(),t.spriteBatch.start()}else for(e=0;e<this.children.length;e++)this.children[e]._renderWebGL(t)}},i.DisplayObjectContainer.prototype._renderCanvas=function(t){if(!1!==this.visible&&0!==this.alpha){if(this._cacheAsBitmap)return void this._renderCachedSprite(t);this._mask&&t.maskManager.pushMask(this._mask,t);for(var e=0;e<this.children.length;e++)this.children[e]._renderCanvas(t);this._mask&&t.maskManager.popMask(t)}},Object.defineProperty(i.DisplayObjectContainer.prototype,"width",{get:function(){return this.getLocalBounds().width*this.scale.x},set:function(t){var e=this.getLocalBounds().width;this.scale.x=0!==e?t/e:1,this._width=t}}),Object.defineProperty(i.DisplayObjectContainer.prototype,"height",{get:function(){return this.getLocalBounds().height*this.scale.y},set:function(t){var e=this.getLocalBounds().height;this.scale.y=0!==e?t/e:1,this._height=t}}),i.Sprite=function(t){i.DisplayObjectContainer.call(this),this.anchor=new i.Point,this.texture=t||i.Texture.emptyTexture,this._width=0,this._height=0,this.tint=16777215,this.cachedTint=-1,this.tintedTexture=null,this.blendMode=i.blendModes.NORMAL,this.shader=null,this.exists=!0,this.texture.baseTexture.hasLoaded&&this.onTextureUpdate(),this.renderable=!0},i.Sprite.prototype=Object.create(i.DisplayObjectContainer.prototype),i.Sprite.prototype.constructor=i.Sprite,Object.defineProperty(i.Sprite.prototype,"width",{get:function(){return this.scale.x*this.texture.frame.width},set:function(t){this.scale.x=t/this.texture.frame.width,this._width=t}}),Object.defineProperty(i.Sprite.prototype,"height",{get:function(){return this.scale.y*this.texture.frame.height},set:function(t){this.scale.y=t/this.texture.frame.height,this._height=t}}),i.Sprite.prototype.setTexture=function(t,e){void 0!==e&&this.texture.baseTexture.destroy(),this.texture.baseTexture.skipRender=!1,this.texture=t,this.texture.valid=!0,this.cachedTint=-1},i.Sprite.prototype.onTextureUpdate=function(){this._width&&(this.scale.x=this._width/this.texture.frame.width),this._height&&(this.scale.y=this._height/this.texture.frame.height)},i.Sprite.prototype.getBounds=function(t){var e=this.texture.frame.width,i=this.texture.frame.height,s=e*(1-this.anchor.x),n=e*-this.anchor.x,r=i*(1-this.anchor.y),o=i*-this.anchor.y,a=t||this.worldTransform,h=a.a,l=a.b,c=a.c,u=a.d,d=a.tx,p=a.ty,f=-1/0,g=-1/0,m=1/0,y=1/0;if(0===l&&0===c){if(h<0){h*=-1;var v=s;s=-n,n=-v}if(u<0){u*=-1;var v=r;r=-o,o=-v}m=h*n+d,f=h*s+d,y=u*o+p,g=u*r+p}else{var b=h*n+c*o+d,x=u*o+l*n+p,w=h*s+c*o+d,_=u*o+l*s+p,P=h*s+c*r+d,T=u*r+l*s+p,C=h*n+c*r+d,S=u*r+l*n+p;m=b<m?b:m,m=w<m?w:m,m=P<m?P:m,m=C<m?C:m,y=x<y?x:y,y=_<y?_:y,y=T<y?T:y,y=S<y?S:y,f=b>f?b:f,f=w>f?w:f,f=P>f?P:f,f=C>f?C:f,g=x>g?x:g,g=_>g?_:g,g=T>g?T:g,g=S>g?S:g}var A=this._bounds;return A.x=m,A.width=f-m,A.y=y,A.height=g-y,this._currentBounds=A,A},i.Sprite.prototype.getLocalBounds=function(){var t=this.worldTransform;this.worldTransform=i.identityMatrix;for(var e=0;e<this.children.length;e++)this.children[e].updateTransform();var s=this.getBounds();for(this.worldTransform=t,e=0;e<this.children.length;e++)this.children[e].updateTransform();return s},i.Sprite.prototype._renderWebGL=function(t,e){if(this.visible&&!(this.alpha<=0)&&this.renderable){var i=this.worldTransform;if(e&&(i=e),this._mask||this._filters){var s=t.spriteBatch;this._filters&&(s.flush(),t.filterManager.pushFilter(this._filterBlock)),this._mask&&(s.stop(),t.maskManager.pushMask(this.mask,t),s.start()),s.render(this);for(var n=0;n<this.children.length;n++)this.children[n]._renderWebGL(t);s.stop(),this._mask&&t.maskManager.popMask(this._mask,t),this._filters&&t.filterManager.popFilter(),s.start()}else{t.spriteBatch.render(this);for(var n=0;n<this.children.length;n++)this.children[n]._renderWebGL(t,i)}}},i.Sprite.prototype._renderCanvas=function(t,e){if(!(!this.visible||0===this.alpha||!this.renderable||this.texture.crop.width<=0||this.texture.crop.height<=0)){var s=this.worldTransform;if(e&&(s=e),this.blendMode!==t.currentBlendMode&&(t.currentBlendMode=this.blendMode,t.context.globalCompositeOperation=i.blendModesCanvas[t.currentBlendMode]),this._mask&&t.maskManager.pushMask(this._mask,t),this.texture.valid){var n=this.texture.baseTexture.resolution/t.resolution;t.context.globalAlpha=this.worldAlpha,t.smoothProperty&&t.scaleMode!==this.texture.baseTexture.scaleMode&&(t.scaleMode=this.texture.baseTexture.scaleMode,t.context[t.smoothProperty]=t.scaleMode===i.scaleModes.LINEAR);var r=this.texture.trim?this.texture.trim.x-this.anchor.x*this.texture.trim.width:this.anchor.x*-this.texture.frame.width,o=this.texture.trim?this.texture.trim.y-this.anchor.y*this.texture.trim.height:this.anchor.y*-this.texture.frame.height,a=s.tx*t.resolution+t.shakeX,h=s.ty*t.resolution+t.shakeY;t.roundPixels?(t.context.setTransform(s.a,s.b,s.c,s.d,0|a,0|h),r|=0,o|=0):t.context.setTransform(s.a,s.b,s.c,s.d,a,h);var l=this.texture.crop.width,c=this.texture.crop.height;if(r/=n,o/=n,16777215!==this.tint)(this.texture.requiresReTint||this.cachedTint!==this.tint)&&(this.tintedTexture=i.CanvasTinter.getTintedTexture(this,this.tint),this.cachedTint=this.tint,this.texture.requiresReTint=!1),t.context.drawImage(this.tintedTexture,0,0,l,c,r,o,l/n,c/n);else{var u=this.texture.crop.x,d=this.texture.crop.y;t.context.drawImage(this.texture.baseTexture.source,u,d,l,c,r,o,l/n,c/n)}}for(var p=0;p<this.children.length;p++)this.children[p]._renderCanvas(t);this._mask&&t.maskManager.popMask(t)}},i.SpriteBatch=function(t){i.DisplayObjectContainer.call(this),this.textureThing=t,this.ready=!1},i.SpriteBatch.prototype=Object.create(i.DisplayObjectContainer.prototype),i.SpriteBatch.prototype.constructor=i.SpriteBatch,i.SpriteBatch.prototype.initWebGL=function(t){this.fastSpriteBatch=new i.WebGLFastSpriteBatch(t),this.ready=!0},i.SpriteBatch.prototype.updateTransform=function(){this.displayObjectUpdateTransform()},i.SpriteBatch.prototype._renderWebGL=function(t){!this.visible||this.alpha<=0||!this.children.length||(this.ready||this.initWebGL(t.gl),this.fastSpriteBatch.gl!==t.gl&&this.fastSpriteBatch.setContext(t.gl),t.spriteBatch.stop(),t.shaderManager.setShader(t.shaderManager.fastShader),this.fastSpriteBatch.begin(this,t),this.fastSpriteBatch.render(this),t.spriteBatch.start())},i.SpriteBatch.prototype._renderCanvas=function(t){if(this.visible&&!(this.alpha<=0)&&this.children.length){var e=t.context;e.globalAlpha=this.worldAlpha,this.displayObjectUpdateTransform();for(var i=this.worldTransform,s=!0,n=0;n<this.children.length;n++){var r=this.children[n];if(r.visible){var o=r.texture,a=o.frame;if(e.globalAlpha=this.worldAlpha*r.alpha,r.rotation%(2*Math.PI)==0)s&&(e.setTransform(i.a,i.b,i.c,i.d,i.tx,i.ty),s=!1),e.drawImage(o.baseTexture.source,a.x,a.y,a.width,a.height,r.anchor.x*(-a.width*r.scale.x)+r.position.x+.5+t.shakeX|0,r.anchor.y*(-a.height*r.scale.y)+r.position.y+.5+t.shakeY|0,a.width*r.scale.x,a.height*r.scale.y);else{s||(s=!0),r.displayObjectUpdateTransform();var h=r.worldTransform,l=h.tx*t.resolution+t.shakeX,c=h.ty*t.resolution+t.shakeY;t.roundPixels?e.setTransform(h.a,h.b,h.c,h.d,0|l,0|c):e.setTransform(h.a,h.b,h.c,h.d,l,c),e.drawImage(o.baseTexture.source,a.x,a.y,a.width,a.height,r.anchor.x*-a.width+.5|0,r.anchor.y*-a.height+.5|0,a.width,a.height)}}}}},i.hex2rgb=function(t){return[(t>>16&255)/255,(t>>8&255)/255,(255&t)/255]},i.rgb2hex=function(t){return(255*t[0]<<16)+(255*t[1]<<8)+255*t[2]},i.canUseNewCanvasBlendModes=function(){if(void 0===document)return!1;var t="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAABAQMAAADD8p2OAAAAA1BMVEX/",e="AAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJggg==",s=new Image;s.src=t+"AP804Oa6"+e;var n=new Image;n.src=t+"/wCKxvRF"+e;var r=i.CanvasPool.create(this,6,1),o=r.getContext("2d");if(o.globalCompositeOperation="multiply",o.drawImage(s,0,0),o.drawImage(n,2,0),!o.getImageData(2,0,1,1))return!1;var a=o.getImageData(2,0,1,1).data;return i.CanvasPool.remove(this),255===a[0]&&0===a[1]&&0===a[2]},i.getNextPowerOfTwo=function(t){if(t>0&&0==(t&t-1))return t;for(var e=1;e<t;)e<<=1;return e},i.isPowerOfTwo=function(t,e){return t>0&&0==(t&t-1)&&e>0&&0==(e&e-1)},i.CanvasPool={create:function(t,e,s){var n,r=i.CanvasPool.getFirst();if(-1===r){var o={parent:t,canvas:document.createElement("canvas")};i.CanvasPool.pool.push(o),n=o.canvas}else i.CanvasPool.pool[r].parent=t,n=i.CanvasPool.pool[r].canvas;return void 0!==e&&(n.width=e,n.height=s),n},getFirst:function(){for(var t=i.CanvasPool.pool,e=0;e<t.length;e++)if(!t[e].parent)return e;return-1},remove:function(t){for(var e=i.CanvasPool.pool,s=0;s<e.length;s++)e[s].parent===t&&(e[s].parent=null,e[s].canvas.width=1,e[s].canvas.height=1)},removeByCanvas:function(t){for(var e=i.CanvasPool.pool,s=0;s<e.length;s++)e[s].canvas===t&&(e[s].parent=null,e[s].canvas.width=1,e[s].canvas.height=1)},getTotal:function(){for(var t=i.CanvasPool.pool,e=0,s=0;s<t.length;s++)t[s].parent&&e++;return e},getFree:function(){for(var t=i.CanvasPool.pool,e=0,s=0;s<t.length;s++)t[s].parent||e++;return e}},i.CanvasPool.pool=[],i.initDefaultShaders=function(){},i.CompileVertexShader=function(t,e){return i._CompileShader(t,e,t.VERTEX_SHADER)},i.CompileFragmentShader=function(t,e){return i._CompileShader(t,e,t.FRAGMENT_SHADER)},i._CompileShader=function(t,e,i){var s=e;Array.isArray(e)&&(s=e.join("\n"));var n=t.createShader(i);return t.shaderSource(n,s),t.compileShader(n),t.getShaderParameter(n,t.COMPILE_STATUS)?n:(window.console.log(t.getShaderInfoLog(n)),null)},i.compileProgram=function(t,e,s){var n=i.CompileFragmentShader(t,s),r=i.CompileVertexShader(t,e),o=t.createProgram();return t.attachShader(o,r),t.attachShader(o,n),t.linkProgram(o),t.getProgramParameter(o,t.LINK_STATUS)||(window.console.log(t.getProgramInfoLog(o)),window.console.log("Could not initialise shaders")),o},i.PixiShader=function(t){this._UID=i._UID++,this.gl=t,this.program=null,this.fragmentSrc=["precision lowp float;","varying vec2 vTextureCoord;","varying vec4 vColor;","uniform sampler2D uSampler;","void main(void) {"," gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;","}"],this.textureCount=0,this.firstRun=!0,this.dirty=!0,this.attributes=[],this.init()},i.PixiShader.prototype.constructor=i.PixiShader,i.PixiShader.prototype.init=function(){var t=this.gl,e=i.compileProgram(t,this.vertexSrc||i.PixiShader.defaultVertexSrc,this.fragmentSrc);t.useProgram(e),this.uSampler=t.getUniformLocation(e,"uSampler"),this.projectionVector=t.getUniformLocation(e,"projectionVector"),this.offsetVector=t.getUniformLocation(e,"offsetVector"),this.dimensions=t.getUniformLocation(e,"dimensions"),this.aVertexPosition=t.getAttribLocation(e,"aVertexPosition"),this.aTextureCoord=t.getAttribLocation(e,"aTextureCoord"),this.colorAttribute=t.getAttribLocation(e,"aColor"),-1===this.colorAttribute&&(this.colorAttribute=2),this.attributes=[this.aVertexPosition,this.aTextureCoord,this.colorAttribute];for(var s in this.uniforms)this.uniforms[s].uniformLocation=t.getUniformLocation(e,s);this.initUniforms(),this.program=e},i.PixiShader.prototype.initUniforms=function(){this.textureCount=1;var t,e=this.gl;for(var i in this.uniforms){t=this.uniforms[i];var s=t.type;"sampler2D"===s?(t._init=!1,null!==t.value&&this.initSampler2D(t)):"mat2"===s||"mat3"===s||"mat4"===s?(t.glMatrix=!0,t.glValueLength=1,"mat2"===s?t.glFunc=e.uniformMatrix2fv:"mat3"===s?t.glFunc=e.uniformMatrix3fv:"mat4"===s&&(t.glFunc=e.uniformMatrix4fv)):(t.glFunc=e["uniform"+s],t.glValueLength="2f"===s||"2i"===s?2:"3f"===s||"3i"===s?3:"4f"===s||"4i"===s?4:1)}},i.PixiShader.prototype.initSampler2D=function(t){if(t.value&&t.value.baseTexture&&t.value.baseTexture.hasLoaded){var e=this.gl;if(e.activeTexture(e["TEXTURE"+this.textureCount]),e.bindTexture(e.TEXTURE_2D,t.value.baseTexture._glTextures[e.id]),t.textureData){var i=t.textureData,s=i.magFilter?i.magFilter:e.LINEAR,n=i.minFilter?i.minFilter:e.LINEAR,r=i.wrapS?i.wrapS:e.CLAMP_TO_EDGE,o=i.wrapT?i.wrapT:e.CLAMP_TO_EDGE,a=i.luminance?e.LUMINANCE:e.RGBA;if(i.repeat&&(r=e.REPEAT,o=e.REPEAT),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!!i.flipY),i.width){var h=i.width?i.width:512,l=i.height?i.height:2,c=i.border?i.border:0;e.texImage2D(e.TEXTURE_2D,0,a,h,l,c,a,e.UNSIGNED_BYTE,null)}else e.texImage2D(e.TEXTURE_2D,0,a,e.RGBA,e.UNSIGNED_BYTE,t.value.baseTexture.source);e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,s),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,n),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,r),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,o)}e.uniform1i(t.uniformLocation,this.textureCount),t._init=!0,this.textureCount++}},i.PixiShader.prototype.syncUniforms=function(){this.textureCount=1;var t,e=this.gl;for(var s in this.uniforms)t=this.uniforms[s],1===t.glValueLength?!0===t.glMatrix?t.glFunc.call(e,t.uniformLocation,t.transpose,t.value):t.glFunc.call(e,t.uniformLocation,t.value):2===t.glValueLength?t.glFunc.call(e,t.uniformLocation,t.value.x,t.value.y):3===t.glValueLength?t.glFunc.call(e,t.uniformLocation,t.value.x,t.value.y,t.value.z):4===t.glValueLength?t.glFunc.call(e,t.uniformLocation,t.value.x,t.value.y,t.value.z,t.value.w):"sampler2D"===t.type&&(t._init?(e.activeTexture(e["TEXTURE"+this.textureCount]),t.value.baseTexture._dirty[e.id]?i.instances[e.id].updateTexture(t.value.baseTexture):e.bindTexture(e.TEXTURE_2D,t.value.baseTexture._glTextures[e.id]),e.uniform1i(t.uniformLocation,this.textureCount),this.textureCount++):this.initSampler2D(t))},i.PixiShader.prototype.destroy=function(){this.gl.deleteProgram(this.program),this.uniforms=null,this.gl=null,this.attributes=null},i.PixiShader.defaultVertexSrc=["attribute vec2 aVertexPosition;","attribute vec2 aTextureCoord;","attribute vec4 aColor;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","varying vec2 vTextureCoord;","varying vec4 vColor;","const vec2 center = vec2(-1.0, 1.0);","void main(void) {"," gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);"," vTextureCoord = aTextureCoord;"," vColor = vec4(aColor.rgb * aColor.a, aColor.a);","}"],i.PixiFastShader=function(t){this._UID=i._UID++,this.gl=t,this.program=null,this.fragmentSrc=["precision lowp float;","varying vec2 vTextureCoord;","varying float vColor;","uniform sampler2D uSampler;","void main(void) {"," gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;","}"],this.vertexSrc=["attribute vec2 aVertexPosition;","attribute vec2 aPositionCoord;","attribute vec2 aScale;","attribute float aRotation;","attribute vec2 aTextureCoord;","attribute float aColor;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","uniform mat3 uMatrix;","varying vec2 vTextureCoord;","varying float vColor;","const vec2 center = vec2(-1.0, 1.0);","void main(void) {"," vec2 v;"," vec2 sv = aVertexPosition * aScale;"," v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);"," v.y = (sv.x) * sin(aRotation) + (sv.y) * cos(aRotation);"," v = ( uMatrix * vec3(v + aPositionCoord , 1.0) ).xy ;"," gl_Position = vec4( ( v / projectionVector) + center , 0.0, 1.0);"," vTextureCoord = aTextureCoord;"," vColor = aColor;","}"],this.textureCount=0,this.init()},i.PixiFastShader.prototype.constructor=i.PixiFastShader,i.PixiFastShader.prototype.init=function(){var t=this.gl,e=i.compileProgram(t,this.vertexSrc,this.fragmentSrc);t.useProgram(e),this.uSampler=t.getUniformLocation(e,"uSampler"),this.projectionVector=t.getUniformLocation(e,"projectionVector"),this.offsetVector=t.getUniformLocation(e,"offsetVector"),this.dimensions=t.getUniformLocation(e,"dimensions"),this.uMatrix=t.getUniformLocation(e,"uMatrix"),this.aVertexPosition=t.getAttribLocation(e,"aVertexPosition"),this.aPositionCoord=t.getAttribLocation(e,"aPositionCoord"),this.aScale=t.getAttribLocation(e,"aScale"),this.aRotation=t.getAttribLocation(e,"aRotation"),this.aTextureCoord=t.getAttribLocation(e,"aTextureCoord"),this.colorAttribute=t.getAttribLocation(e,"aColor"),-1===this.colorAttribute&&(this.colorAttribute=2),this.attributes=[this.aVertexPosition,this.aPositionCoord,this.aScale,this.aRotation,this.aTextureCoord,this.colorAttribute],this.program=e},i.PixiFastShader.prototype.destroy=function(){this.gl.deleteProgram(this.program),this.uniforms=null,this.gl=null,this.attributes=null},i.StripShader=function(t){this._UID=i._UID++,this.gl=t,this.program=null,this.fragmentSrc=["precision mediump float;","varying vec2 vTextureCoord;","uniform float alpha;","uniform sampler2D uSampler;","void main(void) {"," gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;","}"],this.vertexSrc=["attribute vec2 aVertexPosition;","attribute vec2 aTextureCoord;","uniform mat3 translationMatrix;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","varying vec2 vTextureCoord;","void main(void) {"," vec3 v = translationMatrix * vec3(aVertexPosition , 1.0);"," v -= offsetVector.xyx;"," gl_Position = vec4( v.x / projectionVector.x -1.0, v.y / -projectionVector.y + 1.0 , 0.0, 1.0);"," vTextureCoord = aTextureCoord;","}"],this.init()},i.StripShader.prototype.constructor=i.StripShader,i.StripShader.prototype.init=function(){var t=this.gl,e=i.compileProgram(t,this.vertexSrc,this.fragmentSrc);t.useProgram(e),this.uSampler=t.getUniformLocation(e,"uSampler"),this.projectionVector=t.getUniformLocation(e,"projectionVector"),this.offsetVector=t.getUniformLocation(e,"offsetVector"),this.colorAttribute=t.getAttribLocation(e,"aColor"),this.aVertexPosition=t.getAttribLocation(e,"aVertexPosition"),this.aTextureCoord=t.getAttribLocation(e,"aTextureCoord"),this.attributes=[this.aVertexPosition,this.aTextureCoord],this.translationMatrix=t.getUniformLocation(e,"translationMatrix"),this.alpha=t.getUniformLocation(e,"alpha"),this.program=e},i.StripShader.prototype.destroy=function(){this.gl.deleteProgram(this.program),this.uniforms=null,this.gl=null,this.attribute=null},i.PrimitiveShader=function(t){this._UID=i._UID++,this.gl=t,this.program=null,this.fragmentSrc=["precision mediump float;","varying vec4 vColor;","void main(void) {"," gl_FragColor = vColor;","}"],this.vertexSrc=["attribute vec2 aVertexPosition;","attribute vec4 aColor;","uniform mat3 translationMatrix;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","uniform float alpha;","uniform float flipY;","uniform vec3 tint;","varying vec4 vColor;","void main(void) {"," vec3 v = translationMatrix * vec3(aVertexPosition , 1.0);"," v -= offsetVector.xyx;"," gl_Position = vec4( v.x / projectionVector.x -1.0, (v.y / projectionVector.y * -flipY) + flipY , 0.0, 1.0);"," vColor = aColor * vec4(tint * alpha, alpha);","}"],this.init()},i.PrimitiveShader.prototype.constructor=i.PrimitiveShader,i.PrimitiveShader.prototype.init=function(){var t=this.gl,e=i.compileProgram(t,this.vertexSrc,this.fragmentSrc);t.useProgram(e),this.projectionVector=t.getUniformLocation(e,"projectionVector"),this.offsetVector=t.getUniformLocation(e,"offsetVector"),this.tintColor=t.getUniformLocation(e,"tint"),this.flipY=t.getUniformLocation(e,"flipY"),this.aVertexPosition=t.getAttribLocation(e,"aVertexPosition"),this.colorAttribute=t.getAttribLocation(e,"aColor"),this.attributes=[this.aVertexPosition,this.colorAttribute],this.translationMatrix=t.getUniformLocation(e,"translationMatrix"),this.alpha=t.getUniformLocation(e,"alpha"),this.program=e},i.PrimitiveShader.prototype.destroy=function(){this.gl.deleteProgram(this.program),this.uniforms=null,this.gl=null,this.attributes=null},i.ComplexPrimitiveShader=function(t){this._UID=i._UID++,this.gl=t,this.program=null,this.fragmentSrc=["precision mediump float;","varying vec4 vColor;","void main(void) {"," gl_FragColor = vColor;","}"],this.vertexSrc=["attribute vec2 aVertexPosition;","uniform mat3 translationMatrix;","uniform vec2 projectionVector;","uniform vec2 offsetVector;","uniform vec3 tint;","uniform float alpha;","uniform vec3 color;","uniform float flipY;","varying vec4 vColor;","void main(void) {"," vec3 v = translationMatrix * vec3(aVertexPosition , 1.0);"," v -= offsetVector.xyx;"," gl_Position = vec4( v.x / projectionVector.x -1.0, (v.y / projectionVector.y * -flipY) + flipY , 0.0, 1.0);"," vColor = vec4(color * alpha * tint, alpha);","}"],this.init()},i.ComplexPrimitiveShader.prototype.constructor=i.ComplexPrimitiveShader,i.ComplexPrimitiveShader.prototype.init=function(){var t=this.gl,e=i.compileProgram(t,this.vertexSrc,this.fragmentSrc);t.useProgram(e),this.projectionVector=t.getUniformLocation(e,"projectionVector"),this.offsetVector=t.getUniformLocation(e,"offsetVector"),this.tintColor=t.getUniformLocation(e,"tint"),this.color=t.getUniformLocation(e,"color"),this.flipY=t.getUniformLocation(e,"flipY"),this.aVertexPosition=t.getAttribLocation(e,"aVertexPosition"),this.attributes=[this.aVertexPosition,this.colorAttribute],this.translationMatrix=t.getUniformLocation(e,"translationMatrix"),this.alpha=t.getUniformLocation(e,"alpha"),this.program=e},i.ComplexPrimitiveShader.prototype.destroy=function(){this.gl.deleteProgram(this.program),this.uniforms=null,this.gl=null,this.attribute=null},i.glContexts=[],i.instances=[],i.WebGLRenderer=function(t){this.game=t,i.defaultRenderer||(i.defaultRenderer=this),this.type=i.WEBGL_RENDERER,this.resolution=t.resolution,this.transparent=t.transparent,this.autoResize=!1,this.preserveDrawingBuffer=t.preserveDrawingBuffer,this.clearBeforeRender=t.clearBeforeRender,this.width=t.width,this.height=t.height,this.view=t.canvas,this._contextOptions={alpha:this.transparent,antialias:t.antialias,premultipliedAlpha:this.transparent&&"notMultiplied"!==this.transparent,stencil:!0,preserveDrawingBuffer:this.preserveDrawingBuffer},this.projection=new i.Point,this.offset=new i.Point,this.shaderManager=new i.WebGLShaderManager,this.spriteBatch=new i.WebGLSpriteBatch,this.maskManager=new i.WebGLMaskManager,this.filterManager=new i.WebGLFilterManager,this.stencilManager=new i.WebGLStencilManager,this.blendModeManager=new i.WebGLBlendModeManager,this.renderSession={},this.renderSession.game=this.game,this.renderSession.gl=this.gl,this.renderSession.drawCount=0,this.renderSession.shaderManager=this.shaderManager,this.renderSession.maskManager=this.maskManager,this.renderSession.filterManager=this.filterManager,this.renderSession.blendModeManager=this.blendModeManager,this.renderSession.spriteBatch=this.spriteBatch,this.renderSession.stencilManager=this.stencilManager,this.renderSession.renderer=this,this.renderSession.resolution=this.resolution,this.initContext(),this.mapBlendModes()},i.WebGLRenderer.prototype.constructor=i.WebGLRenderer,i.WebGLRenderer.prototype.initContext=function(){var t=this.view.getContext("webgl",this._contextOptions)||this.view.getContext("experimental-webgl",this._contextOptions);if(this.gl=t,!t)throw new Error("This browser does not support webGL. Try using the canvas renderer");this.glContextId=t.id=i.WebGLRenderer.glContextId++,i.glContexts[this.glContextId]=t,i.instances[this.glContextId]=this,t.disable(t.DEPTH_TEST),t.disable(t.CULL_FACE),t.enable(t.BLEND),this.shaderManager.setContext(t),this.spriteBatch.setContext(t),this.maskManager.setContext(t),this.filterManager.setContext(t),this.blendModeManager.setContext(t),this.stencilManager.setContext(t),this.renderSession.gl=this.gl,this.resize(this.width,this.height)},i.WebGLRenderer.prototype.render=function(t){if(!this.contextLost){var e=this.gl;e.viewport(0,0,this.width,this.height),e.bindFramebuffer(e.FRAMEBUFFER,null),this.game.clearBeforeRender&&(e.clearColor(t._bgColor.r,t._bgColor.g,t._bgColor.b,t._bgColor.a),e.clear(e.COLOR_BUFFER_BIT)),this.offset.x=this.game.camera._shake.x,this.offset.y=this.game.camera._shake.y,this.renderDisplayObject(t,this.projection)}},i.WebGLRenderer.prototype.renderDisplayObject=function(t,e,s,n){this.renderSession.blendModeManager.setBlendMode(i.blendModes.NORMAL),this.renderSession.drawCount=0,this.renderSession.flipY=s?-1:1,this.renderSession.projection=e,this.renderSession.offset=this.offset,this.spriteBatch.begin(this.renderSession),this.filterManager.begin(this.renderSession,s),t._renderWebGL(this.renderSession,n),this.spriteBatch.end()},i.WebGLRenderer.prototype.resize=function(t,e){this.width=t*this.resolution,this.height=e*this.resolution,this.view.width=this.width,this.view.height=this.height,this.autoResize&&(this.view.style.width=this.width/this.resolution+"px",this.view.style.height=this.height/this.resolution+"px"),this.gl.viewport(0,0,this.width,this.height),this.projection.x=this.width/2/this.resolution,this.projection.y=-this.height/2/this.resolution},i.WebGLRenderer.prototype.updateTexture=function(t){if(!t.hasLoaded)return!1;var e=this.gl;return t._glTextures[e.id]||(t._glTextures[e.id]=e.createTexture()),e.bindTexture(e.TEXTURE_2D,t._glTextures[e.id]),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultipliedAlpha),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t.source),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,t.scaleMode===i.scaleModes.LINEAR?e.LINEAR:e.NEAREST),t.mipmap&&i.isPowerOfTwo(t.width,t.height)?(e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t.scaleMode===i.scaleModes.LINEAR?e.LINEAR_MIPMAP_LINEAR:e.NEAREST_MIPMAP_NEAREST),e.generateMipmap(e.TEXTURE_2D)):e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,t.scaleMode===i.scaleModes.LINEAR?e.LINEAR:e.NEAREST),t._powerOf2?(e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.REPEAT),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.REPEAT)):(e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),t._dirty[e.id]=!1,!0},i.WebGLRenderer.prototype.destroy=function(){i.glContexts[this.glContextId]=null,this.projection=null,this.offset=null,this.shaderManager.destroy(),this.spriteBatch.destroy(),this.maskManager.destroy(),this.filterManager.destroy(),this.shaderManager=null,this.spriteBatch=null,this.maskManager=null,this.filterManager=null,this.gl=null,this.renderSession=null,i.CanvasPool.remove(this),i.instances[this.glContextId]=null,i.WebGLRenderer.glContextId--},i.WebGLRenderer.prototype.mapBlendModes=function(){var t=this.gl;if(!i.blendModesWebGL){var e=[],s=i.blendModes;e[s.NORMAL]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.ADD]=[t.SRC_ALPHA,t.DST_ALPHA],e[s.MULTIPLY]=[t.DST_COLOR,t.ONE_MINUS_SRC_ALPHA],e[s.SCREEN]=[t.SRC_ALPHA,t.ONE],e[s.OVERLAY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.DARKEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.LIGHTEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.COLOR_DODGE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.COLOR_BURN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.HARD_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.SOFT_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.DIFFERENCE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.EXCLUSION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.HUE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.SATURATION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.COLOR]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[s.LUMINOSITY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],i.blendModesWebGL=e}},i.WebGLRenderer.glContextId=0,i.WebGLBlendModeManager=function(){this.currentBlendMode=99999},i.WebGLBlendModeManager.prototype.constructor=i.WebGLBlendModeManager,i.WebGLBlendModeManager.prototype.setContext=function(t){this.gl=t},i.WebGLBlendModeManager.prototype.setBlendMode=function(t){if(this.currentBlendMode===t)return!1;this.currentBlendMode=t;var e=i.blendModesWebGL[this.currentBlendMode];return e&&this.gl.blendFunc(e[0],e[1]),!0},i.WebGLBlendModeManager.prototype.destroy=function(){this.gl=null},i.WebGLMaskManager=function(){},i.WebGLMaskManager.prototype.constructor=i.WebGLMaskManager,i.WebGLMaskManager.prototype.setContext=function(t){this.gl=t},i.WebGLMaskManager.prototype.pushMask=function(t,e){var s=e.gl;t.dirty&&i.WebGLGraphics.updateGraphics(t,s),void 0!==t._webGL[s.id]&&void 0!==t._webGL[s.id].data&&0!==t._webGL[s.id].data.length&&e.stencilManager.pushStencil(t,t._webGL[s.id].data[0],e)},i.WebGLMaskManager.prototype.popMask=function(t,e){var i=this.gl;void 0!==t._webGL[i.id]&&void 0!==t._webGL[i.id].data&&0!==t._webGL[i.id].data.length&&e.stencilManager.popStencil(t,t._webGL[i.id].data[0],e)},i.WebGLMaskManager.prototype.destroy=function(){this.gl=null},i.WebGLStencilManager=function(){this.stencilStack=[],this.reverse=!0,this.count=0},i.WebGLStencilManager.prototype.setContext=function(t){this.gl=t},i.WebGLStencilManager.prototype.pushStencil=function(t,e,i){var s=this.gl;this.bindGraphics(t,e,i),0===this.stencilStack.length&&(s.enable(s.STENCIL_TEST),s.clear(s.STENCIL_BUFFER_BIT),this.reverse=!0,this.count=0),this.stencilStack.push(e);var n=this.count;s.colorMask(!1,!1,!1,!1),s.stencilFunc(s.ALWAYS,0,255),s.stencilOp(s.KEEP,s.KEEP,s.INVERT),1===e.mode?(s.drawElements(s.TRIANGLE_FAN,e.indices.length-4,s.UNSIGNED_SHORT,0),this.reverse?(s.stencilFunc(s.EQUAL,255-n,255),s.stencilOp(s.KEEP,s.KEEP,s.DECR)):(s.stencilFunc(s.EQUAL,n,255),s.stencilOp(s.KEEP,s.KEEP,s.INCR)),s.drawElements(s.TRIANGLE_FAN,4,s.UNSIGNED_SHORT,2*(e.indices.length-4)),this.reverse?s.stencilFunc(s.EQUAL,255-(n+1),255):s.stencilFunc(s.EQUAL,n+1,255),this.reverse=!this.reverse):(this.reverse?(s.stencilFunc(s.EQUAL,n,255),s.stencilOp(s.KEEP,s.KEEP,s.INCR)):(s.stencilFunc(s.EQUAL,255-n,255),s.stencilOp(s.KEEP,s.KEEP,s.DECR)),s.drawElements(s.TRIANGLE_STRIP,e.indices.length,s.UNSIGNED_SHORT,0),this.reverse?s.stencilFunc(s.EQUAL,n+1,255):s.stencilFunc(s.EQUAL,255-(n+1),255)),s.colorMask(!0,!0,!0,!0),s.stencilOp(s.KEEP,s.KEEP,s.KEEP),this.count++},i.WebGLStencilManager.prototype.bindGraphics=function(t,e,s){this._currentGraphics=t;var n,r=this.gl,o=s.projection,a=s.offset;1===e.mode?(n=s.shaderManager.complexPrimitiveShader,s.shaderManager.setShader(n),r.uniform1f(n.flipY,s.flipY),r.uniformMatrix3fv(n.translationMatrix,!1,t.worldTransform.toArray(!0)),r.uniform2f(n.projectionVector,o.x,-o.y),r.uniform2f(n.offsetVector,-a.x,-a.y),r.uniform3fv(n.tintColor,i.hex2rgb(t.tint)),r.uniform3fv(n.color,e.color),r.uniform1f(n.alpha,t.worldAlpha*e.alpha),r.bindBuffer(r.ARRAY_BUFFER,e.buffer),r.vertexAttribPointer(n.aVertexPosition,2,r.FLOAT,!1,8,0),r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,e.indexBuffer)):(n=s.shaderManager.primitiveShader,s.shaderManager.setShader(n),r.uniformMatrix3fv(n.translationMatrix,!1,t.worldTransform.toArray(!0)),r.uniform1f(n.flipY,s.flipY),r.uniform2f(n.projectionVector,o.x,-o.y),r.uniform2f(n.offsetVector,-a.x,-a.y),r.uniform3fv(n.tintColor,i.hex2rgb(t.tint)),r.uniform1f(n.alpha,t.worldAlpha),r.bindBuffer(r.ARRAY_BUFFER,e.buffer),r.vertexAttribPointer(n.aVertexPosition,2,r.FLOAT,!1,24,0),r.vertexAttribPointer(n.colorAttribute,4,r.FLOAT,!1,24,8),r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,e.indexBuffer))},i.WebGLStencilManager.prototype.popStencil=function(t,e,i){var s=this.gl;if(this.stencilStack.pop(),this.count--,0===this.stencilStack.length)s.disable(s.STENCIL_TEST);else{var n=this.count;this.bindGraphics(t,e,i),s.colorMask(!1,!1,!1,!1),1===e.mode?(this.reverse=!this.reverse,this.reverse?(s.stencilFunc(s.EQUAL,255-(n+1),255),s.stencilOp(s.KEEP,s.KEEP,s.INCR)):(s.stencilFunc(s.EQUAL,n+1,255),s.stencilOp(s.KEEP,s.KEEP,s.DECR)),s.drawElements(s.TRIANGLE_FAN,4,s.UNSIGNED_SHORT,2*(e.indices.length-4)),s.stencilFunc(s.ALWAYS,0,255),s.stencilOp(s.KEEP,s.KEEP,s.INVERT),s.drawElements(s.TRIANGLE_FAN,e.indices.length-4,s.UNSIGNED_SHORT,0),this.reverse?s.stencilFunc(s.EQUAL,n,255):s.stencilFunc(s.EQUAL,255-n,255)):(this.reverse?(s.stencilFunc(s.EQUAL,n+1,255),s.stencilOp(s.KEEP,s.KEEP,s.DECR)):(s.stencilFunc(s.EQUAL,255-(n+1),255),s.stencilOp(s.KEEP,s.KEEP,s.INCR)),s.drawElements(s.TRIANGLE_STRIP,e.indices.length,s.UNSIGNED_SHORT,0),this.reverse?s.stencilFunc(s.EQUAL,n,255):s.stencilFunc(s.EQUAL,255-n,255)),s.colorMask(!0,!0,!0,!0),s.stencilOp(s.KEEP,s.KEEP,s.KEEP)}},i.WebGLStencilManager.prototype.destroy=function(){this.stencilStack=null,this.gl=null},i.WebGLShaderManager=function(){this.maxAttibs=10,this.attribState=[],this.tempAttribState=[];for(var t=0;t<this.maxAttibs;t++)this.attribState[t]=!1;this.stack=[]},i.WebGLShaderManager.prototype.constructor=i.WebGLShaderManager,i.WebGLShaderManager.prototype.setContext=function(t){this.gl=t,this.primitiveShader=new i.PrimitiveShader(t),this.complexPrimitiveShader=new i.ComplexPrimitiveShader(t),this.defaultShader=new i.PixiShader(t),this.fastShader=new i.PixiFastShader(t),this.stripShader=new i.StripShader(t),this.setShader(this.defaultShader)},i.WebGLShaderManager.prototype.setAttribs=function(t){var e;for(e=0;e<this.tempAttribState.length;e++)this.tempAttribState[e]=!1;for(e=0;e<t.length;e++){var i=t[e];this.tempAttribState[i]=!0}var s=this.gl;for(e=0;e<this.attribState.length;e++)this.attribState[e]!==this.tempAttribState[e]&&(this.attribState[e]=this.tempAttribState[e],this.tempAttribState[e]?s.enableVertexAttribArray(e):s.disableVertexAttribArray(e))},i.WebGLShaderManager.prototype.setShader=function(t){return this._currentId!==t._UID&&(this._currentId=t._UID,this.currentShader=t,this.gl.useProgram(t.program),this.setAttribs(t.attributes),!0)},i.WebGLShaderManager.prototype.destroy=function(){this.attribState=null,this.tempAttribState=null,this.primitiveShader.destroy(),this.complexPrimitiveShader.destroy(),this.defaultShader.destroy(),this.fastShader.destroy(),this.stripShader.destroy(),this.gl=null},i.WebGLSpriteBatch=function(){this.vertSize=5,this.size=2e3;var t=4*this.size*4*this.vertSize,e=6*this.size;this.vertices=new i.ArrayBuffer(t),this.positions=new i.Float32Array(this.vertices),this.colors=new i.Uint32Array(this.vertices),this.indices=new i.Uint16Array(e),this.lastIndexCount=0;for(var s=0,n=0;s<e;s+=6,n+=4)this.indices[s+0]=n+0,this.indices[s+1]=n+1,this.indices[s+2]=n+2,this.indices[s+3]=n+0,this.indices[s+4]=n+2,this.indices[s+5]=n+3;this.drawing=!1,this.currentBatchSize=0,this.currentBaseTexture=null,this.dirty=!0,this.textures=[],this.blendModes=[],this.shaders=[],this.sprites=[],this.defaultShader=new i.AbstractFilter(["precision lowp float;","varying vec2 vTextureCoord;","varying vec4 vColor;","uniform sampler2D uSampler;","void main(void) {"," gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;","}"])},i.WebGLSpriteBatch.prototype.setContext=function(t){this.gl=t,this.vertexBuffer=t.createBuffer(),this.indexBuffer=t.createBuffer(),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,this.indices,t.STATIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),t.bufferData(t.ARRAY_BUFFER,this.vertices,t.DYNAMIC_DRAW),this.currentBlendMode=99999;var e=new i.PixiShader(t);e.fragmentSrc=this.defaultShader.fragmentSrc,e.uniforms={},e.init(),this.defaultShader.shaders[t.id]=e},i.WebGLSpriteBatch.prototype.begin=function(t){this.renderSession=t,this.shader=this.renderSession.shaderManager.defaultShader,this.start()},i.WebGLSpriteBatch.prototype.end=function(){this.flush()},i.WebGLSpriteBatch.prototype.render=function(t,e){var i=t.texture,s=t.worldTransform;e&&(s=e),this.currentBatchSize>=this.size&&(this.flush(),this.currentBaseTexture=i.baseTexture);var n=i._uvs;if(n){var r,o,a,h,l=t.anchor.x,c=t.anchor.y;if(i.trim){var u=i.trim;o=u.x-l*u.width,r=o+i.crop.width,h=u.y-c*u.height,a=h+i.crop.height}else r=i.frame.width*(1-l),o=i.frame.width*-l,a=i.frame.height*(1-c),h=i.frame.height*-c;var d=4*this.currentBatchSize*this.vertSize,p=i.baseTexture.resolution,f=s.a/p,g=s.b/p,m=s.c/p,y=s.d/p,v=s.tx,b=s.ty,x=this.colors,w=this.positions;this.renderSession.roundPixels?(w[d]=f*o+m*h+v|0,w[d+1]=y*h+g*o+b|0,w[d+5]=f*r+m*h+v|0,w[d+6]=y*h+g*r+b|0,w[d+10]=f*r+m*a+v|0,w[d+11]=y*a+g*r+b|0,w[d+15]=f*o+m*a+v|0,w[d+16]=y*a+g*o+b|0):(w[d]=f*o+m*h+v,w[d+1]=y*h+g*o+b,w[d+5]=f*r+m*h+v,w[d+6]=y*h+g*r+b,w[d+10]=f*r+m*a+v,w[d+11]=y*a+g*r+b,w[d+15]=f*o+m*a+v,w[d+16]=y*a+g*o+b),w[d+2]=n.x0,w[d+3]=n.y0,w[d+7]=n.x1,w[d+8]=n.y1,w[d+12]=n.x2,w[d+13]=n.y2,w[d+17]=n.x3,w[d+18]=n.y3;var _=t.tint;x[d+4]=x[d+9]=x[d+14]=x[d+19]=(_>>16)+(65280&_)+((255&_)<<16)+(255*t.worldAlpha<<24),this.sprites[this.currentBatchSize++]=t}},i.WebGLSpriteBatch.prototype.renderTilingSprite=function(t){var e=t.tilingTexture;this.currentBatchSize>=this.size&&(this.flush(),this.currentBaseTexture=e.baseTexture),t._uvs||(t._uvs=new i.TextureUvs);var s=t._uvs,n=e.baseTexture.width,r=e.baseTexture.height;t.tilePosition.x%=n*t.tileScaleOffset.x,t.tilePosition.y%=r*t.tileScaleOffset.y;var o=t.tilePosition.x/(n*t.tileScaleOffset.x),a=t.tilePosition.y/(r*t.tileScaleOffset.y),h=t.width/n/(t.tileScale.x*t.tileScaleOffset.x),l=t.height/r/(t.tileScale.y*t.tileScaleOffset.y);s.x0=0-o,s.y0=0-a,s.x1=1*h-o,s.y1=0-a,s.x2=1*h-o,s.y2=1*l-a,s.x3=0-o,s.y3=1*l-a;var c=t.tint,u=(c>>16)+(65280&c)+((255&c)<<16)+(255*t.worldAlpha<<24),d=this.positions,p=this.colors,f=t.width,g=t.height,m=t.anchor.x,y=t.anchor.y,v=f*(1-m),b=f*-m,x=g*(1-y),w=g*-y,_=4*this.currentBatchSize*this.vertSize,P=e.baseTexture.resolution,T=t.worldTransform,C=T.a/P,S=T.b/P,A=T.c/P,E=T.d/P,I=T.tx,M=T.ty;d[_++]=C*b+A*w+I,d[_++]=E*w+S*b+M,d[_++]=s.x0,d[_++]=s.y0,p[_++]=u,d[_++]=C*v+A*w+I,d[_++]=E*w+S*v+M,d[_++]=s.x1,d[_++]=s.y1,p[_++]=u,d[_++]=C*v+A*x+I,d[_++]=E*x+S*v+M,d[_++]=s.x2,d[_++]=s.y2,p[_++]=u,d[_++]=C*b+A*x+I,d[_++]=E*x+S*b+M,d[_++]=s.x3,d[_++]=s.y3,p[_++]=u,this.sprites[this.currentBatchSize++]=t},i.WebGLSpriteBatch.prototype.flush=function(){if(0!==this.currentBatchSize){var t,e=this.gl;if(this.dirty){this.dirty=!1,e.activeTexture(e.TEXTURE0),e.bindBuffer(e.ARRAY_BUFFER,this.vertexBuffer),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer),t=this.defaultShader.shaders[e.id];var s=4*this.vertSize;e.vertexAttribPointer(t.aVertexPosition,2,e.FLOAT,!1,s,0),e.vertexAttribPointer(t.aTextureCoord,2,e.FLOAT,!1,s,8),e.vertexAttribPointer(t.colorAttribute,4,e.UNSIGNED_BYTE,!0,s,16)}if(this.currentBatchSize>.5*this.size)e.bufferSubData(e.ARRAY_BUFFER,0,this.vertices);else{var n=this.positions.subarray(0,4*this.currentBatchSize*this.vertSize);e.bufferSubData(e.ARRAY_BUFFER,0,n)}for(var r,o,a,h,l=0,c=0,u=null,d=this.renderSession.blendModeManager.currentBlendMode,p=null,f=!1,g=!1,m=0,y=this.currentBatchSize;m<y;m++){h=this.sprites[m],r=h.tilingTexture?h.tilingTexture.baseTexture:h.texture.baseTexture,o=h.blendMode,a=h.shader||this.defaultShader,f=d!==o,g=p!==a;var v=r.skipRender;if(v&&h.children.length>0&&(v=!1),(u!==r&&!v||f||g)&&(this.renderBatch(u,l,c),c=m,l=0,u=r,f&&(d=o,this.renderSession.blendModeManager.setBlendMode(d)),g)){p=a,t=p.shaders[e.id],t||(t=new i.PixiShader(e),t.fragmentSrc=p.fragmentSrc,t.uniforms=p.uniforms,t.init(),p.shaders[e.id]=t),this.renderSession.shaderManager.setShader(t),t.dirty&&t.syncUniforms();var b=this.renderSession.projection;e.uniform2f(t.projectionVector,b.x,b.y);var x=this.renderSession.offset;e.uniform2f(t.offsetVector,x.x,x.y)}l++}this.renderBatch(u,l,c),this.currentBatchSize=0}},i.WebGLSpriteBatch.prototype.renderBatch=function(t,e,i){if(0!==e){var s=this.gl;if(t._dirty[s.id]){if(!this.renderSession.renderer.updateTexture(t))return}else s.bindTexture(s.TEXTURE_2D,t._glTextures[s.id]);s.drawElements(s.TRIANGLES,6*e,s.UNSIGNED_SHORT,6*i*2),this.renderSession.drawCount++}},i.WebGLSpriteBatch.prototype.stop=function(){this.flush(),this.dirty=!0},i.WebGLSpriteBatch.prototype.start=function(){this.dirty=!0},i.WebGLSpriteBatch.prototype.destroy=function(){this.vertices=null,this.indices=null,this.gl.deleteBuffer(this.vertexBuffer),this.gl.deleteBuffer(this.indexBuffer),this.currentBaseTexture=null,this.gl=null},i.WebGLFastSpriteBatch=function(t){this.vertSize=10,this.maxSize=6e3,this.size=this.maxSize;var e=4*this.size*this.vertSize,s=6*this.maxSize;this.vertices=new i.Float32Array(e),this.indices=new i.Uint16Array(s),this.vertexBuffer=null,this.indexBuffer=null,this.lastIndexCount=0;for(var n=0,r=0;n<s;n+=6,r+=4)this.indices[n+0]=r+0,this.indices[n+1]=r+1,this.indices[n+2]=r+2,this.indices[n+3]=r+0,this.indices[n+4]=r+2,this.indices[n+5]=r+3;this.drawing=!1,this.currentBatchSize=0,this.currentBaseTexture=null,this.currentBlendMode=0,this.renderSession=null,this.shader=null,this.matrix=null,this.setContext(t)},i.WebGLFastSpriteBatch.prototype.constructor=i.WebGLFastSpriteBatch,i.WebGLFastSpriteBatch.prototype.setContext=function(t){this.gl=t,this.vertexBuffer=t.createBuffer(),this.indexBuffer=t.createBuffer(),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,this.indices,t.STATIC_DRAW),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),t.bufferData(t.ARRAY_BUFFER,this.vertices,t.DYNAMIC_DRAW)},i.WebGLFastSpriteBatch.prototype.begin=function(t,e){this.renderSession=e,this.shader=this.renderSession.shaderManager.fastShader,this.matrix=t.worldTransform.toArray(!0),this.start()},i.WebGLFastSpriteBatch.prototype.end=function(){this.flush()},i.WebGLFastSpriteBatch.prototype.render=function(t){var e=t.children,i=e[0];if(i.texture._uvs){this.currentBaseTexture=i.texture.baseTexture,i.blendMode!==this.renderSession.blendModeManager.currentBlendMode&&(this.flush(),this.renderSession.blendModeManager.setBlendMode(i.blendMode));for(var s=0,n=e.length;s<n;s++)this.renderSprite(e[s]);this.flush()}},i.WebGLFastSpriteBatch.prototype.renderSprite=function(t){if(t.visible&&(t.texture.baseTexture===this.currentBaseTexture||t.texture.baseTexture.skipRender||(this.flush(),this.currentBaseTexture=t.texture.baseTexture,t.texture._uvs))){var e,i,s,n,r,o,a=this.vertices;if(e=t.texture._uvs,t.texture.frame.width,t.texture.frame.height,t.texture.trim){var h=t.texture.trim;s=h.x-t.anchor.x*h.width,i=s+t.texture.crop.width,r=h.y-t.anchor.y*h.height,n=r+t.texture.crop.height}else i=t.texture.frame.width*(1-t.anchor.x),s=t.texture.frame.width*-t.anchor.x,n=t.texture.frame.height*(1-t.anchor.y),r=t.texture.frame.height*-t.anchor.y;o=4*this.currentBatchSize*this.vertSize,a[o++]=s,a[o++]=r,a[o++]=t.position.x,a[o++]=t.position.y,a[o++]=t.scale.x,a[o++]=t.scale.y,a[o++]=t.rotation,a[o++]=e.x0,a[o++]=e.y1,a[o++]=t.alpha,a[o++]=i,a[o++]=r,a[o++]=t.position.x,a[o++]=t.position.y,a[o++]=t.scale.x,a[o++]=t.scale.y,a[o++]=t.rotation,a[o++]=e.x1,a[o++]=e.y1,a[o++]=t.alpha,a[o++]=i,a[o++]=n,a[o++]=t.position.x,a[o++]=t.position.y,a[o++]=t.scale.x,a[o++]=t.scale.y,a[o++]=t.rotation,a[o++]=e.x2,a[o++]=e.y2,a[o++]=t.alpha,a[o++]=s,a[o++]=n,a[o++]=t.position.x,a[o++]=t.position.y,a[o++]=t.scale.x,a[o++]=t.scale.y,a[o++]=t.rotation,a[o++]=e.x3,a[o++]=e.y3,a[o++]=t.alpha,this.currentBatchSize++,this.currentBatchSize>=this.size&&this.flush()}},i.WebGLFastSpriteBatch.prototype.flush=function(){if(0!==this.currentBatchSize){var t=this.gl;if(this.currentBaseTexture._glTextures[t.id]||this.renderSession.renderer.updateTexture(this.currentBaseTexture,t),t.bindTexture(t.TEXTURE_2D,this.currentBaseTexture._glTextures[t.id]),this.currentBatchSize>.5*this.size)t.bufferSubData(t.ARRAY_BUFFER,0,this.vertices);else{var e=this.vertices.subarray(0,4*this.currentBatchSize*this.vertSize);t.bufferSubData(t.ARRAY_BUFFER,0,e)}t.drawElements(t.TRIANGLES,6*this.currentBatchSize,t.UNSIGNED_SHORT,0),this.currentBatchSize=0,this.renderSession.drawCount++}},i.WebGLFastSpriteBatch.prototype.stop=function(){this.flush()},i.WebGLFastSpriteBatch.prototype.start=function(){var t=this.gl;t.activeTexture(t.TEXTURE0),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer);var e=this.renderSession.projection;t.uniform2f(this.shader.projectionVector,e.x,e.y),t.uniformMatrix3fv(this.shader.uMatrix,!1,this.matrix);var i=4*this.vertSize;t.vertexAttribPointer(this.shader.aVertexPosition,2,t.FLOAT,!1,i,0),t.vertexAttribPointer(this.shader.aPositionCoord,2,t.FLOAT,!1,i,8),t.vertexAttribPointer(this.shader.aScale,2,t.FLOAT,!1,i,16),t.vertexAttribPointer(this.shader.aRotation,1,t.FLOAT,!1,i,24),t.vertexAttribPointer(this.shader.aTextureCoord,2,t.FLOAT,!1,i,28),t.vertexAttribPointer(this.shader.colorAttribute,1,t.FLOAT,!1,i,36)},i.WebGLFilterManager=function(){this.filterStack=[],this.offsetX=0,this.offsetY=0},i.WebGLFilterManager.prototype.constructor=i.WebGLFilterManager,i.WebGLFilterManager.prototype.setContext=function(t){this.gl=t,this.texturePool=[],this.initShaderBuffers()},i.WebGLFilterManager.prototype.begin=function(t,e){this.renderSession=t,this.defaultShader=t.shaderManager.defaultShader;var i=this.renderSession.projection;this.width=2*i.x,this.height=2*-i.y,this.buffer=e},i.WebGLFilterManager.prototype.pushFilter=function(t){var e=this.gl,s=this.renderSession.projection,n=this.renderSession.offset;t._filterArea=t.target.filterArea||t.target.getBounds(),t._previous_stencil_mgr=this.renderSession.stencilManager,this.renderSession.stencilManager=new i.WebGLStencilManager,this.renderSession.stencilManager.setContext(e),e.disable(e.STENCIL_TEST),this.filterStack.push(t);var r=t.filterPasses[0];this.offsetX+=t._filterArea.x,this.offsetY+=t._filterArea.y;var o=this.texturePool.pop();o?o.resize(this.width*this.renderSession.resolution,this.height*this.renderSession.resolution):o=new i.FilterTexture(this.gl,this.width*this.renderSession.resolution,this.height*this.renderSession.resolution),e.bindTexture(e.TEXTURE_2D,o.texture);var a=t._filterArea,h=r.padding;a.x-=h,a.y-=h,a.width+=2*h,a.height+=2*h,a.x<0&&(a.x=0),a.width>this.width&&(a.width=this.width),a.y<0&&(a.y=0),a.height>this.height&&(a.height=this.height),e.bindFramebuffer(e.FRAMEBUFFER,o.frameBuffer),e.viewport(0,0,a.width*this.renderSession.resolution,a.height*this.renderSession.resolution),s.x=a.width/2,s.y=-a.height/2,n.x=-a.x,n.y=-a.y,e.colorMask(!0,!0,!0,!0),e.clearColor(0,0,0,0),e.clear(e.COLOR_BUFFER_BIT),t._glFilterTexture=o},i.WebGLFilterManager.prototype.popFilter=function(){var t=this.gl,e=this.filterStack.pop(),s=e._filterArea,n=e._glFilterTexture,r=this.renderSession.projection,o=this.renderSession.offset;if(e.filterPasses.length>1){t.viewport(0,0,s.width*this.renderSession.resolution,s.height*this.renderSession.resolution),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),this.vertexArray[0]=0,this.vertexArray[1]=s.height,this.vertexArray[2]=s.width,this.vertexArray[3]=s.height,this.vertexArray[4]=0,this.vertexArray[5]=0,this.vertexArray[6]=s.width,this.vertexArray[7]=0,t.bufferSubData(t.ARRAY_BUFFER,0,this.vertexArray),t.bindBuffer(t.ARRAY_BUFFER,this.uvBuffer),this.uvArray[2]=s.width/this.width,this.uvArray[5]=s.height/this.height,this.uvArray[6]=s.width/this.width,this.uvArray[7]=s.height/this.height,t.bufferSubData(t.ARRAY_BUFFER,0,this.uvArray);var a=n,h=this.texturePool.pop();h||(h=new i.FilterTexture(this.gl,this.width*this.renderSession.resolution,this.height*this.renderSession.resolution)),h.resize(this.width*this.renderSession.resolution,this.height*this.renderSession.resolution),t.bindFramebuffer(t.FRAMEBUFFER,h.frameBuffer),t.clear(t.COLOR_BUFFER_BIT),t.disable(t.BLEND);for(var l=0;l<e.filterPasses.length-1;l++){var c=e.filterPasses[l];t.bindFramebuffer(t.FRAMEBUFFER,h.frameBuffer),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,a.texture),this.applyFilterPass(c,s,s.width,s.height);var u=a;a=h,h=u}t.enable(t.BLEND),n=a,this.texturePool.push(h)}var d=e.filterPasses[e.filterPasses.length-1];this.offsetX-=s.x,this.offsetY-=s.y;var p=this.width,f=this.height,g=0,m=0,y=this.buffer;if(0===this.filterStack.length)t.colorMask(!0,!0,!0,!0);else{var v=this.filterStack[this.filterStack.length-1];s=v._filterArea,p=s.width,f=s.height,g=s.x,m=s.y,y=v._glFilterTexture.frameBuffer}r.x=p/2,r.y=-f/2,o.x=g,o.y=m,s=e._filterArea;var b=s.x-g,x=s.y-m;t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),this.vertexArray[0]=b,this.vertexArray[1]=x+s.height,this.vertexArray[2]=b+s.width,this.vertexArray[3]=x+s.height,this.vertexArray[4]=b,this.vertexArray[5]=x,this.vertexArray[6]=b+s.width,this.vertexArray[7]=x,t.bufferSubData(t.ARRAY_BUFFER,0,this.vertexArray),t.bindBuffer(t.ARRAY_BUFFER,this.uvBuffer),this.uvArray[2]=s.width/this.width,this.uvArray[5]=s.height/this.height,this.uvArray[6]=s.width/this.width,this.uvArray[7]=s.height/this.height,t.bufferSubData(t.ARRAY_BUFFER,0,this.uvArray),t.viewport(0,0,p*this.renderSession.resolution,f*this.renderSession.resolution),t.bindFramebuffer(t.FRAMEBUFFER,y),t.activeTexture(t.TEXTURE0),t.bindTexture(t.TEXTURE_2D,n.texture),this.renderSession.stencilManager&&this.renderSession.stencilManager.destroy(),this.renderSession.stencilManager=e._previous_stencil_mgr,e._previous_stencil_mgr=null,this.renderSession.stencilManager.count>0?t.enable(t.STENCIL_TEST):t.disable(t.STENCIL_TEST),this.applyFilterPass(d,s,p,f),this.texturePool.push(n),e._glFilterTexture=null},i.WebGLFilterManager.prototype.applyFilterPass=function(t,e,s,n){var r=this.gl,o=t.shaders[r.id];o||(o=new i.PixiShader(r),o.fragmentSrc=t.fragmentSrc,o.uniforms=t.uniforms,o.init(),t.shaders[r.id]=o),this.renderSession.shaderManager.setShader(o),r.uniform2f(o.projectionVector,s/2,-n/2),r.uniform2f(o.offsetVector,0,0),t.uniforms.dimensions&&(t.uniforms.dimensions.value[0]=this.width,t.uniforms.dimensions.value[1]=this.height,t.uniforms.dimensions.value[2]=this.vertexArray[0],t.uniforms.dimensions.value[3]=this.vertexArray[5]),o.syncUniforms(),r.bindBuffer(r.ARRAY_BUFFER,this.vertexBuffer),r.vertexAttribPointer(o.aVertexPosition,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ARRAY_BUFFER,this.uvBuffer),r.vertexAttribPointer(o.aTextureCoord,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ARRAY_BUFFER,this.colorBuffer),r.vertexAttribPointer(o.colorAttribute,2,r.FLOAT,!1,0,0),r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,this.indexBuffer),r.drawElements(r.TRIANGLES,6,r.UNSIGNED_SHORT,0),this.renderSession.drawCount++},i.WebGLFilterManager.prototype.initShaderBuffers=function(){var t=this.gl;this.vertexBuffer=t.createBuffer(),this.uvBuffer=t.createBuffer(),this.colorBuffer=t.createBuffer(),this.indexBuffer=t.createBuffer(),this.vertexArray=new i.Float32Array([0,0,1,0,0,1,1,1]),t.bindBuffer(t.ARRAY_BUFFER,this.vertexBuffer),t.bufferData(t.ARRAY_BUFFER,this.vertexArray,t.STATIC_DRAW),this.uvArray=new i.Float32Array([0,0,1,0,0,1,1,1]),t.bindBuffer(t.ARRAY_BUFFER,this.uvBuffer),t.bufferData(t.ARRAY_BUFFER,this.uvArray,t.STATIC_DRAW),this.colorArray=new i.Float32Array([1,16777215,1,16777215,1,16777215,1,16777215]),t.bindBuffer(t.ARRAY_BUFFER,this.colorBuffer),t.bufferData(t.ARRAY_BUFFER,this.colorArray,t.STATIC_DRAW),t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer),t.bufferData(t.ELEMENT_ARRAY_BUFFER,new Uint16Array([0,1,2,1,3,2]),t.STATIC_DRAW)},i.WebGLFilterManager.prototype.destroy=function(){var t=this.gl;this.filterStack=null,this.offsetX=0,this.offsetY=0;for(var e=0;e<this.texturePool.length;e++)this.texturePool[e].destroy();this.texturePool=null,t.deleteBuffer(this.vertexBuffer),t.deleteBuffer(this.uvBuffer),t.deleteBuffer(this.colorBuffer),t.deleteBuffer(this.indexBuffer)},i.FilterTexture=function(t,e,s,n){this.gl=t,this.frameBuffer=t.createFramebuffer(),this.texture=t.createTexture(),n=n||i.scaleModes.DEFAULT,t.bindTexture(t.TEXTURE_2D,this.texture),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,n===i.scaleModes.LINEAR?t.LINEAR:t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,n===i.scaleModes.LINEAR?t.LINEAR:t.NEAREST),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.bindFramebuffer(t.FRAMEBUFFER,this.frameBuffer),t.bindFramebuffer(t.FRAMEBUFFER,this.frameBuffer),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,this.texture,0),this.renderBuffer=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,this.renderBuffer),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.DEPTH_STENCIL_ATTACHMENT,t.RENDERBUFFER,this.renderBuffer),this.resize(e,s)},i.FilterTexture.prototype.constructor=i.FilterTexture,i.FilterTexture.prototype.clear=function(){var t=this.gl;t.clearColor(0,0,0,0),t.clear(t.COLOR_BUFFER_BIT)},i.FilterTexture.prototype.resize=function(t,e){if(this.width!==t||this.height!==e){this.width=t,this.height=e;var i=this.gl;i.bindTexture(i.TEXTURE_2D,this.texture),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,t,e,0,i.RGBA,i.UNSIGNED_BYTE,null),i.bindRenderbuffer(i.RENDERBUFFER,this.renderBuffer),i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH_STENCIL,t,e)}},i.FilterTexture.prototype.destroy=function(){var t=this.gl;t.deleteFramebuffer(this.frameBuffer),t.deleteTexture(this.texture),this.frameBuffer=null,this.texture=null},i.CanvasBuffer=function(t,e){this.width=t,this.height=e,this.canvas=i.CanvasPool.create(this,this.width,this.height),this.context=this.canvas.getContext("2d"),this.canvas.width=t,this.canvas.height=e},i.CanvasBuffer.prototype.constructor=i.CanvasBuffer,i.CanvasBuffer.prototype.clear=function(){this.context.setTransform(1,0,0,1,0,0),this.context.clearRect(0,0,this.width,this.height)},i.CanvasBuffer.prototype.resize=function(t,e){this.width=this.canvas.width=t,this.height=this.canvas.height=e},i.CanvasBuffer.prototype.destroy=function(){i.CanvasPool.remove(this)},i.CanvasMaskManager=function(){},i.CanvasMaskManager.prototype.constructor=i.CanvasMaskManager,i.CanvasMaskManager.prototype.pushMask=function(t,e){var s=e.context;s.save();var n=t.alpha,r=t.worldTransform,o=e.resolution;s.setTransform(r.a*o,r.b*o,r.c*o,r.d*o,r.tx*o,r.ty*o),i.CanvasGraphics.renderGraphicsMask(t,s),s.clip(),t.worldAlpha=n},i.CanvasMaskManager.prototype.popMask=function(t){t.context.restore()},i.CanvasTinter=function(){},i.CanvasTinter.getTintedTexture=function(t,e){var s=t.tintedTexture||i.CanvasPool.create(this);return i.CanvasTinter.tintMethod(t.texture,e,s),s},i.CanvasTinter.tintWithMultiply=function(t,e,i){var s=i.getContext("2d"),n=t.crop;i.width===n.width&&i.height===n.height||(i.width=n.width,i.height=n.height),s.clearRect(0,0,n.width,n.height),s.fillStyle="#"+("00000"+(0|e).toString(16)).substr(-6),s.fillRect(0,0,n.width,n.height),s.globalCompositeOperation="multiply",s.drawImage(t.baseTexture.source,n.x,n.y,n.width,n.height,0,0,n.width,n.height),s.globalCompositeOperation="destination-atop",s.drawImage(t.baseTexture.source,n.x,n.y,n.width,n.height,0,0,n.width,n.height)},i.CanvasTinter.tintWithPerPixel=function(t,e,s){var n=s.getContext("2d"),r=t.crop;s.width=r.width,s.height=r.height,n.globalCompositeOperation="copy",n.drawImage(t.baseTexture.source,r.x,r.y,r.width,r.height,0,0,r.width,r.height);for(var o=i.hex2rgb(e),a=o[0],h=o[1],l=o[2],c=n.getImageData(0,0,r.width,r.height),u=c.data,d=0;d<u.length;d+=4)if(u[d+0]*=a,u[d+1]*=h,u[d+2]*=l,!i.CanvasTinter.canHandleAlpha){var p=u[d+3];u[d+0]/=255/p,u[d+1]/=255/p,u[d+2]/=255/p}n.putImageData(c,0,0)},i.CanvasTinter.checkInverseAlpha=function(){var t=new i.CanvasBuffer(2,1);t.context.fillStyle="rgba(10, 20, 30, 0.5)",t.context.fillRect(0,0,1,1);var e=t.context.getImageData(0,0,1,1);if(null===e)return!1;t.context.putImageData(e,1,0);var s=t.context.getImageData(1,0,1,1);return s.data[0]===e.data[0]&&s.data[1]===e.data[1]&&s.data[2]===e.data[2]&&s.data[3]===e.data[3]},i.CanvasTinter.canHandleAlpha=i.CanvasTinter.checkInverseAlpha(),i.CanvasTinter.canUseMultiply=i.canUseNewCanvasBlendModes(),i.CanvasTinter.tintMethod=i.CanvasTinter.canUseMultiply?i.CanvasTinter.tintWithMultiply:i.CanvasTinter.tintWithPerPixel,i.CanvasRenderer=function(t){this.game=t,i.defaultRenderer||(i.defaultRenderer=this),this.type=i.CANVAS_RENDERER,this.resolution=t.resolution,this.clearBeforeRender=t.clearBeforeRender,this.transparent=t.transparent,this.autoResize=!1,this.width=t.width*this.resolution,this.height=t.height*this.resolution,this.view=t.canvas,this.context=this.view.getContext("2d",{alpha:this.transparent}),this.refresh=!0,this.count=0,this.maskManager=new i.CanvasMaskManager,this.renderSession={context:this.context,maskManager:this.maskManager,scaleMode:null,smoothProperty:Phaser.Canvas.getSmoothingPrefix(this.context),roundPixels:!1},this.mapBlendModes(),this.resize(this.width,this.height)},i.CanvasRenderer.prototype.constructor=i.CanvasRenderer,i.CanvasRenderer.prototype.render=function(t){this.context.setTransform(1,0,0,1,0,0),this.context.globalAlpha=1,this.renderSession.currentBlendMode=0,this.renderSession.shakeX=this.game.camera._shake.x,this.renderSession.shakeY=this.game.camera._shake.y,this.context.globalCompositeOperation="source-over",navigator.isCocoonJS&&this.view.screencanvas&&(this.context.fillStyle="black",this.context.clear()),this.clearBeforeRender&&(this.transparent?this.context.clearRect(0,0,this.width,this.height):t._bgColor&&(this.context.fillStyle=t._bgColor.rgba,this.context.fillRect(0,0,this.width,this.height))),this.renderDisplayObject(t)},i.CanvasRenderer.prototype.destroy=function(t){void 0===t&&(t=!0),t&&this.view.parent&&this.view.parent.removeChild(this.view),this.view=null,this.context=null,this.maskManager=null,this.renderSession=null},i.CanvasRenderer.prototype.resize=function(t,e){this.width=t*this.resolution,this.height=e*this.resolution,this.view.width=this.width,this.view.height=this.height,this.autoResize&&(this.view.style.width=this.width/this.resolution+"px",this.view.style.height=this.height/this.resolution+"px"),this.renderSession.smoothProperty&&(this.context[this.renderSession.smoothProperty]=this.renderSession.scaleMode===i.scaleModes.LINEAR)},i.CanvasRenderer.prototype.renderDisplayObject=function(t,e,i){this.renderSession.context=e||this.context,this.renderSession.resolution=this.resolution,t._renderCanvas(this.renderSession,i)},i.CanvasRenderer.prototype.mapBlendModes=function(){if(!i.blendModesCanvas){var t=[],e=i.blendModes,s=i.canUseNewCanvasBlendModes();t[e.NORMAL]="source-over",t[e.ADD]="lighter",t[e.MULTIPLY]=s?"multiply":"source-over",t[e.SCREEN]=s?"screen":"source-over",t[e.OVERLAY]=s?"overlay":"source-over",t[e.DARKEN]=s?"darken":"source-over",t[e.LIGHTEN]=s?"lighten":"source-over",t[e.COLOR_DODGE]=s?"color-dodge":"source-over",t[e.COLOR_BURN]=s?"color-burn":"source-over",t[e.HARD_LIGHT]=s?"hard-light":"source-over",t[e.SOFT_LIGHT]=s?"soft-light":"source-over",t[e.DIFFERENCE]=s?"difference":"source-over",t[e.EXCLUSION]=s?"exclusion":"source-over",t[e.HUE]=s?"hue":"source-over",t[e.SATURATION]=s?"saturation":"source-over",t[e.COLOR]=s?"color":"source-over",t[e.LUMINOSITY]=s?"luminosity":"source-over",i.blendModesCanvas=t}},i.BaseTexture=function(t,e){this.resolution=1,this.width=100,this.height=100,this.scaleMode=e||i.scaleModes.DEFAULT,this.hasLoaded=!1,this.source=t,this.premultipliedAlpha=!0,this._glTextures=[],this.mipmap=!1,this._dirty=[!0,!0,!0,!0],t&&((this.source.complete||this.source.getContext)&&this.source.width&&this.source.height&&(this.hasLoaded=!0,this.width=this.source.naturalWidth||this.source.width,this.height=this.source.naturalHeight||this.source.height,this.dirty()),this.skipRender=!1,this._powerOf2=!1)},i.BaseTexture.prototype.constructor=i.BaseTexture,i.BaseTexture.prototype.forceLoaded=function(t,e){this.hasLoaded=!0,this.width=t,this.height=e,this.dirty()},i.BaseTexture.prototype.destroy=function(){this.source&&i.CanvasPool.removeByCanvas(this.source),this.source=null,this.unloadFromGPU()},i.BaseTexture.prototype.updateSourceImage=function(t){console.warn("PIXI.BaseTexture.updateSourceImage is deprecated. Use Phaser.Sprite.loadTexture instead.")},i.BaseTexture.prototype.dirty=function(){for(var t=0;t<this._glTextures.length;t++)this._dirty[t]=!0},i.BaseTexture.prototype.unloadFromGPU=function(){this.dirty();for(var t=this._glTextures.length-1;t>=0;t--){var e=this._glTextures[t],s=i.glContexts[t];s&&e&&s.deleteTexture(e)}this._glTextures.length=0,this.dirty()},i.BaseTexture.fromCanvas=function(t,e){return 0===t.width&&(t.width=1),0===t.height&&(t.height=1),new i.BaseTexture(t,e)},i.TextureSilentFail=!1,i.Texture=function(t,e,s,n){this.noFrame=!1,e||(this.noFrame=!0,e=new i.Rectangle(0,0,1,1)),t instanceof i.Texture&&(t=t.baseTexture),this.baseTexture=t,this.frame=e,this.trim=n,this.valid=!1,this.isTiling=!1,this.requiresUpdate=!1,this.requiresReTint=!1,this._uvs=null,this.width=0,this.height=0,this.crop=s||new i.Rectangle(0,0,1,1),t.hasLoaded&&(this.noFrame&&(e=new i.Rectangle(0,0,t.width,t.height)),this.setFrame(e))},i.Texture.prototype.constructor=i.Texture,i.Texture.prototype.onBaseTextureLoaded=function(){var t=this.baseTexture;this.noFrame&&(this.frame=new i.Rectangle(0,0,t.width,t.height)),this.setFrame(this.frame)},i.Texture.prototype.destroy=function(t){t&&this.baseTexture.destroy(),this.valid=!1},i.Texture.prototype.setFrame=function(t){if(this.noFrame=!1,this.frame=t,this.width=t.width,this.height=t.height,this.crop.x=t.x,this.crop.y=t.y,this.crop.width=t.width,this.crop.height=t.height,!this.trim&&(t.x+t.width>this.baseTexture.width||t.y+t.height>this.baseTexture.height)){if(!i.TextureSilentFail)throw new Error("Texture Error: frame does not fit inside the base Texture dimensions "+this);return void(this.valid=!1)}this.valid=t&&t.width&&t.height&&this.baseTexture.source&&this.baseTexture.hasLoaded,this.trim&&(this.width=this.trim.width,this.height=this.trim.height,this.frame.width=this.trim.width,this.frame.height=this.trim.height),this.valid&&this._updateUvs()},i.Texture.prototype._updateUvs=function(){this._uvs||(this._uvs=new i.TextureUvs);var t=this.crop,e=this.baseTexture.width,s=this.baseTexture.height;this._uvs.x0=t.x/e,this._uvs.y0=t.y/s,this._uvs.x1=(t.x+t.width)/e,this._uvs.y1=t.y/s,this._uvs.x2=(t.x+t.width)/e,this._uvs.y2=(t.y+t.height)/s,this._uvs.x3=t.x/e,this._uvs.y3=(t.y+t.height)/s},i.Texture.fromCanvas=function(t,e){var s=i.BaseTexture.fromCanvas(t,e);return new i.Texture(s)},i.TextureUvs=function(){this.x0=0,this.y0=0,this.x1=0,this.y1=0,this.x2=0,this.y2=0,this.x3=0,this.y3=0},i.RenderTexture=function(t,e,s,n,r){if(this.width=t||100,this.height=e||100,this.resolution=r||1,this.frame=new i.Rectangle(0,0,this.width*this.resolution,this.height*this.resolution),this.crop=new i.Rectangle(0,0,this.width*this.resolution,this.height*this.resolution),this.baseTexture=new i.BaseTexture,this.baseTexture.width=this.width*this.resolution,this.baseTexture.height=this.height*this.resolution,this.baseTexture._glTextures=[],this.baseTexture.resolution=this.resolution,this.baseTexture.scaleMode=n||i.scaleModes.DEFAULT,this.baseTexture.hasLoaded=!0,i.Texture.call(this,this.baseTexture,new i.Rectangle(0,0,this.width*this.resolution,this.height*this.resolution)),this.renderer=s||i.defaultRenderer,this.renderer.type===i.WEBGL_RENDERER){var o=this.renderer.gl;this.baseTexture._dirty[o.id]=!1,this.textureBuffer=new i.FilterTexture(o,this.width,this.height,this.baseTexture.scaleMode),this.baseTexture._glTextures[o.id]=this.textureBuffer.texture,this.render=this.renderWebGL,this.projection=new i.Point(.5*this.width,.5*-this.height)}else this.render=this.renderCanvas,this.textureBuffer=new i.CanvasBuffer(this.width*this.resolution,this.height*this.resolution),this.baseTexture.source=this.textureBuffer.canvas;this.valid=!0,this.tempMatrix=new Phaser.Matrix,this._updateUvs()},i.RenderTexture.prototype=Object.create(i.Texture.prototype),i.RenderTexture.prototype.constructor=i.RenderTexture,i.RenderTexture.prototype.resize=function(t,e,s){t===this.width&&e===this.height||(this.valid=t>0&&e>0,this.width=t,this.height=e,this.frame.width=this.crop.width=t*this.resolution,this.frame.height=this.crop.height=e*this.resolution,s&&(this.baseTexture.width=this.width*this.resolution,this.baseTexture.height=this.height*this.resolution),this.renderer.type===i.WEBGL_RENDERER&&(this.projection.x=this.width/2,this.projection.y=-this.height/2),this.valid&&this.textureBuffer.resize(this.width,this.height))},i.RenderTexture.prototype.clear=function(){this.valid&&(this.renderer.type===i.WEBGL_RENDERER&&this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER,this.textureBuffer.frameBuffer),this.textureBuffer.clear())},i.RenderTexture.prototype.renderWebGL=function(t,e,i){if(this.valid&&0!==t.alpha){var s=t.worldTransform;s.identity(),s.translate(0,2*this.projection.y),e&&s.append(e),s.scale(1,-1);for(var n=0;n<t.children.length;n++)t.children[n].updateTransform();var r=this.renderer.gl;r.viewport(0,0,this.width*this.resolution,this.height*this.resolution),r.bindFramebuffer(r.FRAMEBUFFER,this.textureBuffer.frameBuffer),i&&this.textureBuffer.clear(),this.renderer.spriteBatch.dirty=!0,this.renderer.renderDisplayObject(t,this.projection,this.textureBuffer.frameBuffer,e),this.renderer.spriteBatch.dirty=!0}},i.RenderTexture.prototype.renderCanvas=function(t,e,i){if(this.valid&&0!==t.alpha){var s=t.worldTransform;s.identity(),e&&s.append(e);for(var n=0;n<t.children.length;n++)t.children[n].updateTransform();i&&this.textureBuffer.clear();var r=this.renderer.resolution;this.renderer.resolution=this.resolution,this.renderer.renderDisplayObject(t,this.textureBuffer.context,e),this.renderer.resolution=r}},i.RenderTexture.prototype.getImage=function(){var t=new Image;return t.src=this.getBase64(),t},i.RenderTexture.prototype.getBase64=function(){return this.getCanvas().toDataURL()},i.RenderTexture.prototype.getCanvas=function(){if(this.renderer.type===i.WEBGL_RENDERER){var t=this.renderer.gl,e=this.textureBuffer.width,s=this.textureBuffer.height,n=new Uint8Array(4*e*s);t.bindFramebuffer(t.FRAMEBUFFER,this.textureBuffer.frameBuffer),t.readPixels(0,0,e,s,t.RGBA,t.UNSIGNED_BYTE,n),t.bindFramebuffer(t.FRAMEBUFFER,null);var r=new i.CanvasBuffer(e,s),o=r.context.getImageData(0,0,e,s);return o.data.set(n),r.context.putImageData(o,0,0),r.canvas}return this.textureBuffer.canvas},i.AbstractFilter=function(t,e){this.passes=[this],this.shaders=[],this.dirty=!0,this.padding=0,this.uniforms=e||{},this.fragmentSrc=t||[]},i.AbstractFilter.prototype.constructor=i.AbstractFilter,i.AbstractFilter.prototype.syncUniforms=function(){for(var t=0,e=this.shaders.length;t<e;t++)this.shaders[t].dirty=!0},i.Strip=function(t){i.DisplayObjectContainer.call(this),this.texture=t,this.uvs=new i.Float32Array([0,1,1,1,1,0,0,1]),this.vertices=new i.Float32Array([0,0,100,0,100,100,0,100]),this.colors=new i.Float32Array([1,1,1,1]),this.indices=new i.Uint16Array([0,1,2,3]),this.dirty=!0,this.blendMode=i.blendModes.NORMAL,this.canvasPadding=0,this.drawMode=i.Strip.DrawModes.TRIANGLE_STRIP},i.Strip.prototype=Object.create(i.DisplayObjectContainer.prototype),i.Strip.prototype.constructor=i.Strip,i.Strip.prototype._renderWebGL=function(t){!this.visible||this.alpha<=0||(t.spriteBatch.stop(),this._vertexBuffer||this._initWebGL(t),t.shaderManager.setShader(t.shaderManager.stripShader),this._renderStrip(t),t.spriteBatch.start())},i.Strip.prototype._initWebGL=function(t){var e=t.gl;this._vertexBuffer=e.createBuffer(),this._indexBuffer=e.createBuffer(),this._uvBuffer=e.createBuffer(),this._colorBuffer=e.createBuffer(),e.bindBuffer(e.ARRAY_BUFFER,this._vertexBuffer),e.bufferData(e.ARRAY_BUFFER,this.vertices,e.DYNAMIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,this._uvBuffer),e.bufferData(e.ARRAY_BUFFER,this.uvs,e.STATIC_DRAW),e.bindBuffer(e.ARRAY_BUFFER,this._colorBuffer),e.bufferData(e.ARRAY_BUFFER,this.colors,e.STATIC_DRAW),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this._indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,this.indices,e.STATIC_DRAW)},i.Strip.prototype._renderStrip=function(t){var e=t.gl,s=t.projection,n=t.offset,r=t.shaderManager.stripShader,o=this.drawMode===i.Strip.DrawModes.TRIANGLE_STRIP?e.TRIANGLE_STRIP:e.TRIANGLES;t.blendModeManager.setBlendMode(this.blendMode),e.uniformMatrix3fv(r.translationMatrix,!1,this.worldTransform.toArray(!0)),e.uniform2f(r.projectionVector,s.x,-s.y),e.uniform2f(r.offsetVector,-n.x,-n.y),e.uniform1f(r.alpha,this.worldAlpha),this.dirty?(this.dirty=!1,e.bindBuffer(e.ARRAY_BUFFER,this._vertexBuffer),e.bufferData(e.ARRAY_BUFFER,this.vertices,e.STATIC_DRAW),e.vertexAttribPointer(r.aVertexPosition,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this._uvBuffer),e.bufferData(e.ARRAY_BUFFER,this.uvs,e.STATIC_DRAW),e.vertexAttribPointer(r.aTextureCoord,2,e.FLOAT,!1,0,0),e.activeTexture(e.TEXTURE0),this.texture.baseTexture._dirty[e.id]?t.renderer.updateTexture(this.texture.baseTexture):e.bindTexture(e.TEXTURE_2D,this.texture.baseTexture._glTextures[e.id]),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this._indexBuffer),e.bufferData(e.ELEMENT_ARRAY_BUFFER,this.indices,e.STATIC_DRAW)):(e.bindBuffer(e.ARRAY_BUFFER,this._vertexBuffer),e.bufferSubData(e.ARRAY_BUFFER,0,this.vertices),e.vertexAttribPointer(r.aVertexPosition,2,e.FLOAT,!1,0,0),e.bindBuffer(e.ARRAY_BUFFER,this._uvBuffer),e.vertexAttribPointer(r.aTextureCoord,2,e.FLOAT,!1,0,0),e.activeTexture(e.TEXTURE0),this.texture.baseTexture._dirty[e.id]?t.renderer.updateTexture(this.texture.baseTexture):e.bindTexture(e.TEXTURE_2D,this.texture.baseTexture._glTextures[e.id]),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this._indexBuffer)),e.drawElements(o,this.indices.length,e.UNSIGNED_SHORT,0)},i.Strip.prototype._renderCanvas=function(t){var e=t.context,s=this.worldTransform,n=s.tx*t.resolution+t.shakeX,r=s.ty*t.resolution+t.shakeY;t.roundPixels?e.setTransform(s.a,s.b,s.c,s.d,0|n,0|r):e.setTransform(s.a,s.b,s.c,s.d,n,r),this.drawMode===i.Strip.DrawModes.TRIANGLE_STRIP?this._renderCanvasTriangleStrip(e):this._renderCanvasTriangles(e)},i.Strip.prototype._renderCanvasTriangleStrip=function(t){var e=this.vertices,i=this.uvs,s=e.length/2;this.count++;for(var n=0;n<s-2;n++){var r=2*n;this._renderCanvasDrawTriangle(t,e,i,r,r+2,r+4)}},i.Strip.prototype._renderCanvasTriangles=function(t){var e=this.vertices,i=this.uvs,s=this.indices,n=s.length;this.count++;for(var r=0;r<n;r+=3){var o=2*s[r],a=2*s[r+1],h=2*s[r+2];this._renderCanvasDrawTriangle(t,e,i,o,a,h)}},i.Strip.prototype._renderCanvasDrawTriangle=function(t,e,i,s,n,r){var o=this.texture.baseTexture.source,a=this.texture.width,h=this.texture.height,l=e[s],c=e[n],u=e[r],d=e[s+1],p=e[n+1],f=e[r+1],g=i[s]*a,m=i[n]*a,y=i[r]*a,v=i[s+1]*h,b=i[n+1]*h,x=i[r+1]*h;if(this.canvasPadding>0){var w=this.canvasPadding/this.worldTransform.a,_=this.canvasPadding/this.worldTransform.d,P=(l+c+u)/3,T=(d+p+f)/3,C=l-P,S=d-T,A=Math.sqrt(C*C+S*S);l=P+C/A*(A+w),d=T+S/A*(A+_),C=c-P,S=p-T,A=Math.sqrt(C*C+S*S),c=P+C/A*(A+w),p=T+S/A*(A+_),C=u-P,S=f-T,A=Math.sqrt(C*C+S*S),u=P+C/A*(A+w),f=T+S/A*(A+_)}t.save(),t.beginPath(),t.moveTo(l,d),t.lineTo(c,p),t.lineTo(u,f),t.closePath(),t.clip();var E=g*b+v*y+m*x-b*y-v*m-g*x,I=l*b+v*u+c*x-b*u-v*c-l*x,M=g*c+l*y+m*u-c*y-l*m-g*u,R=g*b*u+v*c*y+l*m*x-l*b*y-v*m*u-g*c*x,B=d*b+v*f+p*x-b*f-v*p-d*x,L=g*p+d*y+m*f-p*y-d*m-g*f,k=g*b*f+v*p*y+d*m*x-d*b*y-v*m*f-g*p*x;t.transform(I/E,B/E,M/E,L/E,R/E,k/E),t.drawImage(o,0,0),t.restore()},i.Strip.prototype.renderStripFlat=function(t){var e=this.context,i=t.vertices,s=i.length/2;this.count++,e.beginPath();for(var n=1;n<s-2;n++){var r=2*n,o=i[r],a=i[r+2],h=i[r+4],l=i[r+1],c=i[r+3],u=i[r+5];e.moveTo(o,l),e.lineTo(a,c),e.lineTo(h,u)}e.fillStyle="#FF0000",e.fill(),e.closePath()},i.Strip.prototype.onTextureUpdate=function(){this.updateFrame=!0},i.Strip.prototype.getBounds=function(t){for(var e=t||this.worldTransform,s=e.a,n=e.b,r=e.c,o=e.d,a=e.tx,h=e.ty,l=-1/0,c=-1/0,u=1/0,d=1/0,p=this.vertices,f=0,g=p.length;f<g;f+=2){var m=p[f],y=p[f+1],v=s*m+r*y+a,b=o*y+n*m+h;u=v<u?v:u,d=b<d?b:d,l=v>l?v:l,c=b>c?b:c}if(u===-1/0||c===1/0)return i.EmptyRectangle;var x=this._bounds;return x.x=u,x.width=l-u,x.y=d,x.height=c-d,this._currentBounds=x,x},i.Strip.DrawModes={TRIANGLE_STRIP:0,TRIANGLES:1},i.Rope=function(t,e){i.Strip.call(this,t),this.points=e,this.vertices=new i.Float32Array(4*e.length),this.uvs=new i.Float32Array(4*e.length),this.colors=new i.Float32Array(2*e.length),this.indices=new i.Uint16Array(2*e.length),this.refresh()},i.Rope.prototype=Object.create(i.Strip.prototype),i.Rope.prototype.constructor=i.Rope,i.Rope.prototype.refresh=function(){var t=this.points;if(!(t.length<1)){var e=this.uvs,i=(t[0],this.indices),s=this.colors;this.count-=.2,e[0]=0,e[1]=0,e[2]=0,e[3]=1,s[0]=1,s[1]=1,i[0]=0,i[1]=1;for(var n,r,o,a=t.length,h=1;h<a;h++)n=t[h],r=4*h,o=h/(a-1),e[r]=o,e[r+1]=0,e[r+2]=o,e[r+3]=1,r=2*h,s[r]=1,s[r+1]=1,r=2*h,i[r]=r,i[r+1]=r+1,n}},i.Rope.prototype.updateTransform=function(){var t=this.points;if(!(t.length<1)){var e,s=t[0],n={x:0,y:0};this.count-=.2;for(var r,o,a,h,l,c=this.vertices,u=t.length,d=0;d<u;d++)r=t[d],o=4*d,e=d<t.length-1?t[d+1]:r,n.y=-(e.x-s.x),n.x=e.y-s.y,a=10*(1-d/(u-1)),a>1&&(a=1),h=Math.sqrt(n.x*n.x+n.y*n.y),l=this.texture.height/2,n.x/=h,n.y/=h,n.x*=l,n.y*=l,c[o]=r.x+n.x,c[o+1]=r.y+n.y,c[o+2]=r.x-n.x,c[o+3]=r.y-n.y,s=r;i.DisplayObjectContainer.prototype.updateTransform.call(this)}},i.Rope.prototype.setTexture=function(t){this.texture=t},i.TilingSprite=function(t,e,s){i.Sprite.call(this,t),this._width=e||128,this._height=s||128,this.tileScale=new i.Point(1,1),this.tileScaleOffset=new i.Point(1,1),this.tilePosition=new i.Point,this.renderable=!0,this.tint=16777215,this.textureDebug=!1,this.blendMode=i.blendModes.NORMAL,this.canvasBuffer=null,this.tilingTexture=null,this.tilePattern=null,this.refreshTexture=!0,this.frameWidth=0,this.frameHeight=0},i.TilingSprite.prototype=Object.create(i.Sprite.prototype),i.TilingSprite.prototype.constructor=i.TilingSprite,i.TilingSprite.prototype.setTexture=function(t){this.texture!==t&&(this.texture=t,this.refreshTexture=!0,this.cachedTint=16777215)},i.TilingSprite.prototype._renderWebGL=function(t){if(this.visible&&this.renderable&&0!==this.alpha){if(this._mask&&(t.spriteBatch.stop(),t.maskManager.pushMask(this.mask,t),t.spriteBatch.start()),this._filters&&(t.spriteBatch.flush(),t.filterManager.pushFilter(this._filterBlock)),this.refreshTexture){if(this.generateTilingTexture(!0,t),!this.tilingTexture)return;this.tilingTexture.needsUpdate&&(t.renderer.updateTexture(this.tilingTexture.baseTexture),this.tilingTexture.needsUpdate=!1)}t.spriteBatch.renderTilingSprite(this);for(var e=0;e<this.children.length;e++)this.children[e]._renderWebGL(t);t.spriteBatch.stop(),this._filters&&t.filterManager.popFilter(),this._mask&&t.maskManager.popMask(this._mask,t),t.spriteBatch.start()}},i.TilingSprite.prototype._renderCanvas=function(t){if(this.visible&&this.renderable&&0!==this.alpha){var e=t.context;this._mask&&t.maskManager.pushMask(this._mask,t),e.globalAlpha=this.worldAlpha;var s=this.worldTransform,n=t.resolution,r=s.tx*n+t.shakeX,o=s.ty*n+t.shakeY;if(e.setTransform(s.a*n,s.b*n,s.c*n,s.d*n,r,o),this.refreshTexture){if(this.generateTilingTexture(!1,t),!this.tilingTexture)return;this.tilePattern=e.createPattern(this.tilingTexture.baseTexture.source,"repeat")}var a=t.currentBlendMode;this.blendMode!==t.currentBlendMode&&(t.currentBlendMode=this.blendMode,e.globalCompositeOperation=i.blendModesCanvas[t.currentBlendMode]);var h=this.tilePosition,l=this.tileScale;h.x%=this.tilingTexture.baseTexture.width,h.y%=this.tilingTexture.baseTexture.height,e.scale(l.x,l.y),e.translate(h.x+this.anchor.x*-this._width,h.y+this.anchor.y*-this._height),e.fillStyle=this.tilePattern;var r=-h.x,o=-h.y,c=this._width/l.x,u=this._height/l.y;t.roundPixels&&(r|=0,o|=0,c|=0,u|=0),e.fillRect(r,o,c,u),e.scale(1/l.x,1/l.y),e.translate(-h.x+this.anchor.x*this._width,-h.y+this.anchor.y*this._height),this._mask&&t.maskManager.popMask(t);for(var d=0;d<this.children.length;d++)this.children[d]._renderCanvas(t);a!==this.blendMode&&(t.currentBlendMode=a,e.globalCompositeOperation=i.blendModesCanvas[a])}},i.TilingSprite.prototype.onTextureUpdate=function(){},i.TilingSprite.prototype.generateTilingTexture=function(t,e){if(this.texture.baseTexture.hasLoaded){var s=this.texture,n=s.frame,r=this._frame.sourceSizeW||this._frame.width,o=this._frame.sourceSizeH||this._frame.height,a=0,h=0;this._frame.trimmed&&(a=this._frame.spriteSourceSizeX,h=this._frame.spriteSourceSizeY),t&&(r=i.getNextPowerOfTwo(r),o=i.getNextPowerOfTwo(o)),this.canvasBuffer?(this.canvasBuffer.resize(r,o),this.tilingTexture.baseTexture.width=r,this.tilingTexture.baseTexture.height=o,this.tilingTexture.needsUpdate=!0):(this.canvasBuffer=new i.CanvasBuffer(r,o),this.tilingTexture=i.Texture.fromCanvas(this.canvasBuffer.canvas),this.tilingTexture.isTiling=!0,this.tilingTexture.needsUpdate=!0),this.textureDebug&&(this.canvasBuffer.context.strokeStyle="#00ff00",this.canvasBuffer.context.strokeRect(0,0,r,o));var l=s.crop.width,c=s.crop.height;l===r&&c===o||(l=r,c=o),this.canvasBuffer.context.drawImage(s.baseTexture.source,s.crop.x,s.crop.y,s.crop.width,s.crop.height,a,h,l,c),this.tileScaleOffset.x=n.width/r,this.tileScaleOffset.y=n.height/o,this.refreshTexture=!1,this.tilingTexture.baseTexture._powerOf2=!0}},i.TilingSprite.prototype.getBounds=function(){var t=this._width,e=this._height,i=t*(1-this.anchor.x),s=t*-this.anchor.x,n=e*(1-this.anchor.y),r=e*-this.anchor.y,o=this.worldTransform,a=o.a,h=o.b,l=o.c,c=o.d,u=o.tx,d=o.ty,p=a*s+l*r+u,f=c*r+h*s+d,g=a*i+l*r+u,m=c*r+h*i+d,y=a*i+l*n+u,v=c*n+h*i+d,b=a*s+l*n+u,x=c*n+h*s+d,w=-1/0,_=-1/0,P=1/0,T=1/0;P=p<P?p:P,P=g<P?g:P,P=y<P?y:P,P=b<P?b:P,T=f<T?f:T,T=m<T?m:T,T=v<T?v:T,T=x<T?x:T,w=p>w?p:w,w=g>w?g:w,w=y>w?y:w,w=b>w?b:w,_=f>_?f:_,_=m>_?m:_,_=v>_?v:_,_=x>_?x:_;var C=this._bounds;return C.x=P,C.width=w-P,C.y=T,C.height=_-T,this._currentBounds=C,C},i.TilingSprite.prototype.destroy=function(){i.Sprite.prototype.destroy.call(this),this.canvasBuffer&&(this.canvasBuffer.destroy(),this.canvasBuffer=null),this.tileScale=null,this.tileScaleOffset=null,this.tilePosition=null,this.tilingTexture&&(this.tilingTexture.destroy(!0),this.tilingTexture=null)},Object.defineProperty(i.TilingSprite.prototype,"width",{get:function(){return this._width},set:function(t){this._width=t}}),Object.defineProperty(i.TilingSprite.prototype,"height",{get:function(){return this._height},set:function(t){this._height=t}}),void 0!==t&&t.exports&&(e=t.exports=i),e.PIXI=i,i}).call(this)},,,,,,,,,,function(t,e,i){t.exports=i(33)}],[102]); |
|
Java | mit | 1669832a0967cb78f2d323547ac58019f6d094cc | 0 | jimregan/jngramtool,jimregan/jngramtool | package ie.tcd.slscs.kfclone;
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;
import java.awt.event.KeyEvent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import javax.swing.AbstractButton;
import javax.swing.JButton;
public class MainInterface {
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
private Font kfFont = new Font("Arial", Font.PLAIN, 11);
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainInterface window = new MainInterface();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MainInterface() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 690, 490);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
mnFile.setMnemonic('F');
menuBar.add(mnFile);
JMenuItem mntmViewNgramFile = new JMenuItem("View n-Gram File");
mntmViewNgramFile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.ALT_MASK));
mnFile.add(mntmViewNgramFile);
JMenuItem mntmNewMenuItem = new JMenuItem("View Text File");
mntmNewMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, InputEvent.ALT_MASK));
mnFile.add(mntmNewMenuItem);
mnFile.addSeparator();
JMenuItem mntmNewMenuItem_1 = new JMenuItem("Exit");
mntmNewMenuItem_1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, InputEvent.ALT_MASK));
mnFile.add(mntmNewMenuItem_1);
JMenu mnTools = new JMenu("Tools");
mnTools.setMnemonic('T');
menuBar.add(mnTools);
JMenuItem mntmGetWordgrams = new JMenuItem("Get Wordgrams");
mntmGetWordgrams.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, InputEvent.CTRL_MASK));
mnTools.add(mntmGetWordgrams);
JMenuItem mntmNewMenuItem_2 = new JMenuItem("Get Chargrams from Wordgram file");
mntmNewMenuItem_2.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK));
mnTools.add(mntmNewMenuItem_2);
mnTools.addSeparator();
JMenuItem mntmMergeTwoOr = new JMenuItem("Merge Two or More Alphabetically-Sorted Wordgram files");
mntmMergeTwoOr.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, InputEvent.CTRL_MASK));
mnTools.add(mntmMergeTwoOr);
JMenuItem mntmConvertAlphabeticSort = new JMenuItem("Convert Alphabetic Sort to Frequency Sort");
mntmConvertAlphabeticSort.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_MASK));
mnTools.add(mntmConvertAlphabeticSort);
mnTools.addSeparator();
JMenuItem mntmNewMenuItem_3 = new JMenuItem("Get Phrase-Frames from Wordgram file");
mntmNewMenuItem_3.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, InputEvent.CTRL_MASK));
mnTools.add(mntmNewMenuItem_3);
JMenuItem mntmBrowsePhraseframeFile = new JMenuItem("Browse Phrase-Frame file");
mntmBrowsePhraseframeFile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_B, InputEvent.CTRL_MASK));
mnTools.add(mntmBrowsePhraseframeFile);
JMenuItem mntmCountTokensIn = new JMenuItem("Count Tokens in Source file");
mntmCountTokensIn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, InputEvent.CTRL_MASK));
mnTools.add(mntmCountTokensIn);
mnTools.addSeparator();
JMenuItem mntmConvertHtmlTo = new JMenuItem("Convert HTML to Text");
mntmConvertHtmlTo.setEnabled(false);
mnTools.add(mntmConvertHtmlTo);
JMenuItem mntmConvertSgml = new JMenuItem("Convert SGML / XML to Text");
mntmConvertSgml.setEnabled(false);
mnTools.add(mntmConvertSgml);
JMenu mnOptions = new JMenu("Options");
mnOptions.setMnemonic('O');
menuBar.add(mnOptions);
JMenuItem mntmNewMenuItem_4 = new JMenuItem("Edit Options");
mntmNewMenuItem_4.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, InputEvent.CTRL_MASK));
mnOptions.add(mntmNewMenuItem_4);
JCheckBoxMenuItem chckbxmntmNewCheckItem = new JCheckBoxMenuItem("Advanced");
chckbxmntmNewCheckItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.ALT_MASK));
chckbxmntmNewCheckItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
AbstractButton absbut = (AbstractButton) evt.getSource();
boolean selected = absbut.getModel().isSelected();
if(selected) {
frame.setBounds(100, 100, 690, 490);
} else {
frame.setBounds(100, 100, 550, 490);
}
}
});
mnOptions.add(chckbxmntmNewCheckItem);
JMenu mnHelp = new JMenu("Help");
mnHelp.setMnemonic('H');
menuBar.add(mnHelp);
JMenuItem mntmNewMenuItem_5 = new JMenuItem("Help");
mntmNewMenuItem_5.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0));
mnHelp.add(mntmNewMenuItem_5);
JMenuItem mntmAbout = new JMenuItem("About");
mnHelp.add(mntmAbout);
frame.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("nGrams (e.g. 1-3, 5, 10)");
lblNewLabel.setFont(kfFont);
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setBounds(2, 2, 120, 25);
frame.getContentPane().add(lblNewLabel);
textField = new JTextField();
textField.setFont(kfFont);
textField.setBounds(130, 7, 110, 15);
frame.getContentPane().add(textField);
textField.setColumns(10);
JLabel lblFloor = new JLabel("Floor");
lblFloor.setFont(kfFont);
lblFloor.setBounds(245, 2, 46, 25);
frame.getContentPane().add(lblFloor);
textField_1 = new JTextField();
textField_1.setFont(kfFont);
textField_1.setBounds(275, 7, 30, 15);
textField_1.setHorizontalAlignment(SwingConstants.CENTER);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
Choice choice = new Choice();
choice.setBounds(315, 3, 95, 20);
choice.setFont(kfFont);
choice.addItem("Don't show");
choice.addItem("Show n-grams");
frame.getContentPane().add(choice);
JLabel lblNewLabel_1 = new JLabel("Chars to sort");
lblNewLabel_1.setFont(kfFont);
lblNewLabel_1.setBounds(415, 2, 65, 20);
frame.getContentPane().add(lblNewLabel_1);
Choice choice_1 = new Choice();
choice_1.setBounds(485, 3, 50, 20);
choice_1.setFont(kfFont);
choice_1.addItem("128");
choice_1.addItem("256");
choice_1.addItem("512");
choice_1.addItem("1024");
choice_1.addItem("2048");
frame.getContentPane().add(choice_1);
JLabel lblAdvOpt = new JLabel("Advanced Options");
lblAdvOpt.setFont(kfFont);
lblAdvOpt.setBounds(540, 2, 95, 20);
frame.getContentPane().add(lblAdvOpt);
Choice choice_2 = new Choice();
choice_2.setBounds(5, 30, 115, 20);
choice_2.setFont(kfFont);
choice_2.addItem("not case-sensitive");
choice_2.addItem("Case sensitive");
frame.getContentPane().add(choice_2);
Choice choice_3 = new Choice();
choice_3.setBounds(125, 30, 145, 20);
choice_3.setFont(kfFont);
choice_3.addItem("Observe TreatAsToken");
choice_3.addItem("Punct. as in KeepChars");
choice_3.addItem("Replace . , - ' with space");
choice_3.addItem("Keep internal . , - '");
choice_3.addItem("Delete internal - keep . , '");
frame.getContentPane().add(choice_3);
Choice choice_4 = new Choice();
choice_4.setFont(kfFont);
choice_4.setBounds(275, 30, 115, 20);
choice_4.addItem("Alphabetical Sort");
choice_4.addItem("Frequency Sort");
frame.getContentPane().add(choice_4);
Choice choice_5 = new Choice();
choice_5.setFont(kfFont);
choice_5.setBounds(395, 30, 130, 20);
choice_5.addItem("Retain numerals");
choice_5.addItem("Change numerals to #");
choice_5.addItem("Make all numbers #");
frame.getContentPane().add(choice_5);
JLabel lblNewLabel_2 = new JLabel("Source files");
lblNewLabel_2.setFont(kfFont);
lblNewLabel_2.setBounds(2, 70, 70, 20);
frame.getContentPane().add(lblNewLabel_2);
JButton btnNewButton = new JButton("<html><center>Add<br><u>S</u>ource files</center></html>");
btnNewButton.setMargin(new Insets(0,0,0,0));
btnNewButton.setFont(kfFont);
btnNewButton.setBounds(2, 95, 75, 35);
frame.getContentPane().add(btnNewButton);
JButton btnNewButton_1 = new JButton("<html><center><u>R</u>eplace<br>Source files</center></html>");
btnNewButton_1.setMargin(new Insets(0,0,0,0));
btnNewButton_1.setFont(kfFont);
btnNewButton_1.setBounds(2, 135, 75, 35);
frame.getContentPane().add(btnNewButton_1);
Choice choice_6 = new Choice();
choice_6.setBounds(0, 277, 28, 20);
frame.getContentPane().add(choice_6);
}
}
| jngramtool-core/src/main/java/ie/tcd/slscs/kfclone/MainInterface.java | package ie.tcd.slscs.kfclone;
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;
import java.awt.event.KeyEvent;
import java.awt.event.InputEvent;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import javax.swing.JButton;
public class MainInterface {
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
private Font kfFont = new Font("Arial", Font.PLAIN, 11);
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainInterface window = new MainInterface();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MainInterface() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 690, 490);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
mnFile.setMnemonic('F');
menuBar.add(mnFile);
JMenuItem mntmViewNgramFile = new JMenuItem("View n-Gram File");
mntmViewNgramFile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.ALT_MASK));
mnFile.add(mntmViewNgramFile);
JMenuItem mntmNewMenuItem = new JMenuItem("View Text File");
mntmNewMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, InputEvent.ALT_MASK));
mnFile.add(mntmNewMenuItem);
mnFile.addSeparator();
JMenuItem mntmNewMenuItem_1 = new JMenuItem("Exit");
mntmNewMenuItem_1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, InputEvent.ALT_MASK));
mnFile.add(mntmNewMenuItem_1);
JMenu mnTools = new JMenu("Tools");
mnTools.setMnemonic('T');
menuBar.add(mnTools);
JMenuItem mntmGetWordgrams = new JMenuItem("Get Wordgrams");
mntmGetWordgrams.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, InputEvent.CTRL_MASK));
mnTools.add(mntmGetWordgrams);
JMenuItem mntmNewMenuItem_2 = new JMenuItem("Get Chargrams from Wordgram file");
mntmNewMenuItem_2.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK));
mnTools.add(mntmNewMenuItem_2);
mnTools.addSeparator();
JMenuItem mntmMergeTwoOr = new JMenuItem("Merge Two or More Alphabetically-Sorted Wordgram files");
mntmMergeTwoOr.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, InputEvent.CTRL_MASK));
mnTools.add(mntmMergeTwoOr);
JMenuItem mntmConvertAlphabeticSort = new JMenuItem("Convert Alphabetic Sort to Frequency Sort");
mntmConvertAlphabeticSort.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_MASK));
mnTools.add(mntmConvertAlphabeticSort);
mnTools.addSeparator();
JMenuItem mntmNewMenuItem_3 = new JMenuItem("Get Phrase-Frames from Wordgram file");
mntmNewMenuItem_3.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, InputEvent.CTRL_MASK));
mnTools.add(mntmNewMenuItem_3);
JMenuItem mntmBrowsePhraseframeFile = new JMenuItem("Browse Phrase-Frame file");
mntmBrowsePhraseframeFile.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_B, InputEvent.CTRL_MASK));
mnTools.add(mntmBrowsePhraseframeFile);
JMenuItem mntmCountTokensIn = new JMenuItem("Count Tokens in Source file");
mntmCountTokensIn.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, InputEvent.CTRL_MASK));
mnTools.add(mntmCountTokensIn);
mnTools.addSeparator();
JMenuItem mntmConvertHtmlTo = new JMenuItem("Convert HTML to Text");
mntmConvertHtmlTo.setEnabled(false);
mnTools.add(mntmConvertHtmlTo);
JMenuItem mntmConvertSgml = new JMenuItem("Convert SGML / XML to Text");
mntmConvertSgml.setEnabled(false);
mnTools.add(mntmConvertSgml);
JMenu mnOptions = new JMenu("Options");
mnOptions.setMnemonic('O');
menuBar.add(mnOptions);
JMenuItem mntmNewMenuItem_4 = new JMenuItem("Edit Options");
mntmNewMenuItem_4.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, InputEvent.CTRL_MASK));
mnOptions.add(mntmNewMenuItem_4);
JCheckBoxMenuItem chckbxmntmNewCheckItem = new JCheckBoxMenuItem("Advanced");
chckbxmntmNewCheckItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.ALT_MASK));
mnOptions.add(chckbxmntmNewCheckItem);
JMenu mnHelp = new JMenu("Help");
mnHelp.setMnemonic('H');
menuBar.add(mnHelp);
JMenuItem mntmNewMenuItem_5 = new JMenuItem("Help");
mntmNewMenuItem_5.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0));
mnHelp.add(mntmNewMenuItem_5);
JMenuItem mntmAbout = new JMenuItem("About");
mnHelp.add(mntmAbout);
frame.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("nGrams (e.g. 1-3, 5, 10)");
lblNewLabel.setFont(kfFont);
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setBounds(2, 2, 120, 25);
frame.getContentPane().add(lblNewLabel);
textField = new JTextField();
textField.setFont(kfFont);
textField.setBounds(130, 7, 110, 15);
frame.getContentPane().add(textField);
textField.setColumns(10);
JLabel lblFloor = new JLabel("Floor");
lblFloor.setFont(kfFont);
lblFloor.setBounds(245, 2, 46, 25);
frame.getContentPane().add(lblFloor);
textField_1 = new JTextField();
textField_1.setFont(kfFont);
textField_1.setBounds(275, 7, 30, 15);
textField_1.setHorizontalAlignment(SwingConstants.CENTER);
frame.getContentPane().add(textField_1);
textField_1.setColumns(10);
Choice choice = new Choice();
choice.setBounds(315, 3, 95, 20);
choice.setFont(kfFont);
choice.addItem("Don't show");
choice.addItem("Show n-grams");
frame.getContentPane().add(choice);
JLabel lblNewLabel_1 = new JLabel("Chars to sort");
lblNewLabel_1.setFont(kfFont);
lblNewLabel_1.setBounds(415, 2, 65, 20);
frame.getContentPane().add(lblNewLabel_1);
Choice choice_1 = new Choice();
choice_1.setBounds(485, 3, 50, 20);
choice_1.setFont(kfFont);
choice_1.addItem("128");
choice_1.addItem("256");
choice_1.addItem("512");
choice_1.addItem("1024");
choice_1.addItem("2048");
frame.getContentPane().add(choice_1);
JLabel lblAdvOpt = new JLabel("Advanced Options");
lblAdvOpt.setFont(kfFont);
lblAdvOpt.setBounds(540, 2, 95, 20);
frame.getContentPane().add(lblAdvOpt);
Choice choice_2 = new Choice();
choice_2.setBounds(5, 30, 115, 20);
choice_2.setFont(kfFont);
choice_2.addItem("not case-sensitive");
choice_2.addItem("Case sensitive");
frame.getContentPane().add(choice_2);
Choice choice_3 = new Choice();
choice_3.setBounds(125, 30, 145, 20);
choice_3.setFont(kfFont);
choice_3.addItem("Observe TreatAsToken");
choice_3.addItem("Punct. as in KeepChars");
choice_3.addItem("Replace . , - ' with space");
choice_3.addItem("Keep internal . , - '");
choice_3.addItem("Delete internal - keep . , '");
frame.getContentPane().add(choice_3);
Choice choice_4 = new Choice();
choice_4.setFont(kfFont);
choice_4.setBounds(275, 30, 115, 20);
choice_4.addItem("Alphabetical Sort");
choice_4.addItem("Frequency Sort");
frame.getContentPane().add(choice_4);
Choice choice_5 = new Choice();
choice_5.setFont(kfFont);
choice_5.setBounds(395, 30, 130, 20);
choice_5.addItem("Retain numerals");
choice_5.addItem("Change numerals to #");
choice_5.addItem("Make all numbers #");
frame.getContentPane().add(choice_5);
JLabel lblNewLabel_2 = new JLabel("Source files");
lblNewLabel_2.setFont(kfFont);
lblNewLabel_2.setBounds(2, 70, 70, 20);
frame.getContentPane().add(lblNewLabel_2);
JButton btnNewButton = new JButton("<html><center>Add<br><u>S</u>ource Files</center></html>");
btnNewButton.setMargin(new Insets(0,0,0,0));
btnNewButton.setFont(kfFont);
btnNewButton.setBounds(2, 95, 75, 35);
frame.getContentPane().add(btnNewButton);
JButton btnNewButton_1 = new JButton("New button");
btnNewButton_1.setFont(kfFont);
btnNewButton_1.setBounds(0, 180, 82, 75);
frame.getContentPane().add(btnNewButton_1);
Choice choice_6 = new Choice();
choice_6.setBounds(0, 277, 28, 20);
frame.getContentPane().add(choice_6);
}
}
| one piece implemented... aside from getting the size right
| jngramtool-core/src/main/java/ie/tcd/slscs/kfclone/MainInterface.java | one piece implemented... aside from getting the size right | <ide><path>ngramtool-core/src/main/java/ie/tcd/slscs/kfclone/MainInterface.java
<ide> import javax.swing.JMenuItem;
<ide> import javax.swing.KeyStroke;
<ide> import java.awt.event.KeyEvent;
<add>import java.awt.event.ActionEvent;
<add>import java.awt.event.ActionListener;
<ide> import java.awt.event.InputEvent;
<ide> import javax.swing.JCheckBoxMenuItem;
<ide> import javax.swing.JLabel;
<ide> import javax.swing.SwingConstants;
<ide> import javax.swing.JTextField;
<add>import javax.swing.AbstractButton;
<ide> import javax.swing.JButton;
<ide>
<ide> public class MainInterface {
<ide> private void initialize() {
<ide> frame = new JFrame();
<ide> frame.setBounds(100, 100, 690, 490);
<add> frame.setResizable(false);
<ide> frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
<ide>
<ide> JMenuBar menuBar = new JMenuBar();
<ide>
<ide> JCheckBoxMenuItem chckbxmntmNewCheckItem = new JCheckBoxMenuItem("Advanced");
<ide> chckbxmntmNewCheckItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.ALT_MASK));
<add> chckbxmntmNewCheckItem.addActionListener(new ActionListener() {
<add> public void actionPerformed(ActionEvent evt) {
<add> AbstractButton absbut = (AbstractButton) evt.getSource();
<add> boolean selected = absbut.getModel().isSelected();
<add> if(selected) {
<add> frame.setBounds(100, 100, 690, 490);
<add> } else {
<add> frame.setBounds(100, 100, 550, 490);
<add> }
<add> }
<add> });
<ide> mnOptions.add(chckbxmntmNewCheckItem);
<ide>
<ide> JMenu mnHelp = new JMenu("Help");
<ide> lblNewLabel_2.setBounds(2, 70, 70, 20);
<ide> frame.getContentPane().add(lblNewLabel_2);
<ide>
<del> JButton btnNewButton = new JButton("<html><center>Add<br><u>S</u>ource Files</center></html>");
<add> JButton btnNewButton = new JButton("<html><center>Add<br><u>S</u>ource files</center></html>");
<ide> btnNewButton.setMargin(new Insets(0,0,0,0));
<ide> btnNewButton.setFont(kfFont);
<ide> btnNewButton.setBounds(2, 95, 75, 35);
<ide> frame.getContentPane().add(btnNewButton);
<ide>
<del> JButton btnNewButton_1 = new JButton("New button");
<add> JButton btnNewButton_1 = new JButton("<html><center><u>R</u>eplace<br>Source files</center></html>");
<add> btnNewButton_1.setMargin(new Insets(0,0,0,0));
<ide> btnNewButton_1.setFont(kfFont);
<del> btnNewButton_1.setBounds(0, 180, 82, 75);
<add> btnNewButton_1.setBounds(2, 135, 75, 35);
<ide> frame.getContentPane().add(btnNewButton_1);
<ide>
<ide> Choice choice_6 = new Choice(); |
|
Java | epl-1.0 | e10831e3a5786614877bc1f6a10a35de64760ef9 | 0 | phat-trien-phan-mem-phan-tan/dynamicpool,phat-trien-phan-mem-phan-tan/dynamicpool,phat-trien-phan-mem-phan-tan/dynamicpool,phat-trien-phan-mem-phan-tan/dynamicpool | DynamicPool/core/src/vn/edu/hust/student/dynamicpool/presentation/gameobject/EDirection.java | package vn.edu.hust.student.dynamicpool.presentation.gameobject;
public enum EDirection {
RIGHT,
TOP,
LEFT,
BOTTOM
}
| chuyen vi tri
| DynamicPool/core/src/vn/edu/hust/student/dynamicpool/presentation/gameobject/EDirection.java | chuyen vi tri | <ide><path>ynamicPool/core/src/vn/edu/hust/student/dynamicpool/presentation/gameobject/EDirection.java
<del>package vn.edu.hust.student.dynamicpool.presentation.gameobject;
<del>
<del>public enum EDirection {
<del> RIGHT,
<del> TOP,
<del> LEFT,
<del> BOTTOM
<del>} |
||
Java | bsd-2-clause | 9edcd69977d92a41bbf49dddb78118059e6e2220 | 0 | Sollace/BlazeLoader,BlazeLoader/BlazeLoader,warriordog/BlazeLoader,Sollace/BlazeLoader,warriordog/BlazeLoader,BlazeLoader/BlazeLoader,BlazeLoader/BlazeLoader | package net.acomputerdog.BlazeLoader.fix;
@Deprecated
/**
* A one-time-run class that is loaded at various times of startup to fix issues with Mojang code.
*/
public abstract class Fix {
/**
* Gets the stage of game startup/run to apply at. Defaults to EFixType.INIT.
* @return Return an EFixType representing the type of fix to apply.
*/
public EFixType getFixType(){
return EFixType.STARTUP;
}
/**
* Applies the fix.
*/
public abstract void apply();
/**
* Gets the name of the fix to be displayed in debug messages.
* @return Returns the name of the fix.
*/
public String getFixName(){
return this.getClass().getSimpleName();
}
}
| net/acomputerdog/BlazeLoader/fix/Fix.java | package net.acomputerdog.BlazeLoader.fix;
import net.acomputerdog.BlazeLoader.annotation.Beta;
@Beta(stable = true)
/**
* A one-time-run class that is loaded at various times of startup to fix issues with Mojang code.
*/
public abstract class Fix {
/**
* Gets the stage of game startup/run to apply at. Defaults to EFixType.INIT.
* @return Return an EFixType representing the type of fix to apply.
*/
public EFixType getFixType(){
return EFixType.STARTUP;
}
/**
* Applies the fix.
*/
public abstract void apply();
/**
* Gets the name of the fix to be displayed in debug messages.
* @return Returns the name of the fix.
*/
public String getFixName(){
return this.getClass().getSimpleName();
}
}
| Deprecate Fix
| net/acomputerdog/BlazeLoader/fix/Fix.java | Deprecate Fix | <ide><path>et/acomputerdog/BlazeLoader/fix/Fix.java
<ide> package net.acomputerdog.BlazeLoader.fix;
<ide>
<del>import net.acomputerdog.BlazeLoader.annotation.Beta;
<del>
<del>@Beta(stable = true)
<add>@Deprecated
<ide> /**
<ide> * A one-time-run class that is loaded at various times of startup to fix issues with Mojang code.
<ide> */ |
|
JavaScript | mit | 6e150a580ff94691486b8d39473ddf90679754bd | 0 | depackt/depackt-map,depackt/depackt-map | /**
* @link https://github.com/choojs/choo
* @link https://github.com/stackcss/sheetify
*/
// require('babel-polyfill')
const choo = require('choo')
const logger = require('choo-log')
const expose = require('choo-expose')
const css = require('sheetify')
const _findIndex = require('lodash/findIndex')
const Nanobounce = require('nanobounce')
const dpckt = require('./lib/depackt-api')
css('./styles/reset.css')
css('./styles/leaflet.css')
css('./styles/MarkerCluster.css')
css('./styles/MarkerCluster.Default.css')
css('./styles/github-markdown.css')
css('./styles/flex.css')
css('./styles/layout.css')
css('./styles/icons.css')
const Layout = require('./views/layout')
const NotFound = require('./views/404')
const AboutView = require('./views/about')
const ResourcesView = require('./views/resources')
const app = choo()
if (process.env.APP_ENV !== 'production') {
app.use(logger())
app.use(expose())
app.use(require('choo-service-worker/clear')())
}
app.use(require('choo-service-worker')())
app.use(store)
app.route('/', Layout(require('./views/main')))
app.route('/:bounds', Layout(require('./views/main')))
app.route('/about', Layout(AboutView))
app.route('/about/:hash', Layout(AboutView))
app.route('/about/:hash/*', Layout(NotFound))
app.route('/resources', Layout(ResourcesView))
app.route('/:bounds/*', Layout(NotFound))
app.mount('#app')
function store (state, emitter) {
state.coords = [50.850340, 4.351710]
state.zoom = 13
state.locations = []
state.tab = 'search'
state.isMobile = !window.matchMedia('(min-width:960px)').matches
state.tiles = state.tiles || undefined
state.tilesAttribution = state.tilesAttribution || undefined
state.mapBackground = state.mapBackground || 'light'
emitter.on('DOMContentLoaded', () => {
emitter.on('set:coords', setCoords)
emitter.on('get:locations', getLocations)
emitter.on('sw:installed', (registration) => {
if (registration.active) {
console.log(registration)
}
})
emitter.on('toggletab', (tab) => {
const opened = state.tab === tab
state.tab = opened ? '' : tab
emitter.emit('render')
})
emitter.emit('get:locations', {})
const nanobounce = Nanobounce()
window.onresize = callback
function callback () {
const prev = Object.assign({}, state)
nanobounce(() => {
emitter.emit('log:debug', 'Called onResize event')
state.isMobile = !window.matchMedia('(min-width:960px)').matches
if (prev.isMobile !== state.isMobile) {
state.header = !state.isMobile
}
emitter.emit('render')
})
}
})
function getLocations (payload) {
const {
lat = 50.850340,
lng = 4.351710,
distanceKm = 1000
} = payload
dpckt.getLocations({lat, lng, distanceKm}).then((response) => {
const { data } = response
if (!data.length) return
const selected = data[0]
const {lat, lng} = selected.address.location
state.coords = [lat, lng]
state.locations = data
const index = _findIndex(state.locations, { _id: selected._id })
state.selectedIndex = index
emitter.emit('render')
}).catch((err) => {
if (err) console.log(err)
})
}
function setCoords (options) {
state.coords = options.coords
state.zoom = options.zoom
emitter.emit('render')
}
}
| app/client/index.js | /**
* @link https://github.com/choojs/choo
* @link https://github.com/stackcss/sheetify
*/
// require('babel-polyfill')
const choo = require('choo')
const logger = require('choo-log')
const expose = require('choo-expose')
const css = require('sheetify')
const _findIndex = require('lodash/findIndex')
const Nanobounce = require('nanobounce')
const dpckt = require('./lib/depackt-api')
css('./styles/reset.css')
css('./styles/leaflet.css')
css('./styles/MarkerCluster.css')
css('./styles/MarkerCluster.Default.css')
css('./styles/github-markdown.css')
css('./styles/flex.css')
css('./styles/layout.css')
css('./styles/icons.css')
const Layout = require('./views/layout')
const NotFound = require('./views/404')
const AboutView = require('./views/about')
const ResourcesView = require('./views/resources')
const app = choo()
if (process.env.APP_ENV !== 'production') {
app.use(logger())
app.use(expose())
app.use(require('choo-service-worker/clear')())
}
app.use(require('choo-service-worker')())
app.use(store)
app.route('/', Layout(require('./views/main')))
app.route('/:bounds', Layout(require('./views/main')))
app.route('/about', Layout(AboutView))
app.route('/about/:hash', Layout(AboutView))
app.route('/about/:hash/*', Layout(NotFound))
app.route('/resources', Layout(ResourcesView))
app.route('/:bounds/*', Layout(NotFound))
app.mount('#app')
function store (state, emitter) {
state.coords = [50.850340, 4.351710]
state.zoom = 13
state.locations = []
state.tab = 'search'
state.isMobile = !window.matchMedia('(min-width:960px)').matches
state.tiles = state.tiles || undefined
state.tilesAttribution = state.tilesAttribution || undefined
state.mapBackground = state.mapBackground || 'light'
emitter.on('DOMContentLoaded', () => {
emitter.on('set:coords', setCoords)
emitter.on('get:locations', getLocations)
emitter.on('toggletab', (tab) => {
const opened = state.tab === tab
state.tab = opened ? '' : tab
emitter.emit('render')
})
emitter.emit('get:locations', {})
const nanobounce = Nanobounce()
window.onresize = callback
function callback () {
const prev = Object.assign({}, state)
nanobounce(() => {
emitter.emit('log:debug', 'Called onResize event')
state.isMobile = !window.matchMedia('(min-width:960px)').matches
if (prev.isMobile !== state.isMobile) {
state.header = !state.isMobile
}
emitter.emit('render')
})
}
})
function getLocations (payload) {
const {
lat = 50.850340,
lng = 4.351710,
distanceKm = 1000
} = payload
dpckt.getLocations({lat, lng, distanceKm}).then((response) => {
const { data } = response
if (!data.length) return
const selected = data[0]
const {lat, lng} = selected.address.location
state.coords = [lat, lng]
state.locations = data
const index = _findIndex(state.locations, { _id: selected._id })
state.selectedIndex = index
emitter.emit('render')
}).catch((err) => {
if (err) console.log(err)
})
}
function setCoords (options) {
state.coords = options.coords
state.zoom = options.zoom
emitter.emit('render')
}
}
| Add listener for serviceworker installation
| app/client/index.js | Add listener for serviceworker installation | <ide><path>pp/client/index.js
<ide> emitter.on('DOMContentLoaded', () => {
<ide> emitter.on('set:coords', setCoords)
<ide> emitter.on('get:locations', getLocations)
<add> emitter.on('sw:installed', (registration) => {
<add> if (registration.active) {
<add> console.log(registration)
<add> }
<add> })
<ide> emitter.on('toggletab', (tab) => {
<ide> const opened = state.tab === tab
<ide> state.tab = opened ? '' : tab |
|
JavaScript | mit | c21e9db27249664107abdc9af05507b0b654fec4 | 0 | styled-components/css-to-react-native | /* eslint-disable no-param-reassign */
const parse = require('postcss-value-parser');
const camelizeStyleName = require('fbjs/lib/camelizeStyleName');
const transforms = require('./transforms');
const TokenStream = require('./TokenStream');
// Note if this is wrong, you'll need to change tokenTypes.js too
const numberOrLengthRe = /^([+-]?(?:\d*\.)?\d+(?:[Ee][+-]?\d+)?)(?:px)?$/i;
const boolRe = /^true|false$/i;
// Undocumented export
export const transformRawValue = (input) => {
const value = input.trim();
const numberMatch = value.match(numberOrLengthRe);
if (numberMatch) return Number(numberMatch[1]);
const boolMatch = input.match(boolRe);
if (boolMatch) return boolMatch[0].toLowerCase() === 'true';
return value;
};
export const getStylesForProperty = (propName, inputValue, allowShorthand) => {
// Undocumented: allow ast to be passed in
let propValue;
const isRawValue = (allowShorthand === false) || !(propName in transforms);
if (isRawValue) {
const value = typeof inputValue === 'string' ? inputValue : parse.stringify(inputValue);
propValue = transformRawValue(value);
} else {
const ast = typeof inputValue === 'string' ? parse(inputValue.trim()) : inputValue;
const tokenStream = new TokenStream(ast.nodes);
propValue = transforms[propName](tokenStream);
}
return (propValue && propValue.$merge)
? propValue.$merge
: { [propName]: propValue };
};
export const getPropertyName = camelizeStyleName;
export default (rules, shorthandBlacklist = []) => rules.reduce((accum, rule) => {
const propertyName = getPropertyName(rule[0]);
const value = rule[1];
const allowShorthand = shorthandBlacklist.indexOf(propertyName) === -1;
return Object.assign(accum, getStylesForProperty(propertyName, value, allowShorthand));
}, {});
| src/index.js | /* eslint-disable no-param-reassign */
const parse = require('postcss-value-parser');
const camelizeStyleName = require('fbjs/lib/camelizeStyleName');
const transforms = require('./transforms');
const TokenStream = require('./TokenStream');
// Note if this is wrong, you'll need to change tokenTypes.js too
const numberOrLengthRe = /^([+-]?(?:\d*\.)?\d+(?:[Ee][+-]?\d+)?)(?:px)?$/;
// Undocumented export
export const transformRawValue = (input) => {
const value = input.trim().match(numberOrLengthRe);
return value ? Number(value[1]) : input;
};
export const getStylesForProperty = (propName, inputValue, allowShorthand) => {
// Undocumented: allow ast to be passed in
let propValue;
const isRawValue = (allowShorthand === false) || !(propName in transforms);
if (isRawValue) {
const value = typeof inputValue === 'string' ? inputValue : parse.stringify(inputValue);
propValue = transformRawValue(value);
} else {
const ast = typeof inputValue === 'string' ? parse(inputValue.trim()) : inputValue;
const tokenStream = new TokenStream(ast.nodes);
propValue = transforms[propName](tokenStream);
}
return (propValue && propValue.$merge)
? propValue.$merge
: { [propName]: propValue };
};
export const getPropertyName = camelizeStyleName;
export default (rules, shorthandBlacklist = []) => rules.reduce((accum, rule) => {
const propertyName = getPropertyName(rule[0]);
const value = rule[1];
const allowShorthand = shorthandBlacklist.indexOf(propertyName) === -1;
return Object.assign(accum, getStylesForProperty(propertyName, value, allowShorthand));
}, {});
| Allow boolean values in CSS (fixes #26)
| src/index.js | Allow boolean values in CSS (fixes #26) | <ide><path>rc/index.js
<ide> const TokenStream = require('./TokenStream');
<ide>
<ide> // Note if this is wrong, you'll need to change tokenTypes.js too
<del>const numberOrLengthRe = /^([+-]?(?:\d*\.)?\d+(?:[Ee][+-]?\d+)?)(?:px)?$/;
<add>const numberOrLengthRe = /^([+-]?(?:\d*\.)?\d+(?:[Ee][+-]?\d+)?)(?:px)?$/i;
<add>const boolRe = /^true|false$/i;
<ide>
<ide> // Undocumented export
<ide> export const transformRawValue = (input) => {
<del> const value = input.trim().match(numberOrLengthRe);
<del> return value ? Number(value[1]) : input;
<add> const value = input.trim();
<add>
<add> const numberMatch = value.match(numberOrLengthRe);
<add> if (numberMatch) return Number(numberMatch[1]);
<add>
<add> const boolMatch = input.match(boolRe);
<add> if (boolMatch) return boolMatch[0].toLowerCase() === 'true';
<add>
<add> return value;
<ide> };
<ide>
<ide> export const getStylesForProperty = (propName, inputValue, allowShorthand) => { |
|
Java | apache-2.0 | 0a1392fd06bea4f5ede36f82021f4e8f6a781b39 | 0 | DmitriyLy/travel_portal,DmitriyLy/travel_portal,DmitriyLy/travel_portal | package com.netcracker.entities;
/**
* Created by dima_2 on 30.11.2016.
*/
public class Category {
private long id;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Category category = (Category) o;
if (id != category.id) return false;
return name != null ? name.equals(category.name) : category.name == null;
}
@Override
public int hashCode() {
int result = (int) (id ^ (id >>> 32));
result = 31 * result + (name != null ? name.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Category{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
| repository/src/main/java/com/netcracker/entities/Category.java | package com.netcracker.entities;
/**
* Created by dima_2 on 30.11.2016.
*/
public class Category {
}
| POJO Category
| repository/src/main/java/com/netcracker/entities/Category.java | POJO Category | <ide><path>epository/src/main/java/com/netcracker/entities/Category.java
<ide> * Created by dima_2 on 30.11.2016.
<ide> */
<ide> public class Category {
<add> private long id;
<add> private String name;
<add>
<add> public long getId() {
<add> return id;
<add> }
<add>
<add> public void setId(long id) {
<add> this.id = id;
<add> }
<add>
<add> public String getName() {
<add> return name;
<add> }
<add>
<add> public void setName(String name) {
<add> this.name = name;
<add> }
<add>
<add> @Override
<add> public boolean equals(Object o) {
<add> if (this == o) return true;
<add> if (o == null || getClass() != o.getClass()) return false;
<add>
<add> Category category = (Category) o;
<add>
<add> if (id != category.id) return false;
<add> return name != null ? name.equals(category.name) : category.name == null;
<add> }
<add>
<add> @Override
<add> public int hashCode() {
<add> int result = (int) (id ^ (id >>> 32));
<add> result = 31 * result + (name != null ? name.hashCode() : 0);
<add> return result;
<add> }
<add>
<add> @Override
<add> public String toString() {
<add> return "Category{" +
<add> "id=" + id +
<add> ", name='" + name + '\'' +
<add> '}';
<add> }
<ide> } |
|
JavaScript | bsd-3-clause | 6127d4f70fa2e6285b12f8fb6007d87e550d2f01 | 0 | jpoirier/stratux,jpoirier/stratux,jpoirier/stratux,westphae/stratux,cyoung/stratux,cyoung/stratux,westphae/stratux,westphae/stratux,cyoung/stratux,jpoirier/stratux,cyoung/stratux,jpoirier/stratux,westphae/stratux,westphae/stratux,westphae/stratux,cyoung/stratux,jpoirier/stratux,cyoung/stratux | angular.module('appControllers').controller('GPSCtrl', GPSCtrl); // get the main module contollers set
GPSCtrl.$inject = ['$rootScope', '$scope', '$state', '$http', '$interval']; // Inject my dependencies
// create our controller function with all necessary logic
function GPSCtrl($rootScope, $scope, $state, $http, $interval) {
$scope.$parent.helppage = 'plates/gps-help.html';
$scope.data_list = [];
$scope.isHidden = false;
function connect($scope) {
if (($scope === undefined) || ($scope === null))
return; // we are getting called once after clicking away from the gps page
if (($scope.socket === undefined) || ($scope.socket === null)) {
socket = new WebSocket(URL_GPS_WS);
$scope.socket = socket; // store socket in scope for enter/exit usage
}
$scope.ConnectState = "Disconnected";
socket.onopen = function (msg) {
// $scope.ConnectStyle = "label-success";
$scope.ConnectState = "Connected";
};
socket.onclose = function (msg) {
// $scope.ConnectStyle = "label-danger";
$scope.ConnectState = "Disconnected";
$scope.$apply();
delete $scope.socket;
setTimeout(function() {connect($scope);}, 1000);
};
socket.onerror = function (msg) {
// $scope.ConnectStyle = "label-danger";
$scope.ConnectState = "Error";
resetSituation();
$scope.$apply();
};
socket.onmessage = function (msg) {
loadSituation(msg.data);
$scope.$apply(); // trigger any needed refreshing of data
};
}
var situation = {};
var display_area_size = -1;
var statusGPS = document.getElementById("status-gps"),
statusIMU = document.getElementById("status-imu"),
statusBMP = document.getElementById("status-bmp"),
statusLog = document.getElementById("status-logging"),
statusCal = document.getElementById("status-calibrating");
function sizeMap() {
var width = 0;
var el = document.getElementById("map_display").parentElement;
width = el.offsetWidth; // was (- (2 * el.offsetLeft))
if (width !== display_area_size) {
display_area_size = width;
$scope.map_width = width;
$scope.map_height = width;
}
return width;
}
function setGeoReferenceMap(la, lo) {
// Mercator projection
// var map = "img/world.png";
var map_width = 2530;
var map_height = 1603;
var map_zero_x = 1192;
var map_zero_y = 1124;
var font_size = 18; // size of font used for marker
sizeMap();
var div_width = $scope.map_width;
var div_height = $scope.map_height;
// longitude: just scale and shift
var x = (map_width * (180 + lo) / 360) - (map_width/2 - map_zero_x); // longitude_shift;
// latitude: using the Mercator projection
la_rad = la * Math.PI / 180; // convert from degrees to radians
merc_n = Math.log(Math.tan((la_rad / 2) + (Math.PI / 4))); // do the Mercator projection (w/ equator of 2pi units)
var y = (map_height / 2) - (map_width * merc_n / (2 * Math.PI)) - (map_height/2 - map_zero_y); // fit it to our map
// dot = '<div style="position:absolute; width:' + dot_size + 'px; height:' + dot_size + 'px; top:' + y + 'px; left:' + x + 'px; background:#ff7f00;"></div>';
// <img src="map-world-medium.png" style="position:absolute;top:0px;left:0px">
$scope.map_pos_x = map_width - Math.round(x - (div_width / 2));
$scope.map_pos_y = map_height - Math.round(y - (div_height / 2));
$scope.map_mark_x = Math.round((div_width - (font_size * 0.85)) / 2);
$scope.map_mark_y = Math.round((div_height - font_size) / 2);
}
function loadSituation(data) { // mySituation
situation = angular.fromJson(data);
// consider using angular.extend()
$scope.raw_data = angular.toJson(data, true); // makes it pretty
$scope.Satellites = situation.GPSSatellites;
$scope.GPS_satellites_tracked = situation.GPSSatellitesTracked;
$scope.GPS_satellites_seen = situation.GPSSatellitesSeen;
$scope.Quality = situation.GPSFixQuality;
var solutionText = "No Fix";
if (situation.GPSFixQuality === 2) {
solutionText = "GPS + SBAS (WAAS / EGNOS)";
} else if (situation.GPSFixQuality === 1) {
solutionText = "3D GPS"
}
$scope.SolutionText = solutionText;
$scope.gps_horizontal_accuracy = situation.GPSHorizontalAccuracy.toFixed(1);
$scope.gps_vertical_accuracy = (situation.GPSVerticalAccuracy*3.2808).toFixed(1); // accuracy is in meters, need to display in ft
// NACp should be an integer value in the range of 0 .. 11
// var accuracies = ["≥ 10 NM", "< 10 NM", "< 4 NM", "< 2 NM", "< 1 NM", "< 0.5 NM", "< 0.3 NM", "< 0.1 NM", "< 100 m", "< 30 m", "< 10 m", "< 3 m"];
// $scope.gps_horizontal_accuracy = accuracies[status.NACp];
// "LastFixLocalTime":"2015-10-11T16:47:03.523085162Z"
$scope.gps_lat = situation.GPSLatitude.toFixed(5); // result is string
$scope.gps_lon = situation.GPSLongitude.toFixed(5); // result is string
$scope.gps_alt = situation.GPSAltitudeMSL.toFixed(1);
$scope.gps_track = situation.GPSTrueCourse.toFixed(1);
$scope.gps_speed = situation.GPSGroundSpeed.toFixed(1);
$scope.gps_vert_speed = situation.GPSVerticalSpeed.toFixed(1);
// "LastGroundTrackTime":"0001-01-01T00:00:00Z"
/* not currently used
$scope.ahrs_temp = status.Temp;
*/
$scope.press_time = Date.parse(situation.BaroLastMeasurementTime);
$scope.gps_time = Date.parse(situation.GPSLastGPSTimeStratuxTime);
if ($scope.gps_time - $scope.press_time < 1000) {
$scope.ahrs_alt = Math.round(situation.BaroPressureAltitude.toFixed(0));
} else {
$scope.ahrs_alt = "---";
}
$scope.ahrs_heading = Math.round(situation.AHRSGyroHeading.toFixed(0));
// pitch and roll are in degrees
$scope.ahrs_pitch = situation.AHRSPitch.toFixed(1);
$scope.ahrs_roll = situation.AHRSRoll.toFixed(1);
$scope.ahrs_slip_skid = situation.AHRSSlipSkid.toFixed(1);
ahrs.update(situation.AHRSPitch, situation.AHRSRoll, situation.AHRSGyroHeading, situation.AHRSSlipSkid);
$scope.ahrs_heading_mag = situation.AHRSMagHeading.toFixed(0);
$scope.ahrs_gload = situation.AHRSGLoad.toFixed(2);
gMeter.update(situation.AHRSGLoad);
if (situation.AHRSTurnRate> 0.6031) {
$scope.ahrs_turn_rate = (6/situation.AHRSTurnRate).toFixed(1); // minutes/turn
} else {
$scope.ahrs_turn_rate = '\u221e';
}
if (situation.AHRSStatus & 0x01) {
statusGPS.classList.remove("off");
statusGPS.classList.add("on");
} else {
statusGPS.classList.add("off");
statusGPS.classList.remove("on");
}
if (situation.AHRSStatus & 0x02) {
if (statusIMU.classList.contains("off")) {
setTimeout(gMeter.reset(), 1000);
}
statusIMU.classList.remove("off");
statusIMU.classList.add("on");
} else {
statusIMU.classList.add("off");
statusIMU.classList.remove("on");
}
if (situation.AHRSStatus & 0x04) {
statusBMP.classList.remove("off");
statusBMP.classList.add("on");
} else {
statusBMP.classList.add("off");
statusBMP.classList.remove("on");
}
if (situation.AHRSStatus & 0x10) {
statusLog.classList.remove("off");
statusLog.classList.add("on");
} else {
statusLog.classList.add("off");
statusLog.classList.remove("on");
}
if (situation.AHRSStatus & 0x08) {
statusCal.classList.add("blink");
statusCal.classList.remove("on");
statusCal.innerText = "Caging";
} else {
statusCal.classList.remove("blink");
statusCal.classList.add("on");
statusCal.innerText = "Ready";
}
// "LastAttitudeTime":"2015-10-11T16:47:03.534615187Z"
setGeoReferenceMap(situation.GPSLatitude, situation.GPSLongitude);
}
function resetSituation() { // mySituation
$scope.raw_data = "error getting gps / ahrs status";
$scope.ahrs_heading = "---";
$scope.ahrs_pitch = "--";
$scope.ahrs_roll = "--";
$scope.ahrs_slip_skid = "--";
$scope.ahrs_heading_mag = "---";
$scope.ahrs_turn_rate = "--";
$scope.ahrs_gload = "--";
statusGPS.classList.add("off");
statusGPS.classList.remove("on");
statusIMU.classList.add("off");
statusIMU.classList.remove("on");
statusBMP.classList.add("off");
statusBMP.classList.remove("on");
statusLog.classList.add("off");
statusLog.classList.remove("on");
statusCal.classList.add("off");
statusCal.classList.remove("on");
statusCal.innerText = "Error";
}
function getSatellites() {
// Simple GET request example (note: response is asynchronous)
$http.get(URL_SATELLITES_GET).
then(function (response) {
loadSatellites(response.data);
}, function (response) {
$scope.raw_data = "error getting satellite data";
});
}
function setSatellite(obj, new_satellite) {
new_satellite.SatelliteNMEA = obj.SatelliteNMEA;
new_satellite.SatelliteID = obj.SatelliteID; // Formatted code indicating source and PRN code. e.g. S138==WAAS satellite 138, G2==GPS satellites 2
new_satellite.Elevation = obj.Elevation; // Angle above local horizon, -xx to +90
new_satellite.Azimuth = obj.Azimuth; // Bearing (degrees true), 0-359
new_satellite.Signal = obj.Signal; // Signal strength, 0 - 99; -99 indicates no reception
new_satellite.InSolution = obj.InSolution; // is this satellite in the position solution
}
function loadSatellites(satellites) {
if (($scope === undefined) || ($scope === null))
return; // we are getting called once after clicking away from the status page
$scope.raw_data = angular.toJson(satellites, true);
$scope.data_list.length = 0; // clear array
// we need to use an array so AngularJS can perform sorting; it also means we need to loop to find a tower in the towers set
for (var key in satellites) {
//if (satellites[key].Messages_last_minute > 0) {
var new_satellite = {};
setSatellite(satellites[key], new_satellite);
$scope.data_list.push(new_satellite); // add to start of array
//}
}
// $scope.$apply();
}
// refresh satellite info once each second (aka polling)
var updateSatellites = $interval(getSatellites, 1000, 0, false);
$state.get('gps').onEnter = function () {
// everything gets handled correctly by the controller
};
$state.get('gps').onExit = function () {
if (($scope.socket !== undefined) && ($scope.socket !== null)) {
$scope.socket.close();
$scope.socket = null;
}
// stop polling for gps/ahrs status
$interval.cancel(updateSatellites);
};
// GPS/AHRS Controller tasks go here
var ahrs = new AHRSRenderer("ahrs_display");
$scope.hideClick = function() {
$scope.isHidden = !$scope.isHidden;
var disp = "block";
if ($scope.isHidden) {
disp = "none";
}
var hiders = document.querySelectorAll(".hider");
for (var i=0; i < hiders.length; i++) {
hiders[i].style.display = disp;
}
};
$scope.AHRSCage = function() {
if (!$scope.IsCaging()) {
$http.post(URL_AHRS_CAGE).then(function (response) {
// do nothing
}, function (response) {
// do nothing
});
}
};
$scope.IsCaging = function() {
var caging = statusCal.innerText === "Caging";
if (caging) {
ahrs.turn_off("Calibrating. Fly straight and do not move sensor.");
} else {
ahrs.turn_on();
}
return caging;
};
var gMeter = new GMeterRenderer("gMeter_display", 4.4, -1.76);
// GPS Controller tasks
connect($scope); // connect - opens a socket and listens for messages
}
| web/plates/js/gps.js | angular.module('appControllers').controller('GPSCtrl', GPSCtrl); // get the main module contollers set
GPSCtrl.$inject = ['$rootScope', '$scope', '$state', '$http', '$interval']; // Inject my dependencies
// create our controller function with all necessary logic
function GPSCtrl($rootScope, $scope, $state, $http, $interval) {
$scope.$parent.helppage = 'plates/gps-help.html';
$scope.data_list = [];
$scope.isHidden = false;
function connect($scope) {
if (($scope === undefined) || ($scope === null))
return; // we are getting called once after clicking away from the gps page
if (($scope.socket === undefined) || ($scope.socket === null)) {
socket = new WebSocket(URL_GPS_WS);
$scope.socket = socket; // store socket in scope for enter/exit usage
}
$scope.ConnectState = "Disconnected";
socket.onopen = function (msg) {
// $scope.ConnectStyle = "label-success";
$scope.ConnectState = "Connected";
};
socket.onclose = function (msg) {
// $scope.ConnectStyle = "label-danger";
$scope.ConnectState = "Disconnected";
$scope.$apply();
delete $scope.socket;
setTimeout(function() {connect($scope);}, 1000);
};
socket.onerror = function (msg) {
// $scope.ConnectStyle = "label-danger";
$scope.ConnectState = "Error";
resetSituation();
$scope.$apply();
};
socket.onmessage = function (msg) {
loadSituation(msg.data);
$scope.$apply(); // trigger any needed refreshing of data
};
}
var situation = {};
var display_area_size = -1;
var statusGPS = document.getElementById("status-gps"),
statusIMU = document.getElementById("status-imu"),
statusBMP = document.getElementById("status-bmp"),
statusLog = document.getElementById("status-logging"),
statusCal = document.getElementById("status-calibrating");
function sizeMap() {
var width = 0;
var el = document.getElementById("map_display").parentElement;
width = el.offsetWidth; // was (- (2 * el.offsetLeft))
if (width !== display_area_size) {
display_area_size = width;
$scope.map_width = width;
$scope.map_height = width;
}
return width;
}
function setGeoReferenceMap(la, lo) {
// Mercator projection
// var map = "img/world.png";
var map_width = 2530;
var map_height = 1603;
var map_zero_x = 1192;
var map_zero_y = 1124;
var font_size = 18; // size of font used for marker
sizeMap();
var div_width = $scope.map_width;
var div_height = $scope.map_height;
// longitude: just scale and shift
var x = (map_width * (180 + lo) / 360) - (map_width/2 - map_zero_x); // longitude_shift;
// latitude: using the Mercator projection
la_rad = la * Math.PI / 180; // convert from degrees to radians
merc_n = Math.log(Math.tan((la_rad / 2) + (Math.PI / 4))); // do the Mercator projection (w/ equator of 2pi units)
var y = (map_height / 2) - (map_width * merc_n / (2 * Math.PI)) - (map_height/2 - map_zero_y); // fit it to our map
// dot = '<div style="position:absolute; width:' + dot_size + 'px; height:' + dot_size + 'px; top:' + y + 'px; left:' + x + 'px; background:#ff7f00;"></div>';
// <img src="map-world-medium.png" style="position:absolute;top:0px;left:0px">
$scope.map_pos_x = map_width - Math.round(x - (div_width / 2));
$scope.map_pos_y = map_height - Math.round(y - (div_height / 2));
$scope.map_mark_x = Math.round((div_width - (font_size * 0.85)) / 2);
$scope.map_mark_y = Math.round((div_height - font_size) / 2);
}
function loadSituation(data) { // mySituation
situation = angular.fromJson(data);
// consider using angular.extend()
$scope.raw_data = angular.toJson(data, true); // makes it pretty
$scope.Satellites = situation.GPSSatellites;
$scope.GPS_satellites_tracked = situation.GPSSatellitesTracked;
$scope.GPS_satellites_seen = situation.GPSSatellitesSeen;
$scope.Quality = situation.GPSFixQuality;
var solutionText = "No Fix";
if (situation.GPSFixQuality === 2) {
solutionText = "GPS + SBAS (WAAS / EGNOS)";
} else if (situation.GPSFixQuality === 1) {
solutionText = "3D GPS"
}
$scope.SolutionText = solutionText;
$scope.gps_horizontal_accuracy = situation.GPSHorizontalAccuracy.toFixed(1);
$scope.gps_vertical_accuracy = (situation.GPSVerticalAccuracy*3.2808).toFixed(1); // accuracy is in meters, need to display in ft
// NACp should be an integer value in the range of 0 .. 11
// var accuracies = ["≥ 10 NM", "< 10 NM", "< 4 NM", "< 2 NM", "< 1 NM", "< 0.5 NM", "< 0.3 NM", "< 0.1 NM", "< 100 m", "< 30 m", "< 10 m", "< 3 m"];
// $scope.gps_horizontal_accuracy = accuracies[status.NACp];
// "LastFixLocalTime":"2015-10-11T16:47:03.523085162Z"
$scope.gps_lat = situation.GPSLatitude.toFixed(5); // result is string
$scope.gps_lon = situation.GPSLongitude.toFixed(5); // result is string
$scope.gps_alt = situation.GPSAltitudeMSL.toFixed(1);
$scope.gps_track = situation.GPSTrueCourse.toFixed(1);
$scope.gps_speed = situation.GPSGroundSpeed.toFixed(1);
$scope.gps_vert_speed = situation.GPSVerticalSpeed.toFixed(1);
// "LastGroundTrackTime":"0001-01-01T00:00:00Z"
/* not currently used
$scope.ahrs_temp = status.Temp;
*/
$scope.press_time = Date.parse(situation.BaroLastMeasurementTime);
$scope.gps_time = Date.parse(situation.GPSLastGPSTimeStratuxTime);
if ($scope.gps_time - $scope.press_time < 1000) {
$scope.ahrs_alt = Math.round(situation.BaroPressureAltitude.toFixed(0));
} else {
$scope.ahrs_alt = "---";
}
$scope.ahrs_heading = Math.round(situation.AHRSGyroHeading.toFixed(0));
// pitch and roll are in degrees
$scope.ahrs_pitch = situation.AHRSPitch.toFixed(1);
$scope.ahrs_roll = situation.AHRSRoll.toFixed(1);
$scope.ahrs_slip_skid = situation.AHRSSlipSkid.toFixed(1);
ahrs.update(situation.AHRSPitch, situation.AHRSRoll, situation.AHRSGyroHeading, situation.AHRSSlipSkid);
$scope.ahrs_heading_mag = situation.AHRSMagHeading.toFixed(0);
$scope.ahrs_gload = situation.AHRSGLoad.toFixed(2);
gMeter.update(situation.AHRSGLoad);
if (situation.AHRSTurnRate> 0.25) {
$scope.ahrs_turn_rate = (60/situation.AHRSTurnRate).toFixed(1); // minutes/turn
} else {
$scope.ahrs_turn_rate = '\u221e';
}
if (situation.AHRSStatus & 0x01) {
statusGPS.classList.remove("off");
statusGPS.classList.add("on");
} else {
statusGPS.classList.add("off");
statusGPS.classList.remove("on");
}
if (situation.AHRSStatus & 0x02) {
if (statusIMU.classList.contains("off")) {
setTimeout(gMeter.reset(), 1000);
}
statusIMU.classList.remove("off");
statusIMU.classList.add("on");
} else {
statusIMU.classList.add("off");
statusIMU.classList.remove("on");
}
if (situation.AHRSStatus & 0x04) {
statusBMP.classList.remove("off");
statusBMP.classList.add("on");
} else {
statusBMP.classList.add("off");
statusBMP.classList.remove("on");
}
if (situation.AHRSStatus & 0x10) {
statusLog.classList.remove("off");
statusLog.classList.add("on");
} else {
statusLog.classList.add("off");
statusLog.classList.remove("on");
}
if (situation.AHRSStatus & 0x08) {
statusCal.classList.add("blink");
statusCal.classList.remove("on");
statusCal.innerText = "Caging";
} else {
statusCal.classList.remove("blink");
statusCal.classList.add("on");
statusCal.innerText = "Ready";
}
// "LastAttitudeTime":"2015-10-11T16:47:03.534615187Z"
setGeoReferenceMap(situation.GPSLatitude, situation.GPSLongitude);
}
function resetSituation() { // mySituation
$scope.raw_data = "error getting gps / ahrs status";
$scope.ahrs_heading = "---";
$scope.ahrs_pitch = "--";
$scope.ahrs_roll = "--";
$scope.ahrs_slip_skid = "--";
$scope.ahrs_heading_mag = "---";
$scope.ahrs_turn_rate = "--";
$scope.ahrs_gload = "--";
statusGPS.classList.add("off");
statusGPS.classList.remove("on");
statusIMU.classList.add("off");
statusIMU.classList.remove("on");
statusBMP.classList.add("off");
statusBMP.classList.remove("on");
statusLog.classList.add("off");
statusLog.classList.remove("on");
statusCal.classList.add("off");
statusCal.classList.remove("on");
statusCal.innerText = "Error";
}
function getSatellites() {
// Simple GET request example (note: response is asynchronous)
$http.get(URL_SATELLITES_GET).
then(function (response) {
loadSatellites(response.data);
}, function (response) {
$scope.raw_data = "error getting satellite data";
});
}
function setSatellite(obj, new_satellite) {
new_satellite.SatelliteNMEA = obj.SatelliteNMEA;
new_satellite.SatelliteID = obj.SatelliteID; // Formatted code indicating source and PRN code. e.g. S138==WAAS satellite 138, G2==GPS satellites 2
new_satellite.Elevation = obj.Elevation; // Angle above local horizon, -xx to +90
new_satellite.Azimuth = obj.Azimuth; // Bearing (degrees true), 0-359
new_satellite.Signal = obj.Signal; // Signal strength, 0 - 99; -99 indicates no reception
new_satellite.InSolution = obj.InSolution; // is this satellite in the position solution
}
function loadSatellites(satellites) {
if (($scope === undefined) || ($scope === null))
return; // we are getting called once after clicking away from the status page
$scope.raw_data = angular.toJson(satellites, true);
$scope.data_list.length = 0; // clear array
// we need to use an array so AngularJS can perform sorting; it also means we need to loop to find a tower in the towers set
for (var key in satellites) {
//if (satellites[key].Messages_last_minute > 0) {
var new_satellite = {};
setSatellite(satellites[key], new_satellite);
$scope.data_list.push(new_satellite); // add to start of array
//}
}
// $scope.$apply();
}
// refresh satellite info once each second (aka polling)
var updateSatellites = $interval(getSatellites, 1000, 0, false);
$state.get('gps').onEnter = function () {
// everything gets handled correctly by the controller
};
$state.get('gps').onExit = function () {
if (($scope.socket !== undefined) && ($scope.socket !== null)) {
$scope.socket.close();
$scope.socket = null;
}
// stop polling for gps/ahrs status
$interval.cancel(updateSatellites);
};
// GPS/AHRS Controller tasks go here
var ahrs = new AHRSRenderer("ahrs_display");
$scope.hideClick = function() {
$scope.isHidden = !$scope.isHidden;
var disp = "block";
if ($scope.isHidden) {
disp = "none";
}
var hiders = document.querySelectorAll(".hider");
for (var i=0; i < hiders.length; i++) {
hiders[i].style.display = disp;
}
};
$scope.AHRSCage = function() {
if (!$scope.IsCaging()) {
$http.post(URL_AHRS_CAGE).then(function (response) {
// do nothing
}, function (response) {
// do nothing
});
}
};
$scope.IsCaging = function() {
var caging = statusCal.innerText === "Caging";
if (caging) {
ahrs.turn_off("Calibrating. Fly straight and do not move sensor.");
} else {
ahrs.turn_on();
}
return caging;
};
var gMeter = new GMeterRenderer("gMeter_display", 4.4, -1.76);
// GPS Controller tasks
connect($scope); // connect - opens a socket and listens for messages
}
| Only report turn tate < 10 min/turn on web UI.
| web/plates/js/gps.js | Only report turn tate < 10 min/turn on web UI. | <ide><path>eb/plates/js/gps.js
<ide> $scope.ahrs_gload = situation.AHRSGLoad.toFixed(2);
<ide> gMeter.update(situation.AHRSGLoad);
<ide>
<del> if (situation.AHRSTurnRate> 0.25) {
<del> $scope.ahrs_turn_rate = (60/situation.AHRSTurnRate).toFixed(1); // minutes/turn
<add> if (situation.AHRSTurnRate> 0.6031) {
<add> $scope.ahrs_turn_rate = (6/situation.AHRSTurnRate).toFixed(1); // minutes/turn
<ide> } else {
<ide> $scope.ahrs_turn_rate = '\u221e';
<ide> } |
|
Java | apache-2.0 | 3d00bda4964a63c862b694342e366627a91741b4 | 0 | OpenHFT/Chronicle-Queue,OpenHFT/Chronicle-Queue | package net.openhft.chronicle.queue.impl.single;
import net.openhft.chronicle.bytes.MethodReader;
import net.openhft.chronicle.queue.ChronicleQueue;
import net.openhft.chronicle.queue.DirectoryUtils;
import net.openhft.chronicle.queue.ExcerptTailer;
import net.openhft.chronicle.queue.TailerDirection;
import net.openhft.chronicle.wire.MessageHistory;
import net.openhft.chronicle.wire.VanillaMessageHistory;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import java.io.File;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
public final class MessageHistoryTest {
@Rule
public final TestName testName = new TestName();
private final AtomicLong clock = new AtomicLong(System.currentTimeMillis());
private File inputQueueDir;
private File middleQueueDir;
private File outputQueueDir;
@Before
public void setUp() {
inputQueueDir = DirectoryUtils.tempDir(testName.getMethodName());
middleQueueDir = DirectoryUtils.tempDir(testName.getMethodName());
outputQueueDir = DirectoryUtils.tempDir(testName.getMethodName());
final VanillaMessageHistory messageHistory = new VanillaMessageHistory();
messageHistory.addSourceDetails(true);
MessageHistory.set(messageHistory);
}
@Test
public void shouldAccessMessageHistory() {
try (final ChronicleQueue inputQueue = createQueue(inputQueueDir, 1);
final ChronicleQueue outputQueue = createQueue(outputQueueDir, 2)) {
generateTestData(inputQueue, outputQueue);
final ExcerptTailer tailer = outputQueue.createTailer();
final ValidatingSecond validatingSecond = new ValidatingSecond();
final MethodReader validator = tailer.methodReader(validatingSecond);
assertThat(validator.readOne(), is(true));
assertThat(validatingSecond.messageHistoryPresent(), is(true));
}
}
@Test
public void shouldAccessMessageHistoryWhenTailerIsMovedToEnd() {
try (final ChronicleQueue inputQueue = createQueue(inputQueueDir, 1);
final ChronicleQueue outputQueue = createQueue(outputQueueDir, 2)) {
generateTestData(inputQueue, outputQueue);
final ExcerptTailer tailer = outputQueue.createTailer();
tailer.direction(TailerDirection.BACKWARD).toEnd();
final ValidatingSecond validatingSecond = new ValidatingSecond();
final MethodReader validator = tailer.methodReader(validatingSecond);
assertThat(validator.readOne(), is(true));
assertThat(validatingSecond.messageHistoryPresent(), is(true));
}
}
@Test
public void chainedMessageHistory() {
try (final ChronicleQueue inputQueue = createQueue(inputQueueDir, 1);
final ChronicleQueue middleQueue = createQueue(middleQueueDir, 2);
final ChronicleQueue outputQueue = createQueue(middleQueueDir, 3)) {
generateTestData(inputQueue, middleQueue);
MethodReader reader = middleQueue.createTailer().methodReader(outputQueue.methodWriter(First.class));
for (int i = 0; i < 3; i++)
assertTrue(reader.readOne());
MethodReader reader2 = outputQueue.createTailer().methodReader((First) this::say3);
for (int i = 0; i < 3; i++)
assertTrue(reader2.readOne());
}
}
private void say3(String text) {
final MessageHistory messageHistory = MessageHistory.get();
assertNotNull(messageHistory);
assertThat(messageHistory.sources(), is(2));
}
private void generateTestData(final ChronicleQueue inputQueue, final ChronicleQueue outputQueue) {
final First first = inputQueue.acquireAppender()
.methodWriterBuilder(First.class)
.recordHistory(true)
.get();
first.say("one");
first.say("two");
first.say("three");
final LoggingFirst loggingFirst =
new LoggingFirst(outputQueue.acquireAppender().
methodWriterBuilder(Second.class).build());
final MethodReader reader = inputQueue.createTailer().
methodReaderBuilder().build(loggingFirst);
assertThat(reader.readOne(), is(true));
assertThat(reader.readOne(), is(true));
// roll queue file
clock.addAndGet(TimeUnit.DAYS.toMillis(2));
assertThat(reader.readOne(), is(true));
assertThat(reader.readOne(), is(false));
}
private ChronicleQueue createQueue(final File queueDir, final int sourceId) {
return ChronicleQueue.singleBuilder(queueDir).sourceId(sourceId).
timeProvider(clock::get).
testBlockSize().build();
}
@FunctionalInterface
interface First {
void say(final String word);
}
@FunctionalInterface
interface Second {
void count(final int value);
}
private static final class LoggingFirst implements First {
private final Second second;
private LoggingFirst(final Second second) {
this.second = second;
}
@Override
public void say(final String word) {
second.count(word.length());
}
}
private static class ValidatingSecond implements Second {
private boolean messageHistoryPresent = false;
@Override
public void count(final int value) {
final MessageHistory messageHistory = MessageHistory.get();
assertNotNull(messageHistory);
assertThat(messageHistory.sources(), is(1));
messageHistoryPresent = true;
}
boolean messageHistoryPresent() {
return messageHistoryPresent;
}
}
} | src/test/java/net/openhft/chronicle/queue/impl/single/MessageHistoryTest.java | package net.openhft.chronicle.queue.impl.single;
import net.openhft.chronicle.bytes.MethodReader;
import net.openhft.chronicle.queue.ChronicleQueue;
import net.openhft.chronicle.queue.DirectoryUtils;
import net.openhft.chronicle.queue.ExcerptTailer;
import net.openhft.chronicle.queue.TailerDirection;
import net.openhft.chronicle.wire.MessageHistory;
import net.openhft.chronicle.wire.VanillaMessageHistory;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import java.io.File;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
public final class MessageHistoryTest {
@Rule
public final TestName testName = new TestName();
private final AtomicLong clock = new AtomicLong(System.currentTimeMillis());
private File inputQueueDir;
private File middleQueueDir;
private File outputQueueDir;
@Before
public void setUp() {
inputQueueDir = DirectoryUtils.tempDir(testName.getMethodName());
middleQueueDir = DirectoryUtils.tempDir(testName.getMethodName());
outputQueueDir = DirectoryUtils.tempDir(testName.getMethodName());
final VanillaMessageHistory messageHistory = new VanillaMessageHistory();
messageHistory.addSourceDetails(true);
MessageHistory.set(messageHistory);
}
@Test
public void shouldAccessMessageHistory() {
try (final ChronicleQueue inputQueue = createQueue(inputQueueDir, 1);
final ChronicleQueue outputQueue = createQueue(outputQueueDir, 2)) {
generateTestData(inputQueue, outputQueue);
final ExcerptTailer tailer = outputQueue.createTailer();
final ValidatingSecond validatingSecond = new ValidatingSecond();
final MethodReader validator = tailer.methodReader(validatingSecond);
assertThat(validator.readOne(), is(true));
assertThat(validatingSecond.messageHistoryPresent(), is(true));
}
}
@Test
public void shouldAccessMessageHistoryWhenTailerIsMovedToEnd() {
try (final ChronicleQueue inputQueue = createQueue(inputQueueDir, 1);
final ChronicleQueue outputQueue = createQueue(outputQueueDir, 2)) {
generateTestData(inputQueue, outputQueue);
final ExcerptTailer tailer = outputQueue.createTailer();
tailer.direction(TailerDirection.BACKWARD).toEnd();
final ValidatingSecond validatingSecond = new ValidatingSecond();
final MethodReader validator = tailer.methodReader(validatingSecond);
assertThat(validator.readOne(), is(true));
assertThat(validatingSecond.messageHistoryPresent(), is(true));
}
}
@Test
public void chainedMessageHistory() {
try (final ChronicleQueue inputQueue = createQueue(inputQueueDir, 1);
final ChronicleQueue middleQueue = createQueue(middleQueueDir, 2);
final ChronicleQueue outputQueue = createQueue(middleQueueDir, 2)) {
generateTestData(inputQueue, middleQueue);
MethodReader reader = middleQueue.createTailer().methodReader(outputQueue.methodWriter(First.class));
for (int i = 0; i < 3; i++)
assertTrue(reader.readOne());
MethodReader reader2 = outputQueue.createTailer().methodReader((First) this::say3);
for (int i = 0; i < 3; i++)
assertTrue(reader2.readOne());
}
}
private void say3(String text) {
final MessageHistory messageHistory = MessageHistory.get();
assertNotNull(messageHistory);
assertThat(messageHistory.sources(), is(2));
}
private void generateTestData(final ChronicleQueue inputQueue, final ChronicleQueue outputQueue) {
final First first = inputQueue.acquireAppender()
.methodWriterBuilder(First.class)
.recordHistory(true)
.get();
first.say("one");
first.say("two");
first.say("three");
final LoggingFirst loggingFirst =
new LoggingFirst(outputQueue.acquireAppender().
methodWriterBuilder(Second.class).build());
final MethodReader reader = inputQueue.createTailer().
methodReaderBuilder().build(loggingFirst);
assertThat(reader.readOne(), is(true));
assertThat(reader.readOne(), is(true));
// roll queue file
clock.addAndGet(TimeUnit.DAYS.toMillis(2));
assertThat(reader.readOne(), is(true));
assertThat(reader.readOne(), is(false));
}
private ChronicleQueue createQueue(final File queueDir, final int sourceId) {
return ChronicleQueue.singleBuilder(queueDir).sourceId(sourceId).
timeProvider(clock::get).
testBlockSize().build();
}
@FunctionalInterface
interface First {
void say(final String word);
}
@FunctionalInterface
interface Second {
void count(final int value);
}
private static final class LoggingFirst implements First {
private final Second second;
private LoggingFirst(final Second second) {
this.second = second;
}
@Override
public void say(final String word) {
second.count(word.length());
}
}
private static class ValidatingSecond implements Second {
private boolean messageHistoryPresent = false;
@Override
public void count(final int value) {
final MessageHistory messageHistory = MessageHistory.get();
assertNotNull(messageHistory);
assertThat(messageHistory.sources(), is(1));
messageHistoryPresent = true;
}
boolean messageHistoryPresent() {
return messageHistoryPresent;
}
}
} | Allow MethodWriters to be thread safe by default, closes https://github.com/OpenHFT/Chronicle-Queue/issues/625
| src/test/java/net/openhft/chronicle/queue/impl/single/MessageHistoryTest.java | Allow MethodWriters to be thread safe by default, closes https://github.com/OpenHFT/Chronicle-Queue/issues/625 | <ide><path>rc/test/java/net/openhft/chronicle/queue/impl/single/MessageHistoryTest.java
<ide> public void chainedMessageHistory() {
<ide> try (final ChronicleQueue inputQueue = createQueue(inputQueueDir, 1);
<ide> final ChronicleQueue middleQueue = createQueue(middleQueueDir, 2);
<del> final ChronicleQueue outputQueue = createQueue(middleQueueDir, 2)) {
<add> final ChronicleQueue outputQueue = createQueue(middleQueueDir, 3)) {
<ide> generateTestData(inputQueue, middleQueue);
<ide>
<ide> MethodReader reader = middleQueue.createTailer().methodReader(outputQueue.methodWriter(First.class)); |
|
Java | bsd-3-clause | 206b4a2190456be34f15fa07f1e27a4a907c7f1f | 0 | turn/tpmml,jpmml/jpmml,jpmml/jpmml | /*
* Copyright (c) 2012 University of Tartu
*/
package org.jpmml.evaluator;
import java.util.*;
import org.jpmml.manager.*;
import org.dmg.pmml.*;
public class ArrayUtil {
private ArrayUtil(){
}
static
public Boolean isIn(Array array, Object value){
List<String> values = getContent(array);
validateDataType(value);
boolean result = values.contains(ParameterUtil.toString(value));
return Boolean.valueOf(result);
}
static
public Boolean isNotIn(Array array, Object value){
List<String> values = getContent(array);
validateDataType(value);
boolean result = !values.contains(ParameterUtil.toString(value));
return Boolean.valueOf(result);
}
static
public List<String> getContent(Array array){
List<String> values = array.getContent();
if(values == null){
values = tokenize(array);
array.setContent(values);
}
return values;
}
static
public List<String> tokenize(Array array){
List<String> result;
Array.Type type = array.getType();
switch(type){
case INT:
case REAL:
result = tokenize(array.getValue(), false);
break;
case STRING:
result = tokenize(array.getValue(), true);
break;
default:
throw new UnsupportedFeatureException(type);
}
Number n = array.getN();
if(n != null && n.intValue() != result.size()){
throw new EvaluationException();
}
return result;
}
static
public List<String> tokenize(String string, boolean enableQuotes){
List<String> result = new ArrayList<String>();
StringBuffer sb = new StringBuffer();
boolean quoted = false;
tokens:
for(int i = 0; i < string.length(); i++){
char c = string.charAt(i);
if(quoted){
if(c == '\\' && i < (string.length() - 1)){
c = string.charAt(i + 1);
if(c == '\"'){
sb.append('\"');
i++;
} else
{
sb.append('\\');
}
continue tokens;
} // End if
sb.append(c);
if(c == '\"'){
result.add(createToken(sb, enableQuotes));
quoted = false;
}
} else
{
if(c == '\"' && enableQuotes){
if(sb.length() > 0){
result.add(createToken(sb, enableQuotes));
}
sb.append('\"');
quoted = true;
} else
if(Character.isWhitespace(c)){
if(sb.length() > 0){
result.add(createToken(sb, enableQuotes));
}
} else
{
sb.append(c);
}
}
}
if(sb.length() > 0){
result.add(createToken(sb, enableQuotes));
}
return result;
}
static
private String createToken(StringBuffer sb, boolean enableQuotes){
String result;
if(sb.length() > 1 && (sb.charAt(0) == '\"' && sb.charAt(sb.length() - 1) == '\"') && enableQuotes){
result = sb.substring(1, sb.length() - 1);
} else
{
result = sb.substring(0, sb.length());
}
sb.setLength(0);
return result;
}
static
private void validateDataType(Object value){
DataType dataType = ParameterUtil.getDataType(value);
switch(dataType){
case STRING:
case INTEGER:
break;
case FLOAT:
case DOUBLE:
throw new UnsupportedFeatureException(dataType);
default:
throw new EvaluationException();
}
}
} | pmml-evaluator/src/main/java/org/jpmml/evaluator/ArrayUtil.java | /*
* Copyright (c) 2012 University of Tartu
*/
package org.jpmml.evaluator;
import java.util.*;
import org.jpmml.manager.*;
import org.dmg.pmml.*;
public class ArrayUtil {
private ArrayUtil(){
}
static
public Boolean isIn(Array array, Object value){
List<String> values = getContent(array);
boolean result = values.contains(ParameterUtil.toString(value));
return Boolean.valueOf(result);
}
static
public Boolean isNotIn(Array array, Object value){
List<String> values = getContent(array);
boolean result = !values.contains(ParameterUtil.toString(value));
return Boolean.valueOf(result);
}
static
public List<String> getContent(Array array){
List<String> values = array.getContent();
if(values == null){
values = tokenize(array);
array.setContent(values);
}
return values;
}
static
public List<String> tokenize(Array array){
List<String> result;
Array.Type type = array.getType();
switch(type){
case INT:
case REAL:
result = tokenize(array.getValue(), false);
break;
case STRING:
result = tokenize(array.getValue(), true);
break;
default:
throw new UnsupportedFeatureException(type);
}
Number n = array.getN();
if(n != null && n.intValue() != result.size()){
throw new EvaluationException();
}
return result;
}
static
public List<String> tokenize(String string, boolean enableQuotes){
List<String> result = new ArrayList<String>();
StringBuffer sb = new StringBuffer();
boolean quoted = false;
tokens:
for(int i = 0; i < string.length(); i++){
char c = string.charAt(i);
if(quoted){
if(c == '\\' && i < (string.length() - 1)){
c = string.charAt(i + 1);
if(c == '\"'){
sb.append('\"');
i++;
} else
{
sb.append('\\');
}
continue tokens;
} // End if
sb.append(c);
if(c == '\"'){
result.add(createToken(sb, enableQuotes));
quoted = false;
}
} else
{
if(c == '\"' && enableQuotes){
if(sb.length() > 0){
result.add(createToken(sb, enableQuotes));
}
sb.append('\"');
quoted = true;
} else
if(Character.isWhitespace(c)){
if(sb.length() > 0){
result.add(createToken(sb, enableQuotes));
}
} else
{
sb.append(c);
}
}
}
if(sb.length() > 0){
result.add(createToken(sb, enableQuotes));
}
return result;
}
static
private String createToken(StringBuffer sb, boolean enableQuotes){
String result;
if(sb.length() > 1 && (sb.charAt(0) == '\"' && sb.charAt(sb.length() - 1) == '\"') && enableQuotes){
result = sb.substring(1, sb.length() - 1);
} else
{
result = sb.substring(0, sb.length());
}
sb.setLength(0);
return result;
}
} | Disallow Array functions for floating-point data types
| pmml-evaluator/src/main/java/org/jpmml/evaluator/ArrayUtil.java | Disallow Array functions for floating-point data types | <ide><path>mml-evaluator/src/main/java/org/jpmml/evaluator/ArrayUtil.java
<ide> public Boolean isIn(Array array, Object value){
<ide> List<String> values = getContent(array);
<ide>
<add> validateDataType(value);
<add>
<ide> boolean result = values.contains(ParameterUtil.toString(value));
<ide>
<ide> return Boolean.valueOf(result);
<ide> static
<ide> public Boolean isNotIn(Array array, Object value){
<ide> List<String> values = getContent(array);
<add>
<add> validateDataType(value);
<ide>
<ide> boolean result = !values.contains(ParameterUtil.toString(value));
<ide>
<ide>
<ide> return result;
<ide> }
<add>
<add> static
<add> private void validateDataType(Object value){
<add> DataType dataType = ParameterUtil.getDataType(value);
<add>
<add> switch(dataType){
<add> case STRING:
<add> case INTEGER:
<add> break;
<add> case FLOAT:
<add> case DOUBLE:
<add> throw new UnsupportedFeatureException(dataType);
<add> default:
<add> throw new EvaluationException();
<add> }
<add> }
<ide> } |
|
JavaScript | mit | 10f0ca690b106ddfa60b2091b2b70eea76dae6fa | 0 | Step7750/ScheduleStorm,Step7750/ScheduleStorm | class Generator {
constructor(classes, blockedTimes) {
// chosen classes
this.classes = JSON.parse(JSON.stringify(classes));
this.convertTimes();
this.addCourseInfo();
// update blocked times
this.blockedTimes = jQuery.extend(true, [], window.calendar.blockedTimes);
this.convertBlockedTimes();
this.schedSort = false;
this.schedgenerator = false;
this.doneGenerating = false;
this.doneScoring = false;
// Generates the schedules
this.schedGen();
}
/*
Spawns a web worker that generates possible schedules given classes
*/
schedGen() {
var self = this;
self.doneGenerating = false;
// Get the user's scoring preferences
// Want to get whether they only allow open classes or not
this.getPreferences();
window.calendar.doneLoading(function () {
// Instantiate the generator
self.schedgenerator = operative({
possibleschedules: [],
combinations: [],
classes: {},
init: function(classes, blockedTimes, onlyOpen, callback) {
this.classes = classes;
this.onlyOpen = onlyOpen;
this.blockedTimes = blockedTimes;
this.findCombinations();
this.iterateCombos();
callback(this.possibleschedules);
},
/*
Iterates through every group combinations to find possible non-conflicting schedules
*/
iterateCombos: function () {
// reset possible schedules
this.possibleschedules = [];
if (this.combinations.length > 0) {
// there must be more than 0 combos for a schedule
for (var combos in this.combinations[0]) {
// create a copy to work with
var combocopy = JSON.parse(JSON.stringify(this.combinations[0][combos]));
// geenrate the schedules
this.generateSchedules([], combocopy);
this.possibleschedulescopy = JSON.parse(JSON.stringify(this.possibleschedules));
if (this.combinations.length > 1) {
// console.log("Processing further groups");
this.possibleschedules = [];
// We have to add the other groups
for (var group = 1; group < this.combinations.length; group++) {
for (var newcombo in this.combinations[group]) {
// for every previous schedule
// TODO: If this starts to become slow, we might want to apply some heuristics
for (var possibleschedule in this.possibleschedulescopy) {
var combocopy = JSON.parse(JSON.stringify(this.combinations[group][newcombo]));
this.generateSchedules(this.possibleschedulescopy[possibleschedule], combocopy);
}
}
if (group < (this.combinations.length-1)) {
// clear the schedules (we don't want partially working schedules)
this.possibleschedulescopy = JSON.parse(JSON.stringify(this.possibleschedules));
this.possibleschedules = [];
}
}
}
}
}
},
/*
Pushes every combination given the type of groups
*/
findCombinations: function () {
this.combinations = [];
for (var group in this.classes) {
var thisgroup = this.classes[group];
var type = thisgroup["type"];
// figure out the length of the courses
var coursekeys = Object.keys(thisgroup["courses"]);
if (coursekeys.length > 0) {
// there must be courses selected
if (type == 0 || type > coursekeys.length) {
// they selected all of or they wanted more courses than chosen
type = coursekeys.length;
}
// convert the courses to an array
var thesecourses = [];
for (var course in thisgroup["courses"]) {
thisgroup["courses"][course]["name"] = course;
thesecourses.push(thisgroup["courses"][course]);
}
// push the combinations
this.combinations.push(this.k_combinations(thesecourses, type));
}
}
},
generateSchedules: function (schedule, queue) {
/*
Given a wanted class queue and current schedule, this method will recursively find every schedule that doesn't conflict
*/
var timeconflict = false;
if (queue.length == 0) {
// we found a successful schedule, push it
// we need to make a copy since the higher depths will undo the actions
this.possibleschedules.push(JSON.parse(JSON.stringify(schedule)));
}
else {
// Check that if they selected that they only want open classes,
// we make sure the most recent one is open
if (schedule.length > 0 && this.onlyOpen == true) {
var addedClass = schedule[schedule.length-1];
if (addedClass["status"] != "Open") {
timeconflict = true;
}
}
if (schedule.length > 0 && timeconflict == false) {
// Check if the most recent class conflicts with any user blocked times
var recentClass = schedule[schedule.length-1];
for (var time in recentClass["times"]) {
var time = recentClass["times"][time];
for (var day in time[0]) {
var day = time[0][day];
if (this.blockedTimes[day] != undefined) {
for (var blockedTime in this.blockedTimes[day]) {
var thisBlockedTime = this.blockedTimes[day][blockedTime];
// The blocked time has a span of 30min, check if it conflicts
if (this.isConflicting(time[1], [thisBlockedTime, thisBlockedTime+30])) {
timeconflict = true;
break
}
}
}
if (timeconflict) break;
}
if (timeconflict) break;
}
}
if (schedule.length > 1 && timeconflict == false) {
// TODO: REFACTOR NEEDED
// Check whether the most recent index has a time conflict with any of the others
for (var x = 0; x < schedule.length-1; x++) {
var thistimes = schedule[x]["times"];
for (var time in thistimes) {
var thistime = thistimes[time];
// compare to last
for (var othertime in schedule[schedule.length-1]["times"]) {
var othertime = schedule[schedule.length-1]["times"][othertime];
// check if any of the days between them are the same
for (var day in thistime[0]) {
var day = thistime[0][day];
if (othertime[0].indexOf(day) > -1) {
// same day, check for time conflict
if (this.isConflicting(thistime[1], othertime[1])) {
timeconflict = true;
}
}
}
if (timeconflict) break;
}
if (timeconflict) break;
}
if (timeconflict) break;
}
}
if (schedule.length > 1 && timeconflict == false) {
// if there are group numbers, make sure all classes are in the same group
// Some Unis require your tutorials to match the specific lecture etc...
// we only need to look at the most recent and second most recent groups
// since classes that belong to the same course are appended consecutively
if (schedule[schedule.length-1]["name"] == schedule[schedule.length-2]["name"]) {
// make sure they have the same group number
if (schedule[schedule.length-1]["group"] != schedule[schedule.length-2]["group"]) {
// we have a conflict
timeconflict = true;
}
}
}
if (timeconflict == false) {
// we can continue
if (Object.keys(queue[0]["types"]).length > 0) {
// find an open type
var foundType = false;
for (var type in queue[0]["types"]) {
if (queue[0]["types"][type] == true) {
// they chose a general class to fulfill
foundType = type;
break;
}
else if (queue[0]["types"][type] != false) {
// they chose a specific class to fulfill
// add the specific class
// find the class
for (var classv in queue[0]["obj"]["classes"]) {
var thisclass = queue[0]["obj"]["classes"][classv];
if (thisclass["id"] == queue[0]["types"][type]) {
// we found the class obj, add it to the schedule
schedule.push(thisclass);
// remove the type from the queue
delete queue[0]["types"][type];
// recursively call the generator
this.generateSchedules(schedule, queue);
// remove the class
schedule.pop();
// add the type again
queue[0]["types"][type] = thisclass["id"];
break;
}
}
break;
}
}
if (foundType != false) {
// remove the type
delete queue[0]["types"][foundType];
// we need to iterate through the classes, find which ones match this type
for (var classv in queue[0]["obj"]["classes"]) {
var thisclass = queue[0]["obj"]["classes"][classv];
if (thisclass["type"] == foundType) {
// Push the class
schedule.push(thisclass);
// recursively go down a depth
this.generateSchedules(schedule, queue);
// pop the class we added
schedule.pop();
}
}
queue[0]["types"][foundType] = true;
}
}
else {
// we've already found all the types for this class, move on to the next
// remove this course
var thisitem = queue.shift();
this.generateSchedules(schedule, queue);
// add the item back
queue.unshift(thisitem);
}
}
}
},
isConflicting: function (time1, time2) {
// time1 and time2 are arrays with the first index being the total minutes
// since 12:00AM that day of the starttime and the second being the endtime
// ex. [570, 645] and [590, 740]
// We check whether the end time of time2 is greater than the start time of time1
// and whether the end time of time1 is greater than the start time of time2
// if so, there is a conflict
if (time1[1] > time2[0] && time2[1] > time1[0]) {
return true;
}
else {
return false;
}
},
k_combinations: function (set, k) {
/**
* Copyright 2012 Akseli Palén.
* Created 2012-07-15.
* Licensed under the MIT license.
*
* <license>
* 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.
* </lisence>
*
* Implements functions to calculate combinations of elements in JS Arrays.
*
* Functions:
* k_combinations(set, k) -- Return all k-sized combinations in a set
* combinations(set) -- Return all combinations of the set
*/
var i, j, combs, head, tailcombs;
// There is no way to take e.g. sets of 5 elements from
// a set of 4.
if (k > set.length || k <= 0) {
return [];
}
// K-sized set has only one K-sized subset.
if (k == set.length) {
return [set];
}
// There is N 1-sized subsets in a N-sized set.
if (k == 1) {
combs = [];
for (i = 0; i < set.length; i++) {
combs.push([set[i]]);
}
return combs;
}
// Assert {1 < k < set.length}
// Algorithm description:
// To get k-combinations of a set, we want to join each element
// with all (k-1)-combinations of the other elements. The set of
// these k-sized sets would be the desired result. However, as we
// represent sets with lists, we need to take duplicates into
// account. To avoid producing duplicates and also unnecessary
// computing, we use the following approach: each element i
// divides the list into three: the preceding elements, the
// current element i, and the subsequent elements. For the first
// element, the list of preceding elements is empty. For element i,
// we compute the (k-1)-computations of the subsequent elements,
// join each with the element i, and store the joined to the set of
// computed k-combinations. We do not need to take the preceding
// elements into account, because they have already been the i:th
// element so they are already computed and stored. When the length
// of the subsequent list drops below (k-1), we cannot find any
// (k-1)-combs, hence the upper limit for the iteration:
combs = [];
for (i = 0; i < set.length - k + 1; i++) {
// head is a list that includes only our current element.
head = set.slice(i, i + 1);
// We take smaller combinations from the subsequent elements
tailcombs = this.k_combinations(set.slice(i + 1), k - 1);
// For each (k-1)-combination we join it with the current
// and store it to the set of k-combinations.
for (j = 0; j < tailcombs.length; j++) {
combs.push(head.concat(tailcombs[j]));
}
}
return combs;
}
});
// only show the loader if the generation is taking longer than 500ms
// since the animations for it would take longer than the actual gen
setTimeout(function () {
if (self.doneScoring == false) window.calendar.startLoading("Generating Schedules...");
}, 500);
// Spawn the generator
self.schedgenerator.init(self.classes, self.blockedTimes, self.onlyOpen, function(result) {
console.log("Web worker finished generating schedules");
self.possibleschedules = result;
self.doneGenerating = true;
// Now score and sort them
self.schedSorter();
});
})
}
/*
Spawns a web worker that sorts and scores the current possibleschedules
*/
schedSorter() {
var self = this;
self.doneScoring = false;
// Get the user's scoring preferences
this.getPreferences();
// Instantiate the sorter
self.schedSort = operative({
possibleschedules: [],
init: function(schedules, morningSlider, nightSlider, consecutiveSlider, rmpSlider, rmpData, rmpAvg, callback) {
// Set local variables in the blob
this.morningSlider = morningSlider;
this.nightSlider = nightSlider;
this.consecutiveSlider = consecutiveSlider;
this.rmpSlider = rmpSlider;
this.rmpData = rmpData;
this.rmpAvg = rmpAvg;
// Add the scores for each schedules
for (var schedule in schedules) {
var thisschedule = schedules[schedule];
// add the score to the first index
thisschedule.unshift(this.scoreSchedule(thisschedule));
}
// Now sort
schedules.sort(this.compareSchedules);
callback(schedules);
},
/*
Compare function for the sorting algorithm
*/
compareSchedules: function (a, b) {
if (a[0] > b[0]) {
return -1;
}
if (b[0] > a[0]) {
return 1;
}
// a must be equal to b
return 0;
},
/*
Returns a numerical score given a schedule that defines how "good" it is given the user's preferences
*/
scoreSchedule: function (schedule) {
var thisscore = 0;
var totalrating = 0;
var totalteachers = 0;
for (var classv in schedule) {
var thisclass = schedule[classv];
// add a score based upon the teachers
totalteachers += thisclass["teachers"].length;
for (var teacher in thisclass["teachers"]) {
teacher = thisclass["teachers"][teacher];
if (this.rmpData[teacher] != undefined && this.rmpData[teacher]["numratings"] > 2) {
totalrating += this.rmpData[teacher]["rating"];
}
else {
// just give them an average rating
totalrating += this.rmpAvg;
}
}
}
var avgrmp = totalrating/totalteachers * 3;
if (this.rmpSlider > 0) {
// make this value worth more to the total score
avgrmp *= (1 + this.rmpSlider/20);
}
//console.log("AVG RMP: " + avgrmp);
thisscore += avgrmp;
// We want to transform the data into a usuable format for easily seeing how apart each class is
var formattedschedule = this.formatScheduleInOrder(schedule);
var classtimescore = 0.0;
for (var day in formattedschedule) {
var day = formattedschedule[day];
// Min/max time of the classes today
var mintime = 9999999;
var maxtime = 0;
for (var x = 0; x < day.length; x++) {
var time = day[x];
if (time[0] < mintime) {
mintime = time[0];
}
if (time[1] > maxtime) {
maxtime = time[1];
}
// check if it starts in the mourning
if (time[0] <= 720) {
classtimescore += this.morningSlider/50;
}
// check if it starts in the night
if (time[0] >= 1020) {
classtimescore += this.nightSlider/50;
}
// check for consecutive classes
// make sure there is a class next
if ((x+1) < day.length && this.consecutiveSlider != 0) {
// get the time of the next class
var nexttime = day[x+1];
// get the difference between the end of class1 and start of class2
var timediff = nexttime[0] - time[1];
var thisconsecscore = 0;
if (this.consecutiveSlider > 0) {
var thisconsecscore = 0.2;
}
else {
var thisconsecscore = -0.2;
}
thisconsecscore += (timediff/10) * (0.006 * -(this.consecutiveSlider/10));
//console.log("Consecutive: " + thisconsecscore);
classtimescore += thisconsecscore;
}
}
// we want there to be less time spent at school overall for a given day
// the longer the difference, the more penalty there is on the score depending on how much the user values time slots
var timediff = maxtime - mintime;
if (timediff > 0) {
if (this.rmpSlider < 0) {
// multiply the value
thisscore -= timediff/60 * (1 + -(this.rmpSlider/40));
}
else {
thisscore -= timediff/60 * 1.5;
}
}
}
// The user prioritizes time slots over professors, multiply this value
if (this.rmpSlider < 0) {
// make this value worth more to the total score
classtimescore *= 1 + -this.rmpSlider/20;
}
thisscore += classtimescore;
//console.log("Classes score: " + classtimescore);
//console.log(formattedschedule);
return thisscore;
},
/*
Formats a given schedule so that it is an array of days with an array of sorted times of each event
*/
formatScheduleInOrder: function (schedule) {
// formats a list of events to the appropriate duration
// the schedule must not have any conflicting events
var formated = [];
//console.log(schedule);
for (var classv in schedule) {
var thisclass = schedule[classv];
// for each time
for (var time in thisclass["times"]) {
var thistime = thisclass["times"][time];
// for each day in this time
for (var day in thistime[0]) {
var day = thistime[0][day];
// check whether the day index is an array
if (!(formated[day] instanceof Array)) {
// make it an array
formated[day] = [];
}
if (formated[day].length == 0) {
//console.log("Appending " + thistime[1] + " to " + day);
// just append the time
formated[day].push(thistime[1]);
}
else {
// iterate through each time already there
for (var formatedtime in formated[day]) {
// check if the end time of this event is less than the start time of the next event
var thisformatedtime = formated[day][formatedtime];
if (thistime[1][1] < thisformatedtime[0]) {
//console.log("Adding " + thistime[1] + " to " + day);
formated[day].splice(parseInt(formatedtime), 0, thistime[1]);
break;
}
else {
if (formated[day][parseInt(formatedtime)+1] == undefined) {
//console.log("Pushing " + thistime[1] + " to the end of " + day);
// push it to the end
formated[day].push(thistime[1]);
}
}
}
}
}
}
}
return formated
}
});
// Spawn the web worker
self.schedSort.init(this.possibleschedules, this.morningSlider, this.nightSlider, this.consecutiveSlider, this.rmpSlider, window.classList.rmpdata, window.classList.rmpavg,
function(result) {
console.log("Web worker finished sorting schedules");
console.log(result);
self.doneScoring = true;
// Replace the reference with the sorted schedules
self.possibleschedules = result;
window.calendar.doneLoading(function () {
self.processSchedules(result);
});
}
);
}
/*
Adds additional course info to each class for easier processing after schedules have been generated
*/
addCourseInfo() {
for (var group in this.classes) {
var thisgroup = this.classes[group];
var thiscourses = thisgroup["courses"];
for (var course in thiscourses) {
var thiscourse = thiscourses[course];
// convert the times of each class
var classobj = thiscourse["obj"]["classes"];
for (var classv in classobj) {
var thisclass = classobj[classv];
thisclass["name"] = course;
}
}
}
}
/*
Converts the times on the desired classes to an easily processable format
*/
convertTimes() {
for (var group in this.classes) {
var thisgroup = this.classes[group];
var thiscourses = thisgroup["courses"];
for (var course in thiscourses) {
var thiscourse = thiscourses[course];
// convert the times of each class
var classobj = thiscourse["obj"]["classes"];
for (var classv in classobj) {
var thisclass = classobj[classv];
// convert time
for (var time in thisclass["times"]) {
thisclass["times"][time] = Generator.convertTime(thisclass["times"][time]);
}
}
}
}
}
/*
Converts the format of the blockedTimes to the total minutes format used by the generator
*/
convertBlockedTimes() {
for (var day in this.blockedTimes) {
for (var time in this.blockedTimes[day]) {
var thistime = this.blockedTimes[day][time];
var totalMin = parseInt(thistime.split("-")[0])*60 + parseInt(thistime.split("-")[1]);
this.blockedTimes[day][time] = totalMin;
}
}
}
/*
Converts a time to total minutes since 12:00AM on that day
*/
static convertToTotalMinutes(time) {
// Format XX:XXPM or AM
var type = time.slice(-2);
var hours = parseInt(time.split(":")[0]);
if (type == "PM" && hours < 12) {
hours += 12;
}
var minutes = time.split(":")[1];
minutes = minutes.substr(0, minutes.length-2);
minutes = parseInt(minutes);
return hours * 60 + minutes;
}
/*
Converts the total minutes from 12:00AM on a given day to the timestamp
*/
static totalMinutesToTime(time) {
var minutes = time % 60;
var hours = Math.floor(time/60);
return hours + ":" + minutes;
}
/*
Converts a time of the form Mo 12:00PM-1:00PM to an array of days and total minutes
*/
static convertTime(time) {
// first index are the days (integer with Monday being 0)
// second index is the array with time
var newtime = [];
// Map the days
var map = {
"Mo": 0,
"Tu": 1,
"We": 2,
"Th": 3,
"R": 3,
"Fr": 4,
"F": 4,
"Sa": 5,
"S": 5,
"Su": 6,
"U": 6
}
// Map for other types of days
var map2 = {
"M": 0,
"T": 1,
"W": 2,
"R": 3,
"F": 4,
"S": 5,
"U": 6
}
if (time.indexOf(" - ") > -1) {
var timesplit = time.split(" - ");
var endtime = Generator.convertToTotalMinutes(timesplit[1]);
var starttime = Generator.convertToTotalMinutes(timesplit[0].split(" ")[1]);
// get the days
var days = timesplit[0].split(" ")[0];
var dayarray = [];
for (var day in map) {
if (days.indexOf(day) > -1) {
days = days.replace(day, "");
dayarray.push(map[day]);
}
}
// For other naming schemes
for (var day in map2) {
if (days.indexOf(day) > -1) {
dayarray.push(map[day]);
}
}
}
else {
// We don't know how to process this time
// This can happen with courses like web based courses with a time of "TBA"
newtime.push([-1]);
newtime.push([0, 0]);
}
newtime.push(dayarray);
newtime.push([starttime, endtime]);
return newtime;
}
/*
Processes a list of successful scored schedules and sets up the calendar
*/
processSchedules(schedules) {
// update the total
window.calendar.setTotalGenerated(schedules.length);
// update current
if (schedules.length == 0) window.calendar.setCurrentIndex(-1);
else if (schedules.length > 0) window.calendar.setCurrentIndex(0);
window.calendar.clearEvents();
if (schedules.length > 0) {
// populate the first one
window.calendar.displaySchedule(schedules[0]);
}
}
/*
Returns the schedule at the specified index
*/
getSchedule(index) {
if ((this.possibleschedules.length-1) >= index) {
return this.possibleschedules[index];
}
else {
return false;
}
}
/*
Sets the local preference values with the current state of the sliders
*/
getPreferences() {
this.morningSlider = preferences.getMorningValue();
this.nightSlider = preferences.getNightValue();
this.consecutiveSlider = preferences.getConsecutiveValue();
this.rmpSlider = preferences.getRMPValue();
this.onlyOpen = preferences.getOnlyOpenValue();
}
/*
Stops any current generation
*/
stop() {
if (this.schedSort != false) this.schedSort.terminate();
if (this.schedgenerator != false) this.schedgenerator.terminate();
}
/*
Updates the sorting for the current schedule given new preferences
*/
updateScores() {
var self = this;
// check whether we have already generated schedules
if (this.doneGenerating == true) {
// terminate any current scorer
this.stop();
// remove current scores
for (var schedule in this.possibleschedules) {
var thisschedule = this.possibleschedules[schedule];
// remove the first index (score) if its a number
if (typeof thisschedule[0] == "number") thisschedule.shift();
}
setTimeout(function () {
if (self.doneScoring == false && window.calendar.isLoading == false) window.calendar.startLoading("Generating Schedules...");
}, 500);
// check whether the current open value is different, if so, we need to regenerate the schedules
if (preferences.getOnlyOpenValue() != this.onlyOpen) {
// we need to fully regenerate the schedule
self.doneScoring = false;
this.schedGen();
}
else {
// now score it again
this.schedSorter();
}
}
}
} | js/Generator.js | class Generator {
constructor(classes, blockedTimes) {
// chosen classes
this.classes = JSON.parse(JSON.stringify(classes));
this.convertTimes();
this.addCourseInfo();
// update blocked times
this.blockedTimes = jQuery.extend(true, [], window.calendar.blockedTimes);
this.convertBlockedTimes();
this.schedSort = false;
this.schedgenerator = false;
this.doneGenerating = false;
this.doneScoring = false;
// Generates the schedules
this.schedGen();
}
/*
Spawns a web worker that generates possible schedules given classes
*/
schedGen() {
var self = this;
self.doneGenerating = false;
// Get the user's scoring preferences
// Want to get whether they only allow open classes or not
this.getPreferences();
window.calendar.doneLoading(function () {
// Instantiate the generator
self.schedgenerator = operative({
possibleschedules: [],
combinations: [],
classes: {},
init: function(classes, blockedTimes, onlyOpen, callback) {
this.classes = classes;
this.onlyOpen = onlyOpen;
this.blockedTimes = blockedTimes;
this.findCombinations();
this.iterateCombos();
callback(this.possibleschedules);
},
/*
Iterates through every group combinations to find possible non-conflicting schedules
*/
iterateCombos: function () {
// reset possible schedules
this.possibleschedules = [];
if (this.combinations.length > 0) {
// there must be more than 0 combos for a schedule
for (var combos in this.combinations[0]) {
// create a copy to work with
var combocopy = JSON.parse(JSON.stringify(this.combinations[0][combos]));
// geenrate the schedules
this.generateSchedules([], combocopy);
this.possibleschedulescopy = JSON.parse(JSON.stringify(this.possibleschedules));
if (this.combinations.length > 1) {
// console.log("Processing further groups");
this.possibleschedules = [];
// We have to add the other groups
for (var group = 1; group < this.combinations.length; group++) {
for (var newcombo in this.combinations[group]) {
// for every previous schedule
// TODO: If this starts to become slow, we might want to apply some heuristics
for (var possibleschedule in this.possibleschedulescopy) {
var combocopy = JSON.parse(JSON.stringify(this.combinations[group][newcombo]));
this.generateSchedules(this.possibleschedulescopy[possibleschedule], combocopy);
}
}
if (group < (this.combinations.length-1)) {
// clear the schedules (we don't want partially working schedules)
this.possibleschedulescopy = JSON.parse(JSON.stringify(this.possibleschedules));
this.possibleschedules = [];
}
}
}
}
}
},
/*
Pushes every combination given the type of groups
*/
findCombinations: function () {
this.combinations = [];
for (var group in this.classes) {
var thisgroup = this.classes[group];
var type = thisgroup["type"];
// figure out the length of the courses
var coursekeys = Object.keys(thisgroup["courses"]);
if (coursekeys.length > 0) {
// there must be courses selected
if (type == 0 || type > coursekeys.length) {
// they selected all of or they wanted more courses than chosen
type = coursekeys.length;
}
// convert the courses to an array
var thesecourses = [];
for (var course in thisgroup["courses"]) {
thisgroup["courses"][course]["name"] = course;
thesecourses.push(thisgroup["courses"][course]);
}
// push the combinations
this.combinations.push(this.k_combinations(thesecourses, type));
}
}
},
generateSchedules: function (schedule, queue) {
/*
Given a wanted class queue and current schedule, this method will recursively find every schedule that doesn't conflict
*/
var timeconflict = false;
if (queue.length == 0) {
// we found a successful schedule, push it
// we need to make a copy since the higher depths will undo the actions
this.possibleschedules.push(JSON.parse(JSON.stringify(schedule)));
}
else {
// Check that if they selected that they only want open classes,
// we make sure the most recent one is open
if (schedule.length > 0 && this.onlyOpen == true) {
var addedClass = schedule[schedule.length-1];
if (addedClass["status"] != "Open") {
timeconflict = true;
}
}
if (schedule.length > 0 && timeconflict == false) {
// Check if the most recent class conflicts with any user blocked times
var recentClass = schedule[schedule.length-1];
for (var time in recentClass["times"]) {
var time = recentClass["times"][time];
for (var day in time[0]) {
var day = time[0][day];
if (this.blockedTimes[day] != undefined) {
for (var blockedTime in this.blockedTimes[day]) {
var thisBlockedTime = this.blockedTimes[day][blockedTime];
// The blocked time has a span of 30min, check if it conflicts
if (this.isConflicting(time[1], [thisBlockedTime, thisBlockedTime+30])) {
timeconflict = true;
break
}
}
}
if (timeconflict) break;
}
if (timeconflict) break;
}
}
if (schedule.length > 1 && timeconflict == false) {
// TODO: REFACTOR NEEDED
// Check whether the most recent index has a time conflict with any of the others
for (var x = 0; x < schedule.length-1; x++) {
var thistimes = schedule[x]["times"];
for (var time in thistimes) {
var thistime = thistimes[time];
// compare to last
for (var othertime in schedule[schedule.length-1]["times"]) {
var othertime = schedule[schedule.length-1]["times"][othertime];
// check if any of the days between them are the same
for (var day in thistime[0]) {
var day = thistime[0][day];
if (othertime[0].indexOf(day) > -1) {
// same day, check for time conflict
if (this.isConflicting(thistime[1], othertime[1])) {
timeconflict = true;
}
}
}
if (timeconflict) break;
}
if (timeconflict) break;
}
if (timeconflict) break;
}
}
if (schedule.length > 1 && timeconflict == false) {
// if there are group numbers, make sure all classes are in the same group
// Some Unis require your tutorials to match the specific lecture etc...
// we only need to look at the most recent and second most recent groups
// since classes that belong to the same course are appended consecutively
if (schedule[schedule.length-1]["name"] == schedule[schedule.length-2]["name"]) {
// make sure they have the same group number
if (schedule[schedule.length-1]["group"] != schedule[schedule.length-2]["group"]) {
// we have a conflict
timeconflict = true;
}
}
}
if (timeconflict == false) {
// we can continue
if (Object.keys(queue[0]["types"]).length > 0) {
// find an open type
var foundType = false;
for (var type in queue[0]["types"]) {
if (queue[0]["types"][type] == true) {
// they chose a general class to fulfill
foundType = type;
break;
}
else if (queue[0]["types"][type] != false) {
// they chose a specific class to fulfill
// add the specific class
// find the class
for (var classv in queue[0]["obj"]["classes"]) {
var thisclass = queue[0]["obj"]["classes"][classv];
if (thisclass["id"] == queue[0]["types"][type]) {
// we found the class obj, add it to the schedule
schedule.push(thisclass);
// remove the type from the queue
delete queue[0]["types"][type];
// recursively call the generator
this.generateSchedules(schedule, queue);
// remove the class
schedule.pop();
// add the type again
queue[0]["types"][type] = thisclass["id"];
break;
}
}
break;
}
}
if (foundType != false) {
// remove the type
delete queue[0]["types"][foundType];
// we need to iterate through the classes, find which ones match this type
for (var classv in queue[0]["obj"]["classes"]) {
var thisclass = queue[0]["obj"]["classes"][classv];
if (thisclass["type"] == foundType) {
// Push the class
schedule.push(thisclass);
// recursively go down a depth
this.generateSchedules(schedule, queue);
// pop the class we added
schedule.pop();
}
}
queue[0]["types"][foundType] = true;
}
}
else {
// we've already found all the types for this class, move on to the next
// remove this course
var thisitem = queue.shift();
this.generateSchedules(schedule, queue);
// add the item back
queue.unshift(thisitem);
}
}
}
},
isConflicting: function (time1, time2) {
// time1 and time2 are arrays with the first index being the total minutes
// since 12:00AM that day of the starttime and the second being the endtime
// ex. [570, 645] and [590, 740]
// We check whether the end time of time2 is greater than the start time of time1
// and whether the end time of time1 is greater than the start time of time2
// if so, there is a conflict
if (time1[1] > time2[0] && time2[1] > time1[0]) {
return true;
}
else {
return false;
}
},
k_combinations: function (set, k) {
/**
* Copyright 2012 Akseli Palén.
* Created 2012-07-15.
* Licensed under the MIT license.
*
* <license>
* 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.
* </lisence>
*
* Implements functions to calculate combinations of elements in JS Arrays.
*
* Functions:
* k_combinations(set, k) -- Return all k-sized combinations in a set
* combinations(set) -- Return all combinations of the set
*/
var i, j, combs, head, tailcombs;
// There is no way to take e.g. sets of 5 elements from
// a set of 4.
if (k > set.length || k <= 0) {
return [];
}
// K-sized set has only one K-sized subset.
if (k == set.length) {
return [set];
}
// There is N 1-sized subsets in a N-sized set.
if (k == 1) {
combs = [];
for (i = 0; i < set.length; i++) {
combs.push([set[i]]);
}
return combs;
}
// Assert {1 < k < set.length}
// Algorithm description:
// To get k-combinations of a set, we want to join each element
// with all (k-1)-combinations of the other elements. The set of
// these k-sized sets would be the desired result. However, as we
// represent sets with lists, we need to take duplicates into
// account. To avoid producing duplicates and also unnecessary
// computing, we use the following approach: each element i
// divides the list into three: the preceding elements, the
// current element i, and the subsequent elements. For the first
// element, the list of preceding elements is empty. For element i,
// we compute the (k-1)-computations of the subsequent elements,
// join each with the element i, and store the joined to the set of
// computed k-combinations. We do not need to take the preceding
// elements into account, because they have already been the i:th
// element so they are already computed and stored. When the length
// of the subsequent list drops below (k-1), we cannot find any
// (k-1)-combs, hence the upper limit for the iteration:
combs = [];
for (i = 0; i < set.length - k + 1; i++) {
// head is a list that includes only our current element.
head = set.slice(i, i + 1);
// We take smaller combinations from the subsequent elements
tailcombs = this.k_combinations(set.slice(i + 1), k - 1);
// For each (k-1)-combination we join it with the current
// and store it to the set of k-combinations.
for (j = 0; j < tailcombs.length; j++) {
combs.push(head.concat(tailcombs[j]));
}
}
return combs;
}
});
// only show the loader if the generation is taking longer than 500ms
// since the animations for it would take longer than the actual gen
setTimeout(function () {
if (self.doneScoring == false) window.calendar.startLoading("Generating Schedules...");
}, 500);
// Spawn the generator
self.schedgenerator.init(self.classes, self.blockedTimes, self.onlyOpen, function(result) {
console.log("Web worker finished generating schedules");
self.possibleschedules = result;
self.doneGenerating = true;
// Now score and sort them
self.schedSorter();
});
})
}
/*
Spawns a web worker that sorts and scores the current possibleschedules
*/
schedSorter() {
var self = this;
self.doneScoring = false;
// Get the user's scoring preferences
this.getPreferences();
// Instantiate the sorter
self.schedSort = operative({
possibleschedules: [],
init: function(schedules, morningSlider, nightSlider, consecutiveSlider, rmpSlider, rmpData, rmpAvg, callback) {
// Set local variables in the blob
this.morningSlider = morningSlider;
this.nightSlider = nightSlider;
this.consecutiveSlider = consecutiveSlider;
this.rmpSlider = rmpSlider;
this.rmpData = rmpData;
this.rmpAvg = rmpAvg;
// Add the scores for each schedules
for (var schedule in schedules) {
var thisschedule = schedules[schedule];
// add the score to the first index
thisschedule.unshift(this.scoreSchedule(thisschedule));
}
// Now sort
schedules.sort(this.compareSchedules);
callback(schedules);
},
/*
Compare function for the sorting algorithm
*/
compareSchedules: function (a, b) {
if (a[0] > b[0]) {
return -1;
}
if (b[0] > a[0]) {
return 1;
}
// a must be equal to b
return 0;
},
/*
Returns a numerical score given a schedule that defines how "good" it is given the user's preferences
*/
scoreSchedule: function (schedule) {
var thisscore = 0;
var totalrating = 0;
var totalteachers = 0;
for (var classv in schedule) {
var thisclass = schedule[classv];
// add a score based upon the teachers
totalteachers += thisclass["teachers"].length;
for (var teacher in thisclass["teachers"]) {
teacher = thisclass["teachers"][teacher];
if (this.rmpData[teacher] != undefined && this.rmpData[teacher]["numratings"] > 2) {
totalrating += this.rmpData[teacher]["rating"];
}
else {
// just give them an average rating
totalrating += this.rmpAvg;
}
}
}
var avgrmp = totalrating/totalteachers * 3;
if (this.rmpSlider > 0) {
// make this value worth more to the total score
avgrmp *= (1 + this.rmpSlider/20);
}
//console.log("AVG RMP: " + avgrmp);
thisscore += avgrmp;
// We want to transform the data into a usuable format for easily seeing how apart each class is
var formattedschedule = this.formatScheduleInOrder(schedule);
var classtimescore = 0.0;
for (var day in formattedschedule) {
var day = formattedschedule[day];
// Min/max time of the classes today
var mintime = 9999999;
var maxtime = 0;
for (var x = 0; x < day.length; x++) {
var time = day[x];
if (time[0] < mintime) {
mintime = time[0];
}
if (time[1] > maxtime) {
maxtime = time[1];
}
// check if it starts in the mourning
if (time[0] <= 720) {
classtimescore += this.morningSlider/50;
}
// check if it starts in the night
if (time[0] >= 1020) {
classtimescore += this.nightSlider/50;
}
// check for consecutive classes
// make sure there is a class next
if ((x+1) < day.length && this.consecutiveSlider != 0) {
// get the time of the next class
var nexttime = day[x+1];
// get the difference between the end of class1 and start of class2
var timediff = nexttime[0] - time[1];
var thisconsecscore = 0;
if (this.consecutiveSlider > 0) {
var thisconsecscore = 0.2;
}
else {
var thisconsecscore = -0.2;
}
thisconsecscore += (timediff/10) * (0.006 * -(this.consecutiveSlider/10));
//console.log("Consecutive: " + thisconsecscore);
classtimescore += thisconsecscore;
}
}
// we want there to be less time spent at school overall for a given day
// the longer the difference, the more penalty there is on the score depending on how much the user values time slots
var timediff = maxtime - mintime;
if (timediff > 0) {
if (this.rmpSlider < 0) {
// multiply the value
thisscore -= timediff/60 * (1 + -(this.rmpSlider/40));
}
else {
thisscore -= timediff/60 * 1.5;
}
}
}
// The user prioritizes time slots over professors, multiply this value
if (this.rmpSlider < 0) {
// make this value worth more to the total score
classtimescore *= 1 + -this.rmpSlider/20;
}
thisscore += classtimescore;
//console.log("Classes score: " + classtimescore);
//console.log(formattedschedule);
return thisscore;
},
/*
Formats a given schedule so that it is an array of days with an array of sorted times of each event
*/
formatScheduleInOrder: function (schedule) {
// formats a list of events to the appropriate duration
// the schedule must not have any conflicting events
var formated = [];
//console.log(schedule);
for (var classv in schedule) {
var thisclass = schedule[classv];
// for each time
for (var time in thisclass["times"]) {
var thistime = thisclass["times"][time];
// for each day in this time
for (var day in thistime[0]) {
var day = thistime[0][day];
// check whether the day index is an array
if (!(formated[day] instanceof Array)) {
// make it an array
formated[day] = [];
}
if (formated[day].length == 0) {
//console.log("Appending " + thistime[1] + " to " + day);
// just append the time
formated[day].push(thistime[1]);
}
else {
// iterate through each time already there
for (var formatedtime in formated[day]) {
// check if the end time of this event is less than the start time of the next event
var thisformatedtime = formated[day][formatedtime];
if (thistime[1][1] < thisformatedtime[0]) {
//console.log("Adding " + thistime[1] + " to " + day);
formated[day].splice(parseInt(formatedtime), 0, thistime[1]);
break;
}
else {
if (formated[day][parseInt(formatedtime)+1] == undefined) {
//console.log("Pushing " + thistime[1] + " to the end of " + day);
// push it to the end
formated[day].push(thistime[1]);
}
}
}
}
}
}
}
return formated
}
});
// Spawn the web worker
self.schedSort.init(this.possibleschedules, this.morningSlider, this.nightSlider, this.consecutiveSlider, this.rmpSlider, window.classList.rmpdata, window.classList.rmpavg,
function(result) {
console.log("Web worker finished sorting schedules");
console.log(result);
self.doneScoring = true;
// Replace the reference with the sorted schedules
self.possibleschedules = result;
window.calendar.doneLoading(function () {
self.processSchedules(result);
});
}
);
}
/*
Adds additional course info to each class for easier processing after schedules have been generated
*/
addCourseInfo() {
for (var group in this.classes) {
var thisgroup = this.classes[group];
var thiscourses = thisgroup["courses"];
for (var course in thiscourses) {
var thiscourse = thiscourses[course];
// convert the times of each class
var classobj = thiscourse["obj"]["classes"];
for (var classv in classobj) {
var thisclass = classobj[classv];
thisclass["name"] = course;
}
}
}
}
/*
Converts the times on the desired classes to an easily processable format
*/
convertTimes() {
for (var group in this.classes) {
var thisgroup = this.classes[group];
var thiscourses = thisgroup["courses"];
for (var course in thiscourses) {
var thiscourse = thiscourses[course];
// convert the times of each class
var classobj = thiscourse["obj"]["classes"];
for (var classv in classobj) {
var thisclass = classobj[classv];
// convert time
for (var time in thisclass["times"]) {
thisclass["times"][time] = Generator.convertTime(thisclass["times"][time]);
}
}
}
}
}
static isConflicting(time1, time2) {
/*
time1 and time2 are arrays with the first index being the total minutes
since 12:00AM that day of the starttime and the second being the endtime
ex. [570, 645] and [590, 740]
We check whether the end time of time2 is greater than the start time of time1
and whether the end time of time1 is greater than the start time of time2
if so, there is a conflict
*/
if (time1[1] > time2[0] && time2[1] > time1[0]) {
return true;
}
else {
return false;
}
}
/*
Converts the format of the blockedTimes to the total minutes format used by the generator
*/
convertBlockedTimes() {
for (var day in this.blockedTimes) {
for (var time in this.blockedTimes[day]) {
var thistime = this.blockedTimes[day][time];
var totalMin = parseInt(thistime.split("-")[0])*60 + parseInt(thistime.split("-")[1]);
this.blockedTimes[day][time] = totalMin;
}
}
}
/*
Converts a time to total minutes since 12:00AM on that day
*/
static convertToTotalMinutes(time) {
// Format XX:XXPM or AM
var type = time.slice(-2);
var hours = parseInt(time.split(":")[0]);
if (type == "PM" && hours < 12) {
hours += 12;
}
var minutes = time.split(":")[1];
minutes = minutes.substr(0, minutes.length-2);
minutes = parseInt(minutes);
return hours * 60 + minutes;
}
/*
Converts the total minutes from 12:00AM on a given day to the timestamp
*/
static totalMinutesToTime(time) {
var minutes = time % 60;
var hours = Math.floor(time/60);
return hours + ":" + minutes;
}
/*
Converts a time of the form Mo 12:00PM-1:00PM to an array of days and total minutes
*/
static convertTime(time) {
// first index are the days (integer with Monday being 0)
// second index is the array with time
var newtime = [];
// Map the days
var map = {
"Mo": 0,
"Tu": 1,
"We": 2,
"Th": 3,
"R": 3,
"Fr": 4,
"F": 4,
"Sa": 5,
"S": 5,
"Su": 6,
"U": 6
}
// Map for other types of days
var map2 = {
"M": 0,
"T": 1,
"W": 2,
"R": 3,
"F": 4,
"S": 5,
"U": 6
}
if (time.indexOf(" - ") > -1) {
var timesplit = time.split(" - ");
var endtime = Generator.convertToTotalMinutes(timesplit[1]);
var starttime = Generator.convertToTotalMinutes(timesplit[0].split(" ")[1]);
// get the days
var days = timesplit[0].split(" ")[0];
var dayarray = [];
for (var day in map) {
if (days.indexOf(day) > -1) {
days = days.replace(day, "");
dayarray.push(map[day]);
}
}
// For other naming schemes
for (var day in map2) {
if (days.indexOf(day) > -1) {
dayarray.push(map[day]);
}
}
}
else {
// We don't know how to process this time
// This can happen with courses like web based courses with a time of "TBA"
newtime.push([-1]);
newtime.push([0, 0]);
}
newtime.push(dayarray);
newtime.push([starttime, endtime]);
return newtime;
}
/*
Processes a list of successful scored schedules and sets up the calendar
*/
processSchedules(schedules) {
// update the total
window.calendar.setTotalGenerated(schedules.length);
// update current
if (schedules.length == 0) window.calendar.setCurrentIndex(-1);
else if (schedules.length > 0) window.calendar.setCurrentIndex(0);
window.calendar.clearEvents();
if (schedules.length > 0) {
// populate the first one
window.calendar.displaySchedule(schedules[0]);
}
}
/*
Returns the schedule at the specified index
*/
getSchedule(index) {
if ((this.possibleschedules.length-1) >= index) {
return this.possibleschedules[index];
}
else {
return false;
}
}
/*
Sets the local preference values with the current state of the sliders
*/
getPreferences() {
this.morningSlider = preferences.getMorningValue();
this.nightSlider = preferences.getNightValue();
this.consecutiveSlider = preferences.getConsecutiveValue();
this.rmpSlider = preferences.getRMPValue();
this.onlyOpen = preferences.getOnlyOpenValue();
}
/*
Stops any current generation
*/
stop() {
if (this.schedSort != false) this.schedSort.terminate();
if (this.schedgenerator != false) this.schedgenerator.terminate();
}
/*
Updates the sorting for the current schedule given new preferences
*/
updateScores() {
var self = this;
// check whether we have already generated schedules
if (this.doneGenerating == true) {
// terminate any current scorer
this.stop();
// remove current scores
for (var schedule in this.possibleschedules) {
var thisschedule = this.possibleschedules[schedule];
// remove the first index (score) if its a number
if (typeof thisschedule[0] == "number") thisschedule.shift();
}
setTimeout(function () {
if (self.doneScoring == false && window.calendar.isLoading == false) window.calendar.startLoading("Generating Schedules...");
}, 500);
// check whether the current open value is different, if so, we need to regenerate the schedules
if (preferences.getOnlyOpenValue() != this.onlyOpen) {
// we need to fully regenerate the schedule
self.doneScoring = false;
this.schedGen();
}
else {
// now score it again
this.schedSorter();
}
}
}
} | Removes Redundant isConflicting Function
| js/Generator.js | Removes Redundant isConflicting Function | <ide><path>s/Generator.js
<ide> }
<ide> }
<ide>
<del> static isConflicting(time1, time2) {
<del> /*
<del> time1 and time2 are arrays with the first index being the total minutes
<del> since 12:00AM that day of the starttime and the second being the endtime
<del> ex. [570, 645] and [590, 740]
<del> We check whether the end time of time2 is greater than the start time of time1
<del> and whether the end time of time1 is greater than the start time of time2
<del> if so, there is a conflict
<del> */
<del>
<del> if (time1[1] > time2[0] && time2[1] > time1[0]) {
<del> return true;
<del> }
<del> else {
<del> return false;
<del> }
<del> }
<del>
<ide> /*
<ide> Converts the format of the blockedTimes to the total minutes format used by the generator
<ide> */ |
|
Java | mit | e3e8bb2e1dc4c9b0ffb30401da53382089e93ca9 | 0 | martenbohlin/lombok,mg6maciej/hrisey,fpeter8/lombok,redundent/lombok,derektom14/lombok,vampiregod1996/lombok,Tradunsky/lombok,Arvoreen/lombok,Arvoreen/lombok,luanpotter/lombok,openlegacy/lombok,dmissoh/lombok,nickbarban/lombok,dcendents/lombok,vampiregod1996/lombok,develhack/develhacked-lombok,arielnetworks/lombok,openlegacy/lombok,Shedings/hrisey,Beabel2/lombok,MaTriXy/lombok,martenbohlin/lombok,jdiasamaro/lombok,Tradunsky/lombok,riccardobl/lombok,timtreibmann/lombokDataReceived,luanpotter/lombok,domix/lombok,rzwitserloot/lombok,timtreibmann/lombokDataReceived,jdiasamaro/lombok,arielnetworks/lombok,dcendents/lombok,dmissoh/lombok,martenbohlin/lombok,fpeter8/lombok,develhack/develhacked-lombok,nickbarban/lombok,nickbarban/lombok,develhack/develhacked-lombok,domix/lombok,jdiasamaro/lombok,timtreibmann/lombokDataReceived,vampiregod1996/lombok,wuwen5/lombok,rzwitserloot/lombok,fpeter8/lombok,yangpeiyong/hrisey,derektom14/lombok,dmissoh/lombok,Arvoreen/lombok,mg6maciej/hrisey,domix/lombok,rzwitserloot/lombok,Shedings/hrisey,wuwen5/lombok,riccardobl/lombok,mg6maciej/hrisey,MaTriXy/lombok,MaTriXy/lombok,derektom14/lombok,Beabel2/lombok,yangpeiyong/hrisey,wuwen5/lombok,dmissoh/lombok,openlegacy/lombok,martenbohlin/lombok,rzwitserloot/lombok,redundent/lombok,Beabel2/lombok,Tradunsky/lombok,Shedings/hrisey,Arvoreen/lombok,Shedings/hrisey,derektom14/lombok,Lekanich/lombok,wuwen5/lombok,dcendents/lombok,Lekanich/lombok,luanpotter/lombok,Lekanich/lombok,nickbarban/lombok,timtreibmann/lombokDataReceived,fpeter8/lombok,fpeter8/lombok,jdiasamaro/lombok,riccardobl/lombok,Lekanich/lombok,yangpeiyong/hrisey,fpeter8/lombok,mg6maciej/hrisey,vampiregod1996/lombok,develhack/develhacked-lombok,Beabel2/lombok,rzwitserloot/lombok,openlegacy/lombok,luanpotter/lombok,redundent/lombok,yangpeiyong/hrisey,consulo/lombokOld,arielnetworks/lombok,MaTriXy/lombok,dcendents/lombok,Tradunsky/lombok,riccardobl/lombok | /*
* Copyright © 2009 Reinier Zwitserloot and Roel Spilker.
*
* 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.
*/
package lombok.installer.netbeans;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import lombok.installer.CorruptedIdeLocationException;
import lombok.installer.IdeFinder;
import lombok.installer.IdeLocation;
import lombok.installer.InstallException;
import lombok.installer.UninstallException;
public class NetbeansLocation extends IdeLocation {
private final String name;
private final File netbeansConfPath;
private volatile boolean hasLombok;
private static final String OS_NEWLINE = IdeFinder.getOS().getLineEnding();
NetbeansLocation(String nameOfLocation, File pathToNetbeansConf) throws CorruptedIdeLocationException {
this.name = nameOfLocation;
this.netbeansConfPath = pathToNetbeansConf;
try {
this.hasLombok = checkForLombok(netbeansConfPath);
} catch (IOException e) {
throw new CorruptedIdeLocationException(
"I can't read the configuration file of the Netbeans installed at " + name + "\n" +
"You may need to run this installer with root privileges if you want to modify that Netbeans.", "netbeans", e);
}
}
@Override public int hashCode() {
return netbeansConfPath.hashCode();
}
@Override public boolean equals(Object o) {
if (!(o instanceof NetbeansLocation)) return false;
return ((NetbeansLocation)o).netbeansConfPath.equals(netbeansConfPath);
}
/**
* Returns the name of this location; generally the path to the netbeans executable.
*/
@Override
public String getName() {
return name;
}
/**
* @return true if the Netbeans installation has been instrumented with lombok.
*/
@Override
public boolean hasLombok() {
return hasLombok;
}
private final String ID_CHARS = "(?:\\\\.|[^\"\\\\])*";
private final Pattern JAVA_AGENT_LINE_MATCHER = Pattern.compile(
"^\\s*netbeans_default_options\\s*=\\s*\"\\s*" + ID_CHARS + "(?<=[ \"])(-J-javaagent:\\\\\"" + ID_CHARS + "lombok" + ID_CHARS + "\\.jar\\\\\")(?=[ \"])" + ID_CHARS +"\\s*\"\\s*(?:#.*)?$", Pattern.CASE_INSENSITIVE);
private final Pattern OPTIONS_LINE_MATCHER = Pattern.compile(
"^\\s*netbeans_default_options\\s*=\\s*\"\\s*" + ID_CHARS + "\\s*(\")\\s*(?:#.*)?$", Pattern.CASE_INSENSITIVE);
private boolean checkForLombok(File iniFile) throws IOException {
if (!iniFile.exists()) return false;
FileInputStream fis = new FileInputStream(iniFile);
try {
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line = br.readLine()) != null) {
if (JAVA_AGENT_LINE_MATCHER.matcher(line.trim()).matches()) return true;
}
return false;
} finally {
fis.close();
}
}
/**
* Uninstalls lombok from this location.
* It's a no-op if lombok wasn't there in the first place,
* and it will remove a half-succeeded lombok installation as well.
*
* @throws UninstallException
* If there's an obvious I/O problem that is preventing
* installation. bugs in the uninstall code will probably throw
* other exceptions; this is intentional.
*/
@Override
public void uninstall() throws UninstallException {
File dir = netbeansConfPath.getParentFile();
File lombokJar = new File(dir, "lombok.jar");
if (lombokJar.exists()) {
if (!lombokJar.delete()) throw new UninstallException(
"Can't delete " + lombokJar.getAbsolutePath() + generateWriteErrorMessage(), null);
}
StringBuilder newContents = new StringBuilder();
if (netbeansConfPath.exists()) {
try {
FileInputStream fis = new FileInputStream(netbeansConfPath);
try {
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line = br.readLine()) != null) {
Matcher m = JAVA_AGENT_LINE_MATCHER.matcher(line);
if (m.matches()) {
newContents.append(line.substring(0, m.start(1)) + line.substring(m.end(1)));
} else {
newContents.append(line);
}
newContents.append(OS_NEWLINE);
}
} finally {
fis.close();
}
FileOutputStream fos = new FileOutputStream(netbeansConfPath);
try {
fos.write(newContents.toString().getBytes());
} finally {
fos.close();
}
} catch (IOException e) {
throw new UninstallException("Cannot uninstall lombok from " + name + generateWriteErrorMessage(), e);
}
}
}
private static String generateWriteErrorMessage() {
String osSpecificError;
switch (IdeFinder.getOS()) {
default:
case MAC_OS_X:
case UNIX:
osSpecificError = ":\nStart terminal, go to the directory with lombok.jar, and run: sudo java -jar lombok.jar";
break;
case WINDOWS:
osSpecificError = ":\nStart a new cmd (dos box) with admin privileges, go to the directory with lombok.jar, and run: java -jar lombok.jar";
break;
}
return ", probably because this installer does not have the access rights.\n" +
"Try re-running the installer with administrative privileges" + osSpecificError;
}
/**
* Install lombok into the Netbeans at this location.
* If lombok is already there, it is overwritten neatly (upgrade mode).
*
* @throws InstallException
* If there's an obvious I/O problem that is preventing
* installation. bugs in the install code will probably throw
* other exceptions; this is intentional.
*/
@Override
public String install() throws InstallException {
boolean installSucceeded = false;
StringBuilder newContents = new StringBuilder();
File lombokJar = new File(netbeansConfPath.getParentFile(), "lombok.jar");
File ourJar = findOurJar();
byte[] b = new byte[524288];
boolean readSucceeded = true;
try {
FileOutputStream out = new FileOutputStream(lombokJar);
try {
readSucceeded = false;
InputStream in = new FileInputStream(ourJar);
try {
while (true) {
int r = in.read(b);
if (r == -1) break;
if (r > 0) readSucceeded = true;
out.write(b, 0, r);
}
} finally {
in.close();
}
} finally {
out.close();
}
} catch (IOException e) {
try {
lombokJar.delete();
} catch (Throwable ignore) { /* Nothing we can do about that. */ }
if (!readSucceeded) throw new InstallException(
"I can't read my own jar file. I think you've found a bug in this installer!\nI suggest you restart it " +
"and use the 'what do I do' link, to manually install lombok. Also, tell us about this at:\n" +
"http://groups.google.com/group/project-lombok - Thanks!", e);
throw new InstallException("I can't write to your Netbeans directory at " + name + generateWriteErrorMessage(), e);
}
try {
FileInputStream fis = new FileInputStream(netbeansConfPath);
try {
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line = br.readLine()) != null) {
Matcher m = JAVA_AGENT_LINE_MATCHER.matcher(line);
if (m.matches()) {
newContents.append(line.substring(0, m.start(1)));
newContents.append("-J-javaagent:\\\"" + canonical(lombokJar) + "\\\"");
newContents.append(line.substring(m.end(1)));
newContents.append(OS_NEWLINE);
continue;
}
m = OPTIONS_LINE_MATCHER.matcher(line);
if (m.matches()) {
newContents.append(line.substring(0, m.start(1)));
newContents.append(" ").append("-J-javaagent:\\\"" + canonical(lombokJar) +"\\\"");
newContents.append(line.substring(m.end(1))).append(OS_NEWLINE);
continue;
}
newContents.append(line).append(OS_NEWLINE);
}
} finally {
fis.close();
}
FileOutputStream fos = new FileOutputStream(netbeansConfPath);
try {
fos.write(newContents.toString().getBytes());
} finally {
fos.close();
}
installSucceeded = true;
} catch (IOException e) {
throw new InstallException("Cannot install lombok at " + name + generateWriteErrorMessage(), e);
} finally {
if (!installSucceeded) try {
lombokJar.delete();
} catch (Throwable ignore) {}
}
if (!installSucceeded) {
throw new InstallException("I can't find the netbeans.conf file. Is this a real Netbeans installation?", null);
}
return "If you start netbeans with custom parameters, you'll need to add:<br>" +
"<code>-J-javaagent:\\\"" + canonical(lombokJar) + "\\\"</code><br>" +
"as parameter as well.";
}
@Override public URL getIdeIcon() {
return NetbeansLocation.class.getResource("netbeans.png");
}
}
| src/installer/lombok/installer/netbeans/NetbeansLocation.java | /*
* Copyright © 2009 Reinier Zwitserloot and Roel Spilker.
*
* 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.
*/
package lombok.installer.netbeans;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import lombok.installer.CorruptedIdeLocationException;
import lombok.installer.IdeFinder;
import lombok.installer.IdeLocation;
import lombok.installer.InstallException;
import lombok.installer.UninstallException;
public class NetbeansLocation extends IdeLocation {
private final String name;
private final File netbeansConfPath;
private volatile boolean hasLombok;
private static final String OS_NEWLINE = IdeFinder.getOS().getLineEnding();
NetbeansLocation(String nameOfLocation, File pathToNetbeansConf) throws CorruptedIdeLocationException {
this.name = nameOfLocation;
this.netbeansConfPath = pathToNetbeansConf;
try {
this.hasLombok = checkForLombok(netbeansConfPath);
} catch (IOException e) {
throw new CorruptedIdeLocationException(
"I can't read the configuration file of the Netbeans installed at " + name + "\n" +
"You may need to run this installer with root privileges if you want to modify that Netbeans.", "netbeans", e);
}
}
@Override public int hashCode() {
return netbeansConfPath.hashCode();
}
@Override public boolean equals(Object o) {
if (!(o instanceof NetbeansLocation)) return false;
return ((NetbeansLocation)o).netbeansConfPath.equals(netbeansConfPath);
}
/**
* Returns the name of this location; generally the path to the netbeans executable.
*/
@Override
public String getName() {
return name;
}
/**
* @return true if the Netbeans installation has been instrumented with lombok.
*/
@Override
public boolean hasLombok() {
return hasLombok;
}
private final String ID_CHARS = "(?:\\\\.|[^\"\\\\])*";
private final String ID_CHARS_NS = "(?:\\\\.|[^\"\\\\ ])*";
private final Pattern JAVA_AGENT_LINE_MATCHER = Pattern.compile(
"^\\s*netbeans_default_options\\s*=\\s*\"\\s*" + ID_CHARS + "(?<=[ \"])(-J-javaagent:" + ID_CHARS_NS + "lombok" + ID_CHARS_NS + "\\.jar)(?=[ \"])" + ID_CHARS +"\\s*\"\\s*(?:#.*)?$", Pattern.CASE_INSENSITIVE);
private final Pattern OPTIONS_LINE_MATCHER = Pattern.compile(
"^\\s*netbeans_default_options\\s*=\\s*\"\\s*" + ID_CHARS + "\\s*(\")\\s*(?:#.*)?$", Pattern.CASE_INSENSITIVE);
private boolean checkForLombok(File iniFile) throws IOException {
if (!iniFile.exists()) return false;
FileInputStream fis = new FileInputStream(iniFile);
try {
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line = br.readLine()) != null) {
if (JAVA_AGENT_LINE_MATCHER.matcher(line.trim()).matches()) return true;
}
return false;
} finally {
fis.close();
}
}
/**
* Uninstalls lombok from this location.
* It's a no-op if lombok wasn't there in the first place,
* and it will remove a half-succeeded lombok installation as well.
*
* @throws UninstallException
* If there's an obvious I/O problem that is preventing
* installation. bugs in the uninstall code will probably throw
* other exceptions; this is intentional.
*/
@Override
public void uninstall() throws UninstallException {
File dir = netbeansConfPath.getParentFile();
File lombokJar = new File(dir, "lombok.jar");
if (lombokJar.exists()) {
if (!lombokJar.delete()) throw new UninstallException(
"Can't delete " + lombokJar.getAbsolutePath() + generateWriteErrorMessage(), null);
}
StringBuilder newContents = new StringBuilder();
if (netbeansConfPath.exists()) {
try {
FileInputStream fis = new FileInputStream(netbeansConfPath);
try {
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line = br.readLine()) != null) {
Matcher m = JAVA_AGENT_LINE_MATCHER.matcher(line);
if (m.matches()) {
newContents.append(line.substring(0, m.start(1)) + line.substring(m.end(1)));
} else {
newContents.append(line);
}
newContents.append(OS_NEWLINE);
}
} finally {
fis.close();
}
FileOutputStream fos = new FileOutputStream(netbeansConfPath);
try {
fos.write(newContents.toString().getBytes());
} finally {
fos.close();
}
} catch (IOException e) {
throw new UninstallException("Cannot uninstall lombok from " + name + generateWriteErrorMessage(), e);
}
}
}
private static String generateWriteErrorMessage() {
String osSpecificError;
switch (IdeFinder.getOS()) {
default:
case MAC_OS_X:
case UNIX:
osSpecificError = ":\nStart terminal, go to the directory with lombok.jar, and run: sudo java -jar lombok.jar";
break;
case WINDOWS:
osSpecificError = ":\nStart a new cmd (dos box) with admin privileges, go to the directory with lombok.jar, and run: java -jar lombok.jar";
break;
}
return ", probably because this installer does not have the access rights.\n" +
"Try re-running the installer with administrative privileges" + osSpecificError;
}
/**
* Install lombok into the Netbeans at this location.
* If lombok is already there, it is overwritten neatly (upgrade mode).
*
* @throws InstallException
* If there's an obvious I/O problem that is preventing
* installation. bugs in the install code will probably throw
* other exceptions; this is intentional.
*/
@Override
public String install() throws InstallException {
boolean installSucceeded = false;
StringBuilder newContents = new StringBuilder();
File lombokJar = new File(netbeansConfPath.getParentFile(), "lombok.jar");
File ourJar = findOurJar();
byte[] b = new byte[524288];
boolean readSucceeded = true;
try {
FileOutputStream out = new FileOutputStream(lombokJar);
try {
readSucceeded = false;
InputStream in = new FileInputStream(ourJar);
try {
while (true) {
int r = in.read(b);
if (r == -1) break;
if (r > 0) readSucceeded = true;
out.write(b, 0, r);
}
} finally {
in.close();
}
} finally {
out.close();
}
} catch (IOException e) {
try {
lombokJar.delete();
} catch (Throwable ignore) { /* Nothing we can do about that. */ }
if (!readSucceeded) throw new InstallException(
"I can't read my own jar file. I think you've found a bug in this installer!\nI suggest you restart it " +
"and use the 'what do I do' link, to manually install lombok. Also, tell us about this at:\n" +
"http://groups.google.com/group/project-lombok - Thanks!", e);
throw new InstallException("I can't write to your Netbeans directory at " + name + generateWriteErrorMessage(), e);
}
try {
FileInputStream fis = new FileInputStream(netbeansConfPath);
try {
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line = br.readLine()) != null) {
Matcher m = JAVA_AGENT_LINE_MATCHER.matcher(line);
if (m.matches()) {
newContents.append(line.substring(0, m.start(1)));
newContents.append("-J-javaagent:" + escapePath(canonical(lombokJar)));
newContents.append(line.substring(m.end(1)));
newContents.append(OS_NEWLINE);
continue;
}
m = OPTIONS_LINE_MATCHER.matcher(line);
if (m.matches()) {
newContents.append(line.substring(0, m.start(1)));
newContents.append(" ").append("-J-javaagent:" + escapePath(canonical(lombokJar)) +"\"");
newContents.append(line.substring(m.end(1))).append(OS_NEWLINE);
continue;
}
newContents.append(line).append(OS_NEWLINE);
}
} finally {
fis.close();
}
FileOutputStream fos = new FileOutputStream(netbeansConfPath);
try {
fos.write(newContents.toString().getBytes());
} finally {
fos.close();
}
installSucceeded = true;
} catch (IOException e) {
throw new InstallException("Cannot install lombok at " + name + generateWriteErrorMessage(), e);
} finally {
if (!installSucceeded) try {
lombokJar.delete();
} catch (Throwable ignore) {}
}
if (!installSucceeded) {
throw new InstallException("I can't find the netbeans.conf file. Is this a real Netbeans installation?", null);
}
return "If you start netbeans with custom parameters, you'll need to add:<br>" +
"<code>-J-javaagent:" + escapePath(canonical(lombokJar)) + "</code><br>" +
"as parameter as well.";
}
@Override public URL getIdeIcon() {
return NetbeansLocation.class.getResource("netbeans.png");
}
}
| Fix for installation - now uses quotes instead of backslash-space, as backslash-space doesn't work in windows.
| src/installer/lombok/installer/netbeans/NetbeansLocation.java | Fix for installation - now uses quotes instead of backslash-space, as backslash-space doesn't work in windows. | <ide><path>rc/installer/lombok/installer/netbeans/NetbeansLocation.java
<ide> }
<ide>
<ide> private final String ID_CHARS = "(?:\\\\.|[^\"\\\\])*";
<del> private final String ID_CHARS_NS = "(?:\\\\.|[^\"\\\\ ])*";
<ide> private final Pattern JAVA_AGENT_LINE_MATCHER = Pattern.compile(
<del> "^\\s*netbeans_default_options\\s*=\\s*\"\\s*" + ID_CHARS + "(?<=[ \"])(-J-javaagent:" + ID_CHARS_NS + "lombok" + ID_CHARS_NS + "\\.jar)(?=[ \"])" + ID_CHARS +"\\s*\"\\s*(?:#.*)?$", Pattern.CASE_INSENSITIVE);
<add> "^\\s*netbeans_default_options\\s*=\\s*\"\\s*" + ID_CHARS + "(?<=[ \"])(-J-javaagent:\\\\\"" + ID_CHARS + "lombok" + ID_CHARS + "\\.jar\\\\\")(?=[ \"])" + ID_CHARS +"\\s*\"\\s*(?:#.*)?$", Pattern.CASE_INSENSITIVE);
<ide>
<ide> private final Pattern OPTIONS_LINE_MATCHER = Pattern.compile(
<ide> "^\\s*netbeans_default_options\\s*=\\s*\"\\s*" + ID_CHARS + "\\s*(\")\\s*(?:#.*)?$", Pattern.CASE_INSENSITIVE);
<ide> Matcher m = JAVA_AGENT_LINE_MATCHER.matcher(line);
<ide> if (m.matches()) {
<ide> newContents.append(line.substring(0, m.start(1)));
<del> newContents.append("-J-javaagent:" + escapePath(canonical(lombokJar)));
<add> newContents.append("-J-javaagent:\\\"" + canonical(lombokJar) + "\\\"");
<ide> newContents.append(line.substring(m.end(1)));
<ide> newContents.append(OS_NEWLINE);
<ide> continue;
<ide> m = OPTIONS_LINE_MATCHER.matcher(line);
<ide> if (m.matches()) {
<ide> newContents.append(line.substring(0, m.start(1)));
<del> newContents.append(" ").append("-J-javaagent:" + escapePath(canonical(lombokJar)) +"\"");
<add> newContents.append(" ").append("-J-javaagent:\\\"" + canonical(lombokJar) +"\\\"");
<ide> newContents.append(line.substring(m.end(1))).append(OS_NEWLINE);
<ide> continue;
<ide> }
<ide> }
<ide>
<ide> return "If you start netbeans with custom parameters, you'll need to add:<br>" +
<del> "<code>-J-javaagent:" + escapePath(canonical(lombokJar)) + "</code><br>" +
<add> "<code>-J-javaagent:\\\"" + canonical(lombokJar) + "\\\"</code><br>" +
<ide> "as parameter as well.";
<ide> }
<ide> |
|
Java | bsd-3-clause | e7ed014d40ef7e9c092fcc31210b36e02440f307 | 0 | jamie-dryad/dryad-repo,ojacobson/dryad-repo,ojacobson/dryad-repo,jamie-dryad/dryad-repo,ojacobson/dryad-repo,rnathanday/dryad-repo,rnathanday/dryad-repo,jimallman/dryad-repo,rnathanday/dryad-repo,jimallman/dryad-repo,jimallman/dryad-repo,ojacobson/dryad-repo,jamie-dryad/dryad-repo,jimallman/dryad-repo,jimallman/dryad-repo,rnathanday/dryad-repo,rnathanday/dryad-repo,jimallman/dryad-repo,ojacobson/dryad-repo,ojacobson/dryad-repo,rnathanday/dryad-repo,jamie-dryad/dryad-repo,jamie-dryad/dryad-repo | /**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.paymentsystem;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Select;
import org.dspace.app.xmlui.wing.element.Text;
import org.dspace.app.xmlui.wing.element.Xref;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.*;
import org.dspace.core.Context;
import org.dspace.eperson.EPerson;
import org.dspace.submit.utils.DryadJournalSubmissionUtils;
import org.dspace.utils.DSpace;
import org.dspace.versioning.VersionHistory;
import org.dspace.versioning.VersionHistoryImpl;
import org.dspace.versioning.VersioningService;
import org.dspace.workflow.DryadWorkflowUtils;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import static org.dspace.app.xmlui.wing.AbstractWingTransformer.message;
/**
* PaymentService provides an interface for the DSpace application to
* interact with the Payment Service implementation and persist
* Shopping Cart Changes
*
* @author Mark Diggory, mdiggory at atmire.com
* @author Fabio Bolognesi, fabio at atmire.com
* @author Lantian Gai, lantian at atmire.com
*/
public class PaymentSystemImpl implements PaymentSystemService {
/** log4j log */
private static Logger log = Logger.getLogger(PaymentSystemImpl.class);
protected static final Message T_Header=
message("xmlui.PaymentSystem.shoppingcart.order.header");
protected static final Message T_Payer=
message("xmlui.PaymentSystem.shoppingcart.order.payer");
protected static final Message T_Price=
message("xmlui.PaymentSystem.shoppingcart.order.price");
protected static final Message T_Surcharge=
message("xmlui.PaymentSystem.shoppingcart.order.surcharge");
protected static final Message T_Total=
message("xmlui.PaymentSystem.shoppingcart.order.total");
protected static final Message T_noInteg=
message("xmlui.PaymentSystem.shoppingcart.order.noIntegrateFee");
protected static final Message T_Country=
message("xmlui.PaymentSystem.shoppingcart.order.country");
protected static final Message T_Voucher=
message("xmlui.PaymentSystem.shoppingcart.order.voucher");
protected static final Message T_Apply=
message("xmlui.PaymentSystem.shoppingcart.order.apply");
protected static final String Country_Help_Text= "Submitters requesting a Waiver must be employees of an institution in an eligible country or be independent researchers in residence in an eligible country. Eligible countries are those classified by the World Bank as low-income or lower-middle-income economies.";
protected static final String Voucher_Help_Text="Organizations may sponsor submissions to Dryad by purchasing and distributing voucher codes redeemable for one Data Publishing Charge. Submitters redeeming vouchers may only use them with the permission of the purchaser.";
protected static final String Currency_Help_Text="Select Currency";
/** Protected Constructor */
protected PaymentSystemImpl()
{
}
public ShoppingCart createNewShoppingCart(Context context, Integer itemId, Integer epersonId, String country, String currency, String status) throws SQLException,
PaymentSystemException {
ShoppingCart newShoppingcart = ShoppingCart.create(context);
newShoppingcart.setCountry(country);
newShoppingcart.setCurrency(currency);
newShoppingcart.setDepositor(epersonId);
newShoppingcart.setExpiration(null);
if(itemId !=null){
//make sure we only create the shoppingcart for data package
Item item = Item.find(context,itemId);
org.dspace.content.Item dataPackage = DryadWorkflowUtils.getDataPackage(context, item);
if(dataPackage!=null)
{
itemId = dataPackage.getID();
}
newShoppingcart.setItem(itemId);
}
newShoppingcart.setStatus(status);
newShoppingcart.setVoucher(null);
newShoppingcart.setTransactionId(null);
newShoppingcart.setJournal(null);
newShoppingcart.setJournalSub(false);
newShoppingcart.setBasicFee(PaymentSystemConfigurationManager.getCurrencyProperty(currency));
newShoppingcart.setNoInteg(PaymentSystemConfigurationManager.getNotIntegratedJournalFeeProperty(currency));
newShoppingcart.setSurcharge(PaymentSystemConfigurationManager.getSizeFileFeeProperty(currency));
Double totalPrice = calculateShoppingCartTotal(context, newShoppingcart, null);
newShoppingcart.setTotal(totalPrice);
newShoppingcart.update();
return newShoppingcart;
}
public void modifyShoppingCart(Context context,ShoppingCart shoppingcart,DSpaceObject dso)throws AuthorizeException, SQLException,PaymentSystemException{
if(shoppingcart.getModified())
{
shoppingcart.update();
shoppingcart.setModified(false);
}
}
public void setCurrency(ShoppingCart shoppingCart,String currency)throws SQLException{
shoppingCart.setCurrency(currency);
shoppingCart.setBasicFee(PaymentSystemConfigurationManager.getCurrencyProperty(currency));
shoppingCart.setNoInteg(PaymentSystemConfigurationManager.getNotIntegratedJournalFeeProperty(currency));
shoppingCart.setSurcharge(PaymentSystemConfigurationManager.getSizeFileFeeProperty(currency));
shoppingCart.update();
shoppingCart.setModified(false);
}
public void deleteShoppingCart(Context context,Integer shoppingcartId) throws AuthorizeException, SQLException, PaymentSystemException {
ShoppingCart trasaction = ShoppingCart.findByTransactionId(context, shoppingcartId);
trasaction.delete();
}
public ShoppingCart getShoppingCart(Context context,Integer shoppingcartId) throws SQLException
{
return ShoppingCart.findByTransactionId(context, shoppingcartId);
}
public ShoppingCart[] findAllShoppingCart(Context context,Integer itemId)throws SQLException,PaymentSystemException{
if(itemId==null||itemId==-1){
return ShoppingCart.findAll(context);
}
else
{
VersioningService versioningService = new DSpace().getSingletonService(VersioningService.class);
VersionHistory history = versioningService.findVersionHistory(context, itemId);
if(history!=null)
{
Item originalItem = history.getFirstVersion().getItem();
itemId = originalItem.getID();
}
ShoppingCart[] shoppingCarts = new ShoppingCart[1];
shoppingCarts[0] = getShoppingCartByItemId(context, itemId);
return shoppingCarts;
}
}
public ShoppingCart getShoppingCartByItemId(Context context,Integer itemId) throws SQLException,PaymentSystemException
{
//make sure we get correct shoppingcart for data package
Item item = Item.find(context,itemId);
org.dspace.content.Item dataPackage = DryadWorkflowUtils.getDataPackage(context, item);
if(dataPackage!=null)
{
itemId = dataPackage.getID();
}
VersioningService versioningService = new DSpace().getSingletonService(VersioningService.class);
VersionHistory history = versioningService.findVersionHistory(context, itemId);
if(history!=null)
{
Item originalItem = history.getFirstVersion().getItem();
itemId = originalItem.getID();
ArrayList<ShoppingCart> shoppingCarts = ShoppingCart.findAllByItem(context,itemId);
if(shoppingCarts.size()>0)
{
return shoppingCarts.get(0);
}
}
List<ShoppingCart> shoppingcartList= ShoppingCart.findAllByItem(context, itemId);
if(shoppingcartList!=null && shoppingcartList.size()>0)
return shoppingcartList.get(0);
else
{
//if no shopping cart , create a new one
return createNewShoppingCart(context,itemId,context.getCurrentUser().getID(),"",ShoppingCart.CURRENCY_US,ShoppingCart.STATUS_OPEN);
}
}
public Double calculateShoppingCartTotal(Context context,ShoppingCart shoppingcart,String journal) throws SQLException{
log.debug("recalculating shopping cart total");
Double price = new Double(0);
if(hasDiscount(context,shoppingcart,journal))
{
//has discount , only caculate the file surcharge fee
price =getSurchargeLargeFileFee(context, shoppingcart);
}
else
{
//no journal,voucher,country discount
Double basicFee = shoppingcart.getBasicFee();
double fileSizeFee=getSurchargeLargeFileFee(context, shoppingcart);
price = basicFee+fileSizeFee;
price = price+getNoIntegrateFee(context,shoppingcart,journal);
}
return price;
}
/**
* Calculate the surcharge for a data package, based on its size in bytes
* @param allowedSize the maximum size allowed before large file surcharge
* @param totalDataFileSize the total size of data files in bytes
* @param fileSizeFeeAfter the fee per unit to assess after exceeding allowedSize
* @param initialSurcharge Initial surcharge, e.g. 15 for the first 1GB exceeding 10GB.
* @param surchargeUnitSize amount of data to assess a fileSizeFeeAfter on, e.g. 1GB = 1*1024*1024
* @return The total surcharge to assess.
*/
public static double calculateFileSizeSurcharge(
long allowedSize,
long totalDataFileSize,
double fileSizeFeeAfter,
double initialSurcharge,
long surchargeUnitSize) {
double totalSurcharge = initialSurcharge;
if(totalDataFileSize > allowedSize){
int unit =0;
//eg. $10 after every 1 gb
if(surchargeUnitSize > 0) {
Long overSize = (totalDataFileSize - allowedSize) / surchargeUnitSize;
unit = overSize.intValue();
}
totalSurcharge = totalSurcharge+fileSizeFeeAfter*unit;
}
return totalSurcharge;
}
/**
* Get the total size in bytes of all bitstreams within a data package.
* Assumes item is a data package and DryadWorkFlowUtils.getDataFiles returns
* data file items with bundles, bitstreams.
* @param context
* @param dataPackage
* @return
* @throws SQLException
*/
public long getTotalDataFileSize(Context context, Item dataPackage) throws SQLException {
Item[] dataFiles = DryadWorkflowUtils.getDataFiles(context, dataPackage);
long size = 0;
for(Item dataFile : dataFiles){
Bundle bundles[] = dataFile.getBundles();
for(Bundle bundle:bundles)
{
Bitstream bitstreams[]=bundle.getBitstreams();
for(Bitstream bitstream:bitstreams)
{
size += bitstream.getSize();
}
}
}
return size;
}
public double getSurchargeLargeFileFee(Context context, ShoppingCart shoppingcart) throws SQLException {
// Extract values from database objects and configuration to pass to calculator
String currency = shoppingcart.getCurrency();
long allowedSize = PaymentSystemConfigurationManager.getMaxFileSize().longValue();
double fileSizeFeeAfter = PaymentSystemConfigurationManager.getAllSizeFileFeeAfterProperty(currency);
Long unitSize = PaymentSystemConfigurationManager.getUnitSize(); //1 GB
Item item = Item.find(context, shoppingcart.getItem());
long totalSizeDataFile = getTotalDataFileSize(context, item);
double totalSurcharge = calculateFileSizeSurcharge(allowedSize, totalSizeDataFile, fileSizeFeeAfter, shoppingcart.getSurcharge(), unitSize);
return totalSurcharge;
}
public boolean getJournalSubscription(Context context, ShoppingCart shoppingcart, String journal) throws SQLException {
if(!shoppingcart.getStatus().equals(ShoppingCart.STATUS_COMPLETED))
{
if(journal==null||journal.length()==0){
Item item = Item.find(context,shoppingcart.getItem()) ;
if(item!=null)
{
try{
//only take the first journal
DCValue[] values = item.getMetadata("prism.publicationName");
if(values!=null && values.length > 0){
journal=values[0].value;
}
}catch (Exception e)
{
log.error("Exception when get journal in journal subscription:", e);
}
}
}
//update the journal and journal subscribtion
updateJournal(shoppingcart,journal);
}
return shoppingcart.getJournalSub();
}
public double getNoIntegrateFee(Context context, ShoppingCart shoppingcart, String journal) throws SQLException {
Double totalPrice = new Double(0);
if(journal==null){
Item item = Item.find(context,shoppingcart.getItem()) ;
if(item!=null)
{
try{
DCValue[] values = item.getMetadata("prism.publicationName");
if(values!=null && values.length > 0){
journal=values[0].value;
}
}catch (Exception e)
{
log.error("Exception when get journal name in geting no integration fee:", e);
}
}
}
if(journal!=null)
{
try{
DryadJournalSubmissionUtils util = new DryadJournalSubmissionUtils();
Map<String, String> properties = util.journalProperties.get(journal);
if(properties!=null){
String subscription = properties.get("integrated");
if(subscription==null || !subscription.equals(ShoppingCart.FREE))
{
totalPrice= shoppingcart.getNoInteg();
}
}
else
{
totalPrice= shoppingcart.getNoInteg();
}
}catch(Exception e){
log.error("Exception when get no integration fee:", e);
}
}
else
{
totalPrice= shoppingcart.getNoInteg();
}
return totalPrice;
}
private boolean voucherValidate(Context context,ShoppingCart shoppingcart){
VoucherValidationService voucherValidationService = new DSpace().getSingletonService(VoucherValidationService.class);
return voucherValidationService.validate(context,shoppingcart.getVoucher(),shoppingcart);
}
public boolean hasDiscount(Context context,ShoppingCart shoppingcart,String journal)throws SQLException{
//this method check all the discount: journal,country,voucher
Boolean journalSubscription = getJournalSubscription(context, shoppingcart, journal);
Boolean countryDiscount = getCountryWaiver(context,shoppingcart,journal);
Boolean voucherDiscount = voucherValidate(context,shoppingcart);
if(journalSubscription||countryDiscount||voucherDiscount){
log.debug("subscription has been paid by journal/country/voucher");
return true;
}
log.debug("submitter is responsible for payment");
return false;
}
public int getWaiver(Context context,ShoppingCart shoppingcart,String journal)throws SQLException{
//this method check all the discount: journal,country,voucher
Boolean journalSubscription = getJournalSubscription(context, shoppingcart, journal);
Boolean countryDiscount = getCountryWaiver(context,shoppingcart,journal);
Boolean voucherDiscount = voucherValidate(context,shoppingcart);
if(countryDiscount){
return ShoppingCart.COUNTRY_WAIVER;
}
else if(journalSubscription){
return ShoppingCart.JOUR_WAIVER;
}else if(voucherDiscount){
return ShoppingCart.VOUCHER_WAIVER;
}
return ShoppingCart.NO_WAIVER;
}
public boolean getCountryWaiver(Context context, ShoppingCart shoppingCart, String journal) throws SQLException{
PaymentSystemConfigurationManager manager = new PaymentSystemConfigurationManager();
Properties countryArray = manager.getAllCountryProperty();
if(shoppingCart.getCountry() != null && shoppingCart.getCountry().length()>0)
{
return countryArray.get(shoppingCart.getCountry()).equals(ShoppingCart.COUNTRYFREE);
}
else {
return false;
}
}
public void updateTotal(Context context, ShoppingCart shoppingCart, String journal) throws SQLException{
if(!shoppingCart.getStatus().equals(ShoppingCart.STATUS_COMPLETED)) {
Double newPrice = calculateShoppingCartTotal(context,shoppingCart,journal);
//TODO:only setup the price when the old total price is higher than the price right now
shoppingCart.setTotal(newPrice);
shoppingCart.update();
shoppingCart.setModified(false);
}
}
public String getPayer(Context context,ShoppingCart shoppingcart,String journal)throws SQLException{
String payerName = "";
EPerson e = EPerson.find(context,shoppingcart.getDepositor());
switch (getWaiver(context,shoppingcart,""))
{
case ShoppingCart.COUNTRY_WAIVER:payerName= "Country";break;
case ShoppingCart.JOUR_WAIVER: payerName = "Journal"; break;
case ShoppingCart.VOUCHER_WAIVER: payerName = "Voucher"; break;
case ShoppingCart.NO_WAIVER:payerName = e.getFullName();break;
}
return payerName;
}
private void updateJournal(ShoppingCart shoppingCart,String journal){
if(!shoppingCart.getStatus().equals(ShoppingCart.STATUS_COMPLETED))
{
if(journal!=null&&journal.length()>0) {
//update shoppingcart journal
Map<String, String> properties = DryadJournalSubmissionUtils.journalProperties.get(journal);
Boolean subscription = false;
if(properties!=null){
if(StringUtils.equals(properties.get("subscriptionPaid"), ShoppingCart.FREE))
{
subscription = true;
}
}
shoppingCart.setJournal(journal);
shoppingCart.setJournalSub(subscription);
}
}
}
private String format(String label, String value){
return label + ": " + value + "\n";
}
public String printShoppingCart(Context c, ShoppingCart shoppingCart){
String result = "";
try{
result += format("Payer", getPayer(c, shoppingCart, null));
String symbol = PaymentSystemConfigurationManager.getCurrencySymbol(shoppingCart.getCurrency());
if(hasDiscount(c,shoppingCart,null))
{
result += format("Price",symbol+"0.0");
}
else
{
result += format("Price",symbol+Double.toString(shoppingCart.getBasicFee()));
}
Double noIntegrateFee = getNoIntegrateFee(c,shoppingCart,null);
//add the no integrate fee if it is not 0
if(!hasDiscount(c,shoppingCart,null)&&noIntegrateFee>0&&!hasDiscount(c,shoppingCart,null))
{
result += format("Non-integrated submission", "" + noIntegrateFee);
}
else
{
result += format("Non-integrated submission", symbol+"0.0");
}
//add the large file surcharge section
format("Excess data storage", symbol+Double.toString(getSurchargeLargeFileFee(c,shoppingCart)));
try
{
Voucher v = Voucher.findById(c, shoppingCart.getVoucher());
if(v != null)
{
result += format("Voucher Applied", v.getCode());
}
}catch (Exception e)
{
log.error(e.getMessage(),e);
}
//add the final total price
result += format("Total", symbol+Double.toString(shoppingCart.getTotal()));
switch (getWaiver(c,shoppingCart,""))
{
case ShoppingCart.COUNTRY_WAIVER: format("Waiver Details", "Data Publishing Charge has been waived due to submitter's association with " + shoppingCart.getCountry() + ".");break;
case ShoppingCart.JOUR_WAIVER: format("Waiver Details", "Data Publishing Charges are covered for all submissions to " + shoppingCart.getJournal() + "."); break;
case ShoppingCart.VOUCHER_WAIVER: format("Waiver Details", "Voucher code applied to Data Publishing Charge."); break;
}
if(shoppingCart.getTransactionId() != null && "".equals(shoppingCart.getTransactionId().trim()))
{
format("Transaction ID", shoppingCart.getTransactionId());
}
}catch (Exception e)
{
result += format("Error", e.getMessage());
log.error(e.getMessage(),e);
}
return result;
}
public void generateShoppingCart(Context context,org.dspace.app.xmlui.wing.element.List info,ShoppingCart shoppingCart,PaymentSystemConfigurationManager manager,String baseUrl,Map<String,String> messages) throws WingException,SQLException
{
Item item = Item.find(context,shoppingCart.getItem());
Long totalSize = new Long(0);
String symbol = PaymentSystemConfigurationManager.getCurrencySymbol(shoppingCart.getCurrency());
org.dspace.app.xmlui.wing.element.List hiddenList = info.addList("transaction");
hiddenList.addItem().addHidden("transactionId").setValue(Integer.toString(shoppingCart.getID()));
hiddenList.addItem().addHidden("baseUrl").setValue(baseUrl);
try{
//add selected currency section
generateCurrencyList(info,manager,shoppingCart);
generatePayer(context,info,shoppingCart,item);
generatePrice(context,info,manager,shoppingCart);
generateCountryList(info,manager,shoppingCart,item);
generateVoucherForm(context,info,manager,shoppingCart,messages);
}catch (Exception e)
{
info.addLabel("Errors when generate the shopping cart form:"+e.getMessage());
}
}
public void generateNoEditableShoppingCart(Context context, org.dspace.app.xmlui.wing.element.List info, ShoppingCart transaction, PaymentSystemConfigurationManager manager, String baseUrl, Map<String, String> messages) throws WingException, SQLException
{
Item item = Item.find(context, transaction.getItem());
Long totalSize = new Long(0);
String symbol = PaymentSystemConfigurationManager.getCurrencySymbol(transaction.getCurrency());
org.dspace.app.xmlui.wing.element.List hiddenList = info.addList("transaction");
hiddenList.addItem().addHidden("transactionId").setValue(Integer.toString(transaction.getID()));
hiddenList.addItem().addHidden("baseUrl").setValue(baseUrl);
try {
//add selected currency section
info.addLabel(T_Header);
info.addItem().addContent(transaction.getCurrency());
generatePayer(context, info, transaction, item);
generatePrice(context, info, manager, transaction);
info.addItem().addContent(transaction.getCountry());
generateNoEditableVoucherForm(context, info, transaction, messages);
} catch (Exception e)
{
info.addLabel("Errors when generate the shopping cart form");
}
}
private void generateNoEditableVoucherForm(Context context, org.dspace.app.xmlui.wing.element.List info, ShoppingCart shoppingCart, Map<String, String> messages) throws WingException, SQLException {
Voucher voucher1 = Voucher.findById(context, shoppingCart.getVoucher());
if (messages.get("voucher") != null)
{
info.addItem("errorMessage", "errorMessage").addContent(messages.get("voucher"));
} else
{
info.addItem("errorMessage", "errorMessage").addContent("");
}
info.addLabel(T_Voucher);
info.addItem().addContent(voucher1.getCode());
}
private void generateCountryList(org.dspace.app.xmlui.wing.element.List info,PaymentSystemConfigurationManager manager,ShoppingCart shoppingCart,Item item) throws WingException{
//only generate country selection list when it is not on the publication select page, to do this we need to check the publication is not empty
java.util.List<String> countryArray = manager.getSortedCountry();
Select countryList = info.addItem("country-list", "select-list").addSelect("country");
countryList.setLabel(T_Country);
countryList.setHelp(Country_Help_Text);
countryList.addOption("","Select Your Country");
for(String temp:countryArray){
String[] countryTemp = temp.split(":");
if(shoppingCart.getCountry()!=null&&shoppingCart.getCountry().length()>0&&shoppingCart.getCountry().equals(countryTemp[0])) {
countryList.addOption(true,countryTemp[0],countryTemp[0]);
}
else
{
countryList.addOption(false,countryTemp[0],countryTemp[0]);
}
}
if(shoppingCart.getCountry().length()>0)
{
info.addItem("remove-country","remove-country").addXref("#","Remove Country : "+shoppingCart.getCountry());
}
else
{
info.addItem("remove-country","remove-country").addXref("#","");
}
}
private void generateSurchargeFeeForm(Context context,org.dspace.app.xmlui.wing.element.List info,PaymentSystemConfigurationManager manager,ShoppingCart shoppingCart) throws WingException,SQLException{
//add the large file surcharge section
String symbol = PaymentSystemConfigurationManager.getCurrencySymbol(shoppingCart.getCurrency());
info.addLabel(T_Surcharge);
info.addItem("surcharge","surcharge").addContent(String.format("%s%.0f", symbol, this.getSurchargeLargeFileFee(context,shoppingCart)));
}
private void generateCurrencyList(org.dspace.app.xmlui.wing.element.List info,PaymentSystemConfigurationManager manager,ShoppingCart shoppingCart) throws WingException,SQLException{
org.dspace.app.xmlui.wing.element.Item currency = info.addItem("currency-list", "select-list");
Select currencyList = currency.addSelect("currency");
currencyList.setLabel(T_Header);
//currencyList.setHelp(Currency_Help_Text);
Properties currencyArray = manager.getAllCurrencyProperty();
for(String currencyTemp: currencyArray.stringPropertyNames())
{
if(shoppingCart.getCurrency().equals(currencyTemp))
{
currencyList.addOption(true, currencyTemp, currencyTemp);
}
else
{
currencyList.addOption(false, currencyTemp, currencyTemp);
}
}
}
private void generateVoucherForm(Context context,org.dspace.app.xmlui.wing.element.List info,PaymentSystemConfigurationManager manager,ShoppingCart shoppingCart,Map<String,String> messages) throws WingException,SQLException{
Voucher voucher1 = Voucher.findById(context,shoppingCart.getVoucher());
if(messages.get("voucher")!=null)
{
info.addItem("errorMessage","errorMessage").addContent(messages.get("voucher"));
}
else
{
info.addItem("errorMessage","errorMessage").addContent("");
}
org.dspace.app.xmlui.wing.element.Item voucher = info.addItem("voucher-list","voucher-list");
Text voucherText = voucher.addText("voucher","voucher");
voucherText.setLabel(T_Voucher);
voucherText.setHelp(Voucher_Help_Text);
voucher.addButton("apply","apply");
if(voucher1!=null){
voucherText.setValue(voucher1.getCode());
info.addItem("remove-voucher","remove-voucher").addXref("#", "Remove Voucher : " + voucher1.getCode(), "remove-voucher", "remove-voucher");
}
else{
info.addItem("remove-voucher","remove-voucher").addXref("#", "", "remove-voucher", "remove-voucher");
}
}
private void generatePrice(Context context,org.dspace.app.xmlui.wing.element.List info,PaymentSystemConfigurationManager manager,ShoppingCart shoppingCart) throws WingException,SQLException{
String waiverMessage = "";
String symbol = PaymentSystemConfigurationManager.getCurrencySymbol(shoppingCart.getCurrency());
switch (this.getWaiver(context,shoppingCart,""))
{
case ShoppingCart.COUNTRY_WAIVER: waiverMessage = "Data Publishing Charge has been waived due to submitter's association with " + shoppingCart.getCountry() + "."; break;
case ShoppingCart.JOUR_WAIVER: waiverMessage = "Data Publishing Charges are covered for all submissions to " + shoppingCart.getJournal() + "."; break;
case ShoppingCart.VOUCHER_WAIVER: waiverMessage = "Voucher code applied to Data Publishing Charge."; break;
}
info.addLabel(T_Price);
if(this.hasDiscount(context,shoppingCart,null))
{
info.addItem("price","price").addContent(symbol+"0");
}
else
{
info.addItem("price","price").addContent(String.format("%s%.0f", symbol, shoppingCart.getBasicFee()));
}
Double noIntegrateFee = this.getNoIntegrateFee(context,shoppingCart,null);
//add the no integrate fee if it is not 0
info.addLabel(T_noInteg);
if(!this.hasDiscount(context,shoppingCart,null)&&noIntegrateFee>0&&!this.hasDiscount(context,shoppingCart,null))
{
info.addItem("no-integret","no-integret").addContent(String.format("%s%.0f", symbol, noIntegrateFee));
}
else
{
info.addItem("no-integret","no-integret").addContent(symbol+"0");
}
generateSurchargeFeeForm(context,info,manager,shoppingCart);
//add the final total price
info.addLabel(T_Total);
info.addItem("total","total").addContent(String.format("%s%.0f",symbol, shoppingCart.getTotal()));
info.addItem("waiver-info","waiver-info").addContent(waiverMessage);
}
private void generatePayer(Context context,org.dspace.app.xmlui.wing.element.List info,ShoppingCart shoppingCart,Item item) throws WingException,SQLException{
info.addLabel(T_Payer);
String payerName = this.getPayer(context, shoppingCart, null);
DCValue[] values= item.getMetadata("prism.publicationName");
if(values!=null&&values.length>0)
{
//on the first page don't generate the payer name, wait until user choose country or journal
info.addItem("payer","payer").addContent(payerName);
}
else
{
info.addItem("payer","payer").addContent("");
}
}
}
| dspace/modules/payment-system/payment-api/src/main/java/org/dspace/paymentsystem/PaymentSystemImpl.java | /**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.paymentsystem;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.dspace.app.xmlui.wing.Message;
import org.dspace.app.xmlui.wing.WingException;
import org.dspace.app.xmlui.wing.element.Select;
import org.dspace.app.xmlui.wing.element.Text;
import org.dspace.app.xmlui.wing.element.Xref;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.*;
import org.dspace.core.Context;
import org.dspace.eperson.EPerson;
import org.dspace.submit.utils.DryadJournalSubmissionUtils;
import org.dspace.utils.DSpace;
import org.dspace.versioning.VersionHistory;
import org.dspace.versioning.VersionHistoryImpl;
import org.dspace.versioning.VersioningService;
import org.dspace.workflow.DryadWorkflowUtils;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import static org.dspace.app.xmlui.wing.AbstractWingTransformer.message;
/**
* PaymentService provides an interface for the DSpace application to
* interact with the Payment Service implementation and persist
* Shopping Cart Changes
*
* @author Mark Diggory, mdiggory at atmire.com
* @author Fabio Bolognesi, fabio at atmire.com
* @author Lantian Gai, lantian at atmire.com
*/
public class PaymentSystemImpl implements PaymentSystemService {
/** log4j log */
private static Logger log = Logger.getLogger(PaymentSystemImpl.class);
protected static final Message T_Header=
message("xmlui.PaymentSystem.shoppingcart.order.header");
protected static final Message T_Payer=
message("xmlui.PaymentSystem.shoppingcart.order.payer");
protected static final Message T_Price=
message("xmlui.PaymentSystem.shoppingcart.order.price");
protected static final Message T_Surcharge=
message("xmlui.PaymentSystem.shoppingcart.order.surcharge");
protected static final Message T_Total=
message("xmlui.PaymentSystem.shoppingcart.order.total");
protected static final Message T_noInteg=
message("xmlui.PaymentSystem.shoppingcart.order.noIntegrateFee");
protected static final Message T_Country=
message("xmlui.PaymentSystem.shoppingcart.order.country");
protected static final Message T_Voucher=
message("xmlui.PaymentSystem.shoppingcart.order.voucher");
protected static final Message T_Apply=
message("xmlui.PaymentSystem.shoppingcart.order.apply");
protected static final String Country_Help_Text= "Submitters requesting a Waiver must be employees of an institution in an eligible country or be independent researchers in residence in an eligible country. Eligible countries are those classified by the World Bank as low-income or lower-middle-income economies.";
protected static final String Voucher_Help_Text="Organizations may sponsor submissions to Dryad by purchasing and distributing voucher codes redeemable for one Data Publishing Charge. Submitters redeeming vouchers may only use them with the permission of the purchaser.";
protected static final String Currency_Help_Text="Select Currency";
/** Protected Constructor */
protected PaymentSystemImpl()
{
}
public ShoppingCart createNewShoppingCart(Context context, Integer itemId, Integer epersonId, String country, String currency, String status) throws SQLException,
PaymentSystemException {
ShoppingCart newShoppingcart = ShoppingCart.create(context);
newShoppingcart.setCountry(country);
newShoppingcart.setCurrency(currency);
newShoppingcart.setDepositor(epersonId);
newShoppingcart.setExpiration(null);
if(itemId !=null){
//make sure we only create the shoppingcart for data package
Item item = Item.find(context,itemId);
org.dspace.content.Item dataPackage = DryadWorkflowUtils.getDataPackage(context, item);
if(dataPackage!=null)
{
itemId = dataPackage.getID();
}
newShoppingcart.setItem(itemId);
}
newShoppingcart.setStatus(status);
newShoppingcart.setVoucher(null);
newShoppingcart.setTransactionId(null);
newShoppingcart.setJournal(null);
newShoppingcart.setJournalSub(false);
newShoppingcart.setBasicFee(PaymentSystemConfigurationManager.getCurrencyProperty(currency));
newShoppingcart.setNoInteg(PaymentSystemConfigurationManager.getNotIntegratedJournalFeeProperty(currency));
newShoppingcart.setSurcharge(PaymentSystemConfigurationManager.getSizeFileFeeProperty(currency));
Double totalPrice = calculateShoppingCartTotal(context, newShoppingcart, null);
newShoppingcart.setTotal(totalPrice);
newShoppingcart.update();
return newShoppingcart;
}
public void modifyShoppingCart(Context context,ShoppingCart shoppingcart,DSpaceObject dso)throws AuthorizeException, SQLException,PaymentSystemException{
if(shoppingcart.getModified())
{
shoppingcart.update();
shoppingcart.setModified(false);
}
}
public void setCurrency(ShoppingCart shoppingCart,String currency)throws SQLException{
shoppingCart.setCurrency(currency);
shoppingCart.setBasicFee(PaymentSystemConfigurationManager.getCurrencyProperty(currency));
shoppingCart.setNoInteg(PaymentSystemConfigurationManager.getNotIntegratedJournalFeeProperty(currency));
shoppingCart.setSurcharge(PaymentSystemConfigurationManager.getSizeFileFeeProperty(currency));
shoppingCart.update();
shoppingCart.setModified(false);
}
public void deleteShoppingCart(Context context,Integer shoppingcartId) throws AuthorizeException, SQLException, PaymentSystemException {
ShoppingCart trasaction = ShoppingCart.findByTransactionId(context, shoppingcartId);
trasaction.delete();
}
public ShoppingCart getShoppingCart(Context context,Integer shoppingcartId) throws SQLException
{
return ShoppingCart.findByTransactionId(context, shoppingcartId);
}
public ShoppingCart[] findAllShoppingCart(Context context,Integer itemId)throws SQLException,PaymentSystemException{
if(itemId==null||itemId==-1){
return ShoppingCart.findAll(context);
}
else
{
VersioningService versioningService = new DSpace().getSingletonService(VersioningService.class);
VersionHistory history = versioningService.findVersionHistory(context, itemId);
if(history!=null)
{
Item originalItem = history.getFirstVersion().getItem();
itemId = originalItem.getID();
}
ShoppingCart[] shoppingCarts = new ShoppingCart[1];
shoppingCarts[0] = getShoppingCartByItemId(context, itemId);
return shoppingCarts;
}
}
public ShoppingCart getShoppingCartByItemId(Context context,Integer itemId) throws SQLException,PaymentSystemException
{
//make sure we get correct shoppingcart for data package
Item item = Item.find(context,itemId);
org.dspace.content.Item dataPackage = DryadWorkflowUtils.getDataPackage(context, item);
if(dataPackage!=null)
{
itemId = dataPackage.getID();
}
VersioningService versioningService = new DSpace().getSingletonService(VersioningService.class);
VersionHistory history = versioningService.findVersionHistory(context, itemId);
if(history!=null)
{
Item originalItem = history.getFirstVersion().getItem();
itemId = originalItem.getID();
ArrayList<ShoppingCart> shoppingCarts = ShoppingCart.findAllByItem(context,itemId);
if(shoppingCarts.size()>0)
{
return shoppingCarts.get(0);
}
}
List<ShoppingCart> shoppingcartList= ShoppingCart.findAllByItem(context, itemId);
if(shoppingcartList!=null && shoppingcartList.size()>0)
return shoppingcartList.get(0);
else
{
//if no shopping cart , create a new one
return createNewShoppingCart(context,itemId,context.getCurrentUser().getID(),"",ShoppingCart.CURRENCY_US,ShoppingCart.STATUS_OPEN);
}
}
public Double calculateShoppingCartTotal(Context context,ShoppingCart shoppingcart,String journal) throws SQLException{
log.debug("recalculating shopping cart total");
Double price = new Double(0);
if(hasDiscount(context,shoppingcart,journal))
{
//has discount , only caculate the file surcharge fee
price =getSurchargeLargeFileFee(context, shoppingcart);
}
else
{
//no journal,voucher,country discount
Double basicFee = shoppingcart.getBasicFee();
double fileSizeFee=getSurchargeLargeFileFee(context, shoppingcart);
price = basicFee+fileSizeFee;
price = price+getNoIntegrateFee(context,shoppingcart,journal);
}
return price;
}
public double getSurchargeLargeFileFee(Context context, ShoppingCart shoppingcart) throws SQLException {
Item item =Item.find(context, shoppingcart.getItem());
Item[] dataFiles = DryadWorkflowUtils.getDataFiles(context, item);
Long allowedSizeT=PaymentSystemConfigurationManager.getMaxFileSize();
long allowedSize = allowedSizeT;
String currency = shoppingcart.getCurrency();
double fileSizeFeeAfter = PaymentSystemConfigurationManager.getAllSizeFileFeeAfterProperty(currency);
double totalSurcharge=0;
long totalSizeDataFile=0;
for(Item dataFile : dataFiles){
Bundle bundles[] = dataFile.getBundles();
for(Bundle bundle:bundles)
{
Bitstream bitstreams[]=bundle.getBitstreams();
for(Bitstream bitstream:bitstreams)
{
totalSizeDataFile=totalSizeDataFile+bitstream.getSize();
}
}
}
if(totalSizeDataFile > allowedSize){
totalSurcharge+=shoppingcart.getSurcharge();
int unit =0;
Long UNITSIZE=PaymentSystemConfigurationManager.getUnitSize(); //1 GB
//eg. $10 after every 1 gb
if(UNITSIZE!=null&&UNITSIZE>0) {
Long overSize = (totalSizeDataFile-allowedSize)/UNITSIZE;
unit = overSize.intValue();
}
totalSurcharge = totalSurcharge+fileSizeFeeAfter*unit;
}
return totalSurcharge;
}
public boolean getJournalSubscription(Context context, ShoppingCart shoppingcart, String journal) throws SQLException {
if(!shoppingcart.getStatus().equals(ShoppingCart.STATUS_COMPLETED))
{
if(journal==null||journal.length()==0){
Item item = Item.find(context,shoppingcart.getItem()) ;
if(item!=null)
{
try{
//only take the first journal
DCValue[] values = item.getMetadata("prism.publicationName");
if(values!=null && values.length > 0){
journal=values[0].value;
}
}catch (Exception e)
{
log.error("Exception when get journal in journal subscription:", e);
}
}
}
//update the journal and journal subscribtion
updateJournal(shoppingcart,journal);
}
return shoppingcart.getJournalSub();
}
public double getNoIntegrateFee(Context context, ShoppingCart shoppingcart, String journal) throws SQLException {
Double totalPrice = new Double(0);
if(journal==null){
Item item = Item.find(context,shoppingcart.getItem()) ;
if(item!=null)
{
try{
DCValue[] values = item.getMetadata("prism.publicationName");
if(values!=null && values.length > 0){
journal=values[0].value;
}
}catch (Exception e)
{
log.error("Exception when get journal name in geting no integration fee:", e);
}
}
}
if(journal!=null)
{
try{
DryadJournalSubmissionUtils util = new DryadJournalSubmissionUtils();
Map<String, String> properties = util.journalProperties.get(journal);
if(properties!=null){
String subscription = properties.get("integrated");
if(subscription==null || !subscription.equals(ShoppingCart.FREE))
{
totalPrice= shoppingcart.getNoInteg();
}
}
else
{
totalPrice= shoppingcart.getNoInteg();
}
}catch(Exception e){
log.error("Exception when get no integration fee:", e);
}
}
else
{
totalPrice= shoppingcart.getNoInteg();
}
return totalPrice;
}
private boolean voucherValidate(Context context,ShoppingCart shoppingcart){
VoucherValidationService voucherValidationService = new DSpace().getSingletonService(VoucherValidationService.class);
return voucherValidationService.validate(context,shoppingcart.getVoucher(),shoppingcart);
}
public boolean hasDiscount(Context context,ShoppingCart shoppingcart,String journal)throws SQLException{
//this method check all the discount: journal,country,voucher
Boolean journalSubscription = getJournalSubscription(context, shoppingcart, journal);
Boolean countryDiscount = getCountryWaiver(context,shoppingcart,journal);
Boolean voucherDiscount = voucherValidate(context,shoppingcart);
if(journalSubscription||countryDiscount||voucherDiscount){
log.debug("subscription has been paid by journal/country/voucher");
return true;
}
log.debug("submitter is responsible for payment");
return false;
}
public int getWaiver(Context context,ShoppingCart shoppingcart,String journal)throws SQLException{
//this method check all the discount: journal,country,voucher
Boolean journalSubscription = getJournalSubscription(context, shoppingcart, journal);
Boolean countryDiscount = getCountryWaiver(context,shoppingcart,journal);
Boolean voucherDiscount = voucherValidate(context,shoppingcart);
if(countryDiscount){
return ShoppingCart.COUNTRY_WAIVER;
}
else if(journalSubscription){
return ShoppingCart.JOUR_WAIVER;
}else if(voucherDiscount){
return ShoppingCart.VOUCHER_WAIVER;
}
return ShoppingCart.NO_WAIVER;
}
public boolean getCountryWaiver(Context context, ShoppingCart shoppingCart, String journal) throws SQLException{
PaymentSystemConfigurationManager manager = new PaymentSystemConfigurationManager();
Properties countryArray = manager.getAllCountryProperty();
if(shoppingCart.getCountry() != null && shoppingCart.getCountry().length()>0)
{
return countryArray.get(shoppingCart.getCountry()).equals(ShoppingCart.COUNTRYFREE);
}
else {
return false;
}
}
public void updateTotal(Context context, ShoppingCart shoppingCart, String journal) throws SQLException{
if(!shoppingCart.getStatus().equals(ShoppingCart.STATUS_COMPLETED)) {
Double newPrice = calculateShoppingCartTotal(context,shoppingCart,journal);
//TODO:only setup the price when the old total price is higher than the price right now
shoppingCart.setTotal(newPrice);
shoppingCart.update();
shoppingCart.setModified(false);
}
}
public String getPayer(Context context,ShoppingCart shoppingcart,String journal)throws SQLException{
String payerName = "";
EPerson e = EPerson.find(context,shoppingcart.getDepositor());
switch (getWaiver(context,shoppingcart,""))
{
case ShoppingCart.COUNTRY_WAIVER:payerName= "Country";break;
case ShoppingCart.JOUR_WAIVER: payerName = "Journal"; break;
case ShoppingCart.VOUCHER_WAIVER: payerName = "Voucher"; break;
case ShoppingCart.NO_WAIVER:payerName = e.getFullName();break;
}
return payerName;
}
private void updateJournal(ShoppingCart shoppingCart,String journal){
if(!shoppingCart.getStatus().equals(ShoppingCart.STATUS_COMPLETED))
{
if(journal!=null&&journal.length()>0) {
//update shoppingcart journal
Map<String, String> properties = DryadJournalSubmissionUtils.journalProperties.get(journal);
Boolean subscription = false;
if(properties!=null){
if(StringUtils.equals(properties.get("subscriptionPaid"), ShoppingCart.FREE))
{
subscription = true;
}
}
shoppingCart.setJournal(journal);
shoppingCart.setJournalSub(subscription);
}
}
}
private String format(String label, String value){
return label + ": " + value + "\n";
}
public String printShoppingCart(Context c, ShoppingCart shoppingCart){
String result = "";
try{
result += format("Payer", getPayer(c, shoppingCart, null));
String symbol = PaymentSystemConfigurationManager.getCurrencySymbol(shoppingCart.getCurrency());
if(hasDiscount(c,shoppingCart,null))
{
result += format("Price",symbol+"0.0");
}
else
{
result += format("Price",symbol+Double.toString(shoppingCart.getBasicFee()));
}
Double noIntegrateFee = getNoIntegrateFee(c,shoppingCart,null);
//add the no integrate fee if it is not 0
if(!hasDiscount(c,shoppingCart,null)&&noIntegrateFee>0&&!hasDiscount(c,shoppingCart,null))
{
result += format("Non-integrated submission", "" + noIntegrateFee);
}
else
{
result += format("Non-integrated submission", symbol+"0.0");
}
//add the large file surcharge section
format("Excess data storage", symbol+Double.toString(getSurchargeLargeFileFee(c,shoppingCart)));
try
{
Voucher v = Voucher.findById(c, shoppingCart.getVoucher());
if(v != null)
{
result += format("Voucher Applied", v.getCode());
}
}catch (Exception e)
{
log.error(e.getMessage(),e);
}
//add the final total price
result += format("Total", symbol+Double.toString(shoppingCart.getTotal()));
switch (getWaiver(c,shoppingCart,""))
{
case ShoppingCart.COUNTRY_WAIVER: format("Waiver Details", "Data Publishing Charge has been waived due to submitter's association with " + shoppingCart.getCountry() + ".");break;
case ShoppingCart.JOUR_WAIVER: format("Waiver Details", "Data Publishing Charges are covered for all submissions to " + shoppingCart.getJournal() + "."); break;
case ShoppingCart.VOUCHER_WAIVER: format("Waiver Details", "Voucher code applied to Data Publishing Charge."); break;
}
if(shoppingCart.getTransactionId() != null && "".equals(shoppingCart.getTransactionId().trim()))
{
format("Transaction ID", shoppingCart.getTransactionId());
}
}catch (Exception e)
{
result += format("Error", e.getMessage());
log.error(e.getMessage(),e);
}
return result;
}
public void generateShoppingCart(Context context,org.dspace.app.xmlui.wing.element.List info,ShoppingCart shoppingCart,PaymentSystemConfigurationManager manager,String baseUrl,Map<String,String> messages) throws WingException,SQLException
{
Item item = Item.find(context,shoppingCart.getItem());
Long totalSize = new Long(0);
String symbol = PaymentSystemConfigurationManager.getCurrencySymbol(shoppingCart.getCurrency());
org.dspace.app.xmlui.wing.element.List hiddenList = info.addList("transaction");
hiddenList.addItem().addHidden("transactionId").setValue(Integer.toString(shoppingCart.getID()));
hiddenList.addItem().addHidden("baseUrl").setValue(baseUrl);
try{
//add selected currency section
generateCurrencyList(info,manager,shoppingCart);
generatePayer(context,info,shoppingCart,item);
generatePrice(context,info,manager,shoppingCart);
generateCountryList(info,manager,shoppingCart,item);
generateVoucherForm(context,info,manager,shoppingCart,messages);
}catch (Exception e)
{
info.addLabel("Errors when generate the shopping cart form:"+e.getMessage());
}
}
public void generateNoEditableShoppingCart(Context context, org.dspace.app.xmlui.wing.element.List info, ShoppingCart transaction, PaymentSystemConfigurationManager manager, String baseUrl, Map<String, String> messages) throws WingException, SQLException
{
Item item = Item.find(context, transaction.getItem());
Long totalSize = new Long(0);
String symbol = PaymentSystemConfigurationManager.getCurrencySymbol(transaction.getCurrency());
org.dspace.app.xmlui.wing.element.List hiddenList = info.addList("transaction");
hiddenList.addItem().addHidden("transactionId").setValue(Integer.toString(transaction.getID()));
hiddenList.addItem().addHidden("baseUrl").setValue(baseUrl);
try {
//add selected currency section
info.addLabel(T_Header);
info.addItem().addContent(transaction.getCurrency());
generatePayer(context, info, transaction, item);
generatePrice(context, info, manager, transaction);
info.addItem().addContent(transaction.getCountry());
generateNoEditableVoucherForm(context, info, transaction, messages);
} catch (Exception e)
{
info.addLabel("Errors when generate the shopping cart form");
}
}
private void generateNoEditableVoucherForm(Context context, org.dspace.app.xmlui.wing.element.List info, ShoppingCart shoppingCart, Map<String, String> messages) throws WingException, SQLException {
Voucher voucher1 = Voucher.findById(context, shoppingCart.getVoucher());
if (messages.get("voucher") != null)
{
info.addItem("errorMessage", "errorMessage").addContent(messages.get("voucher"));
} else
{
info.addItem("errorMessage", "errorMessage").addContent("");
}
info.addLabel(T_Voucher);
info.addItem().addContent(voucher1.getCode());
}
private void generateCountryList(org.dspace.app.xmlui.wing.element.List info,PaymentSystemConfigurationManager manager,ShoppingCart shoppingCart,Item item) throws WingException{
//only generate country selection list when it is not on the publication select page, to do this we need to check the publication is not empty
java.util.List<String> countryArray = manager.getSortedCountry();
Select countryList = info.addItem("country-list", "select-list").addSelect("country");
countryList.setLabel(T_Country);
countryList.setHelp(Country_Help_Text);
countryList.addOption("","Select Your Country");
for(String temp:countryArray){
String[] countryTemp = temp.split(":");
if(shoppingCart.getCountry()!=null&&shoppingCart.getCountry().length()>0&&shoppingCart.getCountry().equals(countryTemp[0])) {
countryList.addOption(true,countryTemp[0],countryTemp[0]);
}
else
{
countryList.addOption(false,countryTemp[0],countryTemp[0]);
}
}
if(shoppingCart.getCountry().length()>0)
{
info.addItem("remove-country","remove-country").addXref("#","Remove Country : "+shoppingCart.getCountry());
}
else
{
info.addItem("remove-country","remove-country").addXref("#","");
}
}
private void generateSurchargeFeeForm(Context context,org.dspace.app.xmlui.wing.element.List info,PaymentSystemConfigurationManager manager,ShoppingCart shoppingCart) throws WingException,SQLException{
//add the large file surcharge section
String symbol = PaymentSystemConfigurationManager.getCurrencySymbol(shoppingCart.getCurrency());
info.addLabel(T_Surcharge);
info.addItem("surcharge","surcharge").addContent(String.format("%s%.0f", symbol, this.getSurchargeLargeFileFee(context,shoppingCart)));
}
private void generateCurrencyList(org.dspace.app.xmlui.wing.element.List info,PaymentSystemConfigurationManager manager,ShoppingCart shoppingCart) throws WingException,SQLException{
org.dspace.app.xmlui.wing.element.Item currency = info.addItem("currency-list", "select-list");
Select currencyList = currency.addSelect("currency");
currencyList.setLabel(T_Header);
//currencyList.setHelp(Currency_Help_Text);
Properties currencyArray = manager.getAllCurrencyProperty();
for(String currencyTemp: currencyArray.stringPropertyNames())
{
if(shoppingCart.getCurrency().equals(currencyTemp))
{
currencyList.addOption(true, currencyTemp, currencyTemp);
}
else
{
currencyList.addOption(false, currencyTemp, currencyTemp);
}
}
}
private void generateVoucherForm(Context context,org.dspace.app.xmlui.wing.element.List info,PaymentSystemConfigurationManager manager,ShoppingCart shoppingCart,Map<String,String> messages) throws WingException,SQLException{
Voucher voucher1 = Voucher.findById(context,shoppingCart.getVoucher());
if(messages.get("voucher")!=null)
{
info.addItem("errorMessage","errorMessage").addContent(messages.get("voucher"));
}
else
{
info.addItem("errorMessage","errorMessage").addContent("");
}
org.dspace.app.xmlui.wing.element.Item voucher = info.addItem("voucher-list","voucher-list");
Text voucherText = voucher.addText("voucher","voucher");
voucherText.setLabel(T_Voucher);
voucherText.setHelp(Voucher_Help_Text);
voucher.addButton("apply","apply");
if(voucher1!=null){
voucherText.setValue(voucher1.getCode());
info.addItem("remove-voucher","remove-voucher").addXref("#", "Remove Voucher : " + voucher1.getCode(), "remove-voucher", "remove-voucher");
}
else{
info.addItem("remove-voucher","remove-voucher").addXref("#", "", "remove-voucher", "remove-voucher");
}
}
private void generatePrice(Context context,org.dspace.app.xmlui.wing.element.List info,PaymentSystemConfigurationManager manager,ShoppingCart shoppingCart) throws WingException,SQLException{
String waiverMessage = "";
String symbol = PaymentSystemConfigurationManager.getCurrencySymbol(shoppingCart.getCurrency());
switch (this.getWaiver(context,shoppingCart,""))
{
case ShoppingCart.COUNTRY_WAIVER: waiverMessage = "Data Publishing Charge has been waived due to submitter's association with " + shoppingCart.getCountry() + "."; break;
case ShoppingCart.JOUR_WAIVER: waiverMessage = "Data Publishing Charges are covered for all submissions to " + shoppingCart.getJournal() + "."; break;
case ShoppingCart.VOUCHER_WAIVER: waiverMessage = "Voucher code applied to Data Publishing Charge."; break;
}
info.addLabel(T_Price);
if(this.hasDiscount(context,shoppingCart,null))
{
info.addItem("price","price").addContent(symbol+"0");
}
else
{
info.addItem("price","price").addContent(String.format("%s%.0f", symbol, shoppingCart.getBasicFee()));
}
Double noIntegrateFee = this.getNoIntegrateFee(context,shoppingCart,null);
//add the no integrate fee if it is not 0
info.addLabel(T_noInteg);
if(!this.hasDiscount(context,shoppingCart,null)&&noIntegrateFee>0&&!this.hasDiscount(context,shoppingCart,null))
{
info.addItem("no-integret","no-integret").addContent(String.format("%s%.0f", symbol, noIntegrateFee));
}
else
{
info.addItem("no-integret","no-integret").addContent(symbol+"0");
}
generateSurchargeFeeForm(context,info,manager,shoppingCart);
//add the final total price
info.addLabel(T_Total);
info.addItem("total","total").addContent(String.format("%s%.0f",symbol, shoppingCart.getTotal()));
info.addItem("waiver-info","waiver-info").addContent(waiverMessage);
}
private void generatePayer(Context context,org.dspace.app.xmlui.wing.element.List info,ShoppingCart shoppingCart,Item item) throws WingException,SQLException{
info.addLabel(T_Payer);
String payerName = this.getPayer(context, shoppingCart, null);
DCValue[] values= item.getMetadata("prism.publicationName");
if(values!=null&&values.length>0)
{
//on the first page don't generate the payer name, wait until user choose country or journal
info.addItem("payer","payer").addContent(payerName);
}
else
{
info.addItem("payer","payer").addContent("");
}
}
}
| Refactor large file surcharge for testability
| dspace/modules/payment-system/payment-api/src/main/java/org/dspace/paymentsystem/PaymentSystemImpl.java | Refactor large file surcharge for testability | <ide><path>space/modules/payment-system/payment-api/src/main/java/org/dspace/paymentsystem/PaymentSystemImpl.java
<ide> return price;
<ide> }
<ide>
<del> public double getSurchargeLargeFileFee(Context context, ShoppingCart shoppingcart) throws SQLException {
<del> Item item =Item.find(context, shoppingcart.getItem());
<del> Item[] dataFiles = DryadWorkflowUtils.getDataFiles(context, item);
<del> Long allowedSizeT=PaymentSystemConfigurationManager.getMaxFileSize();
<del> long allowedSize = allowedSizeT;
<del> String currency = shoppingcart.getCurrency();
<del> double fileSizeFeeAfter = PaymentSystemConfigurationManager.getAllSizeFileFeeAfterProperty(currency);
<del>
<del> double totalSurcharge=0;
<del> long totalSizeDataFile=0;
<add> /**
<add> * Calculate the surcharge for a data package, based on its size in bytes
<add> * @param allowedSize the maximum size allowed before large file surcharge
<add> * @param totalDataFileSize the total size of data files in bytes
<add> * @param fileSizeFeeAfter the fee per unit to assess after exceeding allowedSize
<add> * @param initialSurcharge Initial surcharge, e.g. 15 for the first 1GB exceeding 10GB.
<add> * @param surchargeUnitSize amount of data to assess a fileSizeFeeAfter on, e.g. 1GB = 1*1024*1024
<add> * @return The total surcharge to assess.
<add> */
<add> public static double calculateFileSizeSurcharge(
<add> long allowedSize,
<add> long totalDataFileSize,
<add> double fileSizeFeeAfter,
<add> double initialSurcharge,
<add> long surchargeUnitSize) {
<add> double totalSurcharge = initialSurcharge;
<add> if(totalDataFileSize > allowedSize){
<add> int unit =0;
<add> //eg. $10 after every 1 gb
<add> if(surchargeUnitSize > 0) {
<add> Long overSize = (totalDataFileSize - allowedSize) / surchargeUnitSize;
<add> unit = overSize.intValue();
<add> }
<add> totalSurcharge = totalSurcharge+fileSizeFeeAfter*unit;
<add> }
<add> return totalSurcharge;
<add> }
<add>
<add> /**
<add> * Get the total size in bytes of all bitstreams within a data package.
<add> * Assumes item is a data package and DryadWorkFlowUtils.getDataFiles returns
<add> * data file items with bundles, bitstreams.
<add> * @param context
<add> * @param dataPackage
<add> * @return
<add> * @throws SQLException
<add> */
<add> public long getTotalDataFileSize(Context context, Item dataPackage) throws SQLException {
<add> Item[] dataFiles = DryadWorkflowUtils.getDataFiles(context, dataPackage);
<add> long size = 0;
<ide> for(Item dataFile : dataFiles){
<del>
<ide> Bundle bundles[] = dataFile.getBundles();
<ide> for(Bundle bundle:bundles)
<ide> {
<ide> Bitstream bitstreams[]=bundle.getBitstreams();
<ide> for(Bitstream bitstream:bitstreams)
<ide> {
<del> totalSizeDataFile=totalSizeDataFile+bitstream.getSize();
<add> size += bitstream.getSize();
<ide> }
<ide> }
<del>
<del> }
<del>
<del> if(totalSizeDataFile > allowedSize){
<del> totalSurcharge+=shoppingcart.getSurcharge();
<del> int unit =0;
<del> Long UNITSIZE=PaymentSystemConfigurationManager.getUnitSize(); //1 GB
<del> //eg. $10 after every 1 gb
<del> if(UNITSIZE!=null&&UNITSIZE>0) {
<del> Long overSize = (totalSizeDataFile-allowedSize)/UNITSIZE;
<del> unit = overSize.intValue();
<del> }
<del> totalSurcharge = totalSurcharge+fileSizeFeeAfter*unit;
<del>
<del> }
<del>
<del>
<add> }
<add> return size;
<add> }
<add>
<add> public double getSurchargeLargeFileFee(Context context, ShoppingCart shoppingcart) throws SQLException {
<add> // Extract values from database objects and configuration to pass to calculator
<add> String currency = shoppingcart.getCurrency();
<add>
<add> long allowedSize = PaymentSystemConfigurationManager.getMaxFileSize().longValue();
<add> double fileSizeFeeAfter = PaymentSystemConfigurationManager.getAllSizeFileFeeAfterProperty(currency);
<add> Long unitSize = PaymentSystemConfigurationManager.getUnitSize(); //1 GB
<add>
<add> Item item = Item.find(context, shoppingcart.getItem());
<add> long totalSizeDataFile = getTotalDataFileSize(context, item);
<add> double totalSurcharge = calculateFileSizeSurcharge(allowedSize, totalSizeDataFile, fileSizeFeeAfter, shoppingcart.getSurcharge(), unitSize);
<ide> return totalSurcharge;
<ide> }
<ide> |
|
Java | apache-2.0 | d9ff1132d307760b8e34abc13b4e10a55d8bb62e | 0 | liqianggao/BroadleafCommerce,liqianggao/BroadleafCommerce,cengizhanozcan/BroadleafCommerce,udayinfy/BroadleafCommerce,macielbombonato/BroadleafCommerce,shopizer/BroadleafCommerce,bijukunjummen/BroadleafCommerce,wenmangbo/BroadleafCommerce,alextiannus/BroadleafCommerce,cloudbearings/BroadleafCommerce,daniellavoie/BroadleafCommerce,wenmangbo/BroadleafCommerce,caosg/BroadleafCommerce,TouK/BroadleafCommerce,gengzhengtao/BroadleafCommerce,trombka/blc-tmp,macielbombonato/BroadleafCommerce,cogitoboy/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,zhaorui1/BroadleafCommerce,wenmangbo/BroadleafCommerce,bijukunjummen/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,cengizhanozcan/BroadleafCommerce,arshadalisoomro/BroadleafCommerce,liqianggao/BroadleafCommerce,rawbenny/BroadleafCommerce,lgscofield/BroadleafCommerce,passion1014/metaworks_framework,zhaorui1/BroadleafCommerce,cogitoboy/BroadleafCommerce,trombka/blc-tmp,bijukunjummen/BroadleafCommerce,TouK/BroadleafCommerce,caosg/BroadleafCommerce,passion1014/metaworks_framework,jiman94/BroadleafCommerce-BroadleafCommerce2014,arshadalisoomro/BroadleafCommerce,lgscofield/BroadleafCommerce,ljshj/BroadleafCommerce,udayinfy/BroadleafCommerce,macielbombonato/BroadleafCommerce,shopizer/BroadleafCommerce,trombka/blc-tmp,arshadalisoomro/BroadleafCommerce,lgscofield/BroadleafCommerce,sitexa/BroadleafCommerce,sitexa/BroadleafCommerce,cogitoboy/BroadleafCommerce,caosg/BroadleafCommerce,daniellavoie/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,TouK/BroadleafCommerce,gengzhengtao/BroadleafCommerce,ljshj/BroadleafCommerce,shopizer/BroadleafCommerce,cloudbearings/BroadleafCommerce,cloudbearings/BroadleafCommerce,sanlingdd/broadleaf,alextiannus/BroadleafCommerce,sitexa/BroadleafCommerce,sanlingdd/broadleaf,gengzhengtao/BroadleafCommerce,alextiannus/BroadleafCommerce,daniellavoie/BroadleafCommerce,zhaorui1/BroadleafCommerce,ljshj/BroadleafCommerce,jiman94/BroadleafCommerce-BroadleafCommerce2014,udayinfy/BroadleafCommerce,cengizhanozcan/BroadleafCommerce,passion1014/metaworks_framework,rawbenny/BroadleafCommerce,rawbenny/BroadleafCommerce | /*
* Copyright 2008-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.broadleafcommerce.openadmin.server.dao;
import org.broadleafcommerce.common.persistence.IdOverrideTableGenerator;
import org.broadleafcommerce.openadmin.server.service.DynamicEntityRemoteService;
import org.hibernate.SessionFactory;
import org.hibernate.SessionFactoryObserver;
import java.lang.reflect.Field;
import java.util.Map;
/**
* Clear the static entity metadata caches from {@code DynamicEntityDao}
* upon recycling of the session factory.
*
* @author jfischer
*/
public class SessionFactoryChangeListener implements SessionFactoryObserver {
@Override
public void sessionFactoryClosed(SessionFactory factory) {
//do nothing
}
@Override
public void sessionFactoryCreated(SessionFactory factory) {
synchronized (DynamicEntityDaoImpl.LOCK_OBJECT) {
DynamicEntityDaoImpl.METADATA_CACHE.clear();
DynamicEntityDaoImpl.POLYMORPHIC_ENTITY_CACHE.clear();
try {
Field metadataCache = DynamicEntityRemoteService.class.getDeclaredField("METADATA_CACHE");
metadataCache.setAccessible(true);
((Map) metadataCache.get(null)).clear();
} catch (Throwable e) {
throw new RuntimeException(e);
}
try {
Field fieldCache = IdOverrideTableGenerator.class.getDeclaredField("FIELD_CACHE");
fieldCache.setAccessible(true);
((Map) fieldCache.get(null)).clear();
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
}
}
| admin/broadleaf-open-admin-platform/src/main/java/org/broadleafcommerce/openadmin/server/dao/SessionFactoryChangeListener.java | /*
* Copyright 2008-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.broadleafcommerce.openadmin.server.dao;
import org.broadleafcommerce.openadmin.server.service.DynamicEntityRemoteService;
import org.hibernate.SessionFactory;
import org.hibernate.SessionFactoryObserver;
import java.lang.reflect.Field;
import java.util.Map;
/**
* Clear the static entity metadata caches from {@code DynamicEntityDao}
* upon recycling of the session factory.
*
* @author jfischer
*/
public class SessionFactoryChangeListener implements SessionFactoryObserver {
@Override
public void sessionFactoryClosed(SessionFactory factory) {
//do nothing
}
@Override
public void sessionFactoryCreated(SessionFactory factory) {
synchronized (DynamicEntityDaoImpl.LOCK_OBJECT) {
DynamicEntityDaoImpl.METADATA_CACHE.clear();
DynamicEntityDaoImpl.POLYMORPHIC_ENTITY_CACHE.clear();
try {
Field metadataCache = DynamicEntityRemoteService.class.getDeclaredField("METADATA_CACHE");
metadataCache.setAccessible(true);
((Map) metadataCache.get(null)).clear();
} catch (Throwable e) {
throw new RuntimeException(e);
}
}
}
}
| BLC-694 - org.springframework.orm.hibernate3.HibernateSystemException: Don't change the reference to a collection with cascade="all-delete-orphan" can sometime occur when merging an entity
| admin/broadleaf-open-admin-platform/src/main/java/org/broadleafcommerce/openadmin/server/dao/SessionFactoryChangeListener.java | BLC-694 - org.springframework.orm.hibernate3.HibernateSystemException: Don't change the reference to a collection with cascade="all-delete-orphan" can sometime occur when merging an entity | <ide><path>dmin/broadleaf-open-admin-platform/src/main/java/org/broadleafcommerce/openadmin/server/dao/SessionFactoryChangeListener.java
<ide>
<ide> package org.broadleafcommerce.openadmin.server.dao;
<ide>
<add>import org.broadleafcommerce.common.persistence.IdOverrideTableGenerator;
<ide> import org.broadleafcommerce.openadmin.server.service.DynamicEntityRemoteService;
<ide> import org.hibernate.SessionFactory;
<ide> import org.hibernate.SessionFactoryObserver;
<ide> } catch (Throwable e) {
<ide> throw new RuntimeException(e);
<ide> }
<add> try {
<add> Field fieldCache = IdOverrideTableGenerator.class.getDeclaredField("FIELD_CACHE");
<add> fieldCache.setAccessible(true);
<add> ((Map) fieldCache.get(null)).clear();
<add> } catch (Throwable e) {
<add> throw new RuntimeException(e);
<add> }
<ide> }
<ide> }
<ide> |
|
Java | agpl-3.0 | dc7cb22845cd3960703f79ea8477820a90a68683 | 0 | bio4j/bio4j | /*
# NCBI Taxonomy graph
This graph includes the whole NCBI taxonomy tree.
Files used in the importing process can be found [here](ftp://ftp.ncbi.nih.gov/pub/taxonomy/taxdump.tar.gz)
Once that information is extracted we are building the tree from the information included in the following files:
* **nodes.dmp**
* **names.dmp**
## data model
It simply consists of the vertices of NCBITaxon type plus the hierarchical relationships represented as NCBITaxonParent edges.
### NCBITaxons
We have a `NCBITaxon` vertex which contains property data present for each NCBI taxonomic unit.
##### NCBITaxon properties stored
- id
- name
- comment
- scientific name
- taxonomic rank
*/
package com.bio4j.model.ncbiTaxonomy;
import com.bio4j.angulillos.*;
import com.bio4j.angulillos.Arity.*;
public final class NCBITaxonomyGraph<V,E> extends TypedGraph<NCBITaxonomyGraph<V,E>,V,E> {
public NCBITaxonomyGraph(UntypedGraph<V,E> graph) { super(graph); }
@Override
public final NCBITaxonomyGraph<V,E> self() { return this; }
}
//
//
// public abstract class NCBITaxonomyGraph<
// // untyped graph
// I extends UntypedGraph<RV, RVT, RE, RET>,
// // vertices
// RV, RVT,
// // edges
// RE, RET
// >
// implements
// TypedGraph<
// NCBITaxonomyGraph<I, RV, RVT, RE, RET>,
// I, RV, RVT, RE, RET
// > {
//
// protected I raw = null;
//
// public NCBITaxonomyGraph(I graph){
// raw = graph;
// }
//
// public I raw(){
// return raw;
// }
//
// // indices
// public abstract TypedVertexIndex.Unique <
// // vertex
// NCBITaxon<I, RV, RVT, RE, RET>, NCBITaxonType,
// // property
// NCBITaxonType.id, String,
// // graph
// NCBITaxonomyGraph<I, RV, RVT, RE, RET>,
// I, RV, RVT, RE, RET
// >
// nCBITaxonIdIndex();
//
// // types
// // vertices
// public abstract NCBITaxonType NCBITaxon();
// // edges
// public abstract NCBITaxonParentType NCBITaxonParent();
//
// //////////////////////////////////////////////////////////////////////////////////////////////////////////
// // Vertex types
//
// public final class NCBITaxonType
// extends
// NCBITaxonomyVertexType<
// NCBITaxon<I, RV, RVT, RE, RET>,
// NCBITaxonomyGraph<I, RV, RVT, RE, RET>.NCBITaxonType
// >
// {
//
// public final id id = new id();
// public final name name = new name();
// public final taxonomicRank taxonomicRank = new taxonomicRank();
//
// public NCBITaxonType(RVT raw) {
// super(raw);
// }
//
// @Override
// public final NCBITaxonType value() {
// return graph().NCBITaxon();
// }
//
// @Override
// public final NCBITaxon<I, RV, RVT, RE, RET> from(RV vertex) {
// return new NCBITaxon<I, RV, RVT, RE, RET>(vertex, this);
// }
//
// public final class id
// extends
// NCBITaxonomyVertexProperty<NCBITaxon<I, RV, RVT, RE, RET>, NCBITaxonType, id, String> {
//
// public id() {
// super(NCBITaxonType.this);
// }
//
// public Class<String> valueClass() {
// return String.class;
// }
// }
//
// public final class name
// extends
// NCBITaxonomyVertexProperty<NCBITaxon<I, RV, RVT, RE, RET>, NCBITaxonType, name, String> {
//
// public name() {
// super(NCBITaxonType.this);
// }
//
// public Class<String> valueClass() {
// return String.class;
// }
// }
//
// public final class taxonomicRank
// extends
// NCBITaxonomyVertexProperty<NCBITaxon<I, RV, RVT, RE, RET>, NCBITaxonType, taxonomicRank, String> {
//
// public taxonomicRank() {
// super(NCBITaxonType.this);
// }
//
// public Class<String> valueClass() {
// return String.class;
// }
// }
// }
//
// //////////////////////////////////////////////////////////////////////////////////////////////////////////
// // Edge types
//
// public final class NCBITaxonParentType
// extends
// NCBITaxonomyEdgeType<
// NCBITaxon<I, RV, RVT, RE, RET>, NCBITaxonomyGraph<I, RV, RVT, RE, RET>.NCBITaxonType,
// NCBITaxonParent<I, RV, RVT, RE, RET>, NCBITaxonomyGraph<I, RV, RVT, RE, RET>.NCBITaxonParentType,
// NCBITaxon<I, RV, RVT, RE, RET>, NCBITaxonomyGraph<I, RV, RVT, RE, RET>.NCBITaxonType
// >
// implements
// TypedEdge.Type.OneToMany {
//
// public NCBITaxonParentType(RET raw) {
// super(NCBITaxonomyGraph.this.NCBITaxon(), raw, NCBITaxonomyGraph.this.NCBITaxon());
// }
//
// @Override
// public final NCBITaxonParentType value() {
// return graph().NCBITaxonParent();
// }
//
// @Override
// public final NCBITaxonParent<I, RV, RVT, RE, RET> from(RE edge) {
// return new NCBITaxonParent<I, RV, RVT, RE, RET>(edge, this);
// }
// }
//
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
// // helper classes
//
// public abstract class NCBITaxonomyVertexProperty<
// V extends NCBITaxonomyVertex<V, VT, I, RV, RVT, RE, RET>,
// VT extends NCBITaxonomyGraph<I, RV, RVT, RE, RET>.NCBITaxonomyVertexType<V, VT>,
// P extends NCBITaxonomyVertexProperty<V, VT, P, PV>,
// PV
// >
// implements
// Property<V, VT, P, PV, NCBITaxonomyGraph<I, RV, RVT, RE, RET>, I, RV, RVT, RE, RET> {
//
// protected NCBITaxonomyVertexProperty(VT type) {
//
// this.type = type;
// }
//
// private VT type;
//
// @Override
// public final VT elementType() {
// return type;
// }
// }
//
// public abstract static class NCBITaxonomyVertex<
// V extends NCBITaxonomyVertex<V, VT, I, RV, RVT, RE, RET>,
// VT extends NCBITaxonomyGraph<I, RV, RVT, RE, RET>.NCBITaxonomyVertexType<V, VT>,
// I extends UntypedGraph<RV, RVT, RE, RET>, RV, RVT, RE, RET
// >
// implements
// TypedVertex<V, VT, NCBITaxonomyGraph<I, RV, RVT, RE, RET>, I, RV, RVT, RE, RET> {
//
// private RV vertex;
// private VT type;
//
// protected NCBITaxonomyVertex(RV vertex, VT type) {
//
// this.vertex = vertex;
// this.type = type;
// }
//
// @Override
// public final NCBITaxonomyGraph<I, RV, RVT, RE, RET> graph() {
// return type().graph();
// }
//
// @Override
// public final RV raw() {
// return this.vertex;
// }
//
// @Override
// public final VT type() {
// return type;
// }
// }
//
// abstract class NCBITaxonomyVertexType<
// V extends NCBITaxonomyVertex<V, VT, I, RV, RVT, RE, RET>,
// VT extends NCBITaxonomyGraph<I, RV, RVT, RE, RET>.NCBITaxonomyVertexType<V, VT>
// >
// implements
// TypedVertex.Type<V, VT, NCBITaxonomyGraph<I, RV, RVT, RE, RET>, I, RV, RVT, RE, RET> {
//
// private RVT raw;
//
// protected NCBITaxonomyVertexType(RVT raw) {
// this.raw = raw;
// }
//
// @Override
// public final RVT raw() {
// return raw;
// }
//
// @Override
// public final NCBITaxonomyGraph<I, RV, RVT, RE, RET> graph() {
// return NCBITaxonomyGraph.this;
// }
// }
//
// public abstract static class NCBITaxonomyEdge<
// S extends NCBITaxonomyVertex<S, ST, I, RV, RVT, RE, RET>,
// ST extends NCBITaxonomyGraph<I, RV, RVT, RE, RET>.NCBITaxonomyVertexType<S, ST>,
// E extends NCBITaxonomyEdge<S, ST, E, ET, T, TT, I, RV, RVT, RE, RET>,
// ET extends NCBITaxonomyGraph<I, RV, RVT, RE, RET>.NCBITaxonomyEdgeType<S, ST, E, ET, T, TT>,
// T extends NCBITaxonomyVertex<T, TT, I, RV, RVT, RE, RET>,
// TT extends NCBITaxonomyGraph<I, RV, RVT, RE, RET>.NCBITaxonomyVertexType<T, TT>,
// I extends UntypedGraph<RV, RVT, RE, RET>, RV, RVT, RE, RET
// >
// implements
// TypedEdge<
// S, ST, NCBITaxonomyGraph<I, RV, RVT, RE, RET>,
// E, ET, NCBITaxonomyGraph<I, RV, RVT, RE, RET>, I, RV, RVT, RE, RET,
// T, TT, NCBITaxonomyGraph<I, RV, RVT, RE, RET>
// >
// {
//
// private RE edge;
// private ET type;
//
// protected NCBITaxonomyEdge(RE edge, ET type) {
//
// this.edge = edge;
// this.type = type;
// }
//
// @Override
// public final NCBITaxonomyGraph<I, RV, RVT, RE, RET> graph() {
// return type().graph();
// }
//
// @Override
// public final RE raw() {
// return this.edge;
// }
//
// @Override
// public final ET type() {
// return type;
// }
// }
//
// abstract class NCBITaxonomyEdgeType<
// S extends NCBITaxonomyVertex<S, ST, I, RV, RVT, RE, RET>,
// ST extends NCBITaxonomyGraph<I, RV, RVT, RE, RET>.NCBITaxonomyVertexType<S, ST>,
// E extends NCBITaxonomyEdge<S, ST, E, ET, T, TT, I, RV, RVT, RE, RET>,
// ET extends NCBITaxonomyGraph<I, RV, RVT, RE, RET>.NCBITaxonomyEdgeType<S, ST, E, ET, T, TT>,
// T extends NCBITaxonomyVertex<T, TT, I, RV, RVT, RE, RET>,
// TT extends NCBITaxonomyGraph<I, RV, RVT, RE, RET>.NCBITaxonomyVertexType<T, TT>
// >
// implements
// TypedEdge.Type<
// S, ST, NCBITaxonomyGraph<I, RV, RVT, RE, RET>,
// E, ET, NCBITaxonomyGraph<I, RV, RVT, RE, RET>, I, RV, RVT, RE, RET,
// T, TT, NCBITaxonomyGraph<I, RV, RVT, RE, RET>
// >
// {
//
// private RET raw;
// private ST srcT;
// private TT tgtT;
//
// protected NCBITaxonomyEdgeType(ST srcT, RET raw, TT tgtT) {
//
// this.raw = raw;
// this.srcT = srcT;
// this.tgtT = tgtT;
// }
//
// @Override
// public final ST sourceType() {
// return srcT;
// }
//
// @Override
// public final TT targetType() {
// return tgtT;
// }
//
// @Override
// public final RET raw() {
// return raw;
// }
//
// @Override
// public final NCBITaxonomyGraph<I, RV, RVT, RE, RET> graph() {
// return NCBITaxonomyGraph.this;
// }
// }
// }
| src/main/java/com/bio4j/model/ncbiTaxonomy/NCBITaxonomyGraph.java | // package com.bio4j.model.ncbiTaxonomy;
//
// import com.bio4j.model.ncbiTaxonomy.vertices.*;
// import com.bio4j.model.ncbiTaxonomy.edges.*;
// import com.bio4j.angulillos.*;
//
// /*
//
// # NCBI Taxonomy graph
//
// This graph includes the whole NCBI taxonomy tree.
// Files used in the importing process can be found [here](ftp://ftp.ncbi.nih.gov/pub/taxonomy/taxdump.tar.gz)
//
// Once that information is extracted we are building the tree from the information included in the following files:
//
// * **nodes.dmp**
// * **names.dmp**
//
// ## data model
//
// It simply consists of the vertices of NCBITaxon type plus the hierarchical relationships represented as NCBITaxonParent edges.
//
// ### NCBITaxons
//
// We have a `NCBITaxon` vertex which contains property data present for each NCBI taxonomic unit.
//
// ##### NCBITaxon properties stored
//
// - id
// - name
// - comment
// - scientific name
// - taxonomic rank
//
// */
// public abstract class NCBITaxonomyGraph<
// // untyped graph
// I extends UntypedGraph<RV, RVT, RE, RET>,
// // vertices
// RV, RVT,
// // edges
// RE, RET
// >
// implements
// TypedGraph<
// NCBITaxonomyGraph<I, RV, RVT, RE, RET>,
// I, RV, RVT, RE, RET
// > {
//
// protected I raw = null;
//
// public NCBITaxonomyGraph(I graph){
// raw = graph;
// }
//
// public I raw(){
// return raw;
// }
//
// // indices
// public abstract TypedVertexIndex.Unique <
// // vertex
// NCBITaxon<I, RV, RVT, RE, RET>, NCBITaxonType,
// // property
// NCBITaxonType.id, String,
// // graph
// NCBITaxonomyGraph<I, RV, RVT, RE, RET>,
// I, RV, RVT, RE, RET
// >
// nCBITaxonIdIndex();
//
// // types
// // vertices
// public abstract NCBITaxonType NCBITaxon();
// // edges
// public abstract NCBITaxonParentType NCBITaxonParent();
//
// //////////////////////////////////////////////////////////////////////////////////////////////////////////
// // Vertex types
//
// public final class NCBITaxonType
// extends
// NCBITaxonomyVertexType<
// NCBITaxon<I, RV, RVT, RE, RET>,
// NCBITaxonomyGraph<I, RV, RVT, RE, RET>.NCBITaxonType
// >
// {
//
// public final id id = new id();
// public final name name = new name();
// public final taxonomicRank taxonomicRank = new taxonomicRank();
//
// public NCBITaxonType(RVT raw) {
// super(raw);
// }
//
// @Override
// public final NCBITaxonType value() {
// return graph().NCBITaxon();
// }
//
// @Override
// public final NCBITaxon<I, RV, RVT, RE, RET> from(RV vertex) {
// return new NCBITaxon<I, RV, RVT, RE, RET>(vertex, this);
// }
//
// public final class id
// extends
// NCBITaxonomyVertexProperty<NCBITaxon<I, RV, RVT, RE, RET>, NCBITaxonType, id, String> {
//
// public id() {
// super(NCBITaxonType.this);
// }
//
// public Class<String> valueClass() {
// return String.class;
// }
// }
//
// public final class name
// extends
// NCBITaxonomyVertexProperty<NCBITaxon<I, RV, RVT, RE, RET>, NCBITaxonType, name, String> {
//
// public name() {
// super(NCBITaxonType.this);
// }
//
// public Class<String> valueClass() {
// return String.class;
// }
// }
//
// public final class taxonomicRank
// extends
// NCBITaxonomyVertexProperty<NCBITaxon<I, RV, RVT, RE, RET>, NCBITaxonType, taxonomicRank, String> {
//
// public taxonomicRank() {
// super(NCBITaxonType.this);
// }
//
// public Class<String> valueClass() {
// return String.class;
// }
// }
// }
//
// //////////////////////////////////////////////////////////////////////////////////////////////////////////
// // Edge types
//
// public final class NCBITaxonParentType
// extends
// NCBITaxonomyEdgeType<
// NCBITaxon<I, RV, RVT, RE, RET>, NCBITaxonomyGraph<I, RV, RVT, RE, RET>.NCBITaxonType,
// NCBITaxonParent<I, RV, RVT, RE, RET>, NCBITaxonomyGraph<I, RV, RVT, RE, RET>.NCBITaxonParentType,
// NCBITaxon<I, RV, RVT, RE, RET>, NCBITaxonomyGraph<I, RV, RVT, RE, RET>.NCBITaxonType
// >
// implements
// TypedEdge.Type.OneToMany {
//
// public NCBITaxonParentType(RET raw) {
// super(NCBITaxonomyGraph.this.NCBITaxon(), raw, NCBITaxonomyGraph.this.NCBITaxon());
// }
//
// @Override
// public final NCBITaxonParentType value() {
// return graph().NCBITaxonParent();
// }
//
// @Override
// public final NCBITaxonParent<I, RV, RVT, RE, RET> from(RE edge) {
// return new NCBITaxonParent<I, RV, RVT, RE, RET>(edge, this);
// }
// }
//
// ////////////////////////////////////////////////////////////////////////////////////////////////////////
// // helper classes
//
// public abstract class NCBITaxonomyVertexProperty<
// V extends NCBITaxonomyVertex<V, VT, I, RV, RVT, RE, RET>,
// VT extends NCBITaxonomyGraph<I, RV, RVT, RE, RET>.NCBITaxonomyVertexType<V, VT>,
// P extends NCBITaxonomyVertexProperty<V, VT, P, PV>,
// PV
// >
// implements
// Property<V, VT, P, PV, NCBITaxonomyGraph<I, RV, RVT, RE, RET>, I, RV, RVT, RE, RET> {
//
// protected NCBITaxonomyVertexProperty(VT type) {
//
// this.type = type;
// }
//
// private VT type;
//
// @Override
// public final VT elementType() {
// return type;
// }
// }
//
// public abstract static class NCBITaxonomyVertex<
// V extends NCBITaxonomyVertex<V, VT, I, RV, RVT, RE, RET>,
// VT extends NCBITaxonomyGraph<I, RV, RVT, RE, RET>.NCBITaxonomyVertexType<V, VT>,
// I extends UntypedGraph<RV, RVT, RE, RET>, RV, RVT, RE, RET
// >
// implements
// TypedVertex<V, VT, NCBITaxonomyGraph<I, RV, RVT, RE, RET>, I, RV, RVT, RE, RET> {
//
// private RV vertex;
// private VT type;
//
// protected NCBITaxonomyVertex(RV vertex, VT type) {
//
// this.vertex = vertex;
// this.type = type;
// }
//
// @Override
// public final NCBITaxonomyGraph<I, RV, RVT, RE, RET> graph() {
// return type().graph();
// }
//
// @Override
// public final RV raw() {
// return this.vertex;
// }
//
// @Override
// public final VT type() {
// return type;
// }
// }
//
// abstract class NCBITaxonomyVertexType<
// V extends NCBITaxonomyVertex<V, VT, I, RV, RVT, RE, RET>,
// VT extends NCBITaxonomyGraph<I, RV, RVT, RE, RET>.NCBITaxonomyVertexType<V, VT>
// >
// implements
// TypedVertex.Type<V, VT, NCBITaxonomyGraph<I, RV, RVT, RE, RET>, I, RV, RVT, RE, RET> {
//
// private RVT raw;
//
// protected NCBITaxonomyVertexType(RVT raw) {
// this.raw = raw;
// }
//
// @Override
// public final RVT raw() {
// return raw;
// }
//
// @Override
// public final NCBITaxonomyGraph<I, RV, RVT, RE, RET> graph() {
// return NCBITaxonomyGraph.this;
// }
// }
//
// public abstract static class NCBITaxonomyEdge<
// S extends NCBITaxonomyVertex<S, ST, I, RV, RVT, RE, RET>,
// ST extends NCBITaxonomyGraph<I, RV, RVT, RE, RET>.NCBITaxonomyVertexType<S, ST>,
// E extends NCBITaxonomyEdge<S, ST, E, ET, T, TT, I, RV, RVT, RE, RET>,
// ET extends NCBITaxonomyGraph<I, RV, RVT, RE, RET>.NCBITaxonomyEdgeType<S, ST, E, ET, T, TT>,
// T extends NCBITaxonomyVertex<T, TT, I, RV, RVT, RE, RET>,
// TT extends NCBITaxonomyGraph<I, RV, RVT, RE, RET>.NCBITaxonomyVertexType<T, TT>,
// I extends UntypedGraph<RV, RVT, RE, RET>, RV, RVT, RE, RET
// >
// implements
// TypedEdge<
// S, ST, NCBITaxonomyGraph<I, RV, RVT, RE, RET>,
// E, ET, NCBITaxonomyGraph<I, RV, RVT, RE, RET>, I, RV, RVT, RE, RET,
// T, TT, NCBITaxonomyGraph<I, RV, RVT, RE, RET>
// >
// {
//
// private RE edge;
// private ET type;
//
// protected NCBITaxonomyEdge(RE edge, ET type) {
//
// this.edge = edge;
// this.type = type;
// }
//
// @Override
// public final NCBITaxonomyGraph<I, RV, RVT, RE, RET> graph() {
// return type().graph();
// }
//
// @Override
// public final RE raw() {
// return this.edge;
// }
//
// @Override
// public final ET type() {
// return type;
// }
// }
//
// abstract class NCBITaxonomyEdgeType<
// S extends NCBITaxonomyVertex<S, ST, I, RV, RVT, RE, RET>,
// ST extends NCBITaxonomyGraph<I, RV, RVT, RE, RET>.NCBITaxonomyVertexType<S, ST>,
// E extends NCBITaxonomyEdge<S, ST, E, ET, T, TT, I, RV, RVT, RE, RET>,
// ET extends NCBITaxonomyGraph<I, RV, RVT, RE, RET>.NCBITaxonomyEdgeType<S, ST, E, ET, T, TT>,
// T extends NCBITaxonomyVertex<T, TT, I, RV, RVT, RE, RET>,
// TT extends NCBITaxonomyGraph<I, RV, RVT, RE, RET>.NCBITaxonomyVertexType<T, TT>
// >
// implements
// TypedEdge.Type<
// S, ST, NCBITaxonomyGraph<I, RV, RVT, RE, RET>,
// E, ET, NCBITaxonomyGraph<I, RV, RVT, RE, RET>, I, RV, RVT, RE, RET,
// T, TT, NCBITaxonomyGraph<I, RV, RVT, RE, RET>
// >
// {
//
// private RET raw;
// private ST srcT;
// private TT tgtT;
//
// protected NCBITaxonomyEdgeType(ST srcT, RET raw, TT tgtT) {
//
// this.raw = raw;
// this.srcT = srcT;
// this.tgtT = tgtT;
// }
//
// @Override
// public final ST sourceType() {
// return srcT;
// }
//
// @Override
// public final TT targetType() {
// return tgtT;
// }
//
// @Override
// public final RET raw() {
// return raw;
// }
//
// @Override
// public final NCBITaxonomyGraph<I, RV, RVT, RE, RET> graph() {
// return NCBITaxonomyGraph.this;
// }
// }
// }
| start updating NCBITaxonomy
| src/main/java/com/bio4j/model/ncbiTaxonomy/NCBITaxonomyGraph.java | start updating NCBITaxonomy | <ide><path>rc/main/java/com/bio4j/model/ncbiTaxonomy/NCBITaxonomyGraph.java
<del>// package com.bio4j.model.ncbiTaxonomy;
<del>//
<del>// import com.bio4j.model.ncbiTaxonomy.vertices.*;
<del>// import com.bio4j.model.ncbiTaxonomy.edges.*;
<del>// import com.bio4j.angulillos.*;
<del>//
<del>// /*
<del>//
<del>// # NCBI Taxonomy graph
<del>//
<del>// This graph includes the whole NCBI taxonomy tree.
<del>// Files used in the importing process can be found [here](ftp://ftp.ncbi.nih.gov/pub/taxonomy/taxdump.tar.gz)
<del>//
<del>// Once that information is extracted we are building the tree from the information included in the following files:
<del>//
<del>// * **nodes.dmp**
<del>// * **names.dmp**
<del>//
<del>// ## data model
<del>//
<del>// It simply consists of the vertices of NCBITaxon type plus the hierarchical relationships represented as NCBITaxonParent edges.
<del>//
<del>// ### NCBITaxons
<del>//
<del>// We have a `NCBITaxon` vertex which contains property data present for each NCBI taxonomic unit.
<del>//
<del>// ##### NCBITaxon properties stored
<del>//
<del>// - id
<del>// - name
<del>// - comment
<del>// - scientific name
<del>// - taxonomic rank
<del>//
<del>// */
<add>/*
<add> # NCBI Taxonomy graph
<add>
<add> This graph includes the whole NCBI taxonomy tree.
<add> Files used in the importing process can be found [here](ftp://ftp.ncbi.nih.gov/pub/taxonomy/taxdump.tar.gz)
<add>
<add> Once that information is extracted we are building the tree from the information included in the following files:
<add>
<add> * **nodes.dmp**
<add> * **names.dmp**
<add>
<add> ## data model
<add>
<add> It simply consists of the vertices of NCBITaxon type plus the hierarchical relationships represented as NCBITaxonParent edges.
<add>
<add> ### NCBITaxons
<add>
<add> We have a `NCBITaxon` vertex which contains property data present for each NCBI taxonomic unit.
<add>
<add> ##### NCBITaxon properties stored
<add>
<add> - id
<add> - name
<add> - comment
<add> - scientific name
<add> - taxonomic rank
<add> */
<add>package com.bio4j.model.ncbiTaxonomy;
<add>
<add>import com.bio4j.angulillos.*;
<add>import com.bio4j.angulillos.Arity.*;
<add>
<add>public final class NCBITaxonomyGraph<V,E> extends TypedGraph<NCBITaxonomyGraph<V,E>,V,E> {
<add>
<add> public NCBITaxonomyGraph(UntypedGraph<V,E> graph) { super(graph); }
<add>
<add> @Override
<add> public final NCBITaxonomyGraph<V,E> self() { return this; }
<add>}
<add>//
<add>//
<ide> // public abstract class NCBITaxonomyGraph<
<ide> // // untyped graph
<ide> // I extends UntypedGraph<RV, RVT, RE, RET>, |
|
Java | apache-2.0 | 6248950fe7aa56e50dee0944919dd776fd2c5611 | 0 | metaborg/spoofax,metaborg/spoofax,metaborg/spoofax,metaborg/spoofax | package org.metaborg.spoofax.core.context;
import java.io.IOException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import javax.annotation.Nullable;
import org.apache.commons.vfs2.AllFileSelector;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.metaborg.core.context.ContextIdentifier;
import org.metaborg.core.context.IContext;
import org.metaborg.core.context.IContextInternal;
import org.metaborg.core.language.ILanguageImpl;
import org.metaborg.runtime.task.engine.ITaskEngine;
import org.metaborg.runtime.task.engine.TaskManager;
import org.metaborg.spoofax.core.terms.ITermFactoryService;
import org.metaborg.util.concurrent.ClosableLock;
import org.metaborg.util.concurrent.IClosableLock;
import org.metaborg.util.log.ILogger;
import org.metaborg.util.log.LoggerUtils;
import org.spoofax.interpreter.library.index.IIndex;
import org.spoofax.interpreter.library.index.IndexManager;
import org.spoofax.interpreter.terms.ITermFactory;
import org.spoofax.terms.ParseError;
import com.google.inject.Injector;
public class IndexTaskContext implements IContext, IContextInternal, IIndexTaskContext {
private static final ILogger logger = LoggerUtils.logger(IndexTaskContext.class);
private final Injector injector;
private final ITermFactory termFactory;
private final ReadWriteLock lock;
private final ContextIdentifier identifier;
private IIndex index;
private ITaskEngine taskEngine;
public IndexTaskContext(Injector injector, ITermFactoryService termFactoryService, ContextIdentifier identifier) {
this.injector = injector;
this.termFactory = termFactoryService.get(identifier.language);
this.lock = new ReentrantReadWriteLock(true);
this.identifier = identifier;
}
@Override public ContextIdentifier identifier() {
return identifier;
}
@Override public FileObject location() {
return identifier.location;
}
@Override public ILanguageImpl language() {
return identifier.language;
}
@Override public Injector injector() {
return injector;
}
@Override public @Nullable IIndex index() {
return index;
}
@Override public @Nullable ITaskEngine taskEngine() {
return taskEngine;
}
@Override public IClosableLock read() {
if(index == null || taskEngine == null) {
// THREADING: temporarily acquire a write lock when initializing the index, need exclusive access.
try(IClosableLock lock = writeLock()) {
/*
* THREADING: re-check if index/task engine are still null now that we have exclusive access, there
* could have been a context switch before acquiring the lock. Check is also needed because the null
* check before is disjunct.
*/
if(index == null) {
index = loadIndex();
}
if(taskEngine == null) {
taskEngine = loadTaskEngine();
}
}
}
index.recover();
taskEngine.recover();
return readLock();
}
private IClosableLock readLock() {
final Lock readLock = lock.readLock();
final IClosableLock lock = new ClosableLock(readLock);
return lock;
}
@Override public IClosableLock write() {
final IClosableLock lock = writeLock();
if(index == null) {
index = loadIndex();
}
if(taskEngine == null) {
taskEngine = loadTaskEngine();
}
index.recover();
taskEngine.recover();
return lock;
}
private IClosableLock writeLock() {
final Lock writeLock = lock.writeLock();
final IClosableLock lock = new ClosableLock(writeLock);
return lock;
}
@Override public void persist() throws IOException {
if(index == null && taskEngine == null) {
return;
}
try(IClosableLock lock = readLock()) {
if(index != null) {
IndexManager.write(index, indexFile(), termFactory);
}
if(taskEngine != null) {
TaskManager.write(taskEngine, taskEngineFile(), termFactory);
}
}
}
@Override public void reset() throws FileSystemException {
try(IClosableLock lock = writeLock()) {
if(index != null) {
index.reset();
index = null;
}
if(taskEngine != null) {
taskEngine.reset();
taskEngine = null;
}
final FileObject cacheDir = identifier.location.resolveFile(".cache");
cacheDir.delete(new AllFileSelector());
}
}
@Override public void init() {
if(index != null && taskEngine != null) {
return;
}
try(IClosableLock lock = writeLock()) {
if(index == null) {
index = initIndex();
}
if(taskEngine == null) {
taskEngine = initTaskEngine();
}
}
}
@Override public void load() {
if(index != null && taskEngine != null) {
return;
}
try(IClosableLock lock = writeLock()) {
if(index == null) {
index = loadIndex();
}
if(taskEngine == null) {
taskEngine = loadTaskEngine();
}
}
}
@Override public void unload() {
if(index == null && taskEngine == null) {
return;
}
try(IClosableLock lock = writeLock()) {
index = null;
taskEngine = null;
}
}
private FileObject indexFile() throws FileSystemException {
return IndexManager.cacheFile(identifier.location);
}
private IIndex initIndex() {
return IndexManager.create(termFactory);
}
private IIndex loadIndex() {
try {
final FileObject indexFile = indexFile();
if(indexFile.exists()) {
try {
final IIndex index = IndexManager.read(indexFile, termFactory);
return index;
} catch(ParseError | IOException e) {
logger.error("Loading index from {} failed, deleting that file and returning an empty index. "
+ "Clean the project to reanalyze", e, indexFile);
deleteIndexFile(indexFile);
} catch(Exception e) {
logger.error("Loading index from {} failed, deleting that file and returning an empty index. "
+ "Clean the project to reanalyze", e, indexFile);
deleteIndexFile(indexFile);
}
}
} catch(FileSystemException e) {
logger.error("Locating index file for {} failed, returning an empty index. "
+ "Clean the project to reanalyze", e, this);
}
return initIndex();
}
private void deleteIndexFile(FileObject file) {
try {
file.delete();
} catch(Exception e) {
logger.error("Deleting index file {} failed, please delete the file manually", e, file);
}
}
private FileObject taskEngineFile() throws FileSystemException {
return TaskManager.cacheFile(identifier.location);
}
private ITaskEngine initTaskEngine() {
return TaskManager.create(termFactory);
}
private ITaskEngine loadTaskEngine() {
try {
final FileObject taskEngineFile = taskEngineFile();
if(taskEngineFile.exists()) {
try {
final ITaskEngine taskEngine = TaskManager.read(taskEngineFile, termFactory);
return taskEngine;
} catch(ParseError | IOException e) {
logger.error(
"Loading task engine from {} failed, deleting that file and returning an empty task engine. "
+ "Clean the project to reanalyze", e, taskEngineFile);
deleteTaskEngineFile(taskEngineFile);
} catch(Exception e) {
logger.error(
"Loading task engine from {} failed, deleting that file and returning an empty task engine. "
+ "Clean the project to reanalyze", e, taskEngineFile);
deleteTaskEngineFile(taskEngineFile);
}
}
} catch(FileSystemException e) {
logger.error("Locating task engine file for {} failed, returning an empty task engine. "
+ "Clean the project to reanalyze", e, this);
}
return initTaskEngine();
}
private void deleteTaskEngineFile(FileObject file) {
try {
file.delete();
} catch(Exception e) {
logger.error("Deleting task engine file {} failed, please delete the file manually", e, file);
}
}
@Override public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + identifier.hashCode();
return result;
}
@Override public boolean equals(Object obj) {
if(this == obj)
return true;
if(obj == null)
return false;
if(getClass() != obj.getClass())
return false;
final IndexTaskContext other = (IndexTaskContext) obj;
if(!identifier.equals(other.identifier))
return false;
return true;
}
@Override public String toString() {
return String.format("context for %s, %s", identifier.location, identifier.language);
}
}
| org.metaborg.spoofax.core/src/main/java/org/metaborg/spoofax/core/context/IndexTaskContext.java | package org.metaborg.spoofax.core.context;
import java.io.IOException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import javax.annotation.Nullable;
import org.apache.commons.vfs2.AllFileSelector;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.metaborg.core.context.ContextIdentifier;
import org.metaborg.core.context.IContext;
import org.metaborg.core.context.IContextInternal;
import org.metaborg.core.language.ILanguageImpl;
import org.metaborg.runtime.task.engine.ITaskEngine;
import org.metaborg.runtime.task.engine.TaskManager;
import org.metaborg.spoofax.core.terms.ITermFactoryService;
import org.metaborg.util.concurrent.ClosableLock;
import org.metaborg.util.concurrent.IClosableLock;
import org.metaborg.util.log.ILogger;
import org.metaborg.util.log.LoggerUtils;
import org.spoofax.interpreter.library.index.IIndex;
import org.spoofax.interpreter.library.index.IndexManager;
import org.spoofax.interpreter.terms.ITermFactory;
import org.spoofax.terms.ParseError;
import com.google.inject.Injector;
public class IndexTaskContext implements IContext, IContextInternal, IIndexTaskContext {
private static final ILogger logger = LoggerUtils.logger(IndexTaskContext.class);
private final Injector injector;
private final ITermFactory termFactory;
private final ReadWriteLock lock;
private final ContextIdentifier identifier;
private IIndex index;
private ITaskEngine taskEngine;
public IndexTaskContext(Injector injector, ITermFactoryService termFactoryService, ContextIdentifier identifier) {
this.injector = injector;
this.termFactory = termFactoryService.get(identifier.language);
this.lock = new ReentrantReadWriteLock(true);
this.identifier = identifier;
}
@Override public ContextIdentifier identifier() {
return identifier;
}
@Override public FileObject location() {
return identifier.location;
}
@Override public ILanguageImpl language() {
return identifier.language;
}
@Override public Injector injector() {
return injector;
}
@Override public @Nullable IIndex index() {
return index;
}
@Override public @Nullable ITaskEngine taskEngine() {
return taskEngine;
}
@Override public IClosableLock read() {
if(index == null || taskEngine == null) {
// THREADING: temporarily acquire a write lock when initializing the index, need exclusive access.
try(IClosableLock lock = writeLock()) {
/*
* THREADING: re-check if index/task engine are still null now that we have exclusive access, there
* could have been a context switch before acquiring the lock. Check is also needed because the null
* check before is disjunct.
*/
if(index == null) {
index = initIndex();
}
if(taskEngine == null) {
taskEngine = initTaskEngine();
}
}
}
index.recover();
taskEngine.recover();
return readLock();
}
private IClosableLock readLock() {
final Lock readLock = lock.readLock();
final IClosableLock lock = new ClosableLock(readLock);
return lock;
}
@Override public IClosableLock write() {
final IClosableLock lock = writeLock();
if(index == null) {
index = loadIndex();
}
if(taskEngine == null) {
taskEngine = loadTaskEngine();
}
index.recover();
taskEngine.recover();
return lock;
}
private IClosableLock writeLock() {
final Lock writeLock = lock.writeLock();
final IClosableLock lock = new ClosableLock(writeLock);
return lock;
}
@Override public void persist() throws IOException {
if(index == null && taskEngine == null) {
return;
}
try(IClosableLock lock = readLock()) {
if(index != null) {
IndexManager.write(index, indexFile(), termFactory);
}
if(taskEngine != null) {
TaskManager.write(taskEngine, taskEngineFile(), termFactory);
}
}
}
@Override public void reset() throws FileSystemException {
try(IClosableLock lock = writeLock()) {
if(index != null) {
index.reset();
index = null;
}
if(taskEngine != null) {
taskEngine.reset();
taskEngine = null;
}
final FileObject cacheDir = identifier.location.resolveFile(".cache");
cacheDir.delete(new AllFileSelector());
}
}
@Override public void init() {
if(index != null && taskEngine != null) {
return;
}
try(IClosableLock lock = writeLock()) {
if(index == null) {
index = initIndex();
}
if(taskEngine == null) {
taskEngine = initTaskEngine();
}
}
}
@Override public void load() {
if(index != null && taskEngine != null) {
return;
}
try(IClosableLock lock = writeLock()) {
if(index == null) {
index = loadIndex();
}
if(taskEngine == null) {
taskEngine = loadTaskEngine();
}
}
}
@Override public void unload() {
if(index == null && taskEngine == null) {
return;
}
try(IClosableLock lock = writeLock()) {
index = null;
taskEngine = null;
}
}
private FileObject indexFile() throws FileSystemException {
return IndexManager.cacheFile(identifier.location);
}
private IIndex initIndex() {
return IndexManager.create(termFactory);
}
private IIndex loadIndex() {
try {
final FileObject indexFile = indexFile();
if(indexFile.exists()) {
try {
final IIndex index = IndexManager.read(indexFile, termFactory);
return index;
} catch(ParseError | IOException e) {
logger.error("Loading index from {} failed, deleting that file and returning an empty index. "
+ "Clean the project to reanalyze", e, indexFile);
deleteIndexFile(indexFile);
} catch(Exception e) {
logger.error("Loading index from {} failed, deleting that file and returning an empty index. "
+ "Clean the project to reanalyze", e, indexFile);
deleteIndexFile(indexFile);
}
}
} catch(FileSystemException e) {
logger.error("Locating index file for {} failed, returning an empty index. "
+ "Clean the project to reanalyze", e, this);
}
return initIndex();
}
private void deleteIndexFile(FileObject file) {
try {
file.delete();
} catch(Exception e) {
logger.error("Deleting index file {} failed, please delete the file manually", e, file);
}
}
private FileObject taskEngineFile() throws FileSystemException {
return TaskManager.cacheFile(identifier.location);
}
private ITaskEngine initTaskEngine() {
return TaskManager.create(termFactory);
}
private ITaskEngine loadTaskEngine() {
try {
final FileObject taskEngineFile = taskEngineFile();
if(taskEngineFile.exists()) {
try {
final ITaskEngine taskEngine = TaskManager.read(taskEngineFile, termFactory);
return taskEngine;
} catch(ParseError | IOException e) {
logger.error(
"Loading task engine from {} failed, deleting that file and returning an empty task engine. "
+ "Clean the project to reanalyze", e, taskEngineFile);
deleteTaskEngineFile(taskEngineFile);
} catch(Exception e) {
logger.error(
"Loading task engine from {} failed, deleting that file and returning an empty task engine. "
+ "Clean the project to reanalyze", e, taskEngineFile);
deleteTaskEngineFile(taskEngineFile);
}
}
} catch(FileSystemException e) {
logger.error("Locating task engine file for {} failed, returning an empty task engine. "
+ "Clean the project to reanalyze", e, this);
}
return initTaskEngine();
}
private void deleteTaskEngineFile(FileObject file) {
try {
file.delete();
} catch(Exception e) {
logger.error("Deleting task engine file {} failed, please delete the file manually", e, file);
}
}
@Override public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + identifier.hashCode();
return result;
}
@Override public boolean equals(Object obj) {
if(this == obj)
return true;
if(obj == null)
return false;
if(getClass() != obj.getClass())
return false;
final IndexTaskContext other = (IndexTaskContext) obj;
if(!identifier.equals(other.identifier))
return false;
return true;
}
@Override public String toString() {
return String.format("context for %s, %s", identifier.location, identifier.language);
}
}
| Load index and task engine, instead of initializing them as empty.
| org.metaborg.spoofax.core/src/main/java/org/metaborg/spoofax/core/context/IndexTaskContext.java | Load index and task engine, instead of initializing them as empty. | <ide><path>rg.metaborg.spoofax.core/src/main/java/org/metaborg/spoofax/core/context/IndexTaskContext.java
<ide> * check before is disjunct.
<ide> */
<ide> if(index == null) {
<del> index = initIndex();
<add> index = loadIndex();
<ide> }
<ide> if(taskEngine == null) {
<del> taskEngine = initTaskEngine();
<add> taskEngine = loadTaskEngine();
<ide> }
<ide> }
<ide> } |
|
Java | apache-2.0 | c168b51e0d03ca8070ffd12ce664ab7c6f2a8670 | 0 | allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vfs.impl.local;
import com.intellij.execution.process.OSProcessHandler;
import com.intellij.execution.process.ProcessOutputTypes;
import com.intellij.ide.actions.RevealFileAction;
import com.intellij.notification.NotificationListener;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationBundle;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.openapi.vfs.local.FileWatcherNotificationSink;
import com.intellij.openapi.vfs.local.PluggableFileWatcher;
import com.intellij.openapi.vfs.newvfs.ManagingFS;
import com.intellij.util.ArrayUtil;
import com.intellij.util.TimeoutUtil;
import com.intellij.util.io.BaseDataReader;
import com.intellij.util.io.BaseOutputReader;
import com.sun.jna.Platform;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.text.Normalizer;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
public class NativeFileWatcherImpl extends PluggableFileWatcher {
private static final Logger LOG = Logger.getInstance(NativeFileWatcherImpl.class);
private static final String PROPERTY_WATCHER_DISABLED = "idea.filewatcher.disabled";
private static final String PROPERTY_WATCHER_EXECUTABLE_PATH = "idea.filewatcher.executable.path";
private static final String ROOTS_COMMAND = "ROOTS";
private static final String EXIT_COMMAND = "EXIT";
private static final int MAX_PROCESS_LAUNCH_ATTEMPT_COUNT = 10;
private FileWatcherNotificationSink myNotificationSink;
private File myExecutable;
private volatile MyProcessHandler myProcessHandler;
private final AtomicInteger myStartAttemptCount = new AtomicInteger(0);
private volatile boolean myIsShuttingDown;
private final AtomicInteger mySettingRoots = new AtomicInteger(0);
private volatile List<String> myRecursiveWatchRoots = Collections.emptyList();
private volatile List<String> myFlatWatchRoots = Collections.emptyList();
private final String[] myLastChangedPaths = new String[2];
private int myLastChangedPathIndex;
@Override
public void initialize(@NotNull ManagingFS managingFS, @NotNull FileWatcherNotificationSink notificationSink) {
myNotificationSink = notificationSink;
boolean disabled = isDisabled();
myExecutable = getExecutable();
if (disabled) {
LOG.info("Native file watcher is disabled");
}
else if (myExecutable == null) {
if (SystemInfo.isWindows || SystemInfo.isMac || SystemInfo.isLinux && ArrayUtil.contains(Platform.RESOURCE_PREFIX, "linux-x86", "linux-x86-64")) {
notifyOnFailure(ApplicationBundle.message("watcher.exe.not.found"), null);
}
else if (SystemInfo.isLinux) {
notifyOnFailure(ApplicationBundle.message("watcher.exe.compile"), NotificationListener.URL_OPENING_LISTENER);
}
else {
notifyOnFailure(ApplicationBundle.message("watcher.exe.not.exists"), null);
}
}
else if (!myExecutable.canExecute()) {
String message = ApplicationBundle.message("watcher.exe.not.exe", myExecutable);
notifyOnFailure(message, (notification, event) -> RevealFileAction.openFile(myExecutable));
}
else {
try {
startupProcess(false);
LOG.info("Native file watcher is operational.");
}
catch (IOException e) {
LOG.warn(e.getMessage());
notifyOnFailure(ApplicationBundle.message("watcher.failed.to.start"), null);
}
}
}
@Override
public void dispose() {
myIsShuttingDown = true;
shutdownProcess();
}
@Override
public boolean isOperational() {
return myProcessHandler != null;
}
@Override
public boolean isSettingRoots() {
return isOperational() && mySettingRoots.get() > 0;
}
@Override
public void setWatchRoots(@NotNull List<String> recursive, @NotNull List<String> flat) {
setWatchRoots(recursive, flat, false);
}
/**
* Subclasses should override this method if they want to use custom logic to disable their file watcher.
*/
protected boolean isDisabled() {
if (Boolean.getBoolean(PROPERTY_WATCHER_DISABLED)) return true;
Application app = ApplicationManager.getApplication();
return app.isCommandLine() || app.isUnitTestMode();
}
/**
* Subclasses should override this method to provide a custom binary to run.
*/
protected @Nullable File getExecutable() {
return getFSNotifierExecutable();
}
public static @Nullable File getFSNotifierExecutable() {
String customPath = System.getProperty(PROPERTY_WATCHER_EXECUTABLE_PATH);
if (customPath != null) {
Path customFile = PathManager.findBinFile(customPath);
return customFile != null ? customFile.toFile() : new File(customPath);
}
String[] names = ArrayUtil.EMPTY_STRING_ARRAY;
if (SystemInfo.isWindows) {
if ("win32-x86".equals(Platform.RESOURCE_PREFIX)) {
names = new String[]{"fsnotifier.exe"};
}
else if ("win32-x86-64".equals(Platform.RESOURCE_PREFIX)) {
names = new String[]{"fsnotifier64.exe", "fsnotifier.exe"};
}
}
else if (SystemInfo.isMac) {
names = new String[]{"fsnotifier"};
}
else if (SystemInfo.isLinux) {
if ("linux-x86".equals(Platform.RESOURCE_PREFIX)) {
names = new String[]{"fsnotifier"};
}
else if ("linux-x86-64".equals(Platform.RESOURCE_PREFIX)) {
names = new String[]{"fsnotifier64"};
}
}
for (String name : names) {
Path file = PathManager.findBinFile(name);
if (file != null) {
return file.toFile();
}
}
return null;
}
/* internal stuff */
private void notifyOnFailure(@NlsContexts.NotificationContent String cause, @Nullable NotificationListener listener) {
myNotificationSink.notifyUserOnFailure(cause, listener);
}
private void startupProcess(boolean restart) throws IOException {
if (myIsShuttingDown) {
return;
}
if (ShutDownTracker.isShutdownHookRunning()) {
myIsShuttingDown = true;
return;
}
if (myStartAttemptCount.incrementAndGet() > MAX_PROCESS_LAUNCH_ATTEMPT_COUNT) {
notifyOnFailure(ApplicationBundle.message("watcher.bailed.out.10x"), null);
return;
}
if (restart) {
shutdownProcess();
}
LOG.info("Starting file watcher: " + myExecutable);
Process process = new ProcessBuilder(myExecutable.getAbsolutePath()).start();
myProcessHandler = new MyProcessHandler(process, myExecutable.getName());
myProcessHandler.startNotify();
if (restart) {
List<String> recursive = myRecursiveWatchRoots;
List<String> flat = myFlatWatchRoots;
if (recursive.size() + flat.size() > 0) {
setWatchRoots(recursive, flat, true);
}
}
}
private void shutdownProcess() {
OSProcessHandler processHandler = myProcessHandler;
if (processHandler != null) {
if (!processHandler.isProcessTerminated()) {
try { writeLine(EXIT_COMMAND); }
catch (IOException ignore) { }
if (!processHandler.waitFor(10)) {
Runnable r = () -> {
if (!processHandler.waitFor(500)) {
LOG.warn("File watcher is still alive, doing a force quit.");
processHandler.destroyProcess();
}
};
if (myIsShuttingDown) {
new Thread(r, "fsnotifier shutdown").start();
}
else {
ApplicationManager.getApplication().executeOnPooledThread(r);
}
}
}
myProcessHandler = null;
}
}
private void setWatchRoots(List<String> recursive, List<String> flat, boolean restart) {
if (myProcessHandler == null || myProcessHandler.isProcessTerminated()) return;
if (ApplicationManager.getApplication().isDisposed()) {
recursive = flat = Collections.emptyList();
}
if (!restart && myRecursiveWatchRoots.equals(recursive) && myFlatWatchRoots.equals(flat)) {
return;
}
mySettingRoots.incrementAndGet();
myRecursiveWatchRoots = recursive;
myFlatWatchRoots = flat;
try {
writeLine(ROOTS_COMMAND);
for (String path : recursive) writeLine(path);
for (String path : flat) writeLine('|' + path);
writeLine("#");
}
catch (IOException e) {
LOG.warn(e);
}
}
private void writeLine(String line) throws IOException {
if (LOG.isTraceEnabled()) LOG.trace("<< " + line);
MyProcessHandler processHandler = myProcessHandler;
if (processHandler != null) {
processHandler.writeLine(line);
}
}
@Override
public void resetChangedPaths() {
synchronized (myLastChangedPaths) {
myLastChangedPathIndex = 0;
Arrays.fill(myLastChangedPaths, null);
}
}
private static final Charset CHARSET =
SystemInfo.isWindows || SystemInfo.isMac ? StandardCharsets.UTF_8 : CharsetToolkit.getPlatformCharset();
private static final BaseOutputReader.Options READER_OPTIONS = new BaseOutputReader.Options() {
@Override public BaseDataReader.SleepingPolicy policy() { return BaseDataReader.SleepingPolicy.BLOCKING; }
@Override public boolean sendIncompleteLines() { return false; }
@Override public boolean withSeparators() { return false; }
};
@SuppressWarnings("SpellCheckingInspection")
private enum WatcherOp { GIVEUP, RESET, UNWATCHEABLE, REMAP, MESSAGE, CREATE, DELETE, STATS, CHANGE, DIRTY, RECDIRTY }
private final class MyProcessHandler extends OSProcessHandler {
private final BufferedWriter myWriter;
private WatcherOp myLastOp;
private final List<String> myLines = new ArrayList<>();
MyProcessHandler(Process process, String commandLine) {
super(process, commandLine, CHARSET);
myWriter = new BufferedWriter(new OutputStreamWriter(process.getOutputStream(), CHARSET));
}
void writeLine(String line) throws IOException {
myWriter.write(line);
myWriter.newLine();
myWriter.flush();
}
@Override
protected @NotNull BaseOutputReader.Options readerOptions() {
return READER_OPTIONS;
}
@Override
protected void notifyProcessTerminated(int exitCode) {
super.notifyProcessTerminated(exitCode);
String message = "Watcher terminated with exit code " + exitCode;
if (myIsShuttingDown) LOG.info(message); else LOG.warn(message);
myProcessHandler = null;
try {
startupProcess(true);
}
catch (IOException e) {
shutdownProcess();
LOG.warn("Watcher terminated and attempt to restart has failed. Exiting watching thread.", e);
}
}
@Override
public void notifyTextAvailable(@NotNull String line, @NotNull Key outputType) {
if (outputType == ProcessOutputTypes.STDERR) {
LOG.warn(line);
}
if (outputType != ProcessOutputTypes.STDOUT) {
return;
}
if (LOG.isTraceEnabled()) LOG.trace(">> " + line);
if (myLastOp == null) {
WatcherOp watcherOp;
try {
watcherOp = WatcherOp.valueOf(line);
}
catch (IllegalArgumentException e) {
String message = "Illegal watcher command: '" + line + "'";
if (line.length() <= 20) message += " " + Arrays.toString(line.chars().toArray());
LOG.error(message);
return;
}
if (watcherOp == WatcherOp.GIVEUP) {
notifyOnFailure(ApplicationBundle.message("watcher.gave.up"), null);
myIsShuttingDown = true;
}
else if (watcherOp == WatcherOp.RESET) {
myNotificationSink.notifyReset(null);
}
else {
myLastOp = watcherOp;
}
}
else if (myLastOp == WatcherOp.MESSAGE) {
String localized = Objects.requireNonNullElse(ApplicationBundle.INSTANCE.messageOrNull(line), line); //NON-NLS
LOG.warn(localized);
notifyOnFailure(localized, NotificationListener.URL_OPENING_LISTENER);
myLastOp = null;
}
else if (myLastOp == WatcherOp.REMAP || myLastOp == WatcherOp.UNWATCHEABLE) {
if ("#".equals(line)) {
if (myLastOp == WatcherOp.REMAP) {
processRemap();
}
else {
mySettingRoots.decrementAndGet();
processUnwatchable();
}
myLines.clear();
myLastOp = null;
}
else {
myLines.add(line);
}
}
else {
String path = StringUtil.trimEnd(line.replace('\0', '\n'), File.separator); // unescape
processChange(path, myLastOp);
myLastOp = null;
}
}
private void processRemap() {
Set<Pair<String, String>> pairs = new HashSet<>();
for (int i = 0; i < myLines.size() - 1; i += 2) {
pairs.add(Pair.create(myLines.get(i), myLines.get(i + 1)));
}
myNotificationSink.notifyMapping(pairs);
}
private void processUnwatchable() {
myNotificationSink.notifyManualWatchRoots(myLines);
}
private void processChange(String path, WatcherOp op) {
if (SystemInfo.isWindows && op == WatcherOp.RECDIRTY) {
myNotificationSink.notifyReset(path);
return;
}
if ((op == WatcherOp.CHANGE || op == WatcherOp.STATS) && isRepetition(path)) {
if (LOG.isTraceEnabled()) LOG.trace("repetition: " + path);
return;
}
if (SystemInfo.isMac) {
path = Normalizer.normalize(path, Normalizer.Form.NFC);
}
switch (op) {
case STATS:
case CHANGE:
myNotificationSink.notifyDirtyPath(path);
break;
case CREATE:
case DELETE:
myNotificationSink.notifyPathCreatedOrDeleted(path);
break;
case DIRTY:
myNotificationSink.notifyDirtyDirectory(path);
break;
case RECDIRTY:
myNotificationSink.notifyDirtyPathRecursive(path);
break;
default:
LOG.error("Unexpected op: " + op);
}
}
}
protected boolean isRepetition(String path) {
// collapse subsequent change file change notifications that happen once we copy a large file,
// this allows reduction of path checks at least 20% for Windows
synchronized (myLastChangedPaths) {
for (int i = 0; i < myLastChangedPaths.length; ++i) {
int last = myLastChangedPathIndex - i - 1;
if (last < 0) last += myLastChangedPaths.length;
String lastChangedPath = myLastChangedPaths[last];
if (lastChangedPath != null && lastChangedPath.equals(path)) {
return true;
}
}
myLastChangedPaths[myLastChangedPathIndex++] = path;
if (myLastChangedPathIndex == myLastChangedPaths.length) myLastChangedPathIndex = 0;
}
return false;
}
//<editor-fold desc="Test stuff.">
@Override
@TestOnly
public void startup() throws IOException {
Application app = ApplicationManager.getApplication();
if (app == null || !app.isUnitTestMode()) throw new IllegalStateException();
myIsShuttingDown = false;
myStartAttemptCount.set(0);
startupProcess(false);
}
@Override
@TestOnly
public void shutdown() throws InterruptedException {
Application app = ApplicationManager.getApplication();
if (app == null || !app.isUnitTestMode()) throw new IllegalStateException();
MyProcessHandler processHandler = myProcessHandler;
if (processHandler != null) {
myIsShuttingDown = true;
shutdownProcess();
long t = System.currentTimeMillis();
while (!processHandler.isProcessTerminated()) {
if (System.currentTimeMillis() - t > 15000) {
throw new InterruptedException("Timed out waiting watcher process to terminate");
}
TimeoutUtil.sleep(100);
}
}
}
//</editor-fold>
}
| platform/platform-impl/src/com/intellij/openapi/vfs/impl/local/NativeFileWatcherImpl.java | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vfs.impl.local;
import com.intellij.execution.process.OSProcessHandler;
import com.intellij.execution.process.ProcessOutputTypes;
import com.intellij.ide.actions.RevealFileAction;
import com.intellij.notification.NotificationListener;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationBundle;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.openapi.vfs.local.FileWatcherNotificationSink;
import com.intellij.openapi.vfs.local.PluggableFileWatcher;
import com.intellij.openapi.vfs.newvfs.ManagingFS;
import com.intellij.util.ArrayUtil;
import com.intellij.util.TimeoutUtil;
import com.intellij.util.io.BaseDataReader;
import com.intellij.util.io.BaseOutputReader;
import com.sun.jna.Platform;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.text.Normalizer;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
public class NativeFileWatcherImpl extends PluggableFileWatcher {
private static final Logger LOG = Logger.getInstance(NativeFileWatcherImpl.class);
private static final String PROPERTY_WATCHER_DISABLED = "idea.filewatcher.disabled";
private static final String PROPERTY_WATCHER_EXECUTABLE_PATH = "idea.filewatcher.executable.path";
private static final String ROOTS_COMMAND = "ROOTS";
private static final String EXIT_COMMAND = "EXIT";
private static final int MAX_PROCESS_LAUNCH_ATTEMPT_COUNT = 10;
private FileWatcherNotificationSink myNotificationSink;
private File myExecutable;
private volatile MyProcessHandler myProcessHandler;
private final AtomicInteger myStartAttemptCount = new AtomicInteger(0);
private volatile boolean myIsShuttingDown;
private final AtomicInteger mySettingRoots = new AtomicInteger(0);
private volatile List<String> myRecursiveWatchRoots = Collections.emptyList();
private volatile List<String> myFlatWatchRoots = Collections.emptyList();
private final String[] myLastChangedPaths = new String[2];
private int myLastChangedPathIndex;
@Override
public void initialize(@NotNull ManagingFS managingFS, @NotNull FileWatcherNotificationSink notificationSink) {
myNotificationSink = notificationSink;
boolean disabled = isDisabled();
myExecutable = getExecutable();
if (disabled) {
LOG.info("Native file watcher is disabled");
}
else if (myExecutable == null) {
if (SystemInfo.isWindows || SystemInfo.isMac || SystemInfo.isLinux && ArrayUtil.contains(Platform.RESOURCE_PREFIX, "linux-x86", "linux-x86-64")) {
notifyOnFailure(ApplicationBundle.message("watcher.exe.not.found"), null);
}
else if (SystemInfo.isLinux) {
notifyOnFailure(ApplicationBundle.message("watcher.exe.compile"), NotificationListener.URL_OPENING_LISTENER);
}
else {
notifyOnFailure(ApplicationBundle.message("watcher.exe.not.exists"), null);
}
}
else if (!myExecutable.canExecute()) {
String message = ApplicationBundle.message("watcher.exe.not.exe", myExecutable);
notifyOnFailure(message, (notification, event) -> RevealFileAction.openFile(myExecutable));
}
else {
try {
startupProcess(false);
LOG.info("Native file watcher is operational.");
}
catch (IOException e) {
LOG.warn(e.getMessage());
notifyOnFailure(ApplicationBundle.message("watcher.failed.to.start"), null);
}
}
}
@Override
public void dispose() {
myIsShuttingDown = true;
shutdownProcess();
}
@Override
public boolean isOperational() {
return myProcessHandler != null;
}
@Override
public boolean isSettingRoots() {
return isOperational() && mySettingRoots.get() > 0;
}
@Override
public void setWatchRoots(@NotNull List<String> recursive, @NotNull List<String> flat) {
setWatchRoots(recursive, flat, false);
}
/**
* Subclasses should override this method if they want to use custom logic to disable their file watcher.
*/
protected boolean isDisabled() {
if (Boolean.getBoolean(PROPERTY_WATCHER_DISABLED)) return true;
Application app = ApplicationManager.getApplication();
return app.isCommandLine() || app.isUnitTestMode();
}
/**
* Subclasses should override this method to provide a custom binary to run.
*/
protected @Nullable File getExecutable() {
return getFSNotifierExecutable();
}
public static @Nullable File getFSNotifierExecutable() {
String customPath = System.getProperty(PROPERTY_WATCHER_EXECUTABLE_PATH);
if (customPath != null) {
Path customFile = PathManager.findBinFile(customPath);
return customFile != null ? customFile.toFile() : new File(customPath);
}
String[] names = ArrayUtil.EMPTY_STRING_ARRAY;
if (SystemInfo.isWindows) {
if ("win32-x86".equals(Platform.RESOURCE_PREFIX)) {
names = new String[]{"fsnotifier.exe"};
}
else if ("win32-x86-64".equals(Platform.RESOURCE_PREFIX)) {
names = new String[]{"fsnotifier64.exe", "fsnotifier.exe"};
}
}
else if (SystemInfo.isMac) {
names = new String[]{"fsnotifier"};
}
else if (SystemInfo.isLinux) {
if ("linux-x86".equals(Platform.RESOURCE_PREFIX)) {
names = new String[]{"fsnotifier"};
}
else if ("linux-x86-64".equals(Platform.RESOURCE_PREFIX)) {
names = new String[]{"fsnotifier64"};
}
}
for (String name : names) {
Path file = PathManager.findBinFile(name);
if (file != null) {
return file.toFile();
}
}
return null;
}
/* internal stuff */
private void notifyOnFailure(@NlsContexts.NotificationContent String cause, @Nullable NotificationListener listener) {
myNotificationSink.notifyUserOnFailure(cause, listener);
}
private void startupProcess(boolean restart) throws IOException {
if (myIsShuttingDown) {
return;
}
if (ShutDownTracker.isShutdownHookRunning()) {
myIsShuttingDown = true;
return;
}
if (myStartAttemptCount.incrementAndGet() > MAX_PROCESS_LAUNCH_ATTEMPT_COUNT) {
notifyOnFailure(ApplicationBundle.message("watcher.bailed.out.10x"), null);
return;
}
if (restart) {
shutdownProcess();
}
LOG.info("Starting file watcher: " + myExecutable);
Process process = new ProcessBuilder(myExecutable.getAbsolutePath()).start();
myProcessHandler = new MyProcessHandler(process, myExecutable.getName());
myProcessHandler.startNotify();
if (restart) {
List<String> recursive = myRecursiveWatchRoots;
List<String> flat = myFlatWatchRoots;
if (recursive.size() + flat.size() > 0) {
setWatchRoots(recursive, flat, true);
}
}
}
private void shutdownProcess() {
OSProcessHandler processHandler = myProcessHandler;
if (processHandler != null) {
if (!processHandler.isProcessTerminated()) {
try { writeLine(EXIT_COMMAND); }
catch (IOException ignore) { }
if (!processHandler.waitFor(10)) {
Runnable r = () -> {
if (!processHandler.waitFor(500)) {
LOG.warn("File watcher is still alive, doing a force quit.");
processHandler.destroyProcess();
}
};
if (myIsShuttingDown) {
new Thread(r, "fsnotifier shutdown").start();
}
else {
ApplicationManager.getApplication().executeOnPooledThread(r);
}
}
}
myProcessHandler = null;
}
}
private void setWatchRoots(List<String> recursive, List<String> flat, boolean restart) {
if (myProcessHandler == null || myProcessHandler.isProcessTerminated()) return;
if (ApplicationManager.getApplication().isDisposed()) {
recursive = flat = Collections.emptyList();
}
if (!restart && myRecursiveWatchRoots.equals(recursive) && myFlatWatchRoots.equals(flat)) {
return;
}
mySettingRoots.incrementAndGet();
myRecursiveWatchRoots = recursive;
myFlatWatchRoots = flat;
try {
writeLine(ROOTS_COMMAND);
for (String path : recursive) writeLine(path);
for (String path : flat) writeLine('|' + path);
writeLine("#");
}
catch (IOException e) {
LOG.warn(e);
}
}
private void writeLine(String line) throws IOException {
if (LOG.isTraceEnabled()) LOG.trace("<< " + line);
MyProcessHandler processHandler = myProcessHandler;
if (processHandler != null) {
processHandler.writeLine(line);
}
}
@Override
public void resetChangedPaths() {
synchronized (myLastChangedPaths) {
myLastChangedPathIndex = 0;
Arrays.fill(myLastChangedPaths, null);
}
}
private static final Charset CHARSET =
SystemInfo.isWindows || SystemInfo.isMac ? StandardCharsets.UTF_8 : CharsetToolkit.getPlatformCharset();
private static final BaseOutputReader.Options READER_OPTIONS = new BaseOutputReader.Options() {
@Override public BaseDataReader.SleepingPolicy policy() { return BaseDataReader.SleepingPolicy.BLOCKING; }
@Override public boolean sendIncompleteLines() { return false; }
@Override public boolean withSeparators() { return false; }
};
@SuppressWarnings("SpellCheckingInspection")
private enum WatcherOp { GIVEUP, RESET, UNWATCHEABLE, REMAP, MESSAGE, CREATE, DELETE, STATS, CHANGE, DIRTY, RECDIRTY }
private final class MyProcessHandler extends OSProcessHandler {
private final BufferedWriter myWriter;
private WatcherOp myLastOp;
private final List<String> myLines = new ArrayList<>();
MyProcessHandler(Process process, String commandLine) {
super(process, commandLine, CHARSET);
myWriter = new BufferedWriter(new OutputStreamWriter(process.getOutputStream(), CHARSET));
}
void writeLine(String line) throws IOException {
myWriter.write(line);
myWriter.newLine();
myWriter.flush();
}
@Override
protected @NotNull BaseOutputReader.Options readerOptions() {
return READER_OPTIONS;
}
@Override
protected void notifyProcessTerminated(int exitCode) {
super.notifyProcessTerminated(exitCode);
String message = "Watcher terminated with exit code " + exitCode;
if (myIsShuttingDown) LOG.info(message); else LOG.warn(message);
myProcessHandler = null;
try {
startupProcess(true);
}
catch (IOException e) {
shutdownProcess();
LOG.warn("Watcher terminated and attempt to restart has failed. Exiting watching thread.", e);
}
}
@Override
public void notifyTextAvailable(@NotNull String line, @NotNull Key outputType) {
if (outputType == ProcessOutputTypes.STDERR) {
LOG.warn(line);
}
if (outputType != ProcessOutputTypes.STDOUT) {
return;
}
if (LOG.isTraceEnabled()) LOG.trace(">> " + line);
if (myLastOp == null) {
WatcherOp watcherOp;
try {
watcherOp = WatcherOp.valueOf(line);
}
catch (IllegalArgumentException e) {
String message = "Illegal watcher command: '" + line + "'";
if (line.length() <= 20) message += " " + Arrays.toString(line.chars().toArray());
LOG.error(message);
return;
}
if (watcherOp == WatcherOp.GIVEUP) {
notifyOnFailure(ApplicationBundle.message("watcher.gave.up"), null);
myIsShuttingDown = true;
}
else if (watcherOp == WatcherOp.RESET) {
myNotificationSink.notifyReset(null);
}
else {
myLastOp = watcherOp;
}
}
else if (myLastOp == WatcherOp.MESSAGE) {
String localized = Objects.requireNonNullElse(ApplicationBundle.INSTANCE.messageOrNull(line), line); //NON-NLS
LOG.warn(localized);
notifyOnFailure(localized, NotificationListener.URL_OPENING_LISTENER);
myLastOp = null;
}
else if (myLastOp == WatcherOp.REMAP || myLastOp == WatcherOp.UNWATCHEABLE) {
if ("#".equals(line)) {
if (myLastOp == WatcherOp.REMAP) {
processRemap();
}
else {
mySettingRoots.decrementAndGet();
processUnwatchable();
}
myLines.clear();
myLastOp = null;
}
else {
myLines.add(line);
}
}
else {
String path = StringUtil.trimEnd(line.replace('\0', '\n'), File.separator); // unescape
processChange(path, myLastOp);
myLastOp = null;
}
}
private void processRemap() {
Set<Pair<String, String>> pairs = new HashSet<>();
for (int i = 0; i < myLines.size() - 1; i += 2) {
pairs.add(Pair.create(myLines.get(i), myLines.get(i + 1)));
}
myNotificationSink.notifyMapping(pairs);
}
private void processUnwatchable() {
myNotificationSink.notifyManualWatchRoots(myLines);
}
private void processChange(String path, WatcherOp op) {
if (SystemInfo.isWindows && op == WatcherOp.RECDIRTY) {
myNotificationSink.notifyReset(path);
return;
}
if ((op == WatcherOp.CHANGE || op == WatcherOp.STATS) && isRepetition(path)) {
if (LOG.isTraceEnabled()) LOG.trace("repetition: " + path);
return;
}
if (SystemInfo.isMac) {
path = Normalizer.normalize(path, Normalizer.Form.NFC);
}
switch (op) {
case STATS:
case CHANGE:
myNotificationSink.notifyDirtyPath(path);
break;
case CREATE:
case DELETE:
myNotificationSink.notifyPathCreatedOrDeleted(path);
break;
case DIRTY:
myNotificationSink.notifyDirtyDirectory(path);
break;
case RECDIRTY:
myNotificationSink.notifyDirtyPathRecursive(path);
break;
default:
LOG.error("Unexpected op: " + op);
}
}
}
protected boolean isRepetition(String path) {
// collapse subsequent change file change notifications that happen once we copy a large file,
// this allows reduction of path checks at least 20% for Windows
synchronized (myLastChangedPaths) {
for (int i = 0; i < myLastChangedPaths.length; ++i) {
int last = myLastChangedPathIndex - i - 1;
if (last < 0) last += myLastChangedPaths.length;
String lastChangedPath = myLastChangedPaths[last];
if (lastChangedPath != null && lastChangedPath.equals(path)) {
return true;
}
}
myLastChangedPaths[myLastChangedPathIndex++] = path;
if (myLastChangedPathIndex == myLastChangedPaths.length) myLastChangedPathIndex = 0;
}
return false;
}
//<editor-fold desc="Test stuff.">
@Override
@TestOnly
public void startup() throws IOException {
Application app = ApplicationManager.getApplication();
if (app == null || !app.isUnitTestMode()) throw new IllegalStateException();
myIsShuttingDown = false;
myStartAttemptCount.set(0);
startupProcess(false);
}
@Override
@TestOnly
public void shutdown() throws InterruptedException {
Application app = ApplicationManager.getApplication();
if (app == null || !app.isUnitTestMode()) throw new IllegalStateException();
MyProcessHandler processHandler = myProcessHandler;
if (processHandler != null) {
myIsShuttingDown = true;
shutdownProcess();
long t = System.currentTimeMillis();
while (!processHandler.isProcessTerminated()) {
if (System.currentTimeMillis() - t > 5000) {
throw new InterruptedException("Timed out waiting watcher process to terminate");
}
TimeoutUtil.sleep(100);
}
}
}
//</editor-fold>
}
| [tests] file watcher: allowing longer shutdown
GitOrigin-RevId: 5558ec88bb213fb6f531e650467af50649e72f8f | platform/platform-impl/src/com/intellij/openapi/vfs/impl/local/NativeFileWatcherImpl.java | [tests] file watcher: allowing longer shutdown | <ide><path>latform/platform-impl/src/com/intellij/openapi/vfs/impl/local/NativeFileWatcherImpl.java
<ide>
<ide> long t = System.currentTimeMillis();
<ide> while (!processHandler.isProcessTerminated()) {
<del> if (System.currentTimeMillis() - t > 5000) {
<add> if (System.currentTimeMillis() - t > 15000) {
<ide> throw new InterruptedException("Timed out waiting watcher process to terminate");
<ide> }
<ide> TimeoutUtil.sleep(100); |
|
JavaScript | mit | 836e04848773d117022196af19c810e9fba049a8 | 0 | adrian-castravete/amber,amber-smalltalk/amber,amber-smalltalk/amber,amber-smalltalk/amber,adrian-castravete/amber,adrian-castravete/amber | var path = require('path');
module.exports = function (grunt) {
var helpers = require('./external/amber-dev/lib/helpers');
grunt.loadTasks('./internal/grunt-tasks');
grunt.loadTasks('./external/amber-dev/tasks');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-requirejs');
grunt.loadNpmTasks('grunt-execute');
grunt.registerTask('default', ['peg', 'amberc:all']);
grunt.registerTask('amberc:all', ['amberc:amber', 'amberc:cli', 'amberc:dev']);
grunt.registerTask('test', ['amdconfig:amber', 'requirejs:test_runner', 'execute:test_runner', 'clean:test_runner']);
grunt.registerTask('devel', ['amdconfig:amber']);
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
meta: {
banner: '/*!\n <%= pkg.title || pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %> \n License: <%= pkg.license.type %> \n*/\n'
},
peg: {
parser: {
options: {
cache: true,
export_var: '$globals.SmalltalkParser'
},
src: 'support/parser.pegjs',
dest: 'support/parser.js'
}
},
amdconfig: {amber: {dest: 'config.js'}},
amberc: {
options: {
amber_dir: process.cwd(),
closure_jar: ''
},
amber: {
output_dir: 'src',
src: ['src/Kernel-Objects.st', 'src/Kernel-Classes.st', 'src/Kernel-Methods.st', 'src/Kernel-Collections.st',
'src/Kernel-Infrastructure.st', 'src/Kernel-Exceptions.st', 'src/Kernel-Announcements.st',
'src/Platform-Services.st', 'src/Platform-ImportExport.st', 'src/Platform-Browser.st',
'src/Compiler-Exceptions.st', 'src/Compiler-Core.st', 'src/Compiler-AST.st',
'src/Compiler-IR.st', 'src/Compiler-Inlining.st', 'src/Compiler-Semantic.st', 'src/Compiler-Interpreter.st',
'src/SUnit.st',
'src/Kernel-Tests.st', 'src/Compiler-Tests.st', 'src/SUnit-Tests.st'
],
jsGlobals: ['navigator']
},
cli: {
output_dir: 'external/amber-cli/src',
src: ['external/amber-cli/src/AmberCli.st'],
libraries: [
'Compiler-Exceptions', 'Compiler-Core', 'Compiler-AST',
'Compiler-IR', 'Compiler-Inlining', 'Compiler-Semantic', 'Compiler-Interpreter', 'parser',
'SUnit', 'Platform-ImportExport',
'Kernel-Tests', 'Compiler-Tests', 'SUnit-Tests'
],
main_class: 'AmberCli',
output_name: '../support/amber-cli',
amd_namespace: 'amber_cli'
},
dev: {
output_dir: 'external/amber-dev/lib',
src: ['external/amber-dev/lib/NodeTestRunner.st'],
amd_namespace: 'amber_devkit'
}
},
requirejs: {
test_runner: {
options: {
mainConfigFile: "config.js",
rawText: {
"app": "(" + function () {
define(["amber/devel", "amber_devkit/NodeTestRunner"], function (amber) {
amber.initialize();
amber.globals.NodeTestRunner._main();
});
} + "());"
},
paths: {"amber_devkit": helpers.libPath},
pragmas: {
// none, amber tests test contexts as well as eg. class copying which needs sources
},
include: ['config-node', 'app'],
optimize: "none",
wrap: helpers.nodeWrap('app'),
out: "test_runner.js"
}
}
},
execute: {
test_runner: {
src: ['test_runner.js']
}
},
clean: {
test_runner: ['test_runner.js']
},
jshint: {
amber: ['src/*.js', 'support/[^p]*.js'],
cli: ['external/amber-cli/src/*.js', 'external/amber-cli/support/*.js'],
dev: ['external/amber-dev/lib/*.js'],
grunt: ['Gruntfile.js', 'internal/grunt-tasks/*.js', 'external/amber-dev/tasks/*.js']
}
});
};
| Gruntfile.js | var path = require('path');
module.exports = function (grunt) {
var helpers = require('./external/amber-dev/lib/helpers');
grunt.loadTasks('./internal/grunt-tasks');
grunt.loadTasks('./external/amber-dev/tasks');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-requirejs');
grunt.loadNpmTasks('grunt-execute');
grunt.registerTask('default', ['peg', 'amberc:all']);
grunt.registerTask('amberc:all', ['amberc:amber', 'amberc:cli', 'amberc:dev']);
grunt.registerTask('test', ['requirejs:test_runner', 'execute:test_runner', 'clean:test_runner']);
grunt.registerTask('devel', ['amdconfig:amber']);
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
meta: {
banner: '/*!\n <%= pkg.title || pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %> \n License: <%= pkg.license.type %> \n*/\n'
},
peg: {
parser: {
options: {
cache: true,
export_var: '$globals.SmalltalkParser'
},
src: 'support/parser.pegjs',
dest: 'support/parser.js'
}
},
amdconfig: {amber: {dest: 'config.js'}},
amberc: {
options: {
amber_dir: process.cwd(),
closure_jar: ''
},
amber: {
output_dir: 'src',
src: ['src/Kernel-Objects.st', 'src/Kernel-Classes.st', 'src/Kernel-Methods.st', 'src/Kernel-Collections.st',
'src/Kernel-Infrastructure.st', 'src/Kernel-Exceptions.st', 'src/Kernel-Announcements.st',
'src/Platform-Services.st', 'src/Platform-ImportExport.st', 'src/Platform-Browser.st',
'src/Compiler-Exceptions.st', 'src/Compiler-Core.st', 'src/Compiler-AST.st',
'src/Compiler-IR.st', 'src/Compiler-Inlining.st', 'src/Compiler-Semantic.st', 'src/Compiler-Interpreter.st',
'src/SUnit.st',
'src/Kernel-Tests.st', 'src/Compiler-Tests.st', 'src/SUnit-Tests.st'
],
jsGlobals: ['navigator']
},
cli: {
output_dir: 'external/amber-cli/src',
src: ['external/amber-cli/src/AmberCli.st'],
libraries: [
'Compiler-Exceptions', 'Compiler-Core', 'Compiler-AST',
'Compiler-IR', 'Compiler-Inlining', 'Compiler-Semantic', 'Compiler-Interpreter', 'parser',
'SUnit', 'Platform-ImportExport',
'Kernel-Tests', 'Compiler-Tests', 'SUnit-Tests'
],
main_class: 'AmberCli',
output_name: '../support/amber-cli',
amd_namespace: 'amber_cli'
},
dev: {
output_dir: 'external/amber-dev/lib',
src: ['external/amber-dev/lib/NodeTestRunner.st'],
amd_namespace: 'amber_devkit'
}
},
requirejs: {
test_runner: {
options: {
mainConfigFile: "config.js",
rawText: {
"app": "(" + function () {
define(["amber/devel", "amber_devkit/NodeTestRunner"], function (amber) {
amber.initialize();
amber.globals.NodeTestRunner._main();
});
} + "());"
},
paths: {"amber_devkit": helpers.libPath},
pragmas: {
// none, amber tests test contexts as well as eg. class copying which needs sources
},
include: ['config-node', 'app'],
optimize: "none",
wrap: helpers.nodeWrap('app'),
out: "test_runner.js"
}
}
},
execute: {
test_runner: {
src: ['test_runner.js']
}
},
clean: {
test_runner: ['test_runner.js']
},
jshint: {
amber: ['src/*.js', 'support/[^p]*.js'],
cli: ['external/amber-cli/src/*.js', 'external/amber-cli/support/*.js'],
dev: ['external/amber-dev/lib/*.js'],
grunt: ['Gruntfile.js', 'internal/grunt-tasks/*.js', 'external/amber-dev/tasks/*.js']
}
});
};
| Gruntfile: test generates config.js first
| Gruntfile.js | Gruntfile: test generates config.js first | <ide><path>runtfile.js
<ide>
<ide> grunt.registerTask('default', ['peg', 'amberc:all']);
<ide> grunt.registerTask('amberc:all', ['amberc:amber', 'amberc:cli', 'amberc:dev']);
<del> grunt.registerTask('test', ['requirejs:test_runner', 'execute:test_runner', 'clean:test_runner']);
<add> grunt.registerTask('test', ['amdconfig:amber', 'requirejs:test_runner', 'execute:test_runner', 'clean:test_runner']);
<ide> grunt.registerTask('devel', ['amdconfig:amber']);
<ide>
<ide> grunt.initConfig({ |
|
JavaScript | mit | cdf5888c834afb4daece8a0729f60ba1d3f43fd5 | 0 | vanoden/Porkchop,vanoden/Porkchop,vanoden/Porkchop,vanoden/Porkchop | const gulp = require('gulp');
const template = require('gulp-template');
const data = require('gulp-data');
const debug = require('gulp-debug');
const fs = require('fs');
var preProcessPath = 'html.src/pre';
var postProcessPath = 'tmp';
var today = new Date();
var month = today.getMonth() + 1;
const configJSON = fs.readFileSync('html.src/gulp_config.json');
const configDict = JSON.parse(configJSON);
const videoPath = configDict.videoPath;
const docsPath = configDict.docsPath;
//const staticVersion = today.getFullYear()+"."+month+"."+today.getDate()+"."+today.getHours()+"."+today.getMinutes();
const staticVersion = "20220925";
//const contentBlocks = fs.readFileSync('html.src/gulp_contentBlocks.js');
htmlBlocks = {
"header": "header.html",
"footer": "footer.html",
"footer_monitor": "footer.monitor.html",
"header_2022": "header_2022.html"
};
html2process = {
"static_version": staticVersion,
"video_path": videoPath,
"docs_path": docsPath,
"company_name": configDict.companyName,
"company": configDict.companyCode
};
for (const key in htmlBlocks) {
if (fs.existsSync(postProcessPath+'/'+htmlBlocks[key])) {
console.log(key + ' found');
html2process[key] = fs.readFileSync(postProcessPath+'/'+htmlBlocks[key], 'utf8');
}
else {
console.log(key + ' NOT found');
}
}
gulp.task('hello', function() {
console.log('Hello, Tony');
});
gulp.task('process', ['pre','js','css','jpegs','pngs','svg','gif','ico', 'dashboards'], () =>
gulp.src('html.src/**/*.html')
.pipe(data(() => (html2process)))
.pipe(template())
.pipe(debug())
.pipe(gulp.dest('html'))
);
gulp.task('pre', () =>
gulp.src(preProcessPath+'/*.html')
.pipe(data(() => (
{
"static_version": staticVersion,
"video_path": videoPath,
"docs_path": docsPath,
"header": fs.readFileSync(preProcessPath+'/header.html', 'utf8'),
"footer": fs.readFileSync(preProcessPath+'/footer.html', 'utf8'),
"title": 'Interscan Corporation'
}
)))
.pipe(template().on('error',function(e){
console.log(e);
}))
.pipe(debug())
.pipe(gulp.dest(postProcessPath))
);
gulp.task('js', () =>
gulp.src('html.src/**/*.js')
.pipe(data(() => (
{
"field": "content",
"static_version": staticVersion,
"num": "${num}"
}
)))
.pipe(template())
.pipe(debug())
.pipe(gulp.dest('html'))
);
gulp.task('css', () =>
gulp.src('html.src/**/*.css')
.pipe(data(() => (
{ "field": "content" }
)))
.pipe(template())
.pipe(debug())
.pipe(gulp.dest('html'))
);
gulp.task('pngs', () =>
gulp.src('html.src/**/*.png')
.pipe(debug())
.pipe(gulp.dest('html'))
);
gulp.task('svg', () =>
gulp.src('html.src/**/*.svg')
.pipe(debug())
.pipe(gulp.dest('html'))
);
gulp.task('jpegs', () =>
gulp.src('html.src/**/*.jpg')
.pipe(debug())
.pipe(gulp.dest('html'))
);
gulp.task('gif', () =>
gulp.src('html.src/**/*.gif')
.pipe(debug())
.pipe(gulp.dest('html'))
);
gulp.task('ico', () =>
gulp.src('html.src/**/*.ico')
.pipe(debug())
.pipe(gulp.dest('html'))
);
gulp.task('dashboards', () =>
gulp.src('html.src/dashboards/**/*.html')
.pipe(debug())
.pipe(gulp.dest('html'))
);
| gulpfile.js | const gulp = require('gulp');
const template = require('gulp-template');
const data = require('gulp-data');
const debug = require('gulp-debug');
const fs = require('fs');
var preProcessPath = 'html.src/pre';
var today = new Date();
var month = today.getMonth() + 1;
const configJSON = fs.readFileSync('html.src/gulp_config.json');
const configDict = JSON.parse(configJSON);
const videoPath = configDict.videoPath;
const docsPath = configDict.docsPath;
const staticVersion = today.getFullYear()+"."+month+"."+today.getDate()+"."+today.getHours()+"."+today.getMinutes();
//const contentBlocks = fs.readFileSync('html.src/gulp_contentBlocks.js');
htmlBlocks = {
"header": "header.html",
"footer": "footer.html",
"footer_monitor": "footer.monitor.html",
"header_2022": "header_2022.html"
};
html2process = {
"static_version": staticVersion,
"video_path": videoPath,
"docs_path": docsPath,
"company_name": configDict.companyName,
"company": configDict.companyCode
};
for (const key in htmlBlocks) {
if (fs.existsSync(preProcessPath+'/'+htmlBlocks[key])) {
console.log(key + ' found');
html2process[key] = fs.readFileSync(preProcessPath+'/'+htmlBlocks[key], 'utf8');
}
else {
console.log(key + ' NOT found');
}
}
gulp.task('hello', function() {
console.log('Hello, Tony');
});
gulp.task('process', ['pre','js','css','jpegs','pngs','svg','gif','ico', 'dashboards'], () =>
gulp.src('html.src/**/*.html')
.pipe(data(() => (html2process)))
.pipe(template())
.pipe(debug())
.pipe(gulp.dest('html'))
);
gulp.task('pre', () =>
gulp.src(preProcessPath+'/*.html')
.pipe(data(() => (
{
"static_version": staticVersion,
"video_path": videoPath,
"docs_path": docsPath,
"header": fs.readFileSync(preProcessPath+'/header.html', 'utf8'),
"footer": fs.readFileSync(preProcessPath+'/footer.html', 'utf8'),
"title": 'Interscan Corporation'
}
)))
.pipe(template().on('error',function(e){
console.log(e);
}))
.pipe(debug())
.pipe(gulp.dest('tmp'))
);
gulp.task('js', () =>
gulp.src('html.src/**/*.js')
.pipe(data(() => (
{
"field": "content",
"static_version": staticVersion,
"num": "${num}"
}
)))
.pipe(template())
.pipe(debug())
.pipe(gulp.dest('html'))
);
gulp.task('css', () =>
gulp.src('html.src/**/*.css')
.pipe(data(() => (
{ "field": "content" }
)))
.pipe(template())
.pipe(debug())
.pipe(gulp.dest('html'))
);
gulp.task('pngs', () =>
gulp.src('html.src/**/*.png')
.pipe(debug())
.pipe(gulp.dest('html'))
);
gulp.task('svg', () =>
gulp.src('html.src/**/*.svg')
.pipe(debug())
.pipe(gulp.dest('html'))
);
gulp.task('jpegs', () =>
gulp.src('html.src/**/*.jpg')
.pipe(debug())
.pipe(gulp.dest('html'))
);
gulp.task('gif', () =>
gulp.src('html.src/**/*.gif')
.pipe(debug())
.pipe(gulp.dest('html'))
);
gulp.task('ico', () =>
gulp.src('html.src/**/*.ico')
.pipe(debug())
.pipe(gulp.dest('html'))
);
gulp.task('dashboards', () =>
gulp.src('html.src/dashboards/**/*.html')
.pipe(debug())
.pipe(gulp.dest('html'))
);
| Fixed gulp preprocessing
| gulpfile.js | Fixed gulp preprocessing | <ide><path>ulpfile.js
<ide> const fs = require('fs');
<ide>
<ide> var preProcessPath = 'html.src/pre';
<add>var postProcessPath = 'tmp';
<ide> var today = new Date();
<ide> var month = today.getMonth() + 1;
<ide>
<ide>
<ide> const videoPath = configDict.videoPath;
<ide> const docsPath = configDict.docsPath;
<del>const staticVersion = today.getFullYear()+"."+month+"."+today.getDate()+"."+today.getHours()+"."+today.getMinutes();
<add>//const staticVersion = today.getFullYear()+"."+month+"."+today.getDate()+"."+today.getHours()+"."+today.getMinutes();
<add>const staticVersion = "20220925";
<ide>
<ide> //const contentBlocks = fs.readFileSync('html.src/gulp_contentBlocks.js');
<ide>
<ide> };
<ide>
<ide> for (const key in htmlBlocks) {
<del> if (fs.existsSync(preProcessPath+'/'+htmlBlocks[key])) {
<add> if (fs.existsSync(postProcessPath+'/'+htmlBlocks[key])) {
<ide> console.log(key + ' found');
<del> html2process[key] = fs.readFileSync(preProcessPath+'/'+htmlBlocks[key], 'utf8');
<add> html2process[key] = fs.readFileSync(postProcessPath+'/'+htmlBlocks[key], 'utf8');
<ide> }
<ide> else {
<ide> console.log(key + ' NOT found');
<ide> );
<ide>
<ide> gulp.task('pre', () =>
<del> gulp.src(preProcessPath+'/*.html')
<del> .pipe(data(() => (
<del> {
<del> "static_version": staticVersion,
<add> gulp.src(preProcessPath+'/*.html')
<add> .pipe(data(() => (
<add> {
<add> "static_version": staticVersion,
<ide> "video_path": videoPath,
<ide> "docs_path": docsPath,
<del> "header": fs.readFileSync(preProcessPath+'/header.html', 'utf8'),
<del> "footer": fs.readFileSync(preProcessPath+'/footer.html', 'utf8'),
<add> "header": fs.readFileSync(preProcessPath+'/header.html', 'utf8'),
<add> "footer": fs.readFileSync(preProcessPath+'/footer.html', 'utf8'),
<ide> "title": 'Interscan Corporation'
<del> }
<del> )))
<del> .pipe(template().on('error',function(e){
<add> }
<add> )))
<add> .pipe(template().on('error',function(e){
<ide> console.log(e);
<ide> }))
<del> .pipe(debug())
<del> .pipe(gulp.dest('tmp'))
<add> .pipe(debug())
<add> .pipe(gulp.dest(postProcessPath))
<ide> );
<ide>
<ide> gulp.task('js', () => |
|
JavaScript | mit | 73df384a0f8b817bc0f9b87f7ff64f9a96a62a65 | 0 | RalphSleigh/bookings,RalphSleigh/bookings,RalphSleigh/bookings | import {
Email,
Box,
Item,
Span,
A,
renderEmail
} from 'react-html-email'
import React from 'react'
import ReactMarkdown from 'react-markdown'
import feeFactory from '../../shared/fee/feeFactory.js'
const config = require('../../config');
export function html(values) {
return renderEmail(
<Email title={`Application Approved for ${values.event.name}`}>
<Item>
<p> Hi {values.user.userName}</p>
<p>You have been approved to book into {values.event.name} and can do so at any time here:</p>
<p><A href={config.BASE_PATH}>{config.BASE_PATH}</A></p>
</Item>
<Item>
<p>Blue Skies</p>
<p>Woodcraft Folk</p>
</Item>
</Email>
)
}
export function subject(values) {
return `Application Approved for ${values.event.name}`
} | server/emails/applicationApproved.js | import {
Email,
Box,
Item,
Span,
A,
renderEmail
} from 'react-html-email'
import React from 'react'
import ReactMarkdown from 'react-markdown'
import feeFactory from '../../shared/fee/feeFactory.js'
const config = require('../../config');
export function html(values) {
return renderEmail(
<Email title={`Application Approved for ${values.event.name}`}>
<Item>
<p> Hi {values.user.userName}</p>
<p>You have been approved to book into {values.event.name} and can do so at any time here:</p>
<p><A href={config.BASE_PATH}>{config.BASE_PATH}</A></p>
</Item>
<Item>
<p>Blue Skies</p>
<p>Woodcraft Folk</p>
</Item>
</Email>
)
}
export function subject(values) {
return `Application Approved for ${values.name}`
} | Add note to Roles
| server/emails/applicationApproved.js | Add note to Roles | <ide><path>erver/emails/applicationApproved.js
<ide> }
<ide>
<ide> export function subject(values) {
<del> return `Application Approved for ${values.name}`
<add> return `Application Approved for ${values.event.name}`
<ide> } |
|
Java | apache-2.0 | error: pathspec 'src/main/java/com/scavi/brainsqueeze/adventofcode2016/Day1NoTimeForATaxicab.java' did not match any file(s) known to git
| 33bb1b3be320434f44d3a70c75c331c59cfd9b9e | 1 | Scavi/BrainSqueeze | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.scavi.brainsqueeze.adventofcode2016;
import com.google.common.base.Preconditions;
import java.util.Locale;
import java.util.regex.Pattern;
import static com.scavi.brainsqueeze.adventofcode2016.Day1NoTimeForATaxicab.Direction.R;
import static com.scavi.brainsqueeze.adventofcode2016.Day1NoTimeForATaxicab.Heading.East;
import static com.scavi.brainsqueeze.adventofcode2016.Day1NoTimeForATaxicab.Heading.North;
import static com.scavi.brainsqueeze.adventofcode2016.Day1NoTimeForATaxicab.Heading.South;
import static com.scavi.brainsqueeze.adventofcode2016.Day1NoTimeForATaxicab.Heading.West;
/**
* Solves the question: http://adventofcode.com/2016/day/1
*
* @author Michael Heymel
* @since 01/12/16
*/
class Day1NoTimeForATaxicab {
enum Heading {North, East, West, South}
enum Direction {
R, L;
}
/**
* Determines the shortest
*
* @param movementSequence the given movement sequence
* @return the shortest distance
*/
public int shortestDistance(final Move... movementSequence) {
Preconditions.checkNotNull(movementSequence, "Illegal movement sequence: <null>");
Preconditions.checkArgument(movementSequence.length > 0,
"Illegal movement sequence: 0 instructions");
int xPos = 0;
int yPos = 0;
Heading heading = null;
for (Move move : movementSequence) {
heading = determineHeading(heading, move);
switch (heading) {
case North:
yPos += move.getSteps();
break;
case East:
xPos += move.getSteps();
break;
case South:
yPos -= move.getSteps();
break;
case West:
xPos -= move.getSteps();
break;
}
}
return Math.abs(xPos) + Math.abs(yPos);
}
/**
* Determines the new heading
*
* @param currentHeading the current heading
* @param nextMove the next move
* @return the new heading
*/
private Heading determineHeading(final Heading currentHeading, final Move nextMove) {
Heading newHeading;
if (currentHeading == null) {
newHeading = nextMove.getDirection() == R ? East : West;
} else {
switch (currentHeading) {
case North:
newHeading = nextMove.getDirection() == R ? East : West;
break;
case East:
newHeading = nextMove.getDirection() == R ? South : North;
break;
case South:
newHeading = nextMove.getDirection() == R ? West : East;
break;
case West:
newHeading = nextMove.getDirection() == R ? North : South;
break;
default:
throw new IllegalArgumentException(
"Unsupported heading type: " + currentHeading);
}
}
return newHeading;
}
static class Move {
private final Direction _direction;
private final int _steps;
/**
* Constructor
*
* @param steps the amount of steps into the direction
* @param direction the direction
*/
public Move(final Direction direction, final int steps) {
_direction = direction;
_steps = steps;
}
/**
* @return the amount of steps into the direction
*/
public Direction getDirection() {
return _direction;
}
/**
* @return the direction
*/
public int getSteps() {
return _steps;
}
public static Move[] from(final String input) {
Pattern inputValidation = Pattern.compile("(L|R)\\d+");
String[] moveInput = input.toUpperCase(Locale.getDefault()).split("\\s*,\\s*");
Move[] moves = new Move[moveInput.length];
for (int i = 0; i < moveInput.length; ++i) {
Preconditions.checkArgument(inputValidation.matcher(moveInput[i]).matches(),
String.format(
"Unsupported movement instruction: %s. A direction and steps must be specified",
moveInput[i]));
Direction direction = Direction.valueOf(moveInput[i].substring(0, 1));
int steps = Integer.parseInt(moveInput[i].substring(1));
moves[i] = new Move(direction, steps);
}
return moves;
}
}
}
| src/main/java/com/scavi/brainsqueeze/adventofcode2016/Day1NoTimeForATaxicab.java | solution for day one of advent of code
| src/main/java/com/scavi/brainsqueeze/adventofcode2016/Day1NoTimeForATaxicab.java | solution for day one of advent of code | <ide><path>rc/main/java/com/scavi/brainsqueeze/adventofcode2016/Day1NoTimeForATaxicab.java
<add>/*
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>/*
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package com.scavi.brainsqueeze.adventofcode2016;
<add>
<add>import com.google.common.base.Preconditions;
<add>
<add>import java.util.Locale;
<add>import java.util.regex.Pattern;
<add>
<add>import static com.scavi.brainsqueeze.adventofcode2016.Day1NoTimeForATaxicab.Direction.R;
<add>import static com.scavi.brainsqueeze.adventofcode2016.Day1NoTimeForATaxicab.Heading.East;
<add>import static com.scavi.brainsqueeze.adventofcode2016.Day1NoTimeForATaxicab.Heading.North;
<add>import static com.scavi.brainsqueeze.adventofcode2016.Day1NoTimeForATaxicab.Heading.South;
<add>import static com.scavi.brainsqueeze.adventofcode2016.Day1NoTimeForATaxicab.Heading.West;
<add>
<add>/**
<add> * Solves the question: http://adventofcode.com/2016/day/1
<add> *
<add> * @author Michael Heymel
<add> * @since 01/12/16
<add> */
<add>class Day1NoTimeForATaxicab {
<add> enum Heading {North, East, West, South}
<add>
<add> enum Direction {
<add> R, L;
<add> }
<add>
<add>
<add> /**
<add> * Determines the shortest
<add> *
<add> * @param movementSequence the given movement sequence
<add> * @return the shortest distance
<add> */
<add> public int shortestDistance(final Move... movementSequence) {
<add> Preconditions.checkNotNull(movementSequence, "Illegal movement sequence: <null>");
<add> Preconditions.checkArgument(movementSequence.length > 0,
<add> "Illegal movement sequence: 0 instructions");
<add>
<add> int xPos = 0;
<add> int yPos = 0;
<add> Heading heading = null;
<add>
<add> for (Move move : movementSequence) {
<add> heading = determineHeading(heading, move);
<add>
<add> switch (heading) {
<add> case North:
<add> yPos += move.getSteps();
<add> break;
<add> case East:
<add> xPos += move.getSteps();
<add> break;
<add> case South:
<add> yPos -= move.getSteps();
<add> break;
<add> case West:
<add> xPos -= move.getSteps();
<add> break;
<add> }
<add> }
<add> return Math.abs(xPos) + Math.abs(yPos);
<add> }
<add>
<add>
<add> /**
<add> * Determines the new heading
<add> *
<add> * @param currentHeading the current heading
<add> * @param nextMove the next move
<add> * @return the new heading
<add> */
<add> private Heading determineHeading(final Heading currentHeading, final Move nextMove) {
<add> Heading newHeading;
<add> if (currentHeading == null) {
<add> newHeading = nextMove.getDirection() == R ? East : West;
<add> } else {
<add> switch (currentHeading) {
<add> case North:
<add> newHeading = nextMove.getDirection() == R ? East : West;
<add> break;
<add> case East:
<add> newHeading = nextMove.getDirection() == R ? South : North;
<add> break;
<add> case South:
<add> newHeading = nextMove.getDirection() == R ? West : East;
<add> break;
<add> case West:
<add> newHeading = nextMove.getDirection() == R ? North : South;
<add> break;
<add> default:
<add> throw new IllegalArgumentException(
<add> "Unsupported heading type: " + currentHeading);
<add> }
<add> }
<add> return newHeading;
<add> }
<add>
<add>
<add> static class Move {
<add> private final Direction _direction;
<add> private final int _steps;
<add>
<add>
<add> /**
<add> * Constructor
<add> *
<add> * @param steps the amount of steps into the direction
<add> * @param direction the direction
<add> */
<add> public Move(final Direction direction, final int steps) {
<add> _direction = direction;
<add> _steps = steps;
<add> }
<add>
<add>
<add> /**
<add> * @return the amount of steps into the direction
<add> */
<add> public Direction getDirection() {
<add> return _direction;
<add> }
<add>
<add>
<add> /**
<add> * @return the direction
<add> */
<add> public int getSteps() {
<add> return _steps;
<add> }
<add>
<add>
<add> public static Move[] from(final String input) {
<add>
<add> Pattern inputValidation = Pattern.compile("(L|R)\\d+");
<add> String[] moveInput = input.toUpperCase(Locale.getDefault()).split("\\s*,\\s*");
<add> Move[] moves = new Move[moveInput.length];
<add>
<add> for (int i = 0; i < moveInput.length; ++i) {
<add> Preconditions.checkArgument(inputValidation.matcher(moveInput[i]).matches(),
<add> String.format(
<add> "Unsupported movement instruction: %s. A direction and steps must be specified",
<add> moveInput[i]));
<add> Direction direction = Direction.valueOf(moveInput[i].substring(0, 1));
<add> int steps = Integer.parseInt(moveInput[i].substring(1));
<add> moves[i] = new Move(direction, steps);
<add> }
<add>
<add> return moves;
<add> }
<add> }
<add>} |
|
JavaScript | mit | cfb35269be4b4ca5df47d27be3acd144f8c39bfe | 0 | chartjs/chartjs-plugin-annotation,chartjs/chartjs-plugin-annotation,chartjs/chartjs-plugin-annotation | const istanbul = require('rollup-plugin-istanbul');
const json = require('@rollup/plugin-json');
const resolve = require('@rollup/plugin-node-resolve').default;
const builds = require('./rollup.config');
const yargs = require('yargs');
const env = process.env.NODE_ENV;
module.exports = function(karma) {
const args = yargs
.option('verbose', {default: false})
.argv;
// Use the same rollup config as our dist files: when debugging (npm run dev),
// we will prefer the unminified build which is easier to browse and works
// better with source mapping. In other cases, pick the minified build to
// make sure that the minification process (terser) doesn't break anything.
const regex = karma.autoWatch ? /chartjs-plugin-annotation\.js$/ : /chartjs-plugin-annotation\.min\.js$/;
const build = builds.filter(v => v.output.file && v.output.file.match(regex))[0];
if (env === 'test') {
build.plugins = [
json(),
resolve(),
istanbul({exclude: ['node_modules/**/*.js', 'package.json']})
];
}
karma.set({
frameworks: ['jasmine'],
reporters: ['progress', 'kjhtml'],
browsers: (args.browsers || 'chrome,firefox').split(','),
logLevel: karma.LOG_INFO,
client: {
jasmine: {
failFast: !!karma.autoWatch
}
},
// Explicitly disable hardware acceleration to make image
// diff more stable when ran on Travis and dev machine.
// https://github.com/chartjs/Chart.js/pull/5629
customLaunchers: {
chrome: {
base: 'Chrome',
flags: [
'--disable-accelerated-2d-canvas'
]
},
firefox: {
base: 'Firefox',
prefs: {
'layers.acceleration.disabled': true
}
}
},
files: [
{pattern: 'test/fixtures/**/*.js', included: false},
{pattern: 'test/fixtures/**/*.png', included: false},
{pattern: 'node_modules/chart.js/dist/chart.js'},
{pattern: 'src/index.js', watched: false},
{pattern: 'test/index.js'},
{pattern: 'test/specs/**/**.js'}
],
preprocessors: {
'src/index.js': ['sources'],
'test/index.js': ['rollup']
},
rollupPreprocessor: {
plugins: [
resolve(),
],
output: {
name: 'test',
format: 'umd',
sourcemap: karma.autoWatch ? 'inline' : false
}
},
customPreprocessors: {
sources: {
base: 'rollup',
options: build
}
},
// These settings deal with browser disconnects. We had seen test flakiness from Firefox
// [Firefox 56.0.0 (Linux 0.0.0)]: Disconnected (1 times), because no message in 10000 ms.
// https://github.com/jasmine/jasmine/issues/1327#issuecomment-332939551
captureTimeout: 120000,
browserDisconnectTimeout: 120000,
browserDisconnectTolerance: 3,
browserNoActivityTimeout: 120000,
});
if (env === 'test') {
karma.reporters.push('coverage');
karma.coverageReporter = {
dir: 'coverage/',
reporters: [
{type: 'html', subdir: 'html'},
{type: 'lcovonly', subdir: (browser) => browser.toLowerCase().split(/[ /-]/)[0]}
]
};
}
};
| karma.conf.js | const istanbul = require('rollup-plugin-istanbul');
const json = require('@rollup/plugin-json');
const resolve = require('@rollup/plugin-node-resolve').default;
const builds = require('./rollup.config');
const yargs = require('yargs');
const env = process.env.NODE_ENV;
module.exports = function(karma) {
const args = yargs
.option('verbose', {default: false})
.argv;
// Use the same rollup config as our dist files: when debugging (npm run dev),
// we will prefer the unminified build which is easier to browse and works
// better with source mapping. In other cases, pick the minified build to
// make sure that the minification process (terser) doesn't break anything.
const regex = karma.autoWatch ? /chartjs-plugin-annotation\.js$/ : /chartjs-plugin-annotation\.min\.js$/;
const build = builds.filter(v => v.output.file && v.output.file.match(regex))[0];
if (env === 'test') {
build.plugins = [
json(),
resolve(),
istanbul({exclude: ['node_modules/**/*.js', 'package.json']})
];
}
karma.set({
frameworks: ['jasmine'],
reporters: ['progress', 'kjhtml'],
browsers: (args.browsers || 'chrome,firefox').split(','),
logLevel: karma.LOG_INFO,
client: {
jasmine: {
failFast: !!karma.autoWatch
}
},
// Explicitly disable hardware acceleration to make image
// diff more stable when ran on Travis and dev machine.
// https://github.com/chartjs/Chart.js/pull/5629
customLaunchers: {
chrome: {
base: 'Chrome',
flags: [
'--disable-accelerated-2d-canvas'
]
},
firefox: {
base: 'Firefox',
prefs: {
'layers.acceleration.disabled': true
}
}
},
files: [
{pattern: 'test/fixtures/**/*.js', included: false},
{pattern: 'test/fixtures/**/*.png', included: false},
{pattern: 'node_modules/chart.js/dist/chart.js'},
{pattern: 'src/index.js', watched: false},
{pattern: 'test/index.js'},
{pattern: 'test/specs/**/**.js'}
],
preprocessors: {
'src/index.js': ['sources'],
'test/index.js': ['rollup']
},
rollupPreprocessor: {
plugins: [
resolve(),
],
output: {
name: 'test',
format: 'umd',
sourcemap: karma.autoWatch ? 'inline' : false
}
},
customPreprocessors: {
sources: {
base: 'rollup',
options: build
}
},
// These settings deal with browser disconnects. We had seen test flakiness from Firefox
// [Firefox 56.0.0 (Linux 0.0.0)]: Disconnected (1 times), because no message in 10000 ms.
// https://github.com/jasmine/jasmine/issues/1327#issuecomment-332939551
browserDisconnectTolerance: 3
});
if (env === 'test') {
karma.reporters.push('coverage');
karma.coverageReporter = {
dir: 'coverage/',
reporters: [
{type: 'html', subdir: 'html'},
{type: 'lcovonly', subdir: (browser) => browser.toLowerCase().split(/[ /-]/)[0]}
]
};
}
};
| Insane timeouts for insanely slow actions (#392)
| karma.conf.js | Insane timeouts for insanely slow actions (#392) | <ide><path>arma.conf.js
<ide> // These settings deal with browser disconnects. We had seen test flakiness from Firefox
<ide> // [Firefox 56.0.0 (Linux 0.0.0)]: Disconnected (1 times), because no message in 10000 ms.
<ide> // https://github.com/jasmine/jasmine/issues/1327#issuecomment-332939551
<del> browserDisconnectTolerance: 3
<add> captureTimeout: 120000,
<add> browserDisconnectTimeout: 120000,
<add> browserDisconnectTolerance: 3,
<add> browserNoActivityTimeout: 120000,
<ide> });
<ide>
<ide> if (env === 'test') { |
|
Java | apache-2.0 | e871ae96780686973aca08e3a3388299b1999343 | 0 | vietansegan/gtpounder | package util.govtrack;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import util.IOUtils;
import util.MiscUtils;
/**
* Here are some major differences of this pre-processing pipeline compared to
* GTProcessor:
*
* 1. Associate each turn with a bill so that each debate can be divided into
* smaller segments, each talking about a bill.
*
* @author vietan
*/
public class GTProcessorV2 extends GTProcessor {
public static final String DATETIME = "datetime";
public GTProcessorV2() {
super();
}
public GTProcessorV2(String folder, int congNum) {
super(folder, congNum);
}
// === Processing debates ==================================================
@Override
public void processDebates() {
File crFolder = new File(this.congressFolder, "cr");
if (!crFolder.exists()) {
throw new RuntimeException(crFolder + " not found.");
}
if (verbose) {
System.out.println("Processing debates " + crFolder.getAbsolutePath() + " ...");
}
this.debates = new HashMap<String, GTDebate>();
String[] debateFilenames = crFolder.list();
int count = 0;
int stepSize = MiscUtils.getRoundStepSize(debateFilenames.length, 10);
for (String filename : debateFilenames) {
if (count % stepSize == 0 && verbose) {
System.out.println("--- Processing debate file "
+ count + " / " + debateFilenames.length);
}
count++;
File debateFile = new File(crFolder, filename);
if (debateFile.length() == 0) {
if (verbose) {
System.out.println("--- --- Skipping empty file " + debateFile);
}
continue;
}
GTDebate debate = processSingleDebate(debateFile);
this.debates.put(debate.getId(), debate);
}
if (verbose) {
System.out.println("--- Loaded " + debates.size() + " debates");
int numDebatesMentioningBill = 0;
for (GTDebate debate : debates.values()) {
if (debate.getBillAssociatedWith() != null) {
numDebatesMentioningBill++;
}
}
System.out.println("--- --- # debates having bill(s) mentioned by speakers: "
+ numDebatesMentioningBill);
}
}
public GTDebate processSingleDebate(File debateFile) {
Element docEle;
NodeList nodelist;
Element el;
try {
docEle = getDocumentElement(debateFile.getAbsolutePath());
} catch (Exception e) {
if (verbose) {
System.out.println("--- --- Skipping problematic debate file "
+ debateFile);
e.printStackTrace();
}
return null;
}
String title = docEle.getAttribute("title");
String where = docEle.getAttribute("where");
String datetime = docEle.getAttribute(DATETIME);
String debateId = IOUtils.removeExtension(debateFile.getName());
GTDebate debate = new GTDebate(debateId);
debate.setTitle(title);
debate.addProperty("where", where);
debate.addProperty(DATETIME, datetime);
// list of turns
GTTurn preTurn = null;
int turnCount = 0;
nodelist = docEle.getElementsByTagName("speaking");
for (int i = 0; i < nodelist.getLength(); i++) {
el = (Element) nodelist.item(i);
String speaker = el.getAttribute("speaker");
String topic = el.getAttribute("topic");
// get contents
StringBuilder text = new StringBuilder();
ArrayList<String> paraBillsMentioned = new ArrayList<String>();
NodeList nl = el.getElementsByTagName("paragraph");
for (int j = 0; j < nl.getLength(); j++) {
Element turnEle = (Element) nl.item(j);
// text
String paraText = turnEle.getTextContent();
if (filterOut(paraText)) {
continue;
}
text.append(paraText).append(" ");
// bills mentioned
NodeList billNl = turnEle.getElementsByTagName("bill");
for (int ii = 0; ii < billNl.getLength(); ii++) {
Element billEl = (Element) billNl.item(ii);
String billType = billEl.getAttribute("type");
String billNumber = billEl.getAttribute("number");
String billId = billType + "-" + billNumber;
paraBillsMentioned.add(billId);
debate.addBillMentioned(billId);
}
}
// merge consecutive turns are from the same speaker
if (preTurn != null && preTurn.getSpeakerId().equals(speaker)) {
String preTurnText = preTurn.getText();
preTurnText += " " + text.toString();
preTurn.setText(preTurnText);
preTurn.addBillsMentioned(paraBillsMentioned);
} else { // or create a new turn
GTTurn turn = new GTTurn(
debateId + "_" + turnCount,
speaker,
procecessText(text.toString()));
turn.setBillsMentioned(paraBillsMentioned);
if (!topic.trim().isEmpty()) {
turn.addProperty("topic", topic);
}
debate.addTurn(turn);
preTurn = turn;
turnCount++;
}
}
// estimate main bill mentioned for each turn
if (debate.getBillsMentioned().size() > 0) {
estimateTurnMainBillMentioned(debate);
}
return debate;
}
/**
* Fill in the main bill mentioned for every turn in the debate. If a turn
* does not explicitly mention a bill, the bill mentioned in the most recent
* turn is used to associate with this turn.
*/
public void estimateTurnMainBillMentioned(GTDebate debate) {
String firstBillMentioned = null;
int firstTurnMentioning = -1;
for (int ii = 0; ii < debate.getNumTurns(); ii++) {
GTTurn turn = debate.getTurn(ii);
String billAssoc = turn.getBillAssociatedWith();
if (billAssoc != null) {
firstBillMentioned = billAssoc;
firstTurnMentioning = ii;
}
}
for (int ii = 0; ii <= firstTurnMentioning; ii++) {
debate.getTurn(ii).setMainBillMentioned(firstBillMentioned);
}
String curBillMentioned = firstBillMentioned;
for (int ii = firstTurnMentioning + 1; ii < debate.getNumTurns(); ii++) {
GTTurn turn = debate.getTurn(ii);
String billAssoc = turn.getBillAssociatedWith();
if (billAssoc == null) {
turn.setMainBillMentioned(curBillMentioned);
} else {
turn.setMainBillMentioned(billAssoc);
curBillMentioned = billAssoc;
}
}
}
protected boolean filterOut(String paraText) {
if (paraText.contains("I yield")
|| containBillText(paraText)) {
return true;
}
return false;
}
protected String procecessText(String text) {
return text.replaceAll("\n", " ")
// .replace("nbsp", "")
.replace("&", "");
}
protected boolean containBillText(String text) {
if (text.contains("nbsp")
|| text.contains("<p>")
|| text.contains("<em>")) {
return true;
}
return false;
}
// === End processing debates ==============================================
// === Start processing bills ==============================================
@Override
public void processBills() {
File billFolder = new File(this.congressFolder, "bills");
if (!billFolder.exists()) {
throw new RuntimeException(billFolder + " not found.");
}
File billTextFolder = new File(this.congressFolder, "bills.html");
if (!billTextFolder.exists()) {
throw new RuntimeException(billTextFolder + " not found.");
}
if (verbose) {
System.out.println("\nProcessing bills " + billFolder);
}
this.bills = new HashMap<String, GTBill>();
String[] billFilenames = billFolder.list();
int count = 0;
int stepSize = MiscUtils.getRoundStepSize(billFilenames.length, 10);
for (String billFilename : billFilenames) {
// debug
if (count % stepSize == 0 && verbose) {
System.out.println("--- Processing bill file "
+ count + " / " + billFilenames.length);
}
count++;
File billFile = new File(billFolder, billFilename);
File billTextFile = new File(billTextFolder, billFilename.replaceAll("xml", "txt"));
if (!billTextFile.exists() && verbose) {
System.out.println("--- --- Skipping bill " + billTextFile
+ ". No text found.");
continue;
}
Element docEle;
try {
docEle = getDocumentElement(billFile.getAbsolutePath());
} catch (Exception e) {
if (verbose) {
System.out.println("--- --- Skipping problematic bill file "
+ billFile);
e.printStackTrace();
}
continue;
}
NodeList nodelist;
Element element;
// create bill
String billType = docEle.getAttribute("type");
int billNumber = Integer.parseInt(docEle.getAttribute("number"));
GTBill bill = new GTBill(billType, billNumber);
// titles
nodelist = docEle.getElementsByTagName("title");
for (int ii = 0; ii < nodelist.getLength(); ii++) {
element = (Element) nodelist.item(ii);
String type = element.getAttribute("type");
String title = element.getTextContent();
if (type.equals("popular")) {
bill.setTitle(title);
} else if (type.equals("official")) {
bill.setOfficialTitle(title);
}
}
// subjects (labels) of this bill
ArrayList<String> subjects = new ArrayList<String>();
nodelist = docEle.getElementsByTagName("term");
for (int i = 0; i < nodelist.getLength(); i++) {
element = (Element) nodelist.item(i);
subjects.add(element.getAttribute("name"));
}
bill.setSubjects(subjects);
// bill summary
nodelist = docEle.getElementsByTagName("summary");
element = (Element) nodelist.item(0);
String summary = element.getTextContent();
bill.setSummary(summary);
// bill text
String billText = inputBillText(billTextFile);
bill.setText(billText);
// add bill
this.bills.put(bill.getId(), bill);
}
// store the list of debate turns that discuss each bill
for (GTDebate debate : this.debates.values()) {
for (GTTurn turn : debate.getTurns()) {
String billAssoc = turn.getBillAssociatedWith();
if (billAssoc == null) {
continue;
}
GTBill bill = this.bills.get(billAssoc);
if (bill == null) {
continue;
}
bill.addDebateId(turn.getId());
}
}
if (verbose) {
System.out.println("--- Loaded " + this.bills.size() + " bills.");
int numBillsHaveTurn = 0;
for (GTBill bill : this.bills.values()) {
if (bill.getSpeechIds() != null && bill.getSpeechIds().size() > 0) {
numBillsHaveTurn++;
}
}
System.out.println("--- --- # bills get mentioned: " + numBillsHaveTurn);
}
}
private String inputBillText(File file) {
StringBuilder str = new StringBuilder();
if (!file.exists()) {
return str.toString();
}
try {
BufferedReader reader = IOUtils.getBufferedReader(file);
String line;
while ((line = reader.readLine()) != null) {
if (line.trim().isEmpty()) {
continue;
}
str.append(line.trim()).append(" ");
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Exception while reading file "
+ file);
}
return str.toString();
}
// =========================================================================
@Override
public ArrayList<GTDebate> selectDebates() throws Exception {
if (verbose) {
System.out.println("Selecting debates ...");
System.out.println("--- Total # debates: " + debates.size());
}
ArrayList<GTDebate> selectedDebates = new ArrayList<GTDebate>();
for (GTDebate debate : this.debates.values()) {
if (debate.getNumTurns() > 1) {
selectedDebates.add(debate);
}
}
if (verbose) {
System.out.println("--- # selected debates: " + selectedDebates.size());
}
return selectedDebates;
}
public ArrayList<GTBill> selectBills() throws Exception {
if (verbose) {
System.out.println("Selecting bills ...");
System.out.println("--- Total # bills: " + this.bills.size());
}
ArrayList<GTBill> selectedBills = new ArrayList<GTBill>();
for (GTBill bill : this.bills.values()) {
selectedBills.add(bill);
}
if (verbose) {
System.out.println("--- # selected bills: " + selectedBills.size());
}
return selectedBills;
}
/**
* Select bills by roll-call votes. Only consider bills that are voted.
*/
public ArrayList<GTBill> selectBillsByVotes() throws Exception {
System.out.println("Selecting bills by roll-call votes ...");
System.out.println("# raw bills: " + bills.size());
int numBillsWithMainRollCall = 0;
int numBillsWithRollCall = 0;
ArrayList<GTBill> selectedBills = new ArrayList<GTBill>();
for (GTBill bill : this.bills.values()) {
if (bill.getRollIds() != null && bill.getRollIds().size() > 0) {
numBillsWithRollCall++;
selectedBills.add(bill);
}
String rollID = this.getMainRollId(bill);
if (rollID == null) {
continue;
}
numBillsWithMainRollCall++;
}
System.out.println("# bills with roll-call(s): " + numBillsWithRollCall
+ "\t" + selectedBills.size());
System.out.println("# bills with main roll-call: " + numBillsWithMainRollCall);
// debug
for (GTBill bill : selectedBills) {
System.out.println(bill.getId()
+ "\t" + getMainRollId(bill)
+ "\t" + bill.getRollIds().toString());
}
return selectedBills;
}
// === bills I/O ===
private void outputBillTexts(File billFolder, ArrayList<GTBill> selectedBills) throws Exception {
System.out.println("Outputing bill texts to " + billFolder);
IOUtils.createFolder(billFolder);
BufferedWriter writer;
for (GTBill bill : selectedBills) {
writer = IOUtils.getBufferedWriter(new File(billFolder, bill.getId()));
writer.write(bill.getText().trim() + "\n" + bill.getSummary().trim());
writer.close();
}
}
public void outputSelectedBills(File billFolder, ArrayList<GTBill> selectedBills) throws Exception {
outputBillTexts(new File(billFolder, "texts"), selectedBills);
outputBillSubjects(new File(billFolder, "subjects.txt"));
}
public ArrayList<GTBill> inputSelectedBills(File inputFolder) throws Exception {
File billTextFolder = new File(inputFolder, "texts");
if (!billTextFolder.exists()) {
throw new RuntimeException("Bill text folder not found. "
+ billTextFolder);
}
if (verbose) {
System.out.println("Loading bill turn texts from " + billTextFolder);
}
BufferedReader reader;
String line;
HashMap<String, GTBill> billMap = new HashMap<String, GTBill>();
ArrayList<GTBill> billList = new ArrayList<GTBill>();
String[] filenames = billTextFolder.list();
for (String filename : filenames) {
String type = filename.split("-")[0];
int number = Integer.parseInt(filename.split("-")[1]);
GTBill bill = new GTBill(type, number);
StringBuilder str = new StringBuilder();
reader = IOUtils.getBufferedReader(new File(billTextFolder, filename));
while ((line = reader.readLine()) != null) {
str.append(line).append(" ");
}
reader.close();
bill.setText(str.toString());
billList.add(bill);
}
inputBillSubjects(new File(inputFolder, "subjects.txt"), billMap);
return billList;
}
// === debates I/O ===
public void outputSelectedDebates(File debateTurnFolder, ArrayList<GTDebate> selectedDebates)
throws Exception {
outputDebateTurnText(new File(debateTurnFolder, "texts"), selectedDebates);
outputDebateTurnSubjects(new File(debateTurnFolder, "subjects.txt"), selectedDebates);
outputDebateTurnBills(new File(debateTurnFolder, "bills.txt"), selectedDebates);
outputDebateTurnSpeakers(new File(debateTurnFolder, "speakers.txt"), selectedDebates);
outputDebateTurnDatetime(new File(debateTurnFolder, "datetimes.txt"), selectedDebates);
}
public ArrayList<GTDebate> inputSelectedDebates(File inputFolder) throws Exception {
File debateTextFolder = new File(inputFolder, "texts");
if (!debateTextFolder.exists()) {
throw new RuntimeException("Debate text folder not found. "
+ debateTextFolder);
}
if (verbose) {
System.out.println("Loading debate turn texts from " + debateTextFolder);
}
HashMap<String, GTTurn> turnMap = new HashMap<String, GTTurn>();
BufferedReader reader;
String line;
ArrayList<GTDebate> debateList = new ArrayList<GTDebate>();
String[] filenames = debateTextFolder.list();
for (String filename : filenames) {
GTDebate debate = new GTDebate(filename);
reader = IOUtils.getBufferedReader(new File(debateTextFolder, filename));
while ((line = reader.readLine()) != null) {
int idx = line.indexOf("\t");
String turnId = line.substring(0, idx);
String turnText = line.substring(idx + 1);
GTTurn turn = new GTTurn(turnId);
turn.setText(turnText);
debate.addTurn(turn);
turnMap.put(turnId, turn);
}
reader.close();
}
if (verbose) {
System.out.println("--- Loaded. # debates: " + debateList.size()
+ ". # turns: " + turnMap.size());
}
inputDebateTurnSpeakers(new File(inputFolder, "speakers.txt"), turnMap);
inputDebateTurnBills(new File(inputFolder, "bills.txt"), turnMap);
inputDebateTurnSubjects(new File(inputFolder, "subjects.txt"), turnMap);
inputDebateTurnDatetime(new File(inputFolder, "datetimes.txt"), turnMap);
return debateList;
}
private void outputDebateTurnSpeakers(File debateTurnSpeakerFile,
ArrayList<GTDebate> selectedDebates) throws Exception {
if (verbose) {
System.out.println("Outputing debate turn speakers to " + debateTurnSpeakerFile);
}
BufferedWriter writer = IOUtils.getBufferedWriter(debateTurnSpeakerFile);
for (GTDebate debate : selectedDebates) {
for (int ii = 0; ii < debate.getNumTurns(); ii++) {
GTTurn turn = debate.getTurn(ii);
writer.write(turn.getId()
+ "\t" + turn.getSpeakerId()
+ "\n");
}
}
writer.close();
}
private void inputDebateTurnDatetime(File filepath,
HashMap<String, GTTurn> turnMap) throws Exception {
if (verbose) {
System.out.println("Inputing debate turn datetime from " + filepath);
}
BufferedReader reader = IOUtils.getBufferedReader(filepath);
String line;
while ((line = reader.readLine()) != null) {
int idx = line.indexOf("\t");
String turnId = line.substring(0, idx);
String datetime = line.substring(idx + 1);
GTTurn turn = turnMap.get(turnId);
turn.addProperty(DATETIME, datetime);
}
reader.close();
}
private void outputDebateTurnDatetime(File filepath,
ArrayList<GTDebate> selectedDebates) throws Exception {
if (verbose) {
System.out.println("Outputing debate datetime to " + filepath);
}
BufferedWriter writer = IOUtils.getBufferedWriter(filepath);
for (GTDebate debate : selectedDebates) {
for (int ii = 0; ii < debate.getNumTurns(); ii++) {
GTTurn turn = debate.getTurn(ii);
writer.write(turn.getId()
+ "\t" + debate.getProperty(DATETIME)
+ "\n");
}
}
writer.close();
}
private void inputDebateTurnSpeakers(File debateTurnSpeakerFile,
HashMap<String, GTTurn> turnMap) throws Exception {
if (verbose) {
System.out.println("Inputing debate turn speakers from " + debateTurnSpeakerFile);
}
BufferedReader reader = IOUtils.getBufferedReader(debateTurnSpeakerFile);
String line;
while ((line = reader.readLine()) != null) {
int idx = line.indexOf("\t");
String turnId = line.substring(0, idx);
String turnSpeaker = line.substring(idx + 1);
GTTurn turn = turnMap.get(turnId);
turn.setSpeakerId(turnSpeaker);
}
reader.close();
}
private void outputDebateTurnBills(File debateTurnBillFile,
ArrayList<GTDebate> selectedDebates) throws Exception {
if (verbose) {
System.out.println("Outputing debate turn bills to " + debateTurnBillFile);
}
BufferedWriter writer = IOUtils.getBufferedWriter(debateTurnBillFile);
for (GTDebate debate : selectedDebates) {
for (int ii = 0; ii < debate.getNumTurns(); ii++) {
GTTurn turn = debate.getTurn(ii);
writer.write(turn.getId()
+ "\t" + turn.getMainBillMentioned()
+ "\n");
}
}
writer.close();
}
private void inputDebateTurnBills(File debateTurnBillFile,
HashMap<String, GTTurn> turnMap) throws Exception {
if (verbose) {
System.out.println("Inputing debate turn speakers from " + debateTurnBillFile);
}
BufferedReader reader = IOUtils.getBufferedReader(debateTurnBillFile);
String line;
while ((line = reader.readLine()) != null) {
int idx = line.indexOf("\t");
String turnId = line.substring(0, idx);
String turnBill = line.substring(idx + 1);
if (turnBill.equals("null")) {
turnBill = null;
}
GTTurn turn = turnMap.get(turnId);
turn.setSpeakerId(turnBill);
}
reader.close();
}
private void outputDebateTurnSubjects(File debateTurnSubjFile,
ArrayList<GTDebate> selectedDebates) throws Exception {
if (verbose) {
System.out.println("Outputing debate turn subject to " + debateTurnSubjFile);
}
BufferedWriter writer = IOUtils.getBufferedWriter(debateTurnSubjFile);
for (GTDebate debate : selectedDebates) {
for (int ii = 0; ii < debate.getNumTurns(); ii++) {
GTTurn turn = debate.getTurn(ii);
writer.write(turn.getId());
GTBill bill = this.bills.get(turn.getMainBillMentioned());
if (bill == null) {
writer.write("\n");
continue;
}
ArrayList<String> subjects = bill.getSubjects();
if (subjects == null || subjects.isEmpty()) {
writer.write("\n");
continue;
}
for (String subject : subjects) {
writer.write("\t" + subject);
}
writer.write("\n");
}
}
writer.close();
}
private void inputDebateTurnSubjects(File debateTurnSubjFile,
HashMap<String, GTTurn> turnMap) throws Exception {
if (verbose) {
System.out.println("Inputing debate turn subject from " + debateTurnSubjFile);
}
BufferedReader reader = IOUtils.getBufferedReader(debateTurnSubjFile);
String line;
while ((line = reader.readLine()) != null) {
String[] sline = line.split("\t");
String turnId = sline[0];
GTTurn turn = turnMap.get(turnId);
for (int ii = 1; ii < sline.length; ii++) {
turn.addSubject(sline[ii]);
}
}
reader.close();
}
private void outputDebateTurnText(File debateTurnTextFolder,
ArrayList<GTDebate> selectedDebates) throws Exception {
if (verbose) {
System.out.println("Outputing debate turns to " + debateTurnTextFolder);
}
IOUtils.createFolder(debateTurnTextFolder);
BufferedWriter writer;
for (GTDebate debate : selectedDebates) {
for (int ii = 0; ii < debate.getNumTurns(); ii++) {
GTTurn turn = debate.getTurn(ii);
writer = IOUtils.getBufferedWriter(new File(debateTurnTextFolder, turn.getId()));
writer.write(turn.getText() + "\n");
writer.close();
}
}
}
}
| src/util/govtrack/GTProcessorV2.java | package util.govtrack;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import util.IOUtils;
import util.MiscUtils;
/**
* Here are some major differences of this pre-processing pipeline compared to
* GTProcessor:
*
* 1. Associate each turn with a bill so that each debate can be divided into
* smaller segments, each talking about a bill.
*
* @author vietan
*/
public class GTProcessorV2 extends GTProcessor {
public GTProcessorV2() {
super();
}
public GTProcessorV2(String folder, int congNum) {
super(folder, congNum);
}
// === Processing debates ==================================================
@Override
public void processDebates() {
File crFolder = new File(this.congressFolder, "cr");
if (!crFolder.exists()) {
throw new RuntimeException(crFolder + " not found.");
}
if (verbose) {
System.out.println("Processing debates " + crFolder.getAbsolutePath() + " ...");
}
this.debates = new HashMap<String, GTDebate>();
String[] debateFilenames = crFolder.list();
int count = 0;
int stepSize = MiscUtils.getRoundStepSize(debateFilenames.length, 10);
for (String filename : debateFilenames) {
if (count % stepSize == 0 && verbose) {
System.out.println("--- Processing debate file "
+ count + " / " + debateFilenames.length);
}
count++;
File debateFile = new File(crFolder, filename);
if (debateFile.length() == 0) {
if (verbose) {
System.out.println("--- --- Skipping empty file " + debateFile);
}
continue;
}
GTDebate debate = processSingleDebate(debateFile);
this.debates.put(debate.getId(), debate);
}
if (verbose) {
System.out.println("--- Loaded " + debates.size() + " debates");
int numDebatesMentioningBill = 0;
for (GTDebate debate : debates.values()) {
if (debate.getBillAssociatedWith() != null) {
numDebatesMentioningBill++;
}
}
System.out.println("--- --- # debates having bill(s) mentioned by speakers: "
+ numDebatesMentioningBill);
}
}
public GTDebate processSingleDebate(File debateFile) {
Element docEle;
NodeList nodelist;
Element el;
try {
docEle = getDocumentElement(debateFile.getAbsolutePath());
} catch (Exception e) {
if (verbose) {
System.out.println("--- --- Skipping problematic debate file "
+ debateFile);
e.printStackTrace();
}
return null;
}
String title = docEle.getAttribute("title");
String where = docEle.getAttribute("where");
String debateId = IOUtils.removeExtension(debateFile.getName());
GTDebate debate = new GTDebate(debateId);
debate.setTitle(title);
debate.addProperty("where", where);
// list of turns
GTTurn preTurn = null;
int turnCount = 0;
nodelist = docEle.getElementsByTagName("speaking");
for (int i = 0; i < nodelist.getLength(); i++) {
el = (Element) nodelist.item(i);
String speaker = el.getAttribute("speaker");
String topic = el.getAttribute("topic");
// get contents
StringBuilder text = new StringBuilder();
ArrayList<String> paraBillsMentioned = new ArrayList<String>();
NodeList nl = el.getElementsByTagName("paragraph");
for (int j = 0; j < nl.getLength(); j++) {
Element turnEle = (Element) nl.item(j);
// text
String paraText = turnEle.getTextContent();
if (filterOut(paraText)) {
continue;
}
text.append(paraText).append(" ");
// bills mentioned
NodeList billNl = turnEle.getElementsByTagName("bill");
for (int ii = 0; ii < billNl.getLength(); ii++) {
Element billEl = (Element) billNl.item(ii);
String billType = billEl.getAttribute("type");
String billNumber = billEl.getAttribute("number");
String billId = billType + "-" + billNumber;
paraBillsMentioned.add(billId);
debate.addBillMentioned(billId);
}
}
// merge consecutive turns are from the same speaker
if (preTurn != null && preTurn.getSpeakerId().equals(speaker)) {
String preTurnText = preTurn.getText();
preTurnText += " " + text.toString();
preTurn.setText(preTurnText);
preTurn.addBillsMentioned(paraBillsMentioned);
} else { // or create a new turn
GTTurn turn = new GTTurn(
debateId + "_" + turnCount,
speaker,
procecessText(text.toString()));
turn.setBillsMentioned(paraBillsMentioned);
if (!topic.trim().isEmpty()) {
turn.addProperty("topic", topic);
}
debate.addTurn(turn);
preTurn = turn;
turnCount++;
}
}
// estimate main bill mentioned for each turn
if (debate.getBillsMentioned().size() > 0) {
estimateTurnMainBillMentioned(debate);
}
return debate;
}
/**
* Fill in the main bill mentioned for every turn in the debate. If a turn
* does not explicitly mention a bill, the bill mentioned in the most recent
* turn is used to associate with this turn.
*/
public void estimateTurnMainBillMentioned(GTDebate debate) {
String firstBillMentioned = null;
int firstTurnMentioning = -1;
for (int ii = 0; ii < debate.getNumTurns(); ii++) {
GTTurn turn = debate.getTurn(ii);
String billAssoc = turn.getBillAssociatedWith();
if (billAssoc != null) {
firstBillMentioned = billAssoc;
firstTurnMentioning = ii;
}
}
for (int ii = 0; ii <= firstTurnMentioning; ii++) {
debate.getTurn(ii).setMainBillMentioned(firstBillMentioned);
}
String curBillMentioned = firstBillMentioned;
for (int ii = firstTurnMentioning + 1; ii < debate.getNumTurns(); ii++) {
GTTurn turn = debate.getTurn(ii);
String billAssoc = turn.getBillAssociatedWith();
if (billAssoc == null) {
turn.setMainBillMentioned(curBillMentioned);
} else {
turn.setMainBillMentioned(billAssoc);
curBillMentioned = billAssoc;
}
}
}
protected boolean filterOut(String paraText) {
if (paraText.contains("I yield")
|| containBillText(paraText)) {
return true;
}
return false;
}
protected String procecessText(String text) {
return text.replaceAll("\n", " ")
// .replace("nbsp", "")
.replace("&", "");
}
protected boolean containBillText(String text) {
if (text.contains("nbsp")
|| text.contains("<p>")
|| text.contains("<em>")) {
return true;
}
return false;
}
// === End processing debates ==============================================
// === Start processing bills ==============================================
@Override
public void processBills() {
File billFolder = new File(this.congressFolder, "bills");
if (!billFolder.exists()) {
throw new RuntimeException(billFolder + " not found.");
}
File billTextFolder = new File(this.congressFolder, "bills.html");
if (!billTextFolder.exists()) {
throw new RuntimeException(billTextFolder + " not found.");
}
if (verbose) {
System.out.println("\nProcessing bills " + billFolder);
}
this.bills = new HashMap<String, GTBill>();
String[] billFilenames = billFolder.list();
int count = 0;
int stepSize = MiscUtils.getRoundStepSize(billFilenames.length, 10);
for (String billFilename : billFilenames) {
// debug
if (count % stepSize == 0 && verbose) {
System.out.println("--- Processing bill file "
+ count + " / " + billFilenames.length);
}
count++;
File billFile = new File(billFolder, billFilename);
File billTextFile = new File(billTextFolder, billFilename.replaceAll("xml", "txt"));
if (!billTextFile.exists() && verbose) {
System.out.println("--- --- Skipping bill " + billTextFile
+ ". No text found.");
continue;
}
Element docEle;
try {
docEle = getDocumentElement(billFile.getAbsolutePath());
} catch (Exception e) {
if (verbose) {
System.out.println("--- --- Skipping problematic bill file "
+ billFile);
e.printStackTrace();
}
continue;
}
NodeList nodelist;
Element element;
// create bill
String billType = docEle.getAttribute("type");
int billNumber = Integer.parseInt(docEle.getAttribute("number"));
GTBill bill = new GTBill(billType, billNumber);
// titles
nodelist = docEle.getElementsByTagName("title");
for (int ii = 0; ii < nodelist.getLength(); ii++) {
element = (Element) nodelist.item(ii);
String type = element.getAttribute("type");
String title = element.getTextContent();
if (type.equals("popular")) {
bill.setTitle(title);
} else if (type.equals("official")) {
bill.setOfficialTitle(title);
}
}
// subjects (labels) of this bill
ArrayList<String> subjects = new ArrayList<String>();
nodelist = docEle.getElementsByTagName("term");
for (int i = 0; i < nodelist.getLength(); i++) {
element = (Element) nodelist.item(i);
subjects.add(element.getAttribute("name"));
}
bill.setSubjects(subjects);
// bill summary
nodelist = docEle.getElementsByTagName("summary");
element = (Element) nodelist.item(0);
String summary = element.getTextContent();
bill.setSummary(summary);
// bill text
String billText = inputBillText(billTextFile);
bill.setText(billText);
// add bill
this.bills.put(bill.getId(), bill);
}
// store the list of debate turns that discuss each bill
for (GTDebate debate : this.debates.values()) {
for (GTTurn turn : debate.getTurns()) {
String billAssoc = turn.getBillAssociatedWith();
if (billAssoc == null) {
continue;
}
GTBill bill = this.bills.get(billAssoc);
if (bill == null) {
continue;
}
bill.addDebateId(turn.getId());
}
}
if (verbose) {
System.out.println("--- Loaded " + this.bills.size() + " bills.");
int numBillsHaveTurn = 0;
for (GTBill bill : this.bills.values()) {
if (bill.getSpeechIds() != null && bill.getSpeechIds().size() > 0) {
numBillsHaveTurn++;
}
}
System.out.println("--- --- # bills get mentioned: " + numBillsHaveTurn);
}
}
private String inputBillText(File file) {
StringBuilder str = new StringBuilder();
if (!file.exists()) {
return str.toString();
}
try {
BufferedReader reader = IOUtils.getBufferedReader(file);
String line;
while ((line = reader.readLine()) != null) {
if (line.trim().isEmpty()) {
continue;
}
str.append(line.trim()).append(" ");
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Exception while reading file "
+ file);
}
return str.toString();
}
// =========================================================================
@Override
public ArrayList<GTDebate> selectDebates() throws Exception {
if (verbose) {
System.out.println("Selecting debates ...");
System.out.println("--- Total # debates: " + debates.size());
}
ArrayList<GTDebate> selectedDebates = new ArrayList<GTDebate>();
for (GTDebate debate : this.debates.values()) {
if (debate.getNumTurns() > 1) {
selectedDebates.add(debate);
}
}
if (verbose) {
System.out.println("--- # selected debates: " + selectedDebates.size());
}
return selectedDebates;
}
public ArrayList<GTBill> selectBills() throws Exception {
if (verbose) {
System.out.println("Selecting bills ...");
System.out.println("--- Total # bills: " + this.bills.size());
}
ArrayList<GTBill> selectedBills = new ArrayList<GTBill>();
for (GTBill bill : this.bills.values()) {
selectedBills.add(bill);
}
if (verbose) {
System.out.println("--- # selected bills: " + selectedBills.size());
}
return selectedBills;
}
/**
* Select bills by roll-call votes. Only consider bills that are voted.
*/
public ArrayList<GTBill> selectBillsByVotes() throws Exception {
System.out.println("Selecting bills by roll-call votes ...");
System.out.println("# raw bills: " + bills.size());
int numBillsWithMainRollCall = 0;
int numBillsWithRollCall = 0;
ArrayList<GTBill> selectedBills = new ArrayList<GTBill>();
for (GTBill bill : this.bills.values()) {
if (bill.getRollIds() != null && bill.getRollIds().size() > 0) {
numBillsWithRollCall++;
selectedBills.add(bill);
}
String rollID = this.getMainRollId(bill);
if (rollID == null) {
continue;
}
numBillsWithMainRollCall++;
}
System.out.println("# bills with roll-call(s): " + numBillsWithRollCall
+ "\t" + selectedBills.size());
System.out.println("# bills with main roll-call: " + numBillsWithMainRollCall);
// debug
for (GTBill bill : selectedBills) {
System.out.println(bill.getId()
+ "\t" + getMainRollId(bill)
+ "\t" + bill.getRollIds().toString());
}
return selectedBills;
}
// === bills I/O ===
private void outputBillTexts(File billFolder, ArrayList<GTBill> selectedBills) throws Exception {
System.out.println("Outputing bill texts to " + billFolder);
IOUtils.createFolder(billFolder);
BufferedWriter writer;
for (GTBill bill : selectedBills) {
writer = IOUtils.getBufferedWriter(new File(billFolder, bill.getId()));
writer.write(bill.getText().trim() + "\n" + bill.getSummary().trim());
writer.close();
}
}
public void outputSelectedBills(File billFolder, ArrayList<GTBill> selectedBills) throws Exception {
outputBillTexts(new File(billFolder, "texts"), selectedBills);
outputBillSubjects(new File(billFolder, "subjects.txt"));
}
public ArrayList<GTBill> inputSelectedBills(File inputFolder) throws Exception {
File billTextFolder = new File(inputFolder, "texts");
if (!billTextFolder.exists()) {
throw new RuntimeException("Bill text folder not found. "
+ billTextFolder);
}
if (verbose) {
System.out.println("Loading bill turn texts from " + billTextFolder);
}
BufferedReader reader;
String line;
HashMap<String, GTBill> billMap = new HashMap<String, GTBill>();
ArrayList<GTBill> billList = new ArrayList<GTBill>();
String[] filenames = billTextFolder.list();
for (String filename : filenames) {
String type = filename.split("-")[0];
int number = Integer.parseInt(filename.split("-")[1]);
GTBill bill = new GTBill(type, number);
StringBuilder str = new StringBuilder();
reader = IOUtils.getBufferedReader(new File(billTextFolder, filename));
while ((line = reader.readLine()) != null) {
str.append(line).append(" ");
}
reader.close();
bill.setText(str.toString());
billList.add(bill);
}
inputBillSubjects(new File(inputFolder, "subjects.txt"), billMap);
return billList;
}
// === debates I/O ===
public void outputSelectedDebates(File debateTurnFolder, ArrayList<GTDebate> selectedDebates)
throws Exception {
outputDebateTurnText(new File(debateTurnFolder, "texts"), selectedDebates);
outputDebateTurnSubjects(new File(debateTurnFolder, "subjects.txt"), selectedDebates);
outputDebateTurnBills(new File(debateTurnFolder, "bills.txt"), selectedDebates);
outputDebateTurnSpeakers(new File(debateTurnFolder, "speakers.txt"), selectedDebates);
}
public ArrayList<GTDebate> inputSelectedDebates(File inputFolder) throws Exception {
File debateTextFolder = new File(inputFolder, "texts");
if (!debateTextFolder.exists()) {
throw new RuntimeException("Debate text folder not found. "
+ debateTextFolder);
}
if (verbose) {
System.out.println("Loading debate turn texts from " + debateTextFolder);
}
HashMap<String, GTTurn> turnMap = new HashMap<String, GTTurn>();
BufferedReader reader;
String line;
ArrayList<GTDebate> debateList = new ArrayList<GTDebate>();
String[] filenames = debateTextFolder.list();
for (String filename : filenames) {
GTDebate debate = new GTDebate(filename);
reader = IOUtils.getBufferedReader(new File(debateTextFolder, filename));
while ((line = reader.readLine()) != null) {
int idx = line.indexOf("\t");
String turnId = line.substring(0, idx);
String turnText = line.substring(idx + 1);
GTTurn turn = new GTTurn(turnId);
turn.setText(turnText);
debate.addTurn(turn);
turnMap.put(turnId, turn);
}
reader.close();
}
if (verbose) {
System.out.println("--- Loaded. # debates: " + debateList.size()
+ ". # turns: " + turnMap.size());
}
inputDebateTurnSpeakers(new File(inputFolder, "speakers.txt"), turnMap);
inputDebateTurnBills(new File(inputFolder, "bills.txt"), turnMap);
inputDebateTurnSubjects(new File(inputFolder, "subjects.txt"), turnMap);
return debateList;
}
private void outputDebateTurnSpeakers(File debateTurnSpeakerFile,
ArrayList<GTDebate> selectedDebates) throws Exception {
if (verbose) {
System.out.println("Outputing debate turn speakers to " + debateTurnSpeakerFile);
}
BufferedWriter writer = IOUtils.getBufferedWriter(debateTurnSpeakerFile);
for (GTDebate debate : selectedDebates) {
for (int ii = 0; ii < debate.getNumTurns(); ii++) {
GTTurn turn = debate.getTurn(ii);
writer.write(turn.getId()
+ "\t" + turn.getSpeakerId()
+ "\n");
}
}
writer.close();
}
private void inputDebateTurnSpeakers(File debateTurnSpeakerFile,
HashMap<String, GTTurn> turnMap) throws Exception {
if (verbose) {
System.out.println("Inputing debate turn speakers from " + debateTurnSpeakerFile);
}
BufferedReader reader = IOUtils.getBufferedReader(debateTurnSpeakerFile);
String line;
while ((line = reader.readLine()) != null) {
int idx = line.indexOf("\t");
String turnId = line.substring(0, idx);
String turnSpeaker = line.substring(idx + 1);
GTTurn turn = turnMap.get(turnId);
turn.setSpeakerId(turnSpeaker);
}
reader.close();
}
private void outputDebateTurnBills(File debateTurnBillFile,
ArrayList<GTDebate> selectedDebates) throws Exception {
if (verbose) {
System.out.println("Outputing debate turn bills to " + debateTurnBillFile);
}
BufferedWriter writer = IOUtils.getBufferedWriter(debateTurnBillFile);
for (GTDebate debate : selectedDebates) {
for (int ii = 0; ii < debate.getNumTurns(); ii++) {
GTTurn turn = debate.getTurn(ii);
writer.write(turn.getId()
+ "\t" + turn.getMainBillMentioned()
+ "\n");
}
}
writer.close();
}
private void inputDebateTurnBills(File debateTurnBillFile,
HashMap<String, GTTurn> turnMap) throws Exception {
if (verbose) {
System.out.println("Inputing debate turn speakers from " + debateTurnBillFile);
}
BufferedReader reader = IOUtils.getBufferedReader(debateTurnBillFile);
String line;
while ((line = reader.readLine()) != null) {
int idx = line.indexOf("\t");
String turnId = line.substring(0, idx);
String turnBill = line.substring(idx + 1);
if (turnBill.equals("null")) {
turnBill = null;
}
GTTurn turn = turnMap.get(turnId);
turn.setSpeakerId(turnBill);
}
reader.close();
}
private void outputDebateTurnSubjects(File debateTurnSubjFile,
ArrayList<GTDebate> selectedDebates) throws Exception {
if (verbose) {
System.out.println("Outputing debate turn subject to " + debateTurnSubjFile);
}
BufferedWriter writer = IOUtils.getBufferedWriter(debateTurnSubjFile);
for (GTDebate debate : selectedDebates) {
for (int ii = 0; ii < debate.getNumTurns(); ii++) {
GTTurn turn = debate.getTurn(ii);
writer.write(turn.getId());
GTBill bill = this.bills.get(turn.getMainBillMentioned());
if (bill == null) {
writer.write("\n");
continue;
}
ArrayList<String> subjects = bill.getSubjects();
if (subjects == null || subjects.isEmpty()) {
writer.write("\n");
continue;
}
for (String subject : subjects) {
writer.write("\t" + subject);
}
writer.write("\n");
}
}
writer.close();
}
private void inputDebateTurnSubjects(File debateTurnSubjFile,
HashMap<String, GTTurn> turnMap) throws Exception {
if (verbose) {
System.out.println("Inputing debate turn subject from " + debateTurnSubjFile);
}
BufferedReader reader = IOUtils.getBufferedReader(debateTurnSubjFile);
String line;
while ((line = reader.readLine()) != null) {
String[] sline = line.split("\t");
String turnId = sline[0];
GTTurn turn = turnMap.get(turnId);
for (int ii = 1; ii < sline.length; ii++) {
turn.addSubject(sline[ii]);
}
}
reader.close();
}
private void outputDebateTurnText(File debateTurnTextFolder,
ArrayList<GTDebate> selectedDebates) throws Exception {
if (verbose) {
System.out.println("Outputing debate turns to " + debateTurnTextFolder);
}
IOUtils.createFolder(debateTurnTextFolder);
BufferedWriter writer;
for (GTDebate debate : selectedDebates) {
for (int ii = 0; ii < debate.getNumTurns(); ii++) {
GTTurn turn = debate.getTurn(ii);
writer = IOUtils.getBufferedWriter(new File(debateTurnTextFolder, turn.getId()));
writer.write(turn.getText() + "\n");
writer.close();
}
}
}
}
| Add datetime to debates & debate turns
| src/util/govtrack/GTProcessorV2.java | Add datetime to debates & debate turns | <ide><path>rc/util/govtrack/GTProcessorV2.java
<ide> * @author vietan
<ide> */
<ide> public class GTProcessorV2 extends GTProcessor {
<add>
<add> public static final String DATETIME = "datetime";
<ide>
<ide> public GTProcessorV2() {
<ide> super();
<ide>
<ide> String title = docEle.getAttribute("title");
<ide> String where = docEle.getAttribute("where");
<add> String datetime = docEle.getAttribute(DATETIME);
<ide> String debateId = IOUtils.removeExtension(debateFile.getName());
<ide> GTDebate debate = new GTDebate(debateId);
<ide> debate.setTitle(title);
<ide> debate.addProperty("where", where);
<add> debate.addProperty(DATETIME, datetime);
<ide>
<ide> // list of turns
<ide> GTTurn preTurn = null;
<ide>
<ide> protected String procecessText(String text) {
<ide> return text.replaceAll("\n", " ")
<del>// .replace("nbsp", "")
<add> // .replace("nbsp", "")
<ide> .replace("&", "");
<ide> }
<ide>
<ide> outputDebateTurnSubjects(new File(debateTurnFolder, "subjects.txt"), selectedDebates);
<ide> outputDebateTurnBills(new File(debateTurnFolder, "bills.txt"), selectedDebates);
<ide> outputDebateTurnSpeakers(new File(debateTurnFolder, "speakers.txt"), selectedDebates);
<add> outputDebateTurnDatetime(new File(debateTurnFolder, "datetimes.txt"), selectedDebates);
<ide> }
<ide>
<ide> public ArrayList<GTDebate> inputSelectedDebates(File inputFolder) throws Exception {
<ide> inputDebateTurnSpeakers(new File(inputFolder, "speakers.txt"), turnMap);
<ide> inputDebateTurnBills(new File(inputFolder, "bills.txt"), turnMap);
<ide> inputDebateTurnSubjects(new File(inputFolder, "subjects.txt"), turnMap);
<del>
<add> inputDebateTurnDatetime(new File(inputFolder, "datetimes.txt"), turnMap);
<ide> return debateList;
<ide> }
<ide>
<ide> GTTurn turn = debate.getTurn(ii);
<ide> writer.write(turn.getId()
<ide> + "\t" + turn.getSpeakerId()
<add> + "\n");
<add> }
<add> }
<add> writer.close();
<add> }
<add>
<add> private void inputDebateTurnDatetime(File filepath,
<add> HashMap<String, GTTurn> turnMap) throws Exception {
<add> if (verbose) {
<add> System.out.println("Inputing debate turn datetime from " + filepath);
<add> }
<add>
<add> BufferedReader reader = IOUtils.getBufferedReader(filepath);
<add> String line;
<add> while ((line = reader.readLine()) != null) {
<add> int idx = line.indexOf("\t");
<add> String turnId = line.substring(0, idx);
<add> String datetime = line.substring(idx + 1);
<add> GTTurn turn = turnMap.get(turnId);
<add> turn.addProperty(DATETIME, datetime);
<add> }
<add> reader.close();
<add> }
<add>
<add> private void outputDebateTurnDatetime(File filepath,
<add> ArrayList<GTDebate> selectedDebates) throws Exception {
<add> if (verbose) {
<add> System.out.println("Outputing debate datetime to " + filepath);
<add> }
<add>
<add> BufferedWriter writer = IOUtils.getBufferedWriter(filepath);
<add> for (GTDebate debate : selectedDebates) {
<add> for (int ii = 0; ii < debate.getNumTurns(); ii++) {
<add> GTTurn turn = debate.getTurn(ii);
<add> writer.write(turn.getId()
<add> + "\t" + debate.getProperty(DATETIME)
<ide> + "\n");
<ide> }
<ide> } |
|
Java | apache-2.0 | 5009a2b4570474f4588026bc406651b1ba5711be | 0 | apixandru/intellij-community,ibinti/intellij-community,asedunov/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,semonte/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,apixandru/intellij-community,semonte/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,signed/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,ibinti/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,signed/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,da1z/intellij-community,allotria/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,FHannes/intellij-community,FHannes/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,xfournet/intellij-community,apixandru/intellij-community,semonte/intellij-community,FHannes/intellij-community,apixandru/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,signed/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,michaelgallacher/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,semonte/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,suncycheng/intellij-community,signed/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,xfournet/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,signed/intellij-community,asedunov/intellij-community,asedunov/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,allotria/intellij-community,ibinti/intellij-community,ibinti/intellij-community,FHannes/intellij-community,FHannes/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,semonte/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,allotria/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,FHannes/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,fitermay/intellij-community,fitermay/intellij-community,signed/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,signed/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,fitermay/intellij-community,apixandru/intellij-community,fitermay/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,allotria/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,semonte/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,ibinti/intellij-community,ibinti/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,semonte/intellij-community,da1z/intellij-community,signed/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,da1z/intellij-community,allotria/intellij-community,signed/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,asedunov/intellij-community,apixandru/intellij-community,allotria/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.validation;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiWhiteSpace;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.QualifiedName;
import com.intellij.util.ArrayUtil;
import com.jetbrains.python.PyNames;
import com.jetbrains.python.PyTokenTypes;
import com.jetbrains.python.inspections.quickfix.*;
import com.jetbrains.python.psi.*;
import com.jetbrains.python.psi.impl.PyStringLiteralExpressionImpl;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.function.Predicate;
/**
* User : catherine
*/
public abstract class CompatibilityVisitor extends PyAnnotator {
@NotNull
private static final Map<LanguageLevel, Set<String>> AVAILABLE_PREFIXES = Maps.newHashMap();
@NotNull
private static final Set<String> DEFAULT_PREFIXES = Sets.newHashSet("R", "U", "B", "BR", "RB");
@NotNull
protected static final String COMMON_MESSAGE = "Python version ";
@NotNull
protected List<LanguageLevel> myVersionsToProcess;
static {
AVAILABLE_PREFIXES.put(LanguageLevel.PYTHON24, Sets.newHashSet("R", "U", "UR"));
AVAILABLE_PREFIXES.put(LanguageLevel.PYTHON25, Sets.newHashSet("R", "U", "UR"));
AVAILABLE_PREFIXES.put(LanguageLevel.PYTHON26, Sets.newHashSet("R", "U", "UR", "B", "BR"));
AVAILABLE_PREFIXES.put(LanguageLevel.PYTHON27, Sets.newHashSet("R", "U", "UR", "B", "BR"));
AVAILABLE_PREFIXES.put(LanguageLevel.PYTHON30, Sets.newHashSet("R", "B"));
AVAILABLE_PREFIXES.put(LanguageLevel.PYTHON31, Sets.newHashSet("R", "B", "BR"));
AVAILABLE_PREFIXES.put(LanguageLevel.PYTHON32, Sets.newHashSet("R", "B", "BR"));
AVAILABLE_PREFIXES.put(LanguageLevel.PYTHON36, Sets.newHashSet("R", "U", "B", "BR", "RB", "F", "FR", "RF"));
}
public CompatibilityVisitor(@NotNull List<LanguageLevel> versionsToProcess) {
myVersionsToProcess = versionsToProcess;
}
@Override
public void visitPyAnnotation(PyAnnotation node) {
final PsiElement parent = node.getParent();
if (!(parent instanceof PyFunction || parent instanceof PyNamedParameter)) {
final StringBuilder message = new StringBuilder(COMMON_MESSAGE);
int len = 0;
for (LanguageLevel languageLevel : myVersionsToProcess) {
if (languageLevel.isOlderThan(LanguageLevel.PYTHON36)) {
len = appendLanguageLevel(message, len, languageLevel);
}
}
commonRegisterProblem(message, " not support variable annotations", len, node, null);
}
}
@Override
public void visitPyDictCompExpression(PyDictCompExpression node) {
super.visitPyDictCompExpression(node);
final StringBuilder message = new StringBuilder(COMMON_MESSAGE);
final int len = appendLanguageLevels(message, myVersionsToProcess, level -> !level.supportsSetLiterals());
commonRegisterProblem(message, " not support dictionary comprehensions", len, node, new ConvertDictCompQuickFix(), false);
}
@Override
public void visitPySetLiteralExpression(PySetLiteralExpression node) {
super.visitPySetLiteralExpression(node);
final StringBuilder message = new StringBuilder(COMMON_MESSAGE);
final int len = appendLanguageLevels(message, myVersionsToProcess, level -> !level.supportsSetLiterals());
commonRegisterProblem(message, " not support set literal expressions", len, node, new ConvertSetLiteralQuickFix(), false);
}
@Override
public void visitPySetCompExpression(PySetCompExpression node) {
super.visitPySetCompExpression(node);
final StringBuilder message = new StringBuilder(COMMON_MESSAGE);
final int len = appendLanguageLevels(message, myVersionsToProcess, level -> !level.supportsSetLiterals());
commonRegisterProblem(message, " not support set comprehensions", len, node, null, false);
}
@Override
public void visitPyExceptBlock(PyExceptPart node) {
super.visitPyExceptBlock(node);
final PyExpression exceptClass = node.getExceptClass();
if (exceptClass != null) {
if (myVersionsToProcess.contains(LanguageLevel.PYTHON24) || myVersionsToProcess.contains(LanguageLevel.PYTHON25)) {
PsiElement element = exceptClass.getNextSibling();
while (element instanceof PsiWhiteSpace) {
element = element.getNextSibling();
}
if (element != null && "as".equals(element.getText())) {
registerProblem(node, COMMON_MESSAGE + "2.4, 2.5 do not support this syntax.");
}
}
PsiElement element = exceptClass.getNextSibling();
while (element instanceof PsiWhiteSpace) {
element = element.getNextSibling();
}
if (element != null && ",".equals(element.getText())) {
final StringBuilder message = new StringBuilder(COMMON_MESSAGE);
final int len = appendLanguageLevels(message, myVersionsToProcess, LanguageLevel::isPy3K);
commonRegisterProblem(message, " not support this syntax.", len, node, new ReplaceExceptPartQuickFix());
}
}
}
@Override
public void visitPyImportStatement(PyImportStatement node) {
super.visitPyImportStatement(node);
final PyIfStatement ifParent = PsiTreeUtil.getParentOfType(node, PyIfStatement.class);
if (ifParent != null) return;
for (PyImportElement importElement : node.getImportElements()) {
final QualifiedName qName = importElement.getImportedQName();
if (qName != null) {
final StringBuilder message = new StringBuilder(COMMON_MESSAGE);
final int len;
if (qName.matches("builtins")) {
len = appendLanguageLevels(message, myVersionsToProcess, level -> !level.isPy3K());
commonRegisterProblem(message, " not have module builtins", len, node, new ReplaceBuiltinsQuickFix());
}
else if (qName.matches("__builtin__")) {
len = appendLanguageLevels(message, myVersionsToProcess, LanguageLevel::isPy3K);
commonRegisterProblem(message, " not have module __builtin__", len, node, new ReplaceBuiltinsQuickFix());
}
}
}
}
@Override
public void visitPyStarExpression(PyStarExpression node) {
super.visitPyStarExpression(node);
if (node.isAssignmentTarget()) {
registerFirst(node,
"Python versions < 3.0 do not support starred expressions as assignment targets",
myVersionsToProcess,
level -> level.isOlderThan(LanguageLevel.PYTHON30));
}
if (node.isUnpacking()) {
registerFirst(node,
"Python versions < 3.5 do not support starred expressions in tuples, lists, and sets",
myVersionsToProcess,
level -> level.isOlderThan(LanguageLevel.PYTHON35));
}
}
@Override
public void visitPyDoubleStarExpression(PyDoubleStarExpression node) {
super.visitPyDoubleStarExpression(node);
registerFirst(node,
"Python versions < 3.5 do not support starred expressions in dicts",
myVersionsToProcess,
level -> level.isOlderThan(LanguageLevel.PYTHON35));
}
@Override
public void visitPyBinaryExpression(PyBinaryExpression node) {
super.visitPyBinaryExpression(node);
if (node.isOperator("<>")) {
final StringBuilder message = new StringBuilder(COMMON_MESSAGE);
final int len = appendLanguageLevels(message, myVersionsToProcess, LanguageLevel::isPy3K);
commonRegisterProblem(message, " not support <>, use != instead.", len, node, new ReplaceNotEqOperatorQuickFix());
}
else if (node.isOperator("@")) {
checkMatrixMultiplicationOperator(node.getPsiOperator());
}
}
private void checkMatrixMultiplicationOperator(PsiElement node) {
registerFirst(node,
"Python versions < 3.5 do not support matrix multiplication operators",
myVersionsToProcess,
level -> level.isOlderThan(LanguageLevel.PYTHON35));
}
@Override
public void visitPyNumericLiteralExpression(final PyNumericLiteralExpression node) {
super.visitPyNumericLiteralExpression(node);
final String text = node.getText();
if (node.isIntegerLiteral()) {
if (text.endsWith("l") || text.endsWith("L")) {
final StringBuilder message = new StringBuilder(COMMON_MESSAGE);
final String suffix = " not support a trailing \'l\' or \'L\'.";
final int len = appendLanguageLevels(message, myVersionsToProcess, LanguageLevel::isPy3K);
commonRegisterProblem(message, suffix, len, node, new RemoveTrailingLQuickFix());
}
if (text.length() > 1 && text.charAt(0) == '0') {
final char secondChar = Character.toLowerCase(text.charAt(1));
if (secondChar != 'o' && secondChar != 'b' && secondChar != 'x' && text.chars().anyMatch(c -> c != '0')) {
final StringBuilder message = new StringBuilder(COMMON_MESSAGE);
final String suffix = " not support this syntax. It requires '0o' prefix for octal literals";
int len = appendLanguageLevels(message, myVersionsToProcess, LanguageLevel::isPy3K);
commonRegisterProblem(message, suffix, len, node, new ReplaceOctalNumericLiteralQuickFix());
}
}
}
if (text.contains("_")) {
final StringBuilder message = new StringBuilder(COMMON_MESSAGE);
final String suffix = " not support underscores in numeric literals";
final int len = appendLanguageLevels(message, myVersionsToProcess, level -> level.isOlderThan(LanguageLevel.PYTHON36));
commonRegisterProblem(message, suffix, len, node, new PyRemoveUnderscoresInNumericLiteralsQuickFix());
}
}
@Override
public void visitPyStringLiteralExpression(final PyStringLiteralExpression node) {
super.visitPyStringLiteralExpression(node);
for (ASTNode stringNode : node.getStringNodes()) {
final String text = stringNode.getText();
final int prefixLength = PyStringLiteralExpressionImpl.getPrefixLength(text);
final String prefix = text.substring(0, prefixLength).toUpperCase();
if (prefix.isEmpty()) continue;
final StringBuilder message = new StringBuilder(COMMON_MESSAGE);
final int len =
appendLanguageLevels(message,
myVersionsToProcess,
level -> !AVAILABLE_PREFIXES.getOrDefault(level, DEFAULT_PREFIXES).contains(prefix));
final TextRange range = TextRange.create(stringNode.getStartOffset(), stringNode.getStartOffset() + prefixLength);
commonRegisterProblem(message, " not support a '" + prefix + "' prefix", len, node, range, new RemovePrefixQuickFix(prefix));
}
}
@Override
public void visitPyListCompExpression(final PyListCompExpression node) {
super.visitPyListCompExpression(node);
final StringBuilder message = new StringBuilder(COMMON_MESSAGE);
final int len =
appendLanguageLevels(message, myVersionsToProcess, level -> UnsupportedFeaturesUtil.visitPyListCompExpression(node, level));
for (ComprhForComponent forComponent : node.getForComponents()) {
commonRegisterProblem(message, " not support this syntax in list comprehensions.", len, forComponent.getIteratedList(),
new ReplaceListComprehensionsQuickFix());
}
}
@Override
public void visitPyRaiseStatement(PyRaiseStatement node) {
super.visitPyRaiseStatement(node);
// empty raise
StringBuilder message = new StringBuilder(COMMON_MESSAGE);
int len = appendLanguageLevels(message, myVersionsToProcess, level -> UnsupportedFeaturesUtil.raiseHasNoArgs(node, level));
commonRegisterProblem(message, " not support this syntax. Raise with no arguments can only be used in an except block",
len, node, null, false);
// raise 1, 2, 3
message = new StringBuilder(COMMON_MESSAGE);
len = appendLanguageLevels(message, myVersionsToProcess, level -> UnsupportedFeaturesUtil.raiseHasMoreThenOneArg(node, level));
commonRegisterProblem(message, " not support this syntax.", len, node, new ReplaceRaiseStatementQuickFix());
// raise exception from cause
message = new StringBuilder(COMMON_MESSAGE);
len = appendLanguageLevels(message, myVersionsToProcess, level -> UnsupportedFeaturesUtil.raiseHasFromKeyword(node, level));
commonRegisterProblem(message, " not support this syntax.", len, node, new ReplaceRaiseStatementQuickFix());
}
@Override
public void visitPyReprExpression(PyReprExpression node) {
super.visitPyReprExpression(node);
final StringBuilder message = new StringBuilder(COMMON_MESSAGE);
final int len = appendLanguageLevels(message, myVersionsToProcess, LanguageLevel::isPy3K);
commonRegisterProblem(message, " not support backquotes, use repr() instead", len, node, new ReplaceBackquoteExpressionQuickFix());
}
@Override
public void visitPyWithStatement(PyWithStatement node) {
super.visitPyWithStatement(node);
Set<PyWithItem> problemItems = new HashSet<>();
StringBuilder message = new StringBuilder(COMMON_MESSAGE);
for (int i = 0; i != myVersionsToProcess.size(); ++i) {
LanguageLevel languageLevel = myVersionsToProcess.get(i);
if (languageLevel == LanguageLevel.PYTHON24) {
registerProblem(node, "Python version 2.4 doesn't support this syntax.");
}
else if (!languageLevel.supportsSetLiterals()) {
final PyWithItem[] items = node.getWithItems();
if (items.length > 1) {
for (int j = 1; j < items.length; j++) {
if (!problemItems.isEmpty())
message.append(", ");
message.append(languageLevel.toString());
problemItems.add(items [j]);
}
}
}
}
message.append(" do not support multiple context managers");
for (PyWithItem item : problemItems) {
registerProblem(item, message.toString());
}
checkAsyncKeyword(node);
}
@Override
public void visitPyForStatement(PyForStatement node) {
super.visitPyForStatement(node);
checkAsyncKeyword(node);
}
@Override
public void visitPyClass(PyClass node) { // PY-2719
super.visitPyClass(node);
final PyArgumentList list = node.getSuperClassExpressionList();
if (list != null && list.getArguments().length == 0) {
registerFirst(list, "Python version 2.4 does not support this syntax.", myVersionsToProcess, LanguageLevel.PYTHON24::equals);
}
}
@Override
public void visitPyPrintStatement(PyPrintStatement node) {
super.visitPyPrintStatement(node);
if (shouldBeCompatibleWithPy3()) {
boolean hasProblem = false;
PsiElement[] arguments = node.getChildren();
for (PsiElement element : arguments) {
if (!((element instanceof PyParenthesizedExpression) || (element instanceof PyTupleExpression))) {
hasProblem = true;
break;
}
}
if (hasProblem || arguments.length == 0)
registerProblem(node, "Python version >= 3.0 do not support this syntax. The print statement has been replaced with a print() function",
new CompatibilityPrintCallQuickFix());
}
}
@Override
public void visitPyFromImportStatement(PyFromImportStatement node) {
super.visitPyFromImportStatement(node);
final PyReferenceExpression importSource = node.getImportSource();
if (importSource != null) {
final PsiElement prev = importSource.getPrevSibling();
if (prev != null && prev.getNode().getElementType() == PyTokenTypes.DOT) { // PY-2793
registerFirst(node, "Python version 2.4 doesn't support this syntax.", myVersionsToProcess, LanguageLevel.PYTHON24::equals);
}
}
else {
registerFirst(node, "Python version 2.4 doesn't support this syntax.", myVersionsToProcess, LanguageLevel.PYTHON24::equals);
}
}
@Override
public void visitPyAssignmentStatement(PyAssignmentStatement node) {
super.visitPyAssignmentStatement(node);
if (myVersionsToProcess.contains(LanguageLevel.PYTHON24)) {
PyExpression assignedValue = node.getAssignedValue();
Stack<PsiElement> st = new Stack<>(); // PY-2796
if (assignedValue != null)
st.push(assignedValue);
while (!st.isEmpty()) {
PsiElement el = st.pop();
if (el instanceof PyYieldExpression)
registerProblem(node, "Python version 2.4 doesn't support this syntax. " +
"In Python <= 2.4, yield was a statement; it didn't return any value.");
else {
for (PsiElement e : el.getChildren())
st.push(e);
}
}
}
}
@Override
public void visitPyConditionalExpression(PyConditionalExpression node) { //PY-4293
super.visitPyConditionalExpression(node);
registerFirst(node,
"Python version 2.4 doesn't support this syntax.",
myVersionsToProcess,
LanguageLevel.PYTHON24::equals);
}
@Override
public void visitPyTryExceptStatement(PyTryExceptStatement node) { // PY-2795
super.visitPyTryExceptStatement(node);
final PyExceptPart[] excepts = node.getExceptParts();
final PyFinallyPart finallyPart = node.getFinallyPart();
if (excepts.length != 0 && finallyPart != null) {
registerFirst(node,
"Python version 2.4 doesn't support this syntax. You could use a finally block to ensure " +
"that code is always executed, or one or more except blocks to catch specific exceptions.",
myVersionsToProcess,
LanguageLevel.PYTHON24::equals);
}
}
@Override
public void visitPyCallExpression(PyCallExpression node) {
super.visitPyCallExpression(node);
final PsiElement firstChild = node.getFirstChild();
if (firstChild != null && PyNames.SUPER.equals(firstChild.getText()) && ArrayUtil.isEmpty(node.getArguments())) {
final StringBuilder message = new StringBuilder(COMMON_MESSAGE);
final int len = appendLanguageLevels(message, myVersionsToProcess, level -> !level.isPy3K());
commonRegisterProblem(message, " not support this syntax. super() should have arguments in Python 2", len, node, null);
}
highlightIncorrectArguments(node);
}
@Override
public void visitPyFunction(PyFunction node) {
super.visitPyFunction(node);
checkAsyncKeyword(node);
}
@Override
public void visitPyPrefixExpression(PyPrefixExpression node) {
super.visitPyPrefixExpression(node);
if (node.getOperator() == PyTokenTypes.AWAIT_KEYWORD) {
registerFirst(node,
"Python versions < 3.5 do not support this syntax",
myVersionsToProcess,
level -> level.isOlderThan(LanguageLevel.PYTHON35));
}
}
@Override
public void visitPyYieldExpression(PyYieldExpression node) {
super.visitPyYieldExpression(node);
if (!node.isDelegating()) {
return;
}
registerFirst(node,
"Python versions < 3.3 do not support this syntax. Delegating to a subgenerator is available since " +
"Python 3.3; use explicit iteration over subgenerator instead.",
myVersionsToProcess,
level -> level.isOlderThan(LanguageLevel.PYTHON33));
}
@Override
public void visitPyReturnStatement(PyReturnStatement node) {
boolean allowed = true;
for (LanguageLevel level : myVersionsToProcess) {
if (level.isOlderThan(LanguageLevel.PYTHON33)) {
allowed = false;
break;
}
}
if (allowed) {
return;
}
final PyFunction function = PsiTreeUtil.getParentOfType(node, PyFunction.class, false, PyClass.class);
if (function != null && node.getExpression() != null) {
final YieldVisitor visitor = new YieldVisitor();
function.acceptChildren(visitor);
if (visitor.haveYield()) {
registerProblem(node, "Python versions < 3.3 do not allow 'return' with argument inside generator.");
}
}
}
@Override
public void visitPyNoneLiteralExpression(PyNoneLiteralExpression node) {
if (shouldBeCompatibleWithPy2() && node.isEllipsis()) {
final PySubscriptionExpression subscription = PsiTreeUtil.getParentOfType(node, PySubscriptionExpression.class);
if (subscription != null && PsiTreeUtil.isAncestor(subscription.getIndexExpression(), node, false)) {
return;
}
final PySliceItem sliceItem = PsiTreeUtil.getParentOfType(node, PySliceItem.class);
if (sliceItem != null) {
return;
}
registerProblem(node, "Python versions < 3.0 do not support '...' outside of sequence slicings.");
}
}
@Override
public void visitPyAugAssignmentStatement(PyAugAssignmentStatement node) {
super.visitPyAugAssignmentStatement(node);
final PsiElement operation = node.getOperation();
if (operation != null) {
final IElementType operationType = operation.getNode().getElementType();
if (PyTokenTypes.ATEQ.equals(operationType)) {
checkMatrixMultiplicationOperator(operation);
}
}
}
private void checkAsyncKeyword(@NotNull PsiElement node) {
final ASTNode asyncNode = node.getNode().findChildByType(PyTokenTypes.ASYNC_KEYWORD);
if (asyncNode != null) {
for (LanguageLevel level : myVersionsToProcess) {
if (level.isOlderThan(LanguageLevel.PYTHON35)) {
registerProblem(node, asyncNode.getTextRange(), "Python versions < 3.5 do not support this syntax", null, true);
break;
}
}
}
}
private static class YieldVisitor extends PyElementVisitor {
private boolean _haveYield = false;
public boolean haveYield() {
return _haveYield;
}
@Override
public void visitPyYieldExpression(final PyYieldExpression node) {
_haveYield = true;
}
@Override
public void visitPyElement(final PyElement node) {
if (!_haveYield) {
node.acceptChildren(this);
}
}
@Override
public void visitPyFunction(final PyFunction node) {
// do not go to nested functions
}
}
protected abstract void registerProblem(@Nullable PsiElement node,
@NotNull String message,
@Nullable LocalQuickFix localQuickFix,
boolean asError);
protected abstract void registerProblem(@NotNull PsiElement node,
@NotNull TextRange range,
@NotNull String message,
@Nullable LocalQuickFix localQuickFix,
boolean asError);
protected void registerProblem(@Nullable PsiElement node, @NotNull String message, @Nullable LocalQuickFix localQuickFix) {
registerProblem(node, message, localQuickFix, true);
}
protected void registerProblem(@Nullable PsiElement node, @NotNull String message) {
registerProblem(node, message, null);
}
protected void setVersionsToProcess(@NotNull List<LanguageLevel> versionsToProcess) {
myVersionsToProcess = versionsToProcess;
}
protected void commonRegisterProblem(@NotNull StringBuilder initMessage,
@NotNull String suffix,
int len,
@NotNull PyElement node,
@Nullable LocalQuickFix localQuickFix) {
commonRegisterProblem(initMessage, suffix, len, node, node.getTextRange(), localQuickFix, true);
}
protected void commonRegisterProblem(@NotNull StringBuilder initMessage,
@NotNull String suffix,
int len,
@NotNull PyElement node,
@NotNull TextRange range,
@Nullable LocalQuickFix localQuickFix) {
commonRegisterProblem(initMessage, suffix, len, node, range, localQuickFix, true);
}
protected void commonRegisterProblem(@NotNull StringBuilder initMessage,
@NotNull String suffix,
int len,
@NotNull PyElement node,
@NotNull TextRange range,
@Nullable LocalQuickFix localQuickFix,
boolean asError) {
initMessage.append(" do");
if (len == 1) {
initMessage.append("es");
}
initMessage.append(suffix);
if (len != 0) {
registerProblem(node, range, initMessage.toString(), localQuickFix, asError);
}
}
protected void commonRegisterProblem(@NotNull StringBuilder initMessage,
@NotNull String suffix,
int len,
@NotNull PyElement node,
@Nullable LocalQuickFix localQuickFix,
boolean asError) {
commonRegisterProblem(initMessage, suffix, len, node, node.getTextRange(), localQuickFix, asError);
}
protected static int appendLanguageLevel(@NotNull StringBuilder message, int len, @NotNull LanguageLevel languageLevel) {
if (len != 0) {
message.append(", ");
}
message.append(languageLevel.toString());
return ++len;
}
protected static int appendLanguageLevels(@NotNull StringBuilder message,
@NotNull Collection<LanguageLevel> levels,
@NotNull Predicate<LanguageLevel> levelPredicate) {
int len = 0;
for (LanguageLevel languageLevel : levels) {
if (levelPredicate.test(languageLevel)) {
len = appendLanguageLevel(message, len, languageLevel);
}
}
return len;
}
private void registerFirst(@Nullable PsiElement node,
@NotNull String message,
@NotNull Collection<LanguageLevel> levels,
@NotNull Predicate<LanguageLevel> levelPredicate) {
registerFirst(node, message, null, levels, levelPredicate);
}
private void registerFirst(@Nullable PsiElement node,
@NotNull String message,
@Nullable LocalQuickFix localQuickFix,
@NotNull Collection<LanguageLevel> levels,
@NotNull Predicate<LanguageLevel> levelPredicate) {
if (levels.stream().anyMatch(levelPredicate)) {
registerProblem(node, message, localQuickFix);
}
}
@Override
public void visitPyNonlocalStatement(final PyNonlocalStatement node) {
if (shouldBeCompatibleWithPy2()) {
registerProblem(node, "nonlocal keyword available only since py3", null, false);
}
}
protected boolean shouldBeCompatibleWithPy2() {
for (LanguageLevel level : myVersionsToProcess) {
if (level.isOlderThan(LanguageLevel.PYTHON30)) {
return true;
}
}
return false;
}
protected boolean shouldBeCompatibleWithPy3() {
for (LanguageLevel level : myVersionsToProcess) {
if (level.isPy3K()) {
return true;
}
}
return false;
}
private void highlightIncorrectArguments(@NotNull PyCallExpression callExpression) {
final Set<String> keywordArgumentNames = new HashSet<>();
boolean seenKeywordArgument = false;
boolean seenKeywordContainer = false;
boolean seenPositionalContainer = false;
for (PyExpression argument : callExpression.getArguments()) {
if (argument instanceof PyKeywordArgument) {
final String keyword = ((PyKeywordArgument)argument).getKeyword();
if (keywordArgumentNames.contains(keyword)) {
registerProblem(argument, "Keyword argument repeated", new PyRemoveArgumentQuickFix());
}
else if (seenPositionalContainer) {
registerFirst(argument,
"Python versions < 2.6 do not allow keyword arguments after *expression",
new PyRemoveArgumentQuickFix(),
myVersionsToProcess,
level -> level.isOlderThan(LanguageLevel.PYTHON26));
}
else if (seenKeywordContainer) {
registerFirst(argument,
"Python versions < 3.5 do not allow keyword arguments after **expression",
new PyRemoveArgumentQuickFix(),
myVersionsToProcess,
level -> level.isOlderThan(LanguageLevel.PYTHON35));
}
seenKeywordArgument = true;
keywordArgumentNames.add(keyword);
}
else if (argument instanceof PyStarArgument) {
final PyStarArgument starArgument = (PyStarArgument)argument;
if (starArgument.isKeyword()) {
if (seenKeywordContainer) {
registerFirst(argument,
"Python versions < 3.5 do not allow duplicate **expressions",
new PyRemoveArgumentQuickFix(),
myVersionsToProcess,
level -> level.isOlderThan(LanguageLevel.PYTHON35));
}
seenKeywordContainer = true;
}
else {
if (seenPositionalContainer) {
registerFirst(argument,
"Python versions < 3.5 do not allow duplicate *expressions",
new PyRemoveArgumentQuickFix(),
myVersionsToProcess,
level -> level.isOlderThan(LanguageLevel.PYTHON35));
}
seenPositionalContainer = true;
}
}
else {
if (seenKeywordArgument) {
registerProblem(argument, "Positional argument after keyword argument", new PyRemoveArgumentQuickFix());
}
else if (seenPositionalContainer) {
registerFirst(argument,
"Python versions < 3.5 do not allow positional arguments after *expression",
new PyRemoveArgumentQuickFix(),
myVersionsToProcess,
level -> level.isOlderThan(LanguageLevel.PYTHON35));
}
else if (seenKeywordContainer) {
registerProblem(argument, "Positional argument after **expression", new PyRemoveArgumentQuickFix());
}
}
}
}
}
| python/src/com/jetbrains/python/validation/CompatibilityVisitor.java | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.validation;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiWhiteSpace;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.QualifiedName;
import com.intellij.util.ArrayUtil;
import com.jetbrains.python.PyNames;
import com.jetbrains.python.PyTokenTypes;
import com.jetbrains.python.inspections.quickfix.*;
import com.jetbrains.python.psi.*;
import com.jetbrains.python.psi.impl.PyStringLiteralExpressionImpl;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.function.Predicate;
/**
* User : catherine
*/
public abstract class CompatibilityVisitor extends PyAnnotator {
@NotNull
private static final Map<LanguageLevel, Set<String>> AVAILABLE_PREFIXES = Maps.newHashMap();
@NotNull
private static final Set<String> DEFAULT_PREFIXES = Sets.newHashSet("R", "U", "B", "BR", "RB");
@NotNull
protected static final String COMMON_MESSAGE = "Python version ";
@NotNull
protected List<LanguageLevel> myVersionsToProcess;
static {
AVAILABLE_PREFIXES.put(LanguageLevel.PYTHON24, Sets.newHashSet("R", "U", "UR"));
AVAILABLE_PREFIXES.put(LanguageLevel.PYTHON25, Sets.newHashSet("R", "U", "UR"));
AVAILABLE_PREFIXES.put(LanguageLevel.PYTHON26, Sets.newHashSet("R", "U", "UR", "B", "BR"));
AVAILABLE_PREFIXES.put(LanguageLevel.PYTHON27, Sets.newHashSet("R", "U", "UR", "B", "BR"));
AVAILABLE_PREFIXES.put(LanguageLevel.PYTHON30, Sets.newHashSet("R", "B"));
AVAILABLE_PREFIXES.put(LanguageLevel.PYTHON31, Sets.newHashSet("R", "B", "BR"));
AVAILABLE_PREFIXES.put(LanguageLevel.PYTHON32, Sets.newHashSet("R", "B", "BR"));
AVAILABLE_PREFIXES.put(LanguageLevel.PYTHON36, Sets.newHashSet("R", "U", "B", "BR", "RB", "F", "FR", "RF"));
}
public CompatibilityVisitor(@NotNull List<LanguageLevel> versionsToProcess) {
myVersionsToProcess = versionsToProcess;
}
@Override
public void visitPyAnnotation(PyAnnotation node) {
final PsiElement parent = node.getParent();
if (!(parent instanceof PyFunction || parent instanceof PyNamedParameter)) {
final StringBuilder message = new StringBuilder(COMMON_MESSAGE);
int len = 0;
for (LanguageLevel languageLevel : myVersionsToProcess) {
if (languageLevel.isOlderThan(LanguageLevel.PYTHON36)) {
len = appendLanguageLevel(message, len, languageLevel);
}
}
commonRegisterProblem(message, " not support variable annotations", len, node, null);
}
}
@Override
public void visitPyDictCompExpression(PyDictCompExpression node) {
super.visitPyDictCompExpression(node);
final StringBuilder message = new StringBuilder(COMMON_MESSAGE);
final int len = appendLanguageLevels(message, myVersionsToProcess, level -> !level.supportsSetLiterals());
commonRegisterProblem(message, " not support dictionary comprehensions", len, node, new ConvertDictCompQuickFix(), false);
}
@Override
public void visitPySetLiteralExpression(PySetLiteralExpression node) {
super.visitPySetLiteralExpression(node);
final StringBuilder message = new StringBuilder(COMMON_MESSAGE);
final int len = appendLanguageLevels(message, myVersionsToProcess, level -> !level.supportsSetLiterals());
commonRegisterProblem(message, " not support set literal expressions", len, node, new ConvertSetLiteralQuickFix(), false);
}
@Override
public void visitPySetCompExpression(PySetCompExpression node) {
super.visitPySetCompExpression(node);
final StringBuilder message = new StringBuilder(COMMON_MESSAGE);
final int len = appendLanguageLevels(message, myVersionsToProcess, level -> !level.supportsSetLiterals());
commonRegisterProblem(message, " not support set comprehensions", len, node, null, false);
}
@Override
public void visitPyExceptBlock(PyExceptPart node) {
super.visitPyExceptBlock(node);
final PyExpression exceptClass = node.getExceptClass();
if (exceptClass != null) {
if (myVersionsToProcess.contains(LanguageLevel.PYTHON24) || myVersionsToProcess.contains(LanguageLevel.PYTHON25)) {
PsiElement element = exceptClass.getNextSibling();
while (element instanceof PsiWhiteSpace) {
element = element.getNextSibling();
}
if (element != null && "as".equals(element.getText())) {
registerProblem(node, COMMON_MESSAGE + "2.4, 2.5 do not support this syntax.");
}
}
PsiElement element = exceptClass.getNextSibling();
while (element instanceof PsiWhiteSpace) {
element = element.getNextSibling();
}
if (element != null && ",".equals(element.getText())) {
final StringBuilder message = new StringBuilder(COMMON_MESSAGE);
final int len = appendLanguageLevels(message, myVersionsToProcess, LanguageLevel::isPy3K);
commonRegisterProblem(message, " not support this syntax.", len, node, new ReplaceExceptPartQuickFix());
}
}
}
@Override
public void visitPyImportStatement(PyImportStatement node) {
super.visitPyImportStatement(node);
final PyIfStatement ifParent = PsiTreeUtil.getParentOfType(node, PyIfStatement.class);
if (ifParent != null) return;
for (PyImportElement importElement : node.getImportElements()) {
final QualifiedName qName = importElement.getImportedQName();
if (qName != null) {
final StringBuilder message = new StringBuilder(COMMON_MESSAGE);
final int len;
if (qName.matches("builtins")) {
len = appendLanguageLevels(message, myVersionsToProcess, level -> !level.isPy3K());
commonRegisterProblem(message, " not have module builtins", len, node, new ReplaceBuiltinsQuickFix());
}
else if (qName.matches("__builtin__")) {
len = appendLanguageLevels(message, myVersionsToProcess, LanguageLevel::isPy3K);
commonRegisterProblem(message, " not have module __builtin__", len, node, new ReplaceBuiltinsQuickFix());
}
}
}
}
@Override
public void visitPyStarExpression(PyStarExpression node) {
super.visitPyStarExpression(node);
if (node.isAssignmentTarget()) {
for (LanguageLevel level : myVersionsToProcess) {
if (level.isOlderThan(LanguageLevel.PYTHON30)) {
registerProblem(node, "Python versions < 3.0 do not support starred expressions as assignment targets");
break;
}
}
}
if (node.isUnpacking()) {
for (LanguageLevel level : myVersionsToProcess) {
if (level.isOlderThan(LanguageLevel.PYTHON35)) {
registerProblem(node, "Python versions < 3.5 do not support starred expressions in tuples, lists, and sets");
break;
}
}
}
}
@Override
public void visitPyDoubleStarExpression(PyDoubleStarExpression node) {
super.visitPyDoubleStarExpression(node);
for (LanguageLevel level : myVersionsToProcess) {
if (level.isOlderThan(LanguageLevel.PYTHON35)) {
registerProblem(node, "Python versions < 3.5 do not support starred expressions in dicts");
break;
}
}
}
@Override
public void visitPyBinaryExpression(PyBinaryExpression node) {
super.visitPyBinaryExpression(node);
if (node.isOperator("<>")) {
final StringBuilder message = new StringBuilder(COMMON_MESSAGE);
final int len = appendLanguageLevels(message, myVersionsToProcess, LanguageLevel::isPy3K);
commonRegisterProblem(message, " not support <>, use != instead.", len, node, new ReplaceNotEqOperatorQuickFix());
}
else if (node.isOperator("@")) {
checkMatrixMultiplicationOperator(node.getPsiOperator());
}
}
private void checkMatrixMultiplicationOperator(PsiElement node) {
boolean problem = false;
for (LanguageLevel level : myVersionsToProcess) {
if (level.isOlderThan(LanguageLevel.PYTHON35)) {
problem = true;
break;
}
}
if (problem) {
registerProblem(node, "Python versions < 3.5 do not support matrix multiplication operators");
}
}
@Override
public void visitPyNumericLiteralExpression(final PyNumericLiteralExpression node) {
super.visitPyNumericLiteralExpression(node);
final String text = node.getText();
if (node.isIntegerLiteral()) {
if (text.endsWith("l") || text.endsWith("L")) {
final StringBuilder message = new StringBuilder(COMMON_MESSAGE);
final String suffix = " not support a trailing \'l\' or \'L\'.";
final int len = appendLanguageLevels(message, myVersionsToProcess, LanguageLevel::isPy3K);
commonRegisterProblem(message, suffix, len, node, new RemoveTrailingLQuickFix());
}
if (text.length() > 1 && text.charAt(0) == '0') {
final char secondChar = Character.toLowerCase(text.charAt(1));
if (secondChar != 'o' && secondChar != 'b' && secondChar != 'x' && text.chars().anyMatch(c -> c != '0')) {
final StringBuilder message = new StringBuilder(COMMON_MESSAGE);
final String suffix = " not support this syntax. It requires '0o' prefix for octal literals";
int len = appendLanguageLevels(message, myVersionsToProcess, LanguageLevel::isPy3K);
commonRegisterProblem(message, suffix, len, node, new ReplaceOctalNumericLiteralQuickFix());
}
}
}
if (text.contains("_")) {
final StringBuilder message = new StringBuilder(COMMON_MESSAGE);
final String suffix = " not support underscores in numeric literals";
final int len = appendLanguageLevels(message, myVersionsToProcess, level -> level.isOlderThan(LanguageLevel.PYTHON36));
commonRegisterProblem(message, suffix, len, node, new PyRemoveUnderscoresInNumericLiteralsQuickFix());
}
}
@Override
public void visitPyStringLiteralExpression(final PyStringLiteralExpression node) {
super.visitPyStringLiteralExpression(node);
for (ASTNode stringNode : node.getStringNodes()) {
final String text = stringNode.getText();
final int prefixLength = PyStringLiteralExpressionImpl.getPrefixLength(text);
final String prefix = text.substring(0, prefixLength).toUpperCase();
if (prefix.isEmpty()) continue;
final StringBuilder message = new StringBuilder(COMMON_MESSAGE);
final int len =
appendLanguageLevels(message, myVersionsToProcess,
level -> !AVAILABLE_PREFIXES.getOrDefault(level, DEFAULT_PREFIXES).contains(prefix));
final TextRange range = TextRange.create(stringNode.getStartOffset(), stringNode.getStartOffset() + prefixLength);
commonRegisterProblem(message, " not support a '" + prefix + "' prefix", len, node, range, new RemovePrefixQuickFix(prefix));
}
}
@Override
public void visitPyListCompExpression(final PyListCompExpression node) {
super.visitPyListCompExpression(node);
final StringBuilder message = new StringBuilder(COMMON_MESSAGE);
final int len =
appendLanguageLevels(message, myVersionsToProcess, level -> UnsupportedFeaturesUtil.visitPyListCompExpression(node, level));
for (ComprhForComponent forComponent : node.getForComponents()) {
commonRegisterProblem(message, " not support this syntax in list comprehensions.", len, forComponent.getIteratedList(),
new ReplaceListComprehensionsQuickFix());
}
}
@Override
public void visitPyRaiseStatement(PyRaiseStatement node) {
super.visitPyRaiseStatement(node);
// empty raise
StringBuilder message = new StringBuilder(COMMON_MESSAGE);
int len = appendLanguageLevels(message, myVersionsToProcess, level -> UnsupportedFeaturesUtil.raiseHasNoArgs(node, level));
commonRegisterProblem(message, " not support this syntax. Raise with no arguments can only be used in an except block",
len, node, null, false);
// raise 1, 2, 3
message = new StringBuilder(COMMON_MESSAGE);
len = appendLanguageLevels(message, myVersionsToProcess, level -> UnsupportedFeaturesUtil.raiseHasMoreThenOneArg(node, level));
commonRegisterProblem(message, " not support this syntax.", len, node, new ReplaceRaiseStatementQuickFix());
// raise exception from cause
message = new StringBuilder(COMMON_MESSAGE);
len = appendLanguageLevels(message, myVersionsToProcess, level -> UnsupportedFeaturesUtil.raiseHasFromKeyword(node, level));
commonRegisterProblem(message, " not support this syntax.", len, node, new ReplaceRaiseStatementQuickFix());
}
@Override
public void visitPyReprExpression(PyReprExpression node) {
super.visitPyReprExpression(node);
final StringBuilder message = new StringBuilder(COMMON_MESSAGE);
final int len = appendLanguageLevels(message, myVersionsToProcess, LanguageLevel::isPy3K);
commonRegisterProblem(message, " not support backquotes, use repr() instead", len, node, new ReplaceBackquoteExpressionQuickFix());
}
@Override
public void visitPyWithStatement(PyWithStatement node) {
super.visitPyWithStatement(node);
Set<PyWithItem> problemItems = new HashSet<>();
StringBuilder message = new StringBuilder(COMMON_MESSAGE);
for (int i = 0; i != myVersionsToProcess.size(); ++i) {
LanguageLevel languageLevel = myVersionsToProcess.get(i);
if (languageLevel == LanguageLevel.PYTHON24) {
registerProblem(node, "Python version 2.4 doesn't support this syntax.");
}
else if (!languageLevel.supportsSetLiterals()) {
final PyWithItem[] items = node.getWithItems();
if (items.length > 1) {
for (int j = 1; j < items.length; j++) {
if (!problemItems.isEmpty())
message.append(", ");
message.append(languageLevel.toString());
problemItems.add(items [j]);
}
}
}
}
message.append(" do not support multiple context managers");
for (PyWithItem item : problemItems) {
registerProblem(item, message.toString());
}
checkAsyncKeyword(node);
}
@Override
public void visitPyForStatement(PyForStatement node) {
super.visitPyForStatement(node);
checkAsyncKeyword(node);
}
@Override
public void visitPyClass(PyClass node) { //PY-2719
super.visitPyClass(node);
if (myVersionsToProcess.contains(LanguageLevel.PYTHON24)) {
PyArgumentList list = node.getSuperClassExpressionList();
if (list != null && list.getArguments().length == 0)
registerProblem(list, "Python version 2.4 does not support this syntax.");
}
}
@Override
public void visitPyPrintStatement(PyPrintStatement node) {
super.visitPyPrintStatement(node);
if (shouldBeCompatibleWithPy3()) {
boolean hasProblem = false;
PsiElement[] arguments = node.getChildren();
for (PsiElement element : arguments) {
if (!((element instanceof PyParenthesizedExpression) || (element instanceof PyTupleExpression))) {
hasProblem = true;
break;
}
}
if (hasProblem || arguments.length == 0)
registerProblem(node, "Python version >= 3.0 do not support this syntax. The print statement has been replaced with a print() function",
new CompatibilityPrintCallQuickFix());
}
}
@Override
public void visitPyFromImportStatement(PyFromImportStatement node) {
super.visitPyFromImportStatement(node);
PyReferenceExpression importSource = node.getImportSource();
if (importSource != null) {
if (myVersionsToProcess.contains(LanguageLevel.PYTHON24)) { //PY-2793
PsiElement prev = importSource.getPrevSibling();
if (prev != null && prev.getNode().getElementType() == PyTokenTypes.DOT)
registerProblem(node, "Python version 2.4 doesn't support this syntax.");
}
}
else {
if (myVersionsToProcess.contains(LanguageLevel.PYTHON24))
registerProblem(node, "Python version 2.4 doesn't support this syntax.");
}
}
@Override
public void visitPyAssignmentStatement(PyAssignmentStatement node) {
super.visitPyAssignmentStatement(node);
if (myVersionsToProcess.contains(LanguageLevel.PYTHON24)) {
PyExpression assignedValue = node.getAssignedValue();
Stack<PsiElement> st = new Stack<>(); // PY-2796
if (assignedValue != null)
st.push(assignedValue);
while (!st.isEmpty()) {
PsiElement el = st.pop();
if (el instanceof PyYieldExpression)
registerProblem(node, "Python version 2.4 doesn't support this syntax. " +
"In Python <= 2.4, yield was a statement; it didn't return any value.");
else {
for (PsiElement e : el.getChildren())
st.push(e);
}
}
}
}
@Override
public void visitPyConditionalExpression(PyConditionalExpression node) { //PY-4293
super.visitPyConditionalExpression(node);
if (myVersionsToProcess.contains(LanguageLevel.PYTHON24)) {
registerProblem(node, "Python version 2.4 doesn't support this syntax.");
}
}
@Override
public void visitPyTryExceptStatement(PyTryExceptStatement node) { // PY-2795
super.visitPyTryExceptStatement(node);
if (myVersionsToProcess.contains(LanguageLevel.PYTHON24)) {
PyExceptPart[] excepts = node.getExceptParts();
PyFinallyPart finallyPart = node.getFinallyPart();
if (excepts.length != 0 && finallyPart != null)
registerProblem(node, "Python version 2.4 doesn't support this syntax. You could use a finally block to ensure " +
"that code is always executed, or one or more except blocks to catch specific exceptions.");
}
}
@Override
public void visitPyCallExpression(PyCallExpression node) {
super.visitPyCallExpression(node);
final PsiElement firstChild = node.getFirstChild();
if (firstChild != null && PyNames.SUPER.equals(firstChild.getText()) && ArrayUtil.isEmpty(node.getArguments())) {
final StringBuilder message = new StringBuilder(COMMON_MESSAGE);
final int len = appendLanguageLevels(message, myVersionsToProcess, level -> !level.isPy3K());
commonRegisterProblem(message, " not support this syntax. super() should have arguments in Python 2", len, node, null);
}
highlightIncorrectArguments(node);
}
@Override
public void visitPyFunction(PyFunction node) {
super.visitPyFunction(node);
checkAsyncKeyword(node);
}
@Override
public void visitPyPrefixExpression(PyPrefixExpression node) {
super.visitPyPrefixExpression(node);
if (node.getOperator() == PyTokenTypes.AWAIT_KEYWORD) {
for (LanguageLevel level : myVersionsToProcess) {
if (level.isOlderThan(LanguageLevel.PYTHON35)) {
registerProblem(node, "Python versions < 3.5 do not support this syntax");
break;
}
}
}
}
@Override
public void visitPyYieldExpression(PyYieldExpression node) {
super.visitPyYieldExpression(node);
if (!node.isDelegating()) {
return;
}
for (LanguageLevel level : myVersionsToProcess) {
if (level.isOlderThan(LanguageLevel.PYTHON33)) {
registerProblem(node, "Python versions < 3.3 do not support this syntax. Delegating to a subgenerator is available since " +
"Python 3.3; use explicit iteration over subgenerator instead.");
break;
}
}
}
@Override
public void visitPyReturnStatement(PyReturnStatement node) {
boolean allowed = true;
for (LanguageLevel level : myVersionsToProcess) {
if (level.isOlderThan(LanguageLevel.PYTHON33)) {
allowed = false;
break;
}
}
if (allowed) {
return;
}
final PyFunction function = PsiTreeUtil.getParentOfType(node, PyFunction.class, false, PyClass.class);
if (function != null && node.getExpression() != null) {
final YieldVisitor visitor = new YieldVisitor();
function.acceptChildren(visitor);
if (visitor.haveYield()) {
registerProblem(node, "Python versions < 3.3 do not allow 'return' with argument inside generator.");
}
}
}
@Override
public void visitPyNoneLiteralExpression(PyNoneLiteralExpression node) {
if (shouldBeCompatibleWithPy2() && node.isEllipsis()) {
final PySubscriptionExpression subscription = PsiTreeUtil.getParentOfType(node, PySubscriptionExpression.class);
if (subscription != null && PsiTreeUtil.isAncestor(subscription.getIndexExpression(), node, false)) {
return;
}
final PySliceItem sliceItem = PsiTreeUtil.getParentOfType(node, PySliceItem.class);
if (sliceItem != null) {
return;
}
registerProblem(node, "Python versions < 3.0 do not support '...' outside of sequence slicings.");
}
}
@Override
public void visitPyAugAssignmentStatement(PyAugAssignmentStatement node) {
super.visitPyAugAssignmentStatement(node);
final PsiElement operation = node.getOperation();
if (operation != null) {
final IElementType operationType = operation.getNode().getElementType();
if (PyTokenTypes.ATEQ.equals(operationType)) {
checkMatrixMultiplicationOperator(operation);
}
}
}
private void checkAsyncKeyword(@NotNull PsiElement node) {
final ASTNode asyncNode = node.getNode().findChildByType(PyTokenTypes.ASYNC_KEYWORD);
if (asyncNode != null) {
for (LanguageLevel level : myVersionsToProcess) {
if (level.isOlderThan(LanguageLevel.PYTHON35)) {
registerProblem(node, asyncNode.getTextRange(), "Python versions < 3.5 do not support this syntax", null, true);
break;
}
}
}
}
private static class YieldVisitor extends PyElementVisitor {
private boolean _haveYield = false;
public boolean haveYield() {
return _haveYield;
}
@Override
public void visitPyYieldExpression(final PyYieldExpression node) {
_haveYield = true;
}
@Override
public void visitPyElement(final PyElement node) {
if (!_haveYield) {
node.acceptChildren(this);
}
}
@Override
public void visitPyFunction(final PyFunction node) {
// do not go to nested functions
}
}
protected abstract void registerProblem(@Nullable PsiElement node,
@NotNull String message,
@Nullable LocalQuickFix localQuickFix,
boolean asError);
protected abstract void registerProblem(@NotNull PsiElement node,
@NotNull TextRange range,
@NotNull String message,
@Nullable LocalQuickFix localQuickFix,
boolean asError);
protected void registerProblem(@Nullable PsiElement node, @NotNull String message, @Nullable LocalQuickFix localQuickFix) {
registerProblem(node, message, localQuickFix, true);
}
protected void registerProblem(@Nullable PsiElement node, @NotNull String message) {
registerProblem(node, message, null);
}
protected void setVersionsToProcess(@NotNull List<LanguageLevel> versionsToProcess) {
myVersionsToProcess = versionsToProcess;
}
protected void commonRegisterProblem(@NotNull StringBuilder initMessage,
@NotNull String suffix,
int len,
@NotNull PyElement node,
@Nullable LocalQuickFix localQuickFix) {
commonRegisterProblem(initMessage, suffix, len, node, node.getTextRange(), localQuickFix, true);
}
protected void commonRegisterProblem(@NotNull StringBuilder initMessage,
@NotNull String suffix,
int len,
@NotNull PyElement node,
@NotNull TextRange range,
@Nullable LocalQuickFix localQuickFix) {
commonRegisterProblem(initMessage, suffix, len, node, range, localQuickFix, true);
}
protected void commonRegisterProblem(@NotNull StringBuilder initMessage,
@NotNull String suffix,
int len,
@NotNull PyElement node,
@NotNull TextRange range,
@Nullable LocalQuickFix localQuickFix,
boolean asError) {
initMessage.append(" do");
if (len == 1) {
initMessage.append("es");
}
initMessage.append(suffix);
if (len != 0) {
registerProblem(node, range, initMessage.toString(), localQuickFix, asError);
}
}
protected void commonRegisterProblem(@NotNull StringBuilder initMessage,
@NotNull String suffix,
int len,
@NotNull PyElement node,
@Nullable LocalQuickFix localQuickFix,
boolean asError) {
commonRegisterProblem(initMessage, suffix, len, node, node.getTextRange(), localQuickFix, asError);
}
protected static int appendLanguageLevel(@NotNull StringBuilder message, int len, @NotNull LanguageLevel languageLevel) {
if (len != 0) {
message.append(", ");
}
message.append(languageLevel.toString());
return ++len;
}
protected static int appendLanguageLevels(@NotNull StringBuilder message,
@NotNull Collection<LanguageLevel> levels,
@NotNull Predicate<LanguageLevel> levelPredicate) {
int len = 0;
for (LanguageLevel languageLevel : levels) {
if (levelPredicate.test(languageLevel)) {
len = appendLanguageLevel(message, len, languageLevel);
}
}
return len;
}
@Override
public void visitPyNonlocalStatement(final PyNonlocalStatement node) {
if (shouldBeCompatibleWithPy2()) {
registerProblem(node, "nonlocal keyword available only since py3", null, false);
}
}
protected boolean shouldBeCompatibleWithPy2() {
for (LanguageLevel level : myVersionsToProcess) {
if (level.isOlderThan(LanguageLevel.PYTHON30)) {
return true;
}
}
return false;
}
protected boolean shouldBeCompatibleWithPy3() {
for (LanguageLevel level : myVersionsToProcess) {
if (level.isPy3K()) {
return true;
}
}
return false;
}
private void highlightIncorrectArguments(@NotNull PyCallExpression callExpression) {
final Set<String> keywordArgumentNames = new HashSet<>();
boolean seenKeywordArgument = false;
boolean seenKeywordContainer = false;
boolean seenPositionalContainer = false;
for (PyExpression argument : callExpression.getArguments()) {
if (argument instanceof PyKeywordArgument) {
seenKeywordArgument = true;
final String keyword = ((PyKeywordArgument)argument).getKeyword();
boolean reported = false;
if (keywordArgumentNames.contains(keyword)) {
registerProblem(argument, "Keyword argument repeated", new PyRemoveArgumentQuickFix());
reported = true;
}
if (seenPositionalContainer && !reported) {
for (LanguageLevel level : myVersionsToProcess) {
if (level.isOlderThan(LanguageLevel.PYTHON26)) {
registerProblem(argument, "Python versions < 2.6 do not allow keyword arguments after *expression",
new PyRemoveArgumentQuickFix());
reported = true;
break;
}
}
}
if (seenKeywordContainer && !reported) {
for (LanguageLevel level : myVersionsToProcess) {
if (level.isOlderThan(LanguageLevel.PYTHON35)) {
registerProblem(argument, "Python versions < 3.5 do not allow keyword arguments after **expression",
new PyRemoveArgumentQuickFix());
break;
}
}
}
keywordArgumentNames.add(keyword);
}
else if (argument instanceof PyStarArgument) {
final PyStarArgument starArgument = (PyStarArgument)argument;
if (starArgument.isKeyword()) {
if (seenKeywordContainer) {
for (LanguageLevel level : myVersionsToProcess) {
if (level.isOlderThan(LanguageLevel.PYTHON35)) {
registerProblem(argument, "Python versions < 3.5 do not allow duplicate **expressions", new PyRemoveArgumentQuickFix());
break;
}
}
}
seenKeywordContainer = true;
}
else {
if (seenPositionalContainer) {
for (LanguageLevel level : myVersionsToProcess) {
if (level.isOlderThan(LanguageLevel.PYTHON35)) {
registerProblem(argument, "Python versions < 3.5 do not allow duplicate *expressions", new PyRemoveArgumentQuickFix());
break;
}
}
}
seenPositionalContainer = true;
}
}
else {
if (seenKeywordArgument) {
registerProblem(argument, "Positional argument after keyword argument", new PyRemoveArgumentQuickFix());
}
else if (seenPositionalContainer) {
for (LanguageLevel level : myVersionsToProcess) {
if (level.isOlderThan(LanguageLevel.PYTHON35)) {
registerProblem(argument, "Python versions < 3.5 do not allow positional arguments after *expression",
new PyRemoveArgumentQuickFix());
break;
}
}
}
else if (seenKeywordContainer) {
registerProblem(argument, "Positional argument after **expression", new PyRemoveArgumentQuickFix());
}
}
}
}
}
| Introduce registerFirst method in CompatibilityVisitor to simplify languages processing
| python/src/com/jetbrains/python/validation/CompatibilityVisitor.java | Introduce registerFirst method in CompatibilityVisitor to simplify languages processing | <ide><path>ython/src/com/jetbrains/python/validation/CompatibilityVisitor.java
<ide> super.visitPyStarExpression(node);
<ide>
<ide> if (node.isAssignmentTarget()) {
<del> for (LanguageLevel level : myVersionsToProcess) {
<del> if (level.isOlderThan(LanguageLevel.PYTHON30)) {
<del> registerProblem(node, "Python versions < 3.0 do not support starred expressions as assignment targets");
<del> break;
<del> }
<del> }
<add> registerFirst(node,
<add> "Python versions < 3.0 do not support starred expressions as assignment targets",
<add> myVersionsToProcess,
<add> level -> level.isOlderThan(LanguageLevel.PYTHON30));
<ide> }
<ide>
<ide> if (node.isUnpacking()) {
<del> for (LanguageLevel level : myVersionsToProcess) {
<del> if (level.isOlderThan(LanguageLevel.PYTHON35)) {
<del> registerProblem(node, "Python versions < 3.5 do not support starred expressions in tuples, lists, and sets");
<del> break;
<del> }
<del> }
<add> registerFirst(node,
<add> "Python versions < 3.5 do not support starred expressions in tuples, lists, and sets",
<add> myVersionsToProcess,
<add> level -> level.isOlderThan(LanguageLevel.PYTHON35));
<ide> }
<ide> }
<ide>
<ide> public void visitPyDoubleStarExpression(PyDoubleStarExpression node) {
<ide> super.visitPyDoubleStarExpression(node);
<ide>
<del> for (LanguageLevel level : myVersionsToProcess) {
<del> if (level.isOlderThan(LanguageLevel.PYTHON35)) {
<del> registerProblem(node, "Python versions < 3.5 do not support starred expressions in dicts");
<del> break;
<del> }
<del> }
<add> registerFirst(node,
<add> "Python versions < 3.5 do not support starred expressions in dicts",
<add> myVersionsToProcess,
<add> level -> level.isOlderThan(LanguageLevel.PYTHON35));
<ide> }
<ide>
<ide> @Override
<ide> }
<ide>
<ide> private void checkMatrixMultiplicationOperator(PsiElement node) {
<del> boolean problem = false;
<del> for (LanguageLevel level : myVersionsToProcess) {
<del> if (level.isOlderThan(LanguageLevel.PYTHON35)) {
<del> problem = true;
<del> break;
<del> }
<del> }
<del> if (problem) {
<del> registerProblem(node, "Python versions < 3.5 do not support matrix multiplication operators");
<del> }
<add> registerFirst(node,
<add> "Python versions < 3.5 do not support matrix multiplication operators",
<add> myVersionsToProcess,
<add> level -> level.isOlderThan(LanguageLevel.PYTHON35));
<ide> }
<ide>
<ide> @Override
<ide>
<ide> final StringBuilder message = new StringBuilder(COMMON_MESSAGE);
<ide> final int len =
<del> appendLanguageLevels(message, myVersionsToProcess,
<add> appendLanguageLevels(message,
<add> myVersionsToProcess,
<ide> level -> !AVAILABLE_PREFIXES.getOrDefault(level, DEFAULT_PREFIXES).contains(prefix));
<ide>
<ide> final TextRange range = TextRange.create(stringNode.getStartOffset(), stringNode.getStartOffset() + prefixLength);
<ide> }
<ide>
<ide> @Override
<del> public void visitPyClass(PyClass node) { //PY-2719
<add> public void visitPyClass(PyClass node) { // PY-2719
<ide> super.visitPyClass(node);
<del> if (myVersionsToProcess.contains(LanguageLevel.PYTHON24)) {
<del> PyArgumentList list = node.getSuperClassExpressionList();
<del> if (list != null && list.getArguments().length == 0)
<del> registerProblem(list, "Python version 2.4 does not support this syntax.");
<add>
<add> final PyArgumentList list = node.getSuperClassExpressionList();
<add> if (list != null && list.getArguments().length == 0) {
<add> registerFirst(list, "Python version 2.4 does not support this syntax.", myVersionsToProcess, LanguageLevel.PYTHON24::equals);
<ide> }
<ide> }
<ide>
<ide> @Override
<ide> public void visitPyFromImportStatement(PyFromImportStatement node) {
<ide> super.visitPyFromImportStatement(node);
<del> PyReferenceExpression importSource = node.getImportSource();
<add>
<add> final PyReferenceExpression importSource = node.getImportSource();
<ide> if (importSource != null) {
<del> if (myVersionsToProcess.contains(LanguageLevel.PYTHON24)) { //PY-2793
<del> PsiElement prev = importSource.getPrevSibling();
<del> if (prev != null && prev.getNode().getElementType() == PyTokenTypes.DOT)
<del> registerProblem(node, "Python version 2.4 doesn't support this syntax.");
<add> final PsiElement prev = importSource.getPrevSibling();
<add> if (prev != null && prev.getNode().getElementType() == PyTokenTypes.DOT) { // PY-2793
<add> registerFirst(node, "Python version 2.4 doesn't support this syntax.", myVersionsToProcess, LanguageLevel.PYTHON24::equals);
<ide> }
<ide> }
<ide> else {
<del> if (myVersionsToProcess.contains(LanguageLevel.PYTHON24))
<del> registerProblem(node, "Python version 2.4 doesn't support this syntax.");
<add> registerFirst(node, "Python version 2.4 doesn't support this syntax.", myVersionsToProcess, LanguageLevel.PYTHON24::equals);
<ide> }
<ide> }
<ide>
<ide> @Override
<ide> public void visitPyConditionalExpression(PyConditionalExpression node) { //PY-4293
<ide> super.visitPyConditionalExpression(node);
<del> if (myVersionsToProcess.contains(LanguageLevel.PYTHON24)) {
<del> registerProblem(node, "Python version 2.4 doesn't support this syntax.");
<del> }
<add>
<add> registerFirst(node,
<add> "Python version 2.4 doesn't support this syntax.",
<add> myVersionsToProcess,
<add> LanguageLevel.PYTHON24::equals);
<ide> }
<ide>
<ide> @Override
<ide> public void visitPyTryExceptStatement(PyTryExceptStatement node) { // PY-2795
<ide> super.visitPyTryExceptStatement(node);
<del> if (myVersionsToProcess.contains(LanguageLevel.PYTHON24)) {
<del> PyExceptPart[] excepts = node.getExceptParts();
<del> PyFinallyPart finallyPart = node.getFinallyPart();
<del> if (excepts.length != 0 && finallyPart != null)
<del> registerProblem(node, "Python version 2.4 doesn't support this syntax. You could use a finally block to ensure " +
<del> "that code is always executed, or one or more except blocks to catch specific exceptions.");
<add>
<add> final PyExceptPart[] excepts = node.getExceptParts();
<add> final PyFinallyPart finallyPart = node.getFinallyPart();
<add> if (excepts.length != 0 && finallyPart != null) {
<add> registerFirst(node,
<add> "Python version 2.4 doesn't support this syntax. You could use a finally block to ensure " +
<add> "that code is always executed, or one or more except blocks to catch specific exceptions.",
<add> myVersionsToProcess,
<add> LanguageLevel.PYTHON24::equals);
<ide> }
<ide> }
<ide>
<ide> @Override
<ide> public void visitPyPrefixExpression(PyPrefixExpression node) {
<ide> super.visitPyPrefixExpression(node);
<add>
<ide> if (node.getOperator() == PyTokenTypes.AWAIT_KEYWORD) {
<del> for (LanguageLevel level : myVersionsToProcess) {
<del> if (level.isOlderThan(LanguageLevel.PYTHON35)) {
<del> registerProblem(node, "Python versions < 3.5 do not support this syntax");
<del> break;
<del> }
<del> }
<add> registerFirst(node,
<add> "Python versions < 3.5 do not support this syntax",
<add> myVersionsToProcess,
<add> level -> level.isOlderThan(LanguageLevel.PYTHON35));
<ide> }
<ide> }
<ide>
<ide> @Override
<ide> public void visitPyYieldExpression(PyYieldExpression node) {
<ide> super.visitPyYieldExpression(node);
<add>
<ide> if (!node.isDelegating()) {
<ide> return;
<ide> }
<del> for (LanguageLevel level : myVersionsToProcess) {
<del> if (level.isOlderThan(LanguageLevel.PYTHON33)) {
<del> registerProblem(node, "Python versions < 3.3 do not support this syntax. Delegating to a subgenerator is available since " +
<del> "Python 3.3; use explicit iteration over subgenerator instead.");
<del> break;
<del> }
<del> }
<add>
<add> registerFirst(node,
<add> "Python versions < 3.3 do not support this syntax. Delegating to a subgenerator is available since " +
<add> "Python 3.3; use explicit iteration over subgenerator instead.",
<add> myVersionsToProcess,
<add> level -> level.isOlderThan(LanguageLevel.PYTHON33));
<ide> }
<ide>
<ide> @Override
<ide> return len;
<ide> }
<ide>
<add> private void registerFirst(@Nullable PsiElement node,
<add> @NotNull String message,
<add> @NotNull Collection<LanguageLevel> levels,
<add> @NotNull Predicate<LanguageLevel> levelPredicate) {
<add> registerFirst(node, message, null, levels, levelPredicate);
<add> }
<add>
<add> private void registerFirst(@Nullable PsiElement node,
<add> @NotNull String message,
<add> @Nullable LocalQuickFix localQuickFix,
<add> @NotNull Collection<LanguageLevel> levels,
<add> @NotNull Predicate<LanguageLevel> levelPredicate) {
<add> if (levels.stream().anyMatch(levelPredicate)) {
<add> registerProblem(node, message, localQuickFix);
<add> }
<add> }
<add>
<ide> @Override
<ide> public void visitPyNonlocalStatement(final PyNonlocalStatement node) {
<ide> if (shouldBeCompatibleWithPy2()) {
<ide>
<ide> private void highlightIncorrectArguments(@NotNull PyCallExpression callExpression) {
<ide> final Set<String> keywordArgumentNames = new HashSet<>();
<add>
<ide> boolean seenKeywordArgument = false;
<ide> boolean seenKeywordContainer = false;
<ide> boolean seenPositionalContainer = false;
<add>
<ide> for (PyExpression argument : callExpression.getArguments()) {
<ide> if (argument instanceof PyKeywordArgument) {
<del> seenKeywordArgument = true;
<ide> final String keyword = ((PyKeywordArgument)argument).getKeyword();
<del> boolean reported = false;
<add>
<ide> if (keywordArgumentNames.contains(keyword)) {
<ide> registerProblem(argument, "Keyword argument repeated", new PyRemoveArgumentQuickFix());
<del> reported = true;
<del> }
<del> if (seenPositionalContainer && !reported) {
<del> for (LanguageLevel level : myVersionsToProcess) {
<del> if (level.isOlderThan(LanguageLevel.PYTHON26)) {
<del> registerProblem(argument, "Python versions < 2.6 do not allow keyword arguments after *expression",
<del> new PyRemoveArgumentQuickFix());
<del> reported = true;
<del> break;
<del> }
<del> }
<del> }
<del> if (seenKeywordContainer && !reported) {
<del> for (LanguageLevel level : myVersionsToProcess) {
<del> if (level.isOlderThan(LanguageLevel.PYTHON35)) {
<del> registerProblem(argument, "Python versions < 3.5 do not allow keyword arguments after **expression",
<del> new PyRemoveArgumentQuickFix());
<del> break;
<del> }
<del> }
<del> }
<add> }
<add> else if (seenPositionalContainer) {
<add> registerFirst(argument,
<add> "Python versions < 2.6 do not allow keyword arguments after *expression",
<add> new PyRemoveArgumentQuickFix(),
<add> myVersionsToProcess,
<add> level -> level.isOlderThan(LanguageLevel.PYTHON26));
<add> }
<add> else if (seenKeywordContainer) {
<add> registerFirst(argument,
<add> "Python versions < 3.5 do not allow keyword arguments after **expression",
<add> new PyRemoveArgumentQuickFix(),
<add> myVersionsToProcess,
<add> level -> level.isOlderThan(LanguageLevel.PYTHON35));
<add> }
<add>
<add> seenKeywordArgument = true;
<ide> keywordArgumentNames.add(keyword);
<ide> }
<ide> else if (argument instanceof PyStarArgument) {
<ide> final PyStarArgument starArgument = (PyStarArgument)argument;
<ide> if (starArgument.isKeyword()) {
<ide> if (seenKeywordContainer) {
<del> for (LanguageLevel level : myVersionsToProcess) {
<del> if (level.isOlderThan(LanguageLevel.PYTHON35)) {
<del> registerProblem(argument, "Python versions < 3.5 do not allow duplicate **expressions", new PyRemoveArgumentQuickFix());
<del> break;
<del> }
<del> }
<add> registerFirst(argument,
<add> "Python versions < 3.5 do not allow duplicate **expressions",
<add> new PyRemoveArgumentQuickFix(),
<add> myVersionsToProcess,
<add> level -> level.isOlderThan(LanguageLevel.PYTHON35));
<ide> }
<ide> seenKeywordContainer = true;
<ide> }
<ide> else {
<ide> if (seenPositionalContainer) {
<del> for (LanguageLevel level : myVersionsToProcess) {
<del> if (level.isOlderThan(LanguageLevel.PYTHON35)) {
<del> registerProblem(argument, "Python versions < 3.5 do not allow duplicate *expressions", new PyRemoveArgumentQuickFix());
<del> break;
<del> }
<del> }
<add> registerFirst(argument,
<add> "Python versions < 3.5 do not allow duplicate *expressions",
<add> new PyRemoveArgumentQuickFix(),
<add> myVersionsToProcess,
<add> level -> level.isOlderThan(LanguageLevel.PYTHON35));
<ide> }
<ide> seenPositionalContainer = true;
<ide> }
<ide> registerProblem(argument, "Positional argument after keyword argument", new PyRemoveArgumentQuickFix());
<ide> }
<ide> else if (seenPositionalContainer) {
<del> for (LanguageLevel level : myVersionsToProcess) {
<del> if (level.isOlderThan(LanguageLevel.PYTHON35)) {
<del> registerProblem(argument, "Python versions < 3.5 do not allow positional arguments after *expression",
<del> new PyRemoveArgumentQuickFix());
<del> break;
<del> }
<del> }
<add> registerFirst(argument,
<add> "Python versions < 3.5 do not allow positional arguments after *expression",
<add> new PyRemoveArgumentQuickFix(),
<add> myVersionsToProcess,
<add> level -> level.isOlderThan(LanguageLevel.PYTHON35));
<ide> }
<ide> else if (seenKeywordContainer) {
<ide> registerProblem(argument, "Positional argument after **expression", new PyRemoveArgumentQuickFix()); |
|
JavaScript | mit | 87dbe96516dd6d4695369f1857439dfdc158781d | 0 | elvinyung/strapbots | 'use strict';
var lfmt = require('lfmt');
var errorMsgs = {
noSuchCommand: 'Could not find the command {{query}}',
noHelpData: 'No documentation was provided for the command {{name}}',
noDesc: '(No description was provided for the command {{name}})'
};
var helpPageTemplate = '{{name}} -- {{description}}';
// given a root (as an object), find subcommand as a path.
var findCommand = function findCommand(root, path) {
var node = root;
var child;
while (path.length > 0) {
var target = path.shift();
child = node.subcommands &&
node.subcommands.length > 0 &&
node.subcommands[target];
if (!child) {
break;
}
};
return child;
};
var renderHelpPage = function buildHelpPage(query, command) {
if (!command) {
return lfmt.format(errorMsgs.noSuchCommand, {
query: query
});
}
if (!command.metadata || command.metadata.info) {
return lfmt.format(errorMsgs.noHelpData, {
name: command.name || query
});
}
var rendered = lfmt.format(helpPageTemplate, {
name: command.name || query,
description: command.metadata.info.description ||
command.metadata.description ||
errorMsgs.noDesc
});
var usage = command.metadata.info ?
command.metadata.info.usage : command.metadata.usage;
if (usage) {
rendered += lfmt.format('\nUsage: `{{usage}}`', {
usage: usage
});
}
var subcommands = command.metadata.subcommands;
if (subcommands && subcommands.length > 0) {
rendered += lfmt.format('\nSubcommands:')
subcommands.forEach(function(subcommand) {
rendered += lfmt.format('\n- {{name}}: `{{description}}`', {
name: subcommand.name,
description: subcommand.description || errorMsgs.noDesc
});
});
};
return rendered;
}
var help = function help(argv, bot, response, logger) {
logger.log(lfmt.format('Got help query "{{command}}"', {
command: argv.join(' ')
}));
var query = argv.slice(1),
commands = bot.commands;
if (query.length > 0) {
var command = findCommand(commands, query);
response.end(renderHelpPage(query, command));
}
else {
var commandSet = new Set();
var commandList = Object.keys(commands)
.filter(function filterStep(name) {
return !commandSet.has(commands[name]) && commandSet.add(commands[name]);
})
.map(function renderStep(name) {
var command = commands[name];
if (!command.metadata) {
return lfmt.format('`{{name}}`', {
name: name
});
}
name = command.metadata.name || name;
if (!command.metadata.info) {
return lfmt.format('`{{name}}`', {
name: name
});
}
var description = command.metadata.info.description;
return lfmt.format('`{{name}}` - {{description}}', {
name: name,
description: description
});
})
.join('\n');
response.end(commandList);
};
};
help.metadata = {
name: 'help',
command: 'help',
description: 'Shows help page for commands',
usage: 'help {command}'
};
module.exports = help;
| help/index.js | 'use strict';
var lfmt = require('lfmt');
var errorMsgs = {
noSuchCommand: 'Could not find the command {{query}}',
noHelpData: 'No documentation was provided for the command {{name}}',
noDesc: '(No description was provided for the command {{name}})'
};
var helpPageTemplate = '{{name}} -- {{description}}';
var renderHelpPage = function buildHelpPage(query, command) {
if (!command) {
return lfmt.format(errorMsgs.noSuchCommand, {
query: query
});
}
if (!command.metadata || command.metadata.info) {
return lfmt.format(errorMsgs.noHelpData, {
name: command.name || query
});
}
var rendered = lfmt.format(helpPageTemplate, {
name: command.name || query,
description: command.metadata.info.description ||
command.metadata.description ||
errorMsgs.noDesc
});
var usage = command.metadata.info ?
command.metadata.info.usage : command.metadata.usage;
if (usage) {
rendered += lfmt.format('\nUsage: `{{usage}}`', {
usage: usage
});
}
return rendered;
}
var help = function help(argv, bot, response, logger) {
logger.log(lfmt.format('Got help query "{{command}}"', {
command: argv.join(' ')
}));
var query = argv.slice(1)[0],
commands = bot.commands;
if (query) {
var command = commands[query];
response.end(renderHelpPage(query, command));
}
else {
var commandSet = new Set();
var commandList = Object.keys(commands)
.filter(function filterStep(name) {
return !commandSet.has(commands[name]) && commandSet.add(commands[name]);
})
.map(function renderStep(name) {
var command = commands[name];
if (!command.metadata) {
return lfmt.format('`{{name}}`', {
name: name
});
}
name = command.metadata.name || name;
if (!command.metadata.info) {
return lfmt.format('`{{name}}`', {
name: name
});
}
var description = command.metadata.info.description;
return lfmt.format('`{{name}}` - {{description}}', {
name: name,
description: description
});
})
.join('\n');
response.end(commandList);
};
};
help.metadata = {
name: 'help',
command: 'help',
description: 'Shows help page for commands',
usage: 'help {command}'
};
module.exports = help;
| Add support for traversing subcommands
| help/index.js | Add support for traversing subcommands | <ide><path>elp/index.js
<ide> };
<ide>
<ide> var helpPageTemplate = '{{name}} -- {{description}}';
<add>
<add>// given a root (as an object), find subcommand as a path.
<add>var findCommand = function findCommand(root, path) {
<add>
<add> var node = root;
<add> var child;
<add> while (path.length > 0) {
<add> var target = path.shift();
<add>
<add> child = node.subcommands &&
<add> node.subcommands.length > 0 &&
<add> node.subcommands[target];
<add>
<add> if (!child) {
<add> break;
<add> }
<add> };
<add>
<add> return child;
<add>};
<ide>
<ide> var renderHelpPage = function buildHelpPage(query, command) {
<ide> if (!command) {
<ide> });
<ide> }
<ide>
<add> var subcommands = command.metadata.subcommands;
<add> if (subcommands && subcommands.length > 0) {
<add> rendered += lfmt.format('\nSubcommands:')
<add> subcommands.forEach(function(subcommand) {
<add> rendered += lfmt.format('\n- {{name}}: `{{description}}`', {
<add> name: subcommand.name,
<add> description: subcommand.description || errorMsgs.noDesc
<add> });
<add> });
<add> };
<add>
<ide> return rendered;
<ide> }
<ide>
<ide> command: argv.join(' ')
<ide> }));
<ide>
<del> var query = argv.slice(1)[0],
<add> var query = argv.slice(1),
<ide> commands = bot.commands;
<ide>
<del> if (query) {
<del> var command = commands[query];
<add> if (query.length > 0) {
<add> var command = findCommand(commands, query);
<ide> response.end(renderHelpPage(query, command));
<ide> }
<ide> else { |
|
Java | apache-2.0 | f0a9870c85728fbda611376ec7475d0f2fc8e44b | 0 | mdunker/usergrid,mdunker/usergrid,mdunker/usergrid,mdunker/usergrid,mdunker/usergrid,mdunker/usergrid,mdunker/usergrid,mdunker/usergrid | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.usergrid.management.cassandra;
import java.util.Set;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.usergrid.ServiceITSetup;
import org.apache.usergrid.ServiceITSetupImpl;
import org.apache.usergrid.cassandra.CassandraResource;
import org.apache.usergrid.cassandra.ClearShiroSubject;
import org.apache.usergrid.cassandra.Concurrent;
import org.apache.usergrid.management.ApplicationInfo;
import org.apache.usergrid.management.OrganizationOwnerInfo;
import org.apache.usergrid.persistence.index.impl.ElasticSearchResource;
import static org.apache.usergrid.UUIDTestHelper.newUUIDString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/** @author zznate */
@Concurrent()
public class ApplicationCreatorIT {
@ClassRule
public static CassandraResource cassandraResource = CassandraResource.newWithAvailablePorts();
@ClassRule
public static ElasticSearchResource elasticSearchResource = new ElasticSearchResource();
@Rule
public ClearShiroSubject clearShiroSubject = new ClearShiroSubject();
@Rule
public ServiceITSetup setup = new ServiceITSetupImpl( cassandraResource, elasticSearchResource );
@Test
public void testCreateSampleApplication() throws Exception {
final String orgName = "appcreatortest" + newUUIDString();
final String appName = "nate-appcreatortest" + newUUIDString();
final String expecteAppname = "sandbox";
final String expectedName = orgName + "/" + expecteAppname;
OrganizationOwnerInfo orgOwner = setup.getMgmtSvc().createOwnerAndOrganization( orgName, appName, "Nate",
"nate+appcreatortest" + newUUIDString() + "@apigee.com", "password", true, false );
ApplicationInfo appInfo = setup.getAppCreator().createSampleFor( orgOwner.getOrganization() );
assertNotNull( appInfo );
assertEquals( expectedName, appInfo.getName() );
Set<String> rolePerms = setup.getEmf().getEntityManager( appInfo.getId() ).getRolePermissions( "guest" );
assertNotNull( rolePerms );
assertTrue( rolePerms.contains( "get,post,put,delete:/**" ) );
}
@Test
public void testCreateSampleApplicationAltName() throws Exception {
final String orgName = "appcreatortest" + newUUIDString();
final String appName = "nate-appcreatortest" + newUUIDString();
final String sampleAppName = "messagee" ;
final String expectedName = orgName + "/" + sampleAppName;
OrganizationOwnerInfo orgOwner = setup.getMgmtSvc().createOwnerAndOrganization( orgName, appName, "Nate",
"nate+appcreatortestcustom" + newUUIDString() + "@apigee.com", "password", true, false );
ApplicationCreatorImpl customCreator = new ApplicationCreatorImpl( setup.getEmf(), setup.getMgmtSvc() );
customCreator.setSampleAppName(sampleAppName);
ApplicationInfo appInfo = customCreator.createSampleFor( orgOwner.getOrganization() );
assertNotNull( appInfo );
assertEquals( expectedName, appInfo.getName() );
}
}
| stack/services/src/test/java/org/apache/usergrid/management/cassandra/ApplicationCreatorIT.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.usergrid.management.cassandra;
import java.util.Set;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.usergrid.ServiceITSetup;
import org.apache.usergrid.ServiceITSetupImpl;
import org.apache.usergrid.cassandra.CassandraResource;
import org.apache.usergrid.cassandra.ClearShiroSubject;
import org.apache.usergrid.cassandra.Concurrent;
import org.apache.usergrid.management.ApplicationInfo;
import org.apache.usergrid.management.OrganizationOwnerInfo;
import org.apache.usergrid.persistence.index.impl.ElasticSearchResource;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/** @author zznate */
@Concurrent()
public class ApplicationCreatorIT {
private static final Logger LOG = LoggerFactory.getLogger( ApplicationCreatorIT.class );
@ClassRule
public static CassandraResource cassandraResource = CassandraResource.newWithAvailablePorts();
@ClassRule
public static ElasticSearchResource elasticSearchResource = new ElasticSearchResource();
@Rule
public ClearShiroSubject clearShiroSubject = new ClearShiroSubject();
@Rule
public ServiceITSetup setup = new ServiceITSetupImpl( cassandraResource, elasticSearchResource );
@Test
public void testCreateSampleApplication() throws Exception {
OrganizationOwnerInfo orgOwner = setup.getMgmtSvc()
.createOwnerAndOrganization( "appcreatortest", "nate-appcreatortest",
"Nate", "[email protected]", "password", true,
false );
ApplicationInfo appInfo = setup.getAppCreator().createSampleFor( orgOwner.getOrganization() );
assertNotNull( appInfo );
assertEquals( "appcreatortest/sandbox", appInfo.getName() );
Set<String> rolePerms = setup.getEmf().getEntityManager( appInfo.getId() ).getRolePermissions( "guest" );
assertNotNull( rolePerms );
assertTrue( rolePerms.contains( "get,post,put,delete:/**" ) );
}
@Test
public void testCreateSampleApplicationAltName() throws Exception {
OrganizationOwnerInfo orgOwner = setup.getMgmtSvc().createOwnerAndOrganization( "appcreatortestcustom",
"nate-appcreatortestcustom", "Nate", "[email protected]", "password", true, false );
ApplicationCreatorImpl customCreator = new ApplicationCreatorImpl( setup.getEmf(), setup.getMgmtSvc() );
customCreator.setSampleAppName( "messagee" );
ApplicationInfo appInfo = customCreator.createSampleFor( orgOwner.getOrganization() );
assertNotNull( appInfo );
assertEquals( "appcreatortestcustom/messagee", appInfo.getName() );
}
}
| Fixes Creator test to use unique strings
| stack/services/src/test/java/org/apache/usergrid/management/cassandra/ApplicationCreatorIT.java | Fixes Creator test to use unique strings | <ide><path>tack/services/src/test/java/org/apache/usergrid/management/cassandra/ApplicationCreatorIT.java
<ide> import org.apache.usergrid.management.OrganizationOwnerInfo;
<ide> import org.apache.usergrid.persistence.index.impl.ElasticSearchResource;
<ide>
<add>import static org.apache.usergrid.UUIDTestHelper.newUUIDString;
<ide> import static org.junit.Assert.assertEquals;
<ide> import static org.junit.Assert.assertNotNull;
<ide> import static org.junit.Assert.assertTrue;
<ide> /** @author zznate */
<ide> @Concurrent()
<ide> public class ApplicationCreatorIT {
<del> private static final Logger LOG = LoggerFactory.getLogger( ApplicationCreatorIT.class );
<del>
<ide> @ClassRule
<ide> public static CassandraResource cassandraResource = CassandraResource.newWithAvailablePorts();
<ide>
<ide>
<ide> @Test
<ide> public void testCreateSampleApplication() throws Exception {
<del> OrganizationOwnerInfo orgOwner = setup.getMgmtSvc()
<del> .createOwnerAndOrganization( "appcreatortest", "nate-appcreatortest",
<del> "Nate", "[email protected]", "password", true,
<del> false );
<add>
<add> final String orgName = "appcreatortest" + newUUIDString();
<add> final String appName = "nate-appcreatortest" + newUUIDString();
<add> final String expecteAppname = "sandbox";
<add> final String expectedName = orgName + "/" + expecteAppname;
<add>
<add> OrganizationOwnerInfo orgOwner = setup.getMgmtSvc().createOwnerAndOrganization( orgName, appName, "Nate",
<add> "nate+appcreatortest" + newUUIDString() + "@apigee.com", "password", true, false );
<ide>
<ide> ApplicationInfo appInfo = setup.getAppCreator().createSampleFor( orgOwner.getOrganization() );
<ide> assertNotNull( appInfo );
<del> assertEquals( "appcreatortest/sandbox", appInfo.getName() );
<add> assertEquals( expectedName, appInfo.getName() );
<ide>
<ide> Set<String> rolePerms = setup.getEmf().getEntityManager( appInfo.getId() ).getRolePermissions( "guest" );
<ide> assertNotNull( rolePerms );
<ide>
<ide> @Test
<ide> public void testCreateSampleApplicationAltName() throws Exception {
<del> OrganizationOwnerInfo orgOwner = setup.getMgmtSvc().createOwnerAndOrganization( "appcreatortestcustom",
<del> "nate-appcreatortestcustom", "Nate", "[email protected]", "password", true, false );
<add>
<add> final String orgName = "appcreatortest" + newUUIDString();
<add> final String appName = "nate-appcreatortest" + newUUIDString();
<add> final String sampleAppName = "messagee" ;
<add> final String expectedName = orgName + "/" + sampleAppName;
<add>
<add> OrganizationOwnerInfo orgOwner = setup.getMgmtSvc().createOwnerAndOrganization( orgName, appName, "Nate",
<add> "nate+appcreatortestcustom" + newUUIDString() + "@apigee.com", "password", true, false );
<ide>
<ide> ApplicationCreatorImpl customCreator = new ApplicationCreatorImpl( setup.getEmf(), setup.getMgmtSvc() );
<del> customCreator.setSampleAppName( "messagee" );
<add> customCreator.setSampleAppName(sampleAppName);
<ide> ApplicationInfo appInfo = customCreator.createSampleFor( orgOwner.getOrganization() );
<ide> assertNotNull( appInfo );
<del> assertEquals( "appcreatortestcustom/messagee", appInfo.getName() );
<add> assertEquals( expectedName, appInfo.getName() );
<ide> }
<ide> } |
|
Java | apache-2.0 | 036ca6a2b22d1ae7c4f4f8647e6b5d8c2d4f8ab1 | 0 | atlasapi/atlas-deer,atlasapi/atlas-deer | package org.atlasapi.application;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import javax.annotation.Nullable;
import org.atlasapi.entity.Sourced;
import org.atlasapi.entity.Sourceds;
import org.atlasapi.media.entity.Publisher;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import com.google.common.collect.Sets;
public class ApplicationSources {
private final boolean precedence;
private final List<SourceReadEntry> reads;
private final List<Publisher> writes;
private final Optional<List<Publisher>> contentHierarchyPrecedence;
private final ImmutableSet<Publisher> enabledReadSources;
private final Boolean imagePrecedenceEnabled;
private static final Predicate<SourceReadEntry> ENABLED_READS_FILTER = new Predicate<SourceReadEntry>() {
@Override
public boolean apply(@Nullable SourceReadEntry input) {
return input.getSourceStatus().isEnabled();
}
};
private static final Function<SourceReadEntry, Publisher> SOURCEREADS_TO_PUBLISHER = new Function<SourceReadEntry, Publisher>() {
@Override
public Publisher apply(@Nullable SourceReadEntry input) {
return input.getPublisher();
}
};
private static final Function<SourceReadEntry, Publisher> READ_TO_PUBLISHER = new Function<SourceReadEntry, Publisher>() {
@Override
public Publisher apply(@Nullable SourceReadEntry input) {
return input.getPublisher();
}};
private static final Comparator<SourceReadEntry> SORT_READS_BY_PUBLISHER = new Comparator<SourceReadEntry>() {
@Override
public int compare(SourceReadEntry a, SourceReadEntry b) {
return a.getPublisher().compareTo(b.getPublisher());
}};
private ApplicationSources(Builder builder) {
this.precedence = builder.precedence;
this.reads = ImmutableList.copyOf(builder.reads);
this.writes = ImmutableList.copyOf(builder.writes);
this.contentHierarchyPrecedence = builder.contentHierarchyPrecedence;
this.imagePrecedenceEnabled = builder.imagePrecedenceEnabled;
this.enabledReadSources = ImmutableSet.copyOf(
Iterables.transform(
Iterables.filter(this.getReads(), ENABLED_READS_FILTER),
SOURCEREADS_TO_PUBLISHER)
);;
}
public boolean isPrecedenceEnabled() {
return precedence;
}
public List<SourceReadEntry> getReads() {
return reads;
}
public List<Publisher> getWrites() {
return writes;
}
public Ordering<Publisher> publisherPrecedenceOrdering() {
return Ordering.explicit(Lists.transform(reads, READ_TO_PUBLISHER));
}
private Optional<Ordering<Publisher>> contentHierarchyPrecedenceOrdering() {
if (contentHierarchyPrecedence.isPresent()) {
return Optional.of(Ordering.explicit(contentHierarchyPrecedence.get()));
} else {
return Optional.absent();
}
}
public Optional<List<Publisher>> contentHierarchyPrecedence() {
return contentHierarchyPrecedence;
}
private ImmutableList<Publisher> peoplePrecedence() {
return ImmutableList.of(Publisher.RADIO_TIMES, Publisher.PA, Publisher.BBC, Publisher.C4, Publisher.ITV);
}
public boolean peoplePrecedenceEnabled() {
return peoplePrecedence() != null;
}
public Ordering<Publisher> peoplePrecedenceOrdering() {
// Add missing publishers
return orderingIncludingMissingPublishers(peoplePrecedence());
}
private Ordering<Publisher> orderingIncludingMissingPublishers(List<Publisher> publishers) {
List<Publisher> fullListOfPublishers = Lists.newArrayList(publishers);
for (Publisher publisher : Publisher.values()) {
if (!fullListOfPublishers.contains(publisher)) {
fullListOfPublishers.add(publisher);
}
}
return Ordering.explicit(fullListOfPublishers);
}
public Ordering<Sourced> getSourcedPeoplePrecedenceOrdering() {
return peoplePrecedenceOrdering().onResultOf(Sourceds.toPublisher());
}
/**
* Temporary: these should be persisted and not hardcoded
*/
private ImmutableList<Publisher> imagePrecedence() {
return ImmutableList.of(Publisher.PA, Publisher.BBC, Publisher.C4);
}
public boolean imagePrecedenceEnabled() {
// The default behaviour should be enabled if not specified
return imagePrecedenceEnabled == null || imagePrecedenceEnabled;
}
public Ordering<Publisher> imagePrecedenceOrdering() {
return publisherPrecedenceOrdering();
}
public Ordering<Sourced> getSourcedImagePrecedenceOrdering() {
return imagePrecedenceOrdering().onResultOf(Sourceds.toPublisher());
}
public ImmutableSet<Publisher> getEnabledReadSources() {
return this.enabledReadSources;
}
public boolean isReadEnabled(Publisher source) {
return this.getEnabledReadSources().contains(source);
}
public boolean isWriteEnabled(Publisher source) {
return this.getWrites().contains(source);
}
public SourceStatus readStatusOrDefault(Publisher source) {
for (SourceReadEntry entry : this.getReads()) {
if (entry.getPublisher().equals(source)) {
return entry.getSourceStatus();
}
}
return SourceStatus.fromV3SourceStatus(source.getDefaultSourceStatus());
}
public Ordering<Sourced> getSourcedReadOrdering() {
Ordering<Publisher> ordering = this.publisherPrecedenceOrdering();
return ordering.onResultOf(Sourceds.toPublisher());
}
public Optional<Ordering<Sourced>> getSourcedContentHierarchyOrdering() {
if (!contentHierarchyPrecedence.isPresent()) {
return Optional.absent();
}
Ordering<Publisher> ordering = orderingIncludingMissingPublishers(this.contentHierarchyPrecedence.get());
return Optional.of(ordering.onResultOf(Sourceds.toPublisher()));
}
private static final ApplicationSources dflts = createDefaults();
private static final ApplicationSources createDefaults() {
ApplicationSources dflts = ApplicationSources.builder()
.build()
.copyWithMissingSourcesPopulated();
for (Publisher source : Publisher.all()) {
if (source.enabledWithNoApiKey()) {
dflts = dflts.copyWithChangedReadableSourceStatus(source, SourceStatus.AVAILABLE_ENABLED);
}
}
return dflts;
}
// Build a default configuration, this will get popualated with publishers
// with default source status
public static ApplicationSources defaults() {
return dflts;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof ApplicationSources) {
ApplicationSources other = (ApplicationSources) obj;
if (this.isPrecedenceEnabled() == other.isPrecedenceEnabled()) {
boolean readsEqual = this.getReads().equals(other.getReads());
boolean writesEqual = this.getWrites().containsAll(other.getWrites())
&& this.getWrites().size() == other.getWrites().size();
return readsEqual && writesEqual;
}
}
return false;
}
public ApplicationSources copyWithChangedReadableSourceStatus(Publisher source, SourceStatus status) {
List<SourceReadEntry> reads = Lists.newLinkedList();
for (SourceReadEntry entry : this.getReads()) {
if (entry.getPublisher().equals(source)) {
reads.add(new SourceReadEntry(source, status));
} else {
reads.add(entry);
}
}
return this.copy().withReadableSources(reads).build();
}
/*
* Adds any missing sources to the application.
*/
public ApplicationSources copyWithMissingSourcesPopulated() {
List<SourceReadEntry> readsAll = Lists.newLinkedList();
Set<Publisher> publishersSeen = Sets.newHashSet();
for (SourceReadEntry read : this.getReads()) {
readsAll.add(read);
publishersSeen.add(read.getPublisher());
}
for (Publisher source : Publisher.values()) {
if (!publishersSeen.contains(source)) {
SourceStatus status = SourceStatus.fromV3SourceStatus(source.getDefaultSourceStatus());
readsAll.add(new SourceReadEntry(source, status));
}
}
return this.copy().withReadableSources(readsAll).build();
}
public Builder copy() {
return builder()
.withPrecedence(this.isPrecedenceEnabled())
.withReadableSources(this.getReads())
.withImagePrecedenceEnabled(this.imagePrecedenceEnabled)
.withContentHierarchyPrecedence(this.contentHierarchyPrecedence().orNull())
.withWritableSources(this.getWrites());
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private Optional<List<Publisher>> contentHierarchyPrecedence = Optional.absent();
public boolean precedence = false;
private boolean imagePrecedenceEnabled = true;
private List<SourceReadEntry> reads = Lists.newLinkedList();
private List<Publisher> writes = Lists.newLinkedList();
public Builder withPrecedence(boolean precedence) {
this.precedence = precedence;
return this;
}
public Builder withContentHierarchyPrecedence(List<Publisher> contentHierarchyPrecedence) {
if (contentHierarchyPrecedence != null) {
this.contentHierarchyPrecedence = Optional.of(ImmutableList.copyOf(contentHierarchyPrecedence));
} else {
this.contentHierarchyPrecedence = Optional.absent();
}
return this;
}
public Builder withReadableSources(List<SourceReadEntry> reads) {
this.reads = reads;
return this;
}
public Builder withWritableSources(List<Publisher> writes) {
this.writes = writes;
return this;
}
public Builder withImagePrecedenceEnabled(boolean imagePrecedenceEnabled) {
this.imagePrecedenceEnabled = imagePrecedenceEnabled;
return this;
}
public ApplicationSources build() {
// If precedence not enabled then sort reads by publisher key order
if (!this.precedence) {
Collections.sort(Lists.newArrayList(this.reads), SORT_READS_BY_PUBLISHER);
}
return new ApplicationSources(this);
}
}
}
| atlas-core/src/main/java/org/atlasapi/application/ApplicationSources.java | package org.atlasapi.application;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import javax.annotation.Nullable;
import org.atlasapi.entity.Sourced;
import org.atlasapi.entity.Sourceds;
import org.atlasapi.media.entity.Publisher;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import com.google.common.collect.Sets;
public class ApplicationSources {
private final boolean precedence;
private final List<SourceReadEntry> reads;
private final List<Publisher> writes;
private final Optional<List<Publisher>> contentHierarchyPrecedence;
private final ImmutableSet<Publisher> enabledReadSources;
private final Boolean imagePrecedenceEnabled;
private static final Predicate<SourceReadEntry> ENABLED_READS_FILTER = new Predicate<SourceReadEntry>() {
@Override
public boolean apply(@Nullable SourceReadEntry input) {
return input.getSourceStatus().isEnabled();
}
};
private static final Function<SourceReadEntry, Publisher> SOURCEREADS_TO_PUBLISHER = new Function<SourceReadEntry, Publisher>() {
@Override
public Publisher apply(@Nullable SourceReadEntry input) {
return input.getPublisher();
}
};
private static final Function<SourceReadEntry, Publisher> READ_TO_PUBLISHER = new Function<SourceReadEntry, Publisher>() {
@Override
public Publisher apply(@Nullable SourceReadEntry input) {
return input.getPublisher();
}};
private static final Comparator<SourceReadEntry> SORT_READS_BY_PUBLISHER = new Comparator<SourceReadEntry>() {
@Override
public int compare(SourceReadEntry a, SourceReadEntry b) {
return a.getPublisher().compareTo(b.getPublisher());
}};
private ApplicationSources(Builder builder) {
this.precedence = builder.precedence;
this.reads = ImmutableList.copyOf(builder.reads);
this.writes = ImmutableList.copyOf(builder.writes);
this.contentHierarchyPrecedence = builder.contentHierarchyPrecedence;
this.imagePrecedenceEnabled = builder.imagePrecedenceEnabled;
this.enabledReadSources = ImmutableSet.copyOf(
Iterables.transform(
Iterables.filter(this.getReads(), ENABLED_READS_FILTER),
SOURCEREADS_TO_PUBLISHER)
);;
}
public boolean isPrecedenceEnabled() {
return precedence;
}
public List<SourceReadEntry> getReads() {
return reads;
}
public List<Publisher> getWrites() {
return writes;
}
public Ordering<Publisher> publisherPrecedenceOrdering() {
return Ordering.explicit(Lists.transform(reads, READ_TO_PUBLISHER));
}
private Optional<Ordering<Publisher>> contentHierarchyPrecedenceOrdering() {
if (contentHierarchyPrecedence.isPresent()) {
return Optional.of(Ordering.explicit(contentHierarchyPrecedence.get()));
} else {
return Optional.absent();
}
}
public Optional<List<Publisher>> contentHierarchyPrecedence() {
return contentHierarchyPrecedence;
}
private ImmutableList<Publisher> peoplePrecedence() {
return ImmutableList.of(Publisher.RADIO_TIMES, Publisher.PA, Publisher.BBC, Publisher.C4, Publisher.ITV);
}
public boolean peoplePrecedenceEnabled() {
return peoplePrecedence() != null;
}
public Ordering<Publisher> peoplePrecedenceOrdering() {
// Add missing publishers
return orderingIncludingMissingPublishers(peoplePrecedence());
}
private Ordering<Publisher> orderingIncludingMissingPublishers(List<Publisher> publishers) {
List<Publisher> fullListOfPublishers = Lists.newArrayList(publishers);
for (Publisher publisher : Publisher.values()) {
if (!fullListOfPublishers.contains(publisher)) {
fullListOfPublishers.add(publisher);
}
}
return Ordering.explicit(fullListOfPublishers);
}
public Ordering<Sourced> getSourcedPeoplePrecedenceOrdering() {
return peoplePrecedenceOrdering().onResultOf(Sourceds.toPublisher());
}
/**
* Temporary: these should be persisted and not hardcoded
*/
private ImmutableList<Publisher> imagePrecedence() {
return ImmutableList.of(Publisher.PA, Publisher.BBC, Publisher.C4);
}
public boolean imagePrecedenceEnabled() {
// The default behaviour should be enabled if not specified
return imagePrecedenceEnabled == null || imagePrecedenceEnabled;
}
public Ordering<Publisher> imagePrecedenceOrdering() {
return publisherPrecedenceOrdering();
}
public Ordering<Sourced> getSourcedImagePrecedenceOrdering() {
return imagePrecedenceOrdering().onResultOf(Sourceds.toPublisher());
}
public ImmutableSet<Publisher> getEnabledReadSources() {
return this.enabledReadSources;
}
public boolean isReadEnabled(Publisher source) {
return this.getEnabledReadSources().contains(source);
}
public boolean isWriteEnabled(Publisher source) {
return this.getWrites().contains(source);
}
public SourceStatus readStatusOrDefault(Publisher source) {
for (SourceReadEntry entry : this.getReads()) {
if (entry.getPublisher().equals(source)) {
return entry.getSourceStatus();
}
}
return SourceStatus.fromV3SourceStatus(source.getDefaultSourceStatus());
}
public Ordering<Sourced> getSourcedReadOrdering() {
Ordering<Publisher> ordering = this.publisherPrecedenceOrdering();
return ordering.onResultOf(Sourceds.toPublisher());
}
public Optional<Ordering<Sourced>> getSourcedContentHierarchyOrdering() {
if (!contentHierarchyPrecedence.isPresent()) {
return Optional.absent();
}
Ordering<Publisher> ordering = orderingIncludingMissingPublishers(this.contentHierarchyPrecedence.get());
return Optional.of(ordering.onResultOf(Sourceds.toPublisher()));
}
private static final ApplicationSources dflts = createDefaults();
private static final ApplicationSources createDefaults() {
ApplicationSources dflts = ApplicationSources.builder()
.build()
.copyWithMissingSourcesPopulated();
for (Publisher source : Publisher.all()) {
if (source.enabledWithNoApiKey()) {
dflts = dflts.copyWithChangedReadableSourceStatus(source, SourceStatus.AVAILABLE_ENABLED);
}
}
return dflts;
}
// Build a default configuration, this will get popualated with publishers
// with default source status
public static ApplicationSources defaults() {
return dflts;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof ApplicationSources) {
ApplicationSources other = (ApplicationSources) obj;
if (this.isPrecedenceEnabled() == other.isPrecedenceEnabled()) {
boolean readsEqual = this.getReads().equals(other.getReads());
boolean writesEqual = this.getWrites().containsAll(other.getWrites())
&& this.getWrites().size() == other.getWrites().size();
return readsEqual && writesEqual;
}
}
return false;
}
public ApplicationSources copyWithChangedReadableSourceStatus(Publisher source, SourceStatus status) {
List<SourceReadEntry> reads = Lists.newLinkedList();
for (SourceReadEntry entry : this.getReads()) {
if (entry.getPublisher().equals(source)) {
reads.add(new SourceReadEntry(source, status));
} else {
reads.add(entry);
}
}
return this.copy().withReadableSources(reads).build();
}
/*
* Adds any missing sources to the application.
*/
public ApplicationSources copyWithMissingSourcesPopulated() {
List<SourceReadEntry> readsAll = Lists.newLinkedList();
Set<Publisher> publishersSeen = Sets.newHashSet();
for (SourceReadEntry read : this.getReads()) {
readsAll.add(read);
publishersSeen.add(read.getPublisher());
}
for (Publisher source : Publisher.values()) {
if (!publishersSeen.contains(source)) {
SourceStatus status = SourceStatus.fromV3SourceStatus(source.getDefaultSourceStatus());
readsAll.add(new SourceReadEntry(source, status));
}
}
return this.copy().withReadableSources(readsAll).build();
}
public Builder copy() {
return builder()
.withPrecedence(this.isPrecedenceEnabled())
.withReadableSources(this.getReads())
.withContentHierarchyPrecedence(this.contentHierarchyPrecedence().orNull())
.withWritableSources(this.getWrites());
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private Optional<List<Publisher>> contentHierarchyPrecedence = Optional.absent();
public boolean precedence = false;
private boolean imagePrecedenceEnabled = true;
private List<SourceReadEntry> reads = Lists.newLinkedList();
private List<Publisher> writes = Lists.newLinkedList();
public Builder withPrecedence(boolean precedence) {
this.precedence = precedence;
return this;
}
public Builder withContentHierarchyPrecedence(List<Publisher> contentHierarchyPrecedence) {
if (contentHierarchyPrecedence != null) {
this.contentHierarchyPrecedence = Optional.of(ImmutableList.copyOf(contentHierarchyPrecedence));
} else {
this.contentHierarchyPrecedence = Optional.absent();
}
return this;
}
public Builder withReadableSources(List<SourceReadEntry> reads) {
this.reads = reads;
return this;
}
public Builder withWritableSources(List<Publisher> writes) {
this.writes = writes;
return this;
}
public Builder withImagePrecedenceEnabled(boolean imagePrecedenceEnabled) {
this.imagePrecedenceEnabled = imagePrecedenceEnabled;
return this;
}
public ApplicationSources build() {
// If precedence not enabled then sort reads by publisher key order
if (!this.precedence) {
Collections.sort(Lists.newArrayList(this.reads), SORT_READS_BY_PUBLISHER);
}
return new ApplicationSources(this);
}
}
}
| Copy image precedence status in copy() method
| atlas-core/src/main/java/org/atlasapi/application/ApplicationSources.java | Copy image precedence status in copy() method | <ide><path>tlas-core/src/main/java/org/atlasapi/application/ApplicationSources.java
<ide> return builder()
<ide> .withPrecedence(this.isPrecedenceEnabled())
<ide> .withReadableSources(this.getReads())
<add> .withImagePrecedenceEnabled(this.imagePrecedenceEnabled)
<ide> .withContentHierarchyPrecedence(this.contentHierarchyPrecedence().orNull())
<ide> .withWritableSources(this.getWrites());
<ide> } |
|
Java | mit | cf204425fd661daf0d539535df788437286ea4bd | 0 | nicomero/tarea1distribuidos | import java.io.*;
public class mainServer {
public static void main(String[] args) throws IOException {
new mainServerThread().start();
}
}
| mainServer.java | clase mainServer lista
| mainServer.java | clase mainServer lista | <ide><path>ainServer.java
<add>import java.io.*;
<add>
<add>public class mainServer {
<add> public static void main(String[] args) throws IOException {
<add> new mainServerThread().start();
<add> }
<add>} |
||
Java | apache-2.0 | 172f0310537b3834104f63b6e3bdd8a95fb93c51 | 0 | consulo/consulo-csharp,consulo/consulo-csharp,consulo/consulo-csharp | /*
* Copyright 2013-2014 must-be.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mustbe.consulo.csharp.lang.formatter;
import java.util.List;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.mustbe.consulo.csharp.lang.psi.CSharpCallArgumentList;
import org.mustbe.consulo.csharp.lang.psi.CSharpElements;
import org.mustbe.consulo.csharp.lang.psi.CSharpFieldOrPropertySet;
import org.mustbe.consulo.csharp.lang.psi.CSharpStubElements;
import org.mustbe.consulo.csharp.lang.psi.CSharpTemplateTokens;
import org.mustbe.consulo.csharp.lang.psi.CSharpTokenSets;
import org.mustbe.consulo.csharp.lang.psi.CSharpTokens;
import org.mustbe.consulo.csharp.lang.psi.impl.source.CSharpArrayInitializationExpressionImpl;
import org.mustbe.consulo.csharp.lang.psi.impl.source.CSharpBlockStatementImpl;
import org.mustbe.consulo.dotnet.psi.DotNetExpression;
import org.mustbe.consulo.dotnet.psi.DotNetStatement;
import com.intellij.formatting.Indent;
import com.intellij.formatting.Wrap;
import com.intellij.formatting.WrapType;
import com.intellij.formatting.templateLanguages.DataLanguageBlockWrapper;
import com.intellij.formatting.templateLanguages.TemplateLanguageBlock;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.tree.IElementType;
import com.intellij.util.codeInsight.CommentUtilCore;
import lombok.val;
/**
* @author VISTALL
* @since 15.12.13.
*/
public class CSharpFormattingBlock extends TemplateLanguageBlock implements CSharpElements, CSharpTokens, CSharpTokenSets
{
public CSharpFormattingBlock(
@NotNull CSharpFormattingModelBuilder blockFactory,
@NotNull CodeStyleSettings settings,
@NotNull ASTNode node,
@Nullable List<DataLanguageBlockWrapper> foreignChildren)
{
super(blockFactory, settings, node, foreignChildren);
}
@Nullable
@Override
public Wrap getWrap()
{
ASTNode node = getNode();
IElementType elementType = node.getElementType();
if(elementType == LBRACE || elementType == RBRACE || elementType == CSharpElements.XXX_ACCESSOR)
{
return Wrap.createWrap(WrapType.ALWAYS, true);
}
PsiElement psi = node.getPsi();
PsiElement parent = psi.getParent();
if(psi instanceof CSharpFieldOrPropertySet && !(parent instanceof CSharpCallArgumentList))
{
return Wrap.createWrap(WrapType.ALWAYS, true);
}
if(psi instanceof DotNetStatement && parent instanceof CSharpBlockStatementImpl && ((CSharpBlockStatementImpl) parent).getStatements()[0]
== psi)
{
return Wrap.createWrap(WrapType.ALWAYS, true);
}
return super.getWrap();
}
@Override
public Indent getIndent()
{
PsiElement element = getNode().getPsi();
PsiElement parent = element.getParent();
if(parent instanceof PsiFile)
{
return Indent.getNoneIndent();
}
val elementType = getNode().getElementType();
if(elementType == NAMESPACE_DECLARATION ||
elementType == TYPE_DECLARATION ||
elementType == METHOD_DECLARATION ||
elementType == CONVERSION_METHOD_DECLARATION ||
elementType == FIELD_DECLARATION ||
elementType == FIELD_OR_PROPERTY_SET ||
elementType == ARRAY_METHOD_DECLARATION ||
elementType == PROPERTY_DECLARATION ||
elementType == XXX_ACCESSOR ||
elementType == EVENT_DECLARATION ||
elementType == ENUM_CONSTANT_DECLARATION ||
elementType == USING_LIST ||
elementType == CONSTRUCTOR_DECLARATION ||
element instanceof DotNetExpression && parent instanceof CSharpArrayInitializationExpressionImpl)
{
return Indent.getNormalIndent();
}
else if(elementType == LBRACE || elementType == RBRACE)
{
return Indent.getNoneIndent();
}
else if(CommentUtilCore.isComment(getNode()))
{
return Indent.getNormalIndent();
}
else if(elementType == MODIFIER_LIST)
{
return Indent.getNoneIndent();
}
/* else if(elementType == CSharpParserDefinition.FILE_ELEMENT_TYPE)
{
return Indent.getNoneIndent();
} */
else if(elementType == CSharpStubElements.FILE)
{
return Indent.getNoneIndent();
}
/*else if(elementType == MACRO_BLOCK_START || elementType == MACRO_BLOCK_STOP)
{
PsiElement psi = getNode().getPsi();
if(psi.getParent() instanceof CSharpMacroBlockImpl)
{
return Indent.getNoneIndent();
}
return Indent.getNormalIndent();
} */
else
{
if(parent instanceof CSharpBlockStatementImpl)
{
return Indent.getNormalIndent();
}
return Indent.getNoneIndent();
}
}
@Nullable
@Override
protected Indent getChildIndent()
{
val elementType = getNode().getElementType();
if(elementType == CSharpStubElements.FILE)
{
return Indent.getNoneIndent();
}
return Indent.getNormalIndent();
}
@Override
protected IElementType getTemplateTextElementType()
{
return CSharpTemplateTokens.MACRO_FRAGMENT;
}
}
| csharp-impl/src/org/mustbe/consulo/csharp/lang/formatter/CSharpFormattingBlock.java | /*
* Copyright 2013-2014 must-be.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mustbe.consulo.csharp.lang.formatter;
import java.util.List;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.mustbe.consulo.csharp.lang.psi.CSharpCallArgumentList;
import org.mustbe.consulo.csharp.lang.psi.CSharpElements;
import org.mustbe.consulo.csharp.lang.psi.CSharpFieldOrPropertySet;
import org.mustbe.consulo.csharp.lang.psi.CSharpStubElements;
import org.mustbe.consulo.csharp.lang.psi.CSharpTemplateTokens;
import org.mustbe.consulo.csharp.lang.psi.CSharpTokenSets;
import org.mustbe.consulo.csharp.lang.psi.CSharpTokens;
import org.mustbe.consulo.csharp.lang.psi.impl.source.CSharpArrayInitializationExpressionImpl;
import org.mustbe.consulo.csharp.lang.psi.impl.source.CSharpBlockStatementImpl;
import org.mustbe.consulo.dotnet.psi.DotNetExpression;
import com.intellij.formatting.Indent;
import com.intellij.formatting.Wrap;
import com.intellij.formatting.WrapType;
import com.intellij.formatting.templateLanguages.DataLanguageBlockWrapper;
import com.intellij.formatting.templateLanguages.TemplateLanguageBlock;
import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.tree.IElementType;
import com.intellij.util.codeInsight.CommentUtilCore;
import lombok.val;
/**
* @author VISTALL
* @since 15.12.13.
*/
public class CSharpFormattingBlock extends TemplateLanguageBlock implements CSharpElements, CSharpTokens, CSharpTokenSets
{
public CSharpFormattingBlock(
@NotNull CSharpFormattingModelBuilder blockFactory,
@NotNull CodeStyleSettings settings,
@NotNull ASTNode node,
@Nullable List<DataLanguageBlockWrapper> foreignChildren)
{
super(blockFactory, settings, node, foreignChildren);
}
@Nullable
@Override
public Wrap getWrap()
{
ASTNode node = getNode();
IElementType elementType = node.getElementType();
if(elementType == LBRACE || elementType == RBRACE || elementType == CSharpElements.XXX_ACCESSOR)
{
return Wrap.createWrap(WrapType.ALWAYS, true);
}
PsiElement psi = node.getPsi();
if(psi instanceof CSharpFieldOrPropertySet && !(psi.getParent() instanceof CSharpCallArgumentList))
{
return Wrap.createWrap(WrapType.ALWAYS, true);
}
return super.getWrap();
}
@Override
public Indent getIndent()
{
PsiElement element = getNode().getPsi();
PsiElement parent = element.getParent();
if(parent instanceof PsiFile)
{
return Indent.getNoneIndent();
}
val elementType = getNode().getElementType();
if(elementType == NAMESPACE_DECLARATION ||
elementType == TYPE_DECLARATION ||
elementType == METHOD_DECLARATION ||
elementType == CONVERSION_METHOD_DECLARATION ||
elementType == FIELD_DECLARATION ||
elementType == FIELD_OR_PROPERTY_SET ||
elementType == ARRAY_METHOD_DECLARATION ||
elementType == PROPERTY_DECLARATION ||
elementType == XXX_ACCESSOR ||
elementType == EVENT_DECLARATION ||
elementType == ENUM_CONSTANT_DECLARATION ||
elementType == USING_LIST ||
elementType == CONSTRUCTOR_DECLARATION ||
element instanceof DotNetExpression && parent instanceof CSharpArrayInitializationExpressionImpl)
{
return Indent.getNormalIndent();
}
else if(elementType == LBRACE || elementType == RBRACE)
{
return Indent.getNoneIndent();
}
else if(CommentUtilCore.isComment(getNode()))
{
return Indent.getNormalIndent();
}
else if(elementType == MODIFIER_LIST)
{
return Indent.getNoneIndent();
}
/* else if(elementType == CSharpParserDefinition.FILE_ELEMENT_TYPE)
{
return Indent.getNoneIndent();
} */
else if(elementType == CSharpStubElements.FILE)
{
return Indent.getNoneIndent();
}
/*else if(elementType == MACRO_BLOCK_START || elementType == MACRO_BLOCK_STOP)
{
PsiElement psi = getNode().getPsi();
if(psi.getParent() instanceof CSharpMacroBlockImpl)
{
return Indent.getNoneIndent();
}
return Indent.getNormalIndent();
} */
else
{
if(parent instanceof CSharpBlockStatementImpl)
{
return Indent.getNormalIndent();
}
return Indent.getNoneIndent();
}
}
@Nullable
@Override
protected Indent getChildIndent()
{
val elementType = getNode().getElementType();
if(elementType == CSharpStubElements.FILE)
{
return Indent.getNoneIndent();
}
return Indent.getNormalIndent();
}
@Override
protected IElementType getTemplateTextElementType()
{
return CSharpTemplateTokens.MACRO_FRAGMENT;
}
}
| always wrap first statement of block statement
| csharp-impl/src/org/mustbe/consulo/csharp/lang/formatter/CSharpFormattingBlock.java | always wrap first statement of block statement | <ide><path>sharp-impl/src/org/mustbe/consulo/csharp/lang/formatter/CSharpFormattingBlock.java
<ide> import org.mustbe.consulo.csharp.lang.psi.impl.source.CSharpArrayInitializationExpressionImpl;
<ide> import org.mustbe.consulo.csharp.lang.psi.impl.source.CSharpBlockStatementImpl;
<ide> import org.mustbe.consulo.dotnet.psi.DotNetExpression;
<add>import org.mustbe.consulo.dotnet.psi.DotNetStatement;
<ide> import com.intellij.formatting.Indent;
<ide> import com.intellij.formatting.Wrap;
<ide> import com.intellij.formatting.WrapType;
<ide> }
<ide>
<ide> PsiElement psi = node.getPsi();
<del> if(psi instanceof CSharpFieldOrPropertySet && !(psi.getParent() instanceof CSharpCallArgumentList))
<add> PsiElement parent = psi.getParent();
<add> if(psi instanceof CSharpFieldOrPropertySet && !(parent instanceof CSharpCallArgumentList))
<add> {
<add> return Wrap.createWrap(WrapType.ALWAYS, true);
<add> }
<add>
<add> if(psi instanceof DotNetStatement && parent instanceof CSharpBlockStatementImpl && ((CSharpBlockStatementImpl) parent).getStatements()[0]
<add> == psi)
<ide> {
<ide> return Wrap.createWrap(WrapType.ALWAYS, true);
<ide> } |
|
Java | agpl-3.0 | f7c664a23dafe1e0cb1996b16991018782cacc63 | 0 | acontes/scheduling,acontes/scheduling,acontes/scheduling,acontes/scheduling,acontes/scheduling,acontes/scheduling,acontes/scheduling | /*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2010 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: [email protected] or [email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* If needed, contact us to obtain a release under GPL Version 2
* or a different license than the GPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
* $$PROACTIVE_INITIAL_DEV$$
*/
package org.ow2.proactive.resourcemanager.frontend;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.log4j.Logger;
import org.objectweb.proactive.Body;
import org.objectweb.proactive.InitActive;
import org.objectweb.proactive.api.PAActiveObject;
import org.objectweb.proactive.core.ProActiveException;
import org.objectweb.proactive.core.UniqueID;
import org.objectweb.proactive.core.util.log.ProActiveLogger;
import org.objectweb.proactive.core.util.wrapper.BooleanWrapper;
import org.ow2.proactive.resourcemanager.common.RMConstants;
import org.ow2.proactive.resourcemanager.common.event.RMEvent;
import org.ow2.proactive.resourcemanager.common.event.RMEventType;
import org.ow2.proactive.resourcemanager.common.event.RMInitialState;
import org.ow2.proactive.resourcemanager.common.event.RMNodeEvent;
import org.ow2.proactive.resourcemanager.common.event.RMNodeSourceEvent;
import org.ow2.proactive.resourcemanager.core.RMCore;
import org.ow2.proactive.resourcemanager.core.RMCoreInterface;
import org.ow2.proactive.resourcemanager.core.properties.PAResourceManagerProperties;
import org.ow2.proactive.resourcemanager.exception.RMException;
import org.ow2.proactive.resourcemanager.utils.AtomicRMStatisticsHolder;
import org.ow2.proactive.resourcemanager.utils.RMLoggers;
/**
* Active object designed for the Monitoring of the Resource Manager.
* This class provides a way for a monitor to ask at
* Resource Manager to throw events
* generated by nodes and nodes sources management. RMMonitoring dispatch
* events thrown by {@link RMCore} to all its monitors.
*
*
* @see org.ow2.proactive.resourcemanager.frontend.RMEventListener
*
* @author The ProActive Team
* @since ProActive Scheduling 0.9
*/
public class RMMonitoringImpl implements RMMonitoring, RMEventListener, InitActive {
private static final Logger logger = ProActiveLogger.getLogger(RMLoggers.MONITORING);
// Attributes
private RMCoreInterface rmcore;
private Map<UniqueID, RMEventListener> listeners;
private HashMap<EventDispatcher, LinkedList<RMEvent>> pendingEvents = new HashMap<EventDispatcher, LinkedList<RMEvent>>();
private transient ExecutorService eventDispatcherThreadPool;
/** Resource Manager's statistics */
public static final AtomicRMStatisticsHolder rmStatistics = new AtomicRMStatisticsHolder();
// ----------------------------------------------------------------------//
// CONSTRUTORS
/** ProActive empty constructor */
public RMMonitoringImpl() {
}
/**
* Creates the RMMonitoring active object.
* @param rmcore Stub of the RMCore active object.
*/
public RMMonitoringImpl(RMCoreInterface rmcore) {
listeners = new HashMap<UniqueID, RMEventListener>();
this.rmcore = rmcore;
}
/**
* @see org.objectweb.proactive.InitActive#initActivity(org.objectweb.proactive.Body)
*/
public void initActivity(Body body) {
try {
PAActiveObject.registerByName(PAActiveObject.getStubOnThis(),
RMConstants.NAME_ACTIVE_OBJECT_RMMONITORING);
eventDispatcherThreadPool = Executors
.newFixedThreadPool(PAResourceManagerProperties.RM_MONITORING_MAX_THREAD_NUMBER
.getValueAsInt());
} catch (ProActiveException e) {
logger.debug("Cannot register RMMonitoring. Aborting...", e);
PAActiveObject.terminateActiveObject(true);
}
}
private class EventDispatcher implements Runnable {
private UniqueID listenerId;
private ReentrantLock lock = new ReentrantLock();
public EventDispatcher(UniqueID listenerId) {
this.listenerId = listenerId;
}
public void run() {
if (lock.isLocked()) {
if (logger.isDebugEnabled()) {
logger.debug("Communication to the client " + listenerId.shortString() +
" is in progress in one thread of the thread pool. " +
"Either events come too quick or the client is slow. " +
"Do not initiate connection from another thread.");
}
return;
}
lock.lock();
int numberOfEventDelivered = 0;
long timeStamp = System.currentTimeMillis();
if (logger.isDebugEnabled()) {
logger.debug("Initializing " + Thread.currentThread() + " for events delivery to client '" +
listenerId.shortString() + "'");
}
LinkedList<RMEvent> events = pendingEvents.get(this);
while (true) {
RMEvent event = null;
synchronized (events) {
if (logger.isDebugEnabled()) {
logger.debug(events.size() + " pending events for the client '" +
listenerId.shortString() + "'");
}
if (events.size() > 0) {
event = events.removeFirst();
}
}
if (event != null) {
deliverEvent(event);
numberOfEventDelivered++;
} else {
lock.unlock();
break;
}
}
if (logger.isDebugEnabled()) {
logger.debug("Finnishing delivery in " + Thread.currentThread() + " to client '" +
listenerId.shortString() + "'. " + numberOfEventDelivered + " events were delivered in " +
(System.currentTimeMillis() - timeStamp) + " ms");
}
}
private void deliverEvent(RMEvent event) {
RMEventListener listener = null;
synchronized (listeners) {
listener = listeners.get(listenerId);
}
if (listener == null) {
return;
}
//dispatch event
long timeStamp = System.currentTimeMillis();
if (logger.isDebugEnabled()) {
logger.debug("Dispatching event '" + event.toString() + "' to client " +
listenerId.shortString());
}
try {
if (event instanceof RMNodeEvent) {
RMNodeEvent nodeEvent = (RMNodeEvent) event;
listener.nodeEvent(nodeEvent);
} else if (event instanceof RMNodeSourceEvent) {
RMNodeSourceEvent sourceEvent = (RMNodeSourceEvent) event;
listener.nodeSourceEvent(sourceEvent);
} else {
listener.rmEvent(event);
}
long time = System.currentTimeMillis() - timeStamp;
if (logger.isDebugEnabled()) {
logger.debug("Event '" + event.toString() + "' has been delivered to client " +
listenerId.shortString() + " in " + time + " ms");
}
} catch (Exception e) {
// probably listener was removed or became down
RMEventListener l = null;
synchronized (listeners) {
l = listeners.remove(listenerId);
pendingEvents.remove(this);
}
if (l != null) {
logger.debug("", e);
logger.info("User known as '" + listenerId.shortString() +
"' has been removed from listeners");
}
}
}
public boolean equals(Object obj) {
EventDispatcher other = (EventDispatcher) obj;
return listenerId.equals(other.listenerId);
}
}
/** Register a new Resource manager listener.
* Way to a monitor object to ask at RMMonitoring to throw
* RM events to it.
* @param listener a listener object which implements {@link RMEventListener}
* interface.
* @param events list of wanted events that must be received.
* @return RMInitialState snapshot of RM's current state : nodes and node sources.
* */
public RMInitialState addRMEventListener(RMEventListener listener, RMEventType... events) {
UniqueID id = PAActiveObject.getContext().getCurrentRequest().getSourceBodyID();
synchronized (listeners) {
this.listeners.put(id, listener);
this.pendingEvents.put(new EventDispatcher(id), new LinkedList<RMEvent>());
}
return rmcore.getRMInitialState();
}
/**
* Removes a listener from RMMonitoring. Only listener itself must call this method
*/
public void removeRMEventListener() throws RMException {
UniqueID id = PAActiveObject.getContext().getCurrentRequest().getSourceBodyID();
synchronized (listeners) {
if (listeners.containsKey(id)) {
listeners.remove(id);
pendingEvents.remove(new EventDispatcher(id));
} else {
throw new RMException("Listener is unknown");
}
}
}
/**
* @see org.ow2.proactive.resourcemanager.frontend.RMMonitoring#isAlive()
*/
public boolean isAlive() {
return true;
}
public void queueEvent(RMEvent event) {
//dispatch event
if (logger.isDebugEnabled()) {
logger.debug("Queueing event '" + event.toString() + "'");
}
synchronized (listeners) {
for (Collection<RMEvent> events : pendingEvents.values()) {
synchronized (events) {
events.add(event);
}
}
for (Runnable eventDispatcher : pendingEvents.keySet()) {
eventDispatcherThreadPool.submit(eventDispatcher);
}
}
}
/**
* @see org.ow2.proactive.resourcemanager.frontend.RMEventListener#nodeEvent(org.ow2.proactive.resourcemanager.common.event.RMNodeEvent)
*/
public void nodeEvent(RMNodeEvent event) {
RMMonitoringImpl.rmStatistics.nodeEvent(event);
queueEvent(event);
}
/**
* @see org.ow2.proactive.resourcemanager.frontend.RMEventListener#nodeSourceEvent(org.ow2.proactive.resourcemanager.common.event.RMNodeSourceEvent)
*/
public void nodeSourceEvent(RMNodeSourceEvent event) {
queueEvent(event);
}
/**
* @see org.ow2.proactive.resourcemanager.frontend.RMEventListener#rmEvent(org.ow2.proactive.resourcemanager.common.event.RMEvent)
*/
public void rmEvent(RMEvent event) {
RMMonitoringImpl.rmStatistics.rmEvent(event);
queueEvent(event);
}
/**
* Stop and remove monitoring active object
*/
public BooleanWrapper shutdown() {
//throwing shutdown event
rmEvent(new RMEvent(RMEventType.SHUTDOWN));
PAActiveObject.terminateActiveObject(false);
// initiating shutdown
eventDispatcherThreadPool.shutdown();
try {
// waiting until all clients will be notified
eventDispatcherThreadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
logger.warn("", e);
}
return new BooleanWrapper(true);
}
public Logger getLogger() {
return logger;
}
}
| src/resource-manager/src/org/ow2/proactive/resourcemanager/frontend/RMMonitoringImpl.java | /*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2010 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: [email protected] or [email protected]
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* If needed, contact us to obtain a release under GPL Version 2
* or a different license than the GPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
* $$PROACTIVE_INITIAL_DEV$$
*/
package org.ow2.proactive.resourcemanager.frontend;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.log4j.Logger;
import org.objectweb.proactive.Body;
import org.objectweb.proactive.InitActive;
import org.objectweb.proactive.api.PAActiveObject;
import org.objectweb.proactive.core.ProActiveException;
import org.objectweb.proactive.core.UniqueID;
import org.objectweb.proactive.core.util.log.ProActiveLogger;
import org.objectweb.proactive.core.util.wrapper.BooleanWrapper;
import org.ow2.proactive.resourcemanager.common.RMConstants;
import org.ow2.proactive.resourcemanager.common.event.RMEvent;
import org.ow2.proactive.resourcemanager.common.event.RMEventType;
import org.ow2.proactive.resourcemanager.common.event.RMInitialState;
import org.ow2.proactive.resourcemanager.common.event.RMNodeEvent;
import org.ow2.proactive.resourcemanager.common.event.RMNodeSourceEvent;
import org.ow2.proactive.resourcemanager.core.RMCore;
import org.ow2.proactive.resourcemanager.core.RMCoreInterface;
import org.ow2.proactive.resourcemanager.core.properties.PAResourceManagerProperties;
import org.ow2.proactive.resourcemanager.exception.RMException;
import org.ow2.proactive.resourcemanager.utils.AtomicRMStatisticsHolder;
import org.ow2.proactive.resourcemanager.utils.RMLoggers;
/**
* Active object designed for the Monitoring of the Resource Manager.
* This class provides a way for a monitor to ask at
* Resource Manager to throw events
* generated by nodes and nodes sources management. RMMonitoring dispatch
* events thrown by {@link RMCore} to all its monitors.
*
*
* @see org.ow2.proactive.resourcemanager.frontend.RMEventListener
*
* @author The ProActive Team
* @since ProActive Scheduling 0.9
*/
public class RMMonitoringImpl implements RMMonitoring, RMEventListener, InitActive {
private static final Logger logger = ProActiveLogger.getLogger(RMLoggers.MONITORING);
// Attributes
private RMCoreInterface rmcore;
private Map<UniqueID, RMEventListener> listeners;
private HashMap<EventDispatcher, LinkedList<RMEvent>> pendingEvents = new HashMap<EventDispatcher, LinkedList<RMEvent>>();
private transient ExecutorService eventDispatcherThreadPool;
/** Resource Manager's statistics */
public static final AtomicRMStatisticsHolder rmStatistics = new AtomicRMStatisticsHolder();
// ----------------------------------------------------------------------//
// CONSTRUTORS
/** ProActive empty constructor */
public RMMonitoringImpl() {
}
/**
* Creates the RMMonitoring active object.
* @param rmcore Stub of the RMCore active object.
*/
public RMMonitoringImpl(RMCoreInterface rmcore) {
listeners = new HashMap<UniqueID, RMEventListener>();
this.rmcore = rmcore;
}
/**
* @see org.objectweb.proactive.InitActive#initActivity(org.objectweb.proactive.Body)
*/
public void initActivity(Body body) {
try {
PAActiveObject.registerByName(PAActiveObject.getStubOnThis(),
RMConstants.NAME_ACTIVE_OBJECT_RMMONITORING);
eventDispatcherThreadPool = Executors
.newFixedThreadPool(PAResourceManagerProperties.RM_MONITORING_MAX_THREAD_NUMBER
.getValueAsInt());
} catch (ProActiveException e) {
logger.debug("Cannot register RMMonitoring. Aborting...", e);
PAActiveObject.terminateActiveObject(true);
}
}
private class EventDispatcher implements Runnable {
private UniqueID listenerId;
private ReentrantLock lock = new ReentrantLock();
public EventDispatcher(UniqueID listenerId) {
this.listenerId = listenerId;
}
public void run() {
if (lock.isLocked()) {
if (logger.isDebugEnabled()) {
logger.debug("Communication to the client " + listenerId.shortString() +
" is in progress in one thread of the thread pool. " +
"Either events come too quick or the client is slow. " +
"Do not initiate connection from another thread.");
}
return;
}
lock.lock();
int numberOfEventDelivered = 0;
long timeStamp = System.currentTimeMillis();
if (logger.isDebugEnabled()) {
logger.debug("Initializing " + Thread.currentThread() + " for events delivery to client '" +
listenerId.shortString() + "'");
}
LinkedList<RMEvent> events = pendingEvents.get(this);
while (true) {
RMEvent event = null;
synchronized (events) {
if (logger.isDebugEnabled()) {
logger.debug(events.size() + " pending events for the client '" +
listenerId.shortString() + "'");
}
if (events.size() > 0) {
event = events.removeFirst();
}
}
if (event != null) {
deliverEvent(event);
numberOfEventDelivered++;
} else {
lock.unlock();
break;
}
}
if (logger.isDebugEnabled()) {
logger.debug("Finnishing delivery in " + Thread.currentThread() + " to client '" +
listenerId.shortString() + "'. " + numberOfEventDelivered + " events were delivered in " +
(System.currentTimeMillis() - timeStamp) + " ms");
}
}
private void deliverEvent(RMEvent event) {
RMEventListener listener = null;
synchronized (listeners) {
listener = listeners.get(listenerId);
}
if (listener == null) {
return;
}
//dispatch event
long timeStamp = System.currentTimeMillis();
if (logger.isDebugEnabled()) {
logger.debug("Dispatching event '" + event.toString() + "' to client " +
listenerId.shortString());
}
try {
if (event instanceof RMNodeEvent) {
RMNodeEvent nodeEvent = (RMNodeEvent) event;
RMMonitoringImpl.rmStatistics.nodeEvent(nodeEvent);
listener.nodeEvent(nodeEvent);
} else if (event instanceof RMNodeSourceEvent) {
RMNodeSourceEvent sourceEvent = (RMNodeSourceEvent) event;
listener.nodeSourceEvent(sourceEvent);
} else {
RMMonitoringImpl.rmStatistics.rmEvent(event);
listener.rmEvent(event);
}
long time = System.currentTimeMillis() - timeStamp;
if (logger.isDebugEnabled()) {
logger.debug("Event '" + event.toString() + "' has been delivered to client " +
listenerId.shortString() + " in " + time + " ms");
}
} catch (Exception e) {
// probably listener was removed or became down
RMEventListener l = null;
synchronized (listeners) {
l = listeners.remove(listenerId);
pendingEvents.remove(this);
}
if (l != null) {
logger.debug("", e);
logger.info("User known as '" + listenerId.shortString() +
"' has been removed from listeners");
}
}
}
public boolean equals(Object obj) {
EventDispatcher other = (EventDispatcher) obj;
return listenerId.equals(other.listenerId);
}
}
/** Register a new Resource manager listener.
* Way to a monitor object to ask at RMMonitoring to throw
* RM events to it.
* @param listener a listener object which implements {@link RMEventListener}
* interface.
* @param events list of wanted events that must be received.
* @return RMInitialState snapshot of RM's current state : nodes and node sources.
* */
public RMInitialState addRMEventListener(RMEventListener listener, RMEventType... events) {
UniqueID id = PAActiveObject.getContext().getCurrentRequest().getSourceBodyID();
synchronized (listeners) {
this.listeners.put(id, listener);
this.pendingEvents.put(new EventDispatcher(id), new LinkedList<RMEvent>());
}
return rmcore.getRMInitialState();
}
/**
* Removes a listener from RMMonitoring. Only listener itself must call this method
*/
public void removeRMEventListener() throws RMException {
UniqueID id = PAActiveObject.getContext().getCurrentRequest().getSourceBodyID();
synchronized (listeners) {
if (listeners.containsKey(id)) {
listeners.remove(id);
pendingEvents.remove(new EventDispatcher(id));
} else {
throw new RMException("Listener is unknown");
}
}
}
/**
* @see org.ow2.proactive.resourcemanager.frontend.RMMonitoring#isAlive()
*/
public boolean isAlive() {
return true;
}
public void queueEvent(RMEvent event) {
//dispatch event
if (logger.isDebugEnabled()) {
logger.debug("Queueing event '" + event.toString() + "'");
}
synchronized (listeners) {
for (Collection<RMEvent> events : pendingEvents.values()) {
synchronized (events) {
events.add(event);
}
}
for (Runnable eventDispatcher : pendingEvents.keySet()) {
eventDispatcherThreadPool.submit(eventDispatcher);
}
}
}
/**
* @see org.ow2.proactive.resourcemanager.frontend.RMEventListener#nodeEvent(org.ow2.proactive.resourcemanager.common.event.RMNodeEvent)
*/
public void nodeEvent(RMNodeEvent event) {
queueEvent(event);
}
/**
* @see org.ow2.proactive.resourcemanager.frontend.RMEventListener#nodeSourceEvent(org.ow2.proactive.resourcemanager.common.event.RMNodeSourceEvent)
*/
public void nodeSourceEvent(RMNodeSourceEvent event) {
queueEvent(event);
}
/**
* @see org.ow2.proactive.resourcemanager.frontend.RMEventListener#rmEvent(org.ow2.proactive.resourcemanager.common.event.RMEvent)
*/
public void rmEvent(RMEvent event) {
queueEvent(event);
}
/**
* Stop and remove monitoring active object
*/
public BooleanWrapper shutdown() {
//throwing shutdown event
rmEvent(new RMEvent(RMEventType.SHUTDOWN));
PAActiveObject.terminateActiveObject(false);
// initiating shutdown
eventDispatcherThreadPool.shutdown();
try {
// waiting until all clients will be notified
eventDispatcherThreadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
logger.warn("", e);
}
return new BooleanWrapper(true);
}
public Logger getLogger() {
return logger;
}
}
| SCHEDULING-572 JMX statistics fixed in the resource manager
git-svn-id: 27916816d6cfa57849e9a885196bf7392b80e1ac@15615 28e8926c-6b08-0410-baaa-805c5e19b8d6
| src/resource-manager/src/org/ow2/proactive/resourcemanager/frontend/RMMonitoringImpl.java | SCHEDULING-572 JMX statistics fixed in the resource manager | <ide><path>rc/resource-manager/src/org/ow2/proactive/resourcemanager/frontend/RMMonitoringImpl.java
<ide> try {
<ide> if (event instanceof RMNodeEvent) {
<ide> RMNodeEvent nodeEvent = (RMNodeEvent) event;
<del> RMMonitoringImpl.rmStatistics.nodeEvent(nodeEvent);
<ide> listener.nodeEvent(nodeEvent);
<ide> } else if (event instanceof RMNodeSourceEvent) {
<ide> RMNodeSourceEvent sourceEvent = (RMNodeSourceEvent) event;
<ide> listener.nodeSourceEvent(sourceEvent);
<ide> } else {
<del> RMMonitoringImpl.rmStatistics.rmEvent(event);
<ide> listener.rmEvent(event);
<ide> }
<ide>
<ide> * @see org.ow2.proactive.resourcemanager.frontend.RMEventListener#nodeEvent(org.ow2.proactive.resourcemanager.common.event.RMNodeEvent)
<ide> */
<ide> public void nodeEvent(RMNodeEvent event) {
<add> RMMonitoringImpl.rmStatistics.nodeEvent(event);
<ide> queueEvent(event);
<ide> }
<ide>
<ide> * @see org.ow2.proactive.resourcemanager.frontend.RMEventListener#rmEvent(org.ow2.proactive.resourcemanager.common.event.RMEvent)
<ide> */
<ide> public void rmEvent(RMEvent event) {
<add> RMMonitoringImpl.rmStatistics.rmEvent(event);
<ide> queueEvent(event);
<ide> }
<ide> |
|
Java | mit | 574facf79b308e407c1a69b232b9c2aa03db8f03 | 0 | rollbar/rollbar-java,rollbar/rollbar-java,rollbar/rollbar-java | package com.rollbar.web.provider;
import static java.util.Arrays.asList;
import com.rollbar.api.payload.Payload;
import com.rollbar.api.payload.data.Request;
import com.rollbar.notifier.provider.Provider;
import com.rollbar.web.listener.RollbarRequestListener;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletRequest;
/**
* {@link Request} provider.
*/
public class RequestProvider implements Provider<Request> {
private final String userIpHeaderName;
private final int captureIp;
static final String CAPTURE_IP_ANONYMIZE = "anonymize";
static final String CAPTURE_IP_NONE = "none";
static final int CAPTURE_IP_TYPE_FULL = 0;
static final int CAPTURE_IP_TYPE_ANONYMIZE = 1;
static final int CAPTURE_IP_TYPE_NONE = 2;
/**
* Constructor.
*/
RequestProvider(Builder builder) {
this.userIpHeaderName = builder.userIpHeaderName;
if (builder.captureIp != null) {
if (builder.captureIp.equals(CAPTURE_IP_ANONYMIZE)) {
this.captureIp = CAPTURE_IP_TYPE_ANONYMIZE;
} else if (builder.captureIp.equals(CAPTURE_IP_NONE)) {
this.captureIp = CAPTURE_IP_TYPE_NONE;
} else {
this.captureIp = CAPTURE_IP_TYPE_FULL;
}
} else {
this.captureIp = CAPTURE_IP_TYPE_FULL;
}
}
@Override
public Request provide() {
HttpServletRequest req = RollbarRequestListener.getServletRequest();
if (req != null) {
Request request = new Request.Builder()
.url(url(req))
.method(method(req))
.headers(headers(req))
.get(getParams(req))
.queryString(queryString(req))
.userIp(userIp(req))
.build();
return request;
}
return null;
}
private String userIp(HttpServletRequest request) {
String rawIp;
if (userIpHeaderName == null || "".equals(userIpHeaderName)) {
rawIp = request.getRemoteAddr();
} else {
rawIp = request.getHeader(userIpHeaderName);
}
if (rawIp == null) {
return rawIp;
}
if (captureIp == CAPTURE_IP_TYPE_FULL) {
return rawIp;
} else if (captureIp == CAPTURE_IP_TYPE_ANONYMIZE) {
if (rawIp.contains(".")) {
// IPV4
String[] parts = rawIp.split("\\.");
if (parts.length > 3) {
// Java 7 does not have String.join
StringBuffer ip = new StringBuffer(parts[0]);
ip.append(".");
ip.append(parts[1]);
ip.append(".");
ip.append(parts[2]);
ip.append(".0/24");
return ip.toString();
}
return rawIp;
} else if (rawIp.contains(":")) {
// IPV6
if (rawIp.length() > 12) {
return rawIp.substring(0, 12).concat("...");
}
return rawIp;
} else {
return rawIp;
}
} else if (captureIp == CAPTURE_IP_TYPE_NONE) {
return null;
}
return null;
}
private static String url(HttpServletRequest request) {
return request.getRequestURL().toString();
}
private static String method(HttpServletRequest request) {
return request.getMethod();
}
private static Map<String, String> headers(HttpServletRequest request) {
Map<String, String> headers = new HashMap<>();
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
headers.put(headerName, request.getHeader(headerName));
}
return headers;
}
private static Map<String, List<String>> getParams(HttpServletRequest request) {
if ("GET".equalsIgnoreCase(request.getMethod())) {
Map<String, List<String>> params = new HashMap<>();
Map<String, String[]> paramNames = request.getParameterMap();
for (Entry<String, String[]> param : paramNames.entrySet()) {
if (param.getValue() != null && param.getValue().length > 0) {
params.put(param.getKey(), asList(param.getValue()));
}
}
return params;
}
return null;
}
private static String queryString(HttpServletRequest request) {
return request.getQueryString();
}
/**
* Builder class for {@link RequestProvider}.
*/
public static final class Builder {
private String userIpHeaderName;
private String captureIp;
/**
* The request header name to retrieve the user ip.
* @param userIpHeaderName the header name.
* @return the builder instance.
*/
public Builder userIpHeaderName(String userIpHeaderName) {
this.userIpHeaderName = userIpHeaderName;
return this;
}
/**
* The policy to use for capturing the user ip.
* @param captureIp One of: full, anonymize, none
* If this value is empty, null, or otherwise invalid the default policy is full.
* @return the builder instance.
*/
public Builder captureIp(String captureIp) {
this.captureIp = captureIp;
return this;
}
/**
* Builds the {@link RequestProvider request provider}.
*
* @return the payload.
*/
public RequestProvider build() {
return new RequestProvider(this);
}
}
}
| rollbar-web/src/main/java/com/rollbar/web/provider/RequestProvider.java | package com.rollbar.web.provider;
import static java.util.Arrays.asList;
import com.rollbar.api.payload.Payload;
import com.rollbar.api.payload.data.Request;
import com.rollbar.notifier.provider.Provider;
import com.rollbar.web.listener.RollbarRequestListener;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletRequest;
/**
* {@link Request} provider.
*/
public class RequestProvider implements Provider<Request> {
private final String userIpHeaderName;
private final int captureIp;
static final String CAPTURE_IP_ANONYMIZE = "anonymize";
static final String CAPTURE_IP_NONE = "none";
static final int CAPTURE_IP_TYPE_FULL = 0;
static final int CAPTURE_IP_TYPE_ANONYMIZE = 1;
static final int CAPTURE_IP_TYPE_NONE = 2;
/**
* Constructor.
*/
RequestProvider(Builder builder) {
this.userIpHeaderName = builder.userIpHeaderName;
if (builder.captureIp != null) {
if (builder.captureIp.equals(CAPTURE_IP_ANONYMIZE)) {
this.captureIp = CAPTURE_IP_TYPE_ANONYMIZE;
} else if (builder.captureIp.equals(CAPTURE_IP_NONE)) {
this.captureIp = CAPTURE_IP_TYPE_NONE;
} else {
this.captureIp = CAPTURE_IP_TYPE_FULL;
}
} else {
this.captureIp = CAPTURE_IP_TYPE_FULL;
}
}
@Override
public Request provide() {
HttpServletRequest req = RollbarRequestListener.getServletRequest();
if (req != null) {
Request request = new Request.Builder()
.url(url(req))
.method(method(req))
.headers(headers(req))
.get(getParams(req))
.queryString(queryString(req))
.userIp(userIp(req))
.build();
return request;
}
return null;
}
private String userIp(HttpServletRequest request) {
String rawIp;
if (userIpHeaderName == null || "".equals(userIpHeaderName)) {
rawIp = request.getRemoteAddr();
} else {
rawIp = request.getHeader(userIpHeaderName);
}
if (rawIp == null) {
return rawIp;
}
if (captureIp == CAPTURE_IP_TYPE_FULL) {
return rawIp;
} else if (captureIp == CAPTURE_IP_TYPE_ANONYMIZE) {
if (rawIp.contains(".")) {
// IPV4
String[] parts = rawIp.split("\\.");
if (parts.length > 3) {
// Java 7 does not have String.join
StringBuffer ip = new StringBuffer(parts[0]);
ip.append(".");
ip.append(parts[1]);
ip.append(".");
ip.append(parts[2]);
ip.append(".0/24");
return ip.toString();
}
return rawIp;
} else if (rawIp.contains(":")) {
// IPV6
if (rawIp.length() > 12) {
return rawIp.substring(0, 12).concat("...");
}
return rawIp;
} else {
return rawIp;
}
} else if (captureIp == CAPTURE_IP_TYPE_NONE) {
return null;
}
return null;
}
private static String url(HttpServletRequest request) {
return request.getRequestURL().toString();
}
private static String method(HttpServletRequest request) {
return request.getMethod();
}
private static Map<String, String> headers(HttpServletRequest request) {
Map<String, String> headers = new HashMap<>();
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
headers.put(headerName, request.getHeader(headerName));
}
return headers;
}
private static Map<String, List<String>> getParams(HttpServletRequest request) {
if ("GET".equalsIgnoreCase(request.getMethod())) {
Map<String, List<String>> params = new HashMap<>();
Map<String, String[]> paramNames = request.getParameterMap();
for (Entry<String, String[]> param : paramNames.entrySet()) {
if (param.getValue() != null && param.getValue().length > 0) {
params.put(param.getKey(), asList(param.getValue()));
}
}
return params;
}
return null;
}
private static String queryString(HttpServletRequest request) {
return request.getQueryString();
}
/**
* Builder class for {@link RequestProvider}.
*/
public static final class Builder {
private String userIpHeaderName;
private String captureIp;
/**
* The request header name to retrieve the user ip.
* @param userIpHeaderName the header name.
* @return the builder instance.
*/
public Builder userIpHeaderName(String userIpHeaderName) {
this.userIpHeaderName = userIpHeaderName;
return this;
}
/**
* The policy to use for capturing the user ip.
* @param captureIp One of: full, anonymize, none
* If this value is empty, null, or otherwise invalid
* the default policy is full.
* @return the builder instance.
*/
public Builder captureIp(String captureIp) {
this.captureIp = captureIp;
return this;
}
/**
* Builds the {@link RequestProvider request provider}.
*
* @return the payload.
*/
public RequestProvider build() {
return new RequestProvider(this);
}
}
}
| fix style of comment
| rollbar-web/src/main/java/com/rollbar/web/provider/RequestProvider.java | fix style of comment | <ide><path>ollbar-web/src/main/java/com/rollbar/web/provider/RequestProvider.java
<ide> /**
<ide> * The policy to use for capturing the user ip.
<ide> * @param captureIp One of: full, anonymize, none
<del> * If this value is empty, null, or otherwise invalid
<del> * the default policy is full.
<add> * If this value is empty, null, or otherwise invalid the default policy is full.
<ide> * @return the builder instance.
<ide> */
<ide> public Builder captureIp(String captureIp) { |
|
Java | apache-2.0 | 022949989eb2c96884ef5c401ff7729208edf25d | 0 | sitexa/AndroidFFmpeg,kyawkyaw/AndroidFFmpeg,lulufei/AndroidFFmpeg,sitexa/AndroidFFmpeg,shakin/AndroidFFmpeg,QDPeng/AndroidFFmpeg,lulufei/AndroidFFmpeg,ShawnKoo/AndroidFFmpeg,mondoktamas/AndroidFFmpeg,kyawkyaw/AndroidFFmpeg,mrduongnv/AndroidFFmpeg,shakin/AndroidFFmpeg,lulufei/AndroidFFmpeg,shine-chen/AndroidFFmpeg-with-RTMP,mrduongnv/AndroidFFmpeg,appunite/AndroidFFmpeg,lulufei/AndroidFFmpeg,appunite/AndroidFFmpeg,q273255702/AndroidFFmpeg,mondoktamas/AndroidFFmpeg,boke/AndroidFFmpeg,q273255702/AndroidFFmpeg,mobdim/AndroidFFmpeg,guoyuqing/ffmpeg,QDPeng/AndroidFFmpeg,shine-chen/AndroidFFmpeg-with-RTMP,boke/AndroidFFmpeg,kyawkyaw/AndroidFFmpeg,guoyuqing/ffmpeg,mrduongnv/AndroidFFmpeg,shine-chen/AndroidFFmpeg-with-RTMP,mobdim/AndroidFFmpeg,mrduongnv/AndroidFFmpeg,q273255702/AndroidFFmpeg,ShawnKoo/AndroidFFmpeg,mobdim/AndroidFFmpeg,shakin/AndroidFFmpeg,appunite/AndroidFFmpeg,shine-chen/AndroidFFmpeg-with-RTMP,boke/AndroidFFmpeg,QDPeng/AndroidFFmpeg,q273255702/AndroidFFmpeg,ShawnKoo/AndroidFFmpeg,shakin/AndroidFFmpeg,QDPeng/AndroidFFmpeg,guoyuqing/ffmpeg,kyawkyaw/AndroidFFmpeg,mondoktamas/AndroidFFmpeg,appunite/AndroidFFmpeg,sitexa/AndroidFFmpeg,ShawnKoo/AndroidFFmpeg,boke/AndroidFFmpeg,sitexa/AndroidFFmpeg,mondoktamas/AndroidFFmpeg,guoyuqing/ffmpeg,mobdim/AndroidFFmpeg | example/src/main/java/com/ffmpegtest/helpers/RectEvaluator.java | package com.ffmpegtest.helpers;
import android.animation.TypeEvaluator;
import android.graphics.RectF;
public class RectEvaluator implements TypeEvaluator<RectF> {
private RectF mRectF;
public RectEvaluator() {
mRectF = new RectF();
}
private float evaluate(float fraction, float startValue, float endValue) {
return startValue + fraction * (endValue - startValue);
}
@Override
public RectF evaluate(float fraction, RectF startValue, RectF endValue) {
float left = evaluate(fraction, startValue.left, endValue.left);
float top = evaluate(fraction, startValue.top, endValue.top);
float right = evaluate(fraction, startValue.right, endValue.right);
float bottom = evaluate(fraction, startValue.bottom, endValue.bottom);
mRectF.set(left, top, right, bottom);
return mRectF;
}
} | Removed unused evaluator
| example/src/main/java/com/ffmpegtest/helpers/RectEvaluator.java | Removed unused evaluator | <ide><path>xample/src/main/java/com/ffmpegtest/helpers/RectEvaluator.java
<del>package com.ffmpegtest.helpers;
<del>
<del>import android.animation.TypeEvaluator;
<del>import android.graphics.RectF;
<del>
<del>public class RectEvaluator implements TypeEvaluator<RectF> {
<del>
<del> private RectF mRectF;
<del>
<del> public RectEvaluator() {
<del> mRectF = new RectF();
<del> }
<del>
<del> private float evaluate(float fraction, float startValue, float endValue) {
<del> return startValue + fraction * (endValue - startValue);
<del> }
<del>
<del> @Override
<del> public RectF evaluate(float fraction, RectF startValue, RectF endValue) {
<del> float left = evaluate(fraction, startValue.left, endValue.left);
<del> float top = evaluate(fraction, startValue.top, endValue.top);
<del> float right = evaluate(fraction, startValue.right, endValue.right);
<del> float bottom = evaluate(fraction, startValue.bottom, endValue.bottom);
<del> mRectF.set(left, top, right, bottom);
<del> return mRectF;
<del> }
<del>
<del>} |
||
Java | mit | 653d3ed1d3d704bdd1c010ceb555e04612cdc235 | 0 | sapirgolan/MFIBlocking,sapirgolan/MFIBlocking,sapirgolan/MFIBlocking,sapirgolan/MFIBlocking,sapirgolan/MFIBlocking,sapirgolan/MFIBlocking,sapirgolan/MFIBlocking | package il.ac.technion.ie.experiments.threads;
import il.ac.technion.ie.experiments.exception.OSNotSupportedException;
import il.ac.technion.ie.experiments.model.ConvexBPContext;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
/**
* Created by I062070 on 26/09/2015.
*/
public class CommandExacter {
static final Logger logger = Logger.getLogger(CommandExacter.class);
public File execute(ConvexBPContext context) throws IOException, OSNotSupportedException, InterruptedException {
File outputFile;
int numberOfExecutions = 1;
checkOS();
Runtime runtime = Runtime.getRuntime();
String command = createCommand(context);
do {
logger.info(String.format("Executing convexBP algorithm for #%d time", numberOfExecutions));
logger.debug(String.format("Executing read UAI file by command: '%s'", command));
long startTime = System.nanoTime();
Process process = runtime.exec(command, new String[]{}, new File(context.getDir()));
long afterExecTime = System.currentTimeMillis();
Thread thread = new Thread(new ProcessTimeoutThread(process, afterExecTime, context.getWaitInterval()));
thread.start();
// any error message?
StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream(), StreamGobbler.ChanelType.ERROR);
// any output?
StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream(), StreamGobbler.ChanelType.OUTPUT);
// kick them off
errorGobbler.start();
outputGobbler.start();
// wait, if necessary, until the process object has terminated
logger.debug("Waiting if needed for previous read job to finish");
long waitTime = System.nanoTime();
int exitVal = process.waitFor();
long endTime = System.nanoTime();
logger.info(String.format("Total execution & waitTime of convexBP: %d, %d",
TimeUnit.NANOSECONDS.toSeconds(endTime - startTime), TimeUnit.NANOSECONDS.toSeconds(endTime - waitTime)));
logger.debug("ExitValue: " + exitVal);
outputFile = new File(context.getPathToOutputFile());
numberOfExecutions++;
} while (keepJobRunning(outputFile, numberOfExecutions));
return outputFile;
}
private boolean keepJobRunning(File outputFile, int numberOfExecutions) {
if (outputFileNotPrepared(outputFile) && numberOfExecutions < 11) {
if (numberOfExecutions == 10) {
logger.error("Failed to run convexBP for 10 times");
}
return true;
}
return false;
}
private boolean outputFileNotPrepared(File outputFile) {
return (outputFile == null || !outputFile.exists());
}
private String createCommand(ConvexBPContext context) {
return context.getCommand();
}
private void checkOS() throws OSNotSupportedException {
String osName = System.getProperty("os.name");
if (StringUtils.indexOfIgnoreCase(osName, "windows") == -1) {
throw new OSNotSupportedException(String.format("Only 'Windows NT' is supported, this OS is: '%s'", osName));
}
}
}
| MFIblocks/experiments/src/main/java/il/ac/technion/ie/experiments/threads/CommandExacter.java | package il.ac.technion.ie.experiments.threads;
import il.ac.technion.ie.experiments.exception.OSNotSupportedException;
import il.ac.technion.ie.experiments.model.ConvexBPContext;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
/**
* Created by I062070 on 26/09/2015.
*/
public class CommandExacter {
static final Logger logger = Logger.getLogger(CommandExacter.class);
public File execute(ConvexBPContext context) throws IOException, OSNotSupportedException, InterruptedException {
File outputFile;
int numberOfExecutions = 1;
checkOS();
Runtime runtime = Runtime.getRuntime();
String command = createCommand(context);
do {
logger.info(String.format("Executing convexBP algorithm for #%d time", numberOfExecutions));
logger.debug(String.format("Executing read UAI file by command: '%s'", command));
long startTime = System.nanoTime();
Process process = runtime.exec(command, new String[]{}, new File(context.getDir()));
long afterExecTime = System.currentTimeMillis();
Thread thread = new Thread(new ProcessTimeoutThread(process, afterExecTime, context.getWaitInterval()));
thread.start();
// any error message?
StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream(), StreamGobbler.ChanelType.ERROR);
// any output?
StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream(), StreamGobbler.ChanelType.OUTPUT);
// kick them off
errorGobbler.start();
outputGobbler.start();
// wait, if necessary, until the process object has terminated
logger.debug("Waiting if needed for previous read job to finish");
long waitTime = System.nanoTime();
int exitVal = process.waitFor();
long endTime = System.nanoTime();
logger.info(String.format("Total execution & waitTime of convexBP: %d, %d",
TimeUnit.NANOSECONDS.toSeconds(endTime - startTime), TimeUnit.NANOSECONDS.toSeconds(endTime - waitTime)));
logger.debug("ExitValue: " + exitVal);
outputFile = new File(context.getPathToOutputFile());
numberOfExecutions++;
} while (keepJobRunning(outputFile, numberOfExecutions));
return outputFile;
}
private boolean keepJobRunning(File outputFile, int numberOfExecutions) {
if ((outputFile == null || !outputFile.exists()) && numberOfExecutions < 11) {
return true;
}
logger.error("Failed to run convexBP for 10 times");
return false;
}
private String createCommand(ConvexBPContext context) {
return context.getCommand();
}
private void checkOS() throws OSNotSupportedException {
String osName = System.getProperty("os.name");
if (StringUtils.indexOfIgnoreCase(osName, "windows") == -1) {
throw new OSNotSupportedException(String.format("Only 'Windows NT' is supported, this OS is: '%s'", osName));
}
}
}
| Changed the logging if statement
| MFIblocks/experiments/src/main/java/il/ac/technion/ie/experiments/threads/CommandExacter.java | Changed the logging if statement | <ide><path>FIblocks/experiments/src/main/java/il/ac/technion/ie/experiments/threads/CommandExacter.java
<ide> }
<ide>
<ide> private boolean keepJobRunning(File outputFile, int numberOfExecutions) {
<del> if ((outputFile == null || !outputFile.exists()) && numberOfExecutions < 11) {
<add> if (outputFileNotPrepared(outputFile) && numberOfExecutions < 11) {
<add> if (numberOfExecutions == 10) {
<add> logger.error("Failed to run convexBP for 10 times");
<add> }
<ide> return true;
<ide> }
<del> logger.error("Failed to run convexBP for 10 times");
<ide> return false;
<add> }
<add>
<add> private boolean outputFileNotPrepared(File outputFile) {
<add> return (outputFile == null || !outputFile.exists());
<ide> }
<ide>
<ide> private String createCommand(ConvexBPContext context) { |
|
Java | apache-2.0 | d13f01f9238a429395352963f571764fba65842e | 0 | akuhtz/izpack,Sage-ERP-X3/izpack,tomas-forsman/izpack,rkrell/izpack,dasapich/izpack,Sage-ERP-X3/izpack,optotronic/izpack,izpack/izpack,awilhelm/izpack-with-ips,kanayo/izpack,codehaus/izpack,dasapich/izpack,izpack/izpack,rkrell/izpack,Sage-ERP-X3/izpack,codehaus/izpack,stenix71/izpack,kanayo/izpack,yukron/izpack,izpack/izpack,Murdock01/izpack,yukron/izpack,dasapich/izpack,kanayo/izpack,Helpstone/izpack,optotronic/izpack,Helpstone/izpack,Murdock01/izpack,mtjandra/izpack,kanayo/izpack,mtjandra/izpack,codehaus/izpack,Murdock01/izpack,stenix71/izpack,maichler/izpack,tomas-forsman/izpack,tomas-forsman/izpack,rsharipov/izpack,bradcfisher/izpack,kanayo/izpack,akuhtz/izpack,tomas-forsman/izpack,awilhelm/izpack-with-ips,codehaus/izpack,mtjandra/izpack,maichler/izpack,izpack/izpack,optotronic/izpack,awilhelm/izpack-with-ips,stenix71/izpack,stenix71/izpack,rsharipov/izpack,rkrell/izpack,Sage-ERP-X3/izpack,yukron/izpack,kanayo/izpack,akuhtz/izpack,akuhtz/izpack,maichler/izpack,stenix71/izpack,izpack/izpack,mtjandra/izpack,optotronic/izpack,akuhtz/izpack,awilhelm/izpack-with-ips,yukron/izpack,rsharipov/izpack,Helpstone/izpack,codehaus/izpack,codehaus/izpack,dasapich/izpack,Helpstone/izpack,optotronic/izpack,Murdock01/izpack,yukron/izpack,stenix71/izpack,rkrell/izpack,stenix71/izpack,Helpstone/izpack,optotronic/izpack,akuhtz/izpack,bradcfisher/izpack,mtjandra/izpack,tomas-forsman/izpack,codehaus/izpack,bradcfisher/izpack,Sage-ERP-X3/izpack,Murdock01/izpack,maichler/izpack,Helpstone/izpack,bradcfisher/izpack,akuhtz/izpack,rsharipov/izpack,maichler/izpack,Sage-ERP-X3/izpack,izpack/izpack,rkrell/izpack,tomas-forsman/izpack,dasapich/izpack,Sage-ERP-X3/izpack,maichler/izpack,dasapich/izpack,mtjandra/izpack,mtjandra/izpack,Helpstone/izpack,awilhelm/izpack-with-ips,Murdock01/izpack,bradcfisher/izpack,rkrell/izpack,maichler/izpack,optotronic/izpack,rsharipov/izpack,yukron/izpack,yukron/izpack,dasapich/izpack,izpack/izpack,rkrell/izpack,bradcfisher/izpack,rsharipov/izpack,tomas-forsman/izpack,bradcfisher/izpack,Murdock01/izpack,rsharipov/izpack | /*
* IzPack - Copyright 2001-2005 Julien Ponge, All Rights Reserved.
*
* http://www.izforge.com/izpack/
* http://developer.berlios.de/projects/izpack/
*
* Copyright 2004 Elmar Klaus Bartz
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.izforge.izpack.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.StringTokenizer;
/**
* <p>
* Class with some IO related helper.
* </p>
*
*/
public class IoHelper
{
// This class uses the same values for family and flavor as
// TargetFactory. But this class should not depends on TargetFactory,
// because it is possible that TargetFactory is not bound. Therefore
// the definition here again.
// ------------------------------------------------------------------------
// Constant Definitions
// ------------------------------------------------------------------------
/** Placeholder during translatePath computing */
private static final String MASKED_SLASH_PLACEHOLDER = "~&_&~";
private static Properties envVars = null;
/**
* Default constructor
*/
private IoHelper()
{
}
/**
* Copies the contents of inFile into outFile.
*
* @param inFile path of file which should be copied
* @param outFile path of file to create and copy the contents of inFile into
*/
public static void copyFile(String inFile, String outFile) throws IOException
{
copyFile(new File(inFile), new File(outFile));
}
/**
* Creates an in- and output stream for the given File objects and copies all the data from the
* specified input to the specified output.
*
* @param inFile File object for input
* @param outFile File object for output
* @exception IOException if an I/O error occurs
*/
public static void copyFile(File inFile, File outFile) throws IOException
{
copyFile(inFile, outFile, null, null);
}
/**
* Creates an in- and output stream for the given File objects and copies all the data from the
* specified input to the specified output. If permissions is not null, a chmod will be done on
* the output file.
*
* @param inFile File object for input
* @param outFile File object for output
* @param permissions permissions for the output file
* @exception IOException if an I/O error occurs
*/
public static void copyFile(File inFile, File outFile, String permissions) throws IOException
{
copyFile(inFile, outFile, permissions, null);
}
/**
* Creates an in- and output stream for the given File objects and copies all the data from the
* specified input to the specified output. If the VariableSubstitutor is not null, a substition
* will be done during copy.
*
* @param inFile File object for input
* @param outFile File object for output
* @param vss substitutor which is used during copying
* @exception IOException if an I/O error occurs
*/
public static void copyFile(File inFile, File outFile, VariableSubstitutor vss)
throws IOException
{
copyFile(inFile, outFile, null, vss);
}
/**
* Creates an in- and output stream for the given File objects and copies all the data from the
* specified input to the specified output. If the VariableSubstitutor is not null, a substition
* will be done during copy. If permissions is not null, a chmod will be done on the output
* file.
*
* @param inFile File object for input
* @param outFile File object for output
* @param permissions permissions for the output file
* @param vs substitutor which is used during copying
* @exception IOException if an I/O error occurs
*/
public static void copyFile(File inFile, File outFile, String permissions,
VariableSubstitutor vs) throws IOException
{
copyFile(inFile, outFile, permissions, vs, null);
}
/**
* Creates an in- and output stream for the given File objects and copies all the data from the
* specified input to the specified output. If the VariableSubstitutor is not null, a substition
* will be done during copy. If permissions is not null, a chmod will be done on the output
* file. If type is not null, that type is used as file type at substitution.
*
* @param inFile File object for input
* @param outFile File object for output
* @param permissions permissions for the output file
* @param vs substitutor which is used during copying
* @param type file type for the substitutor
* @exception IOException if an I/O error occurs
*/
public static void copyFile(File inFile, File outFile, String permissions,
VariableSubstitutor vs, String type) throws IOException
{
FileOutputStream out = new FileOutputStream(outFile);
FileInputStream in = new FileInputStream(inFile);
if (vs == null)
{
byte[] buffer = new byte[5120];
long bytesCopied = 0;
int bytesInBuffer;
while ((bytesInBuffer = in.read(buffer)) != -1)
{
out.write(buffer, 0, bytesInBuffer);
bytesCopied += bytesInBuffer;
}
in.close();
out.close();
}
else
{
BufferedInputStream bin = new BufferedInputStream(in, 5120);
BufferedOutputStream bout = new BufferedOutputStream(out, 5120);
vs.substitute(bin, bout, type, null);
bin.close();
bout.close();
}
if (permissions != null && IoHelper.supported("chmod"))
{
chmod(outFile.getAbsolutePath(), permissions);
}
}
/**
* Creates a temp file with delete on exit rule. The extension is extracted from the template if
* possible, else the default extension is used. The contents of template will be copied into
* the temporary file.
*
* @param template file to copy from and define file extension
* @param defaultExtension file extension if no is contained in template
* @return newly created and filled temporary file
* @throws IOException
*/
public static File copyToTempFile(File template, String defaultExtension) throws IOException
{
return copyToTempFile(template, defaultExtension, null);
}
/**
* Creates a temp file with delete on exit rule. The extension is extracted from the template if
* possible, else the default extension is used. The contents of template will be copied into
* the temporary file. If the variable substitutor is not null, variables will be replaced
* during copying.
*
* @param template file to copy from and define file extension
* @param defaultExtension file extension if no is contained in template
* @param vss substitutor which is used during copying
* @return newly created and filled temporary file
* @throws IOException
*/
public static File copyToTempFile(File template, String defaultExtension,
VariableSubstitutor vss) throws IOException
{
String path = template.getCanonicalPath();
int pos = path.lastIndexOf('.');
String ext = path.substring(pos);
if (ext == null) ext = defaultExtension;
File tmpFile = File.createTempFile("izpack_io", ext);
tmpFile.deleteOnExit();
IoHelper.copyFile(template, tmpFile, vss);
return tmpFile;
}
/**
* Creates a temp file with delete on exit rule. The extension is extracted from the template if
* possible, else the default extension is used. The contents of template will be copied into
* the temporary file.
*
* @param template file to copy from and define file extension
* @param defaultExtension file extension if no is contained in template
* @return newly created and filled temporary file
* @throws IOException
*/
public static File copyToTempFile(String template, String defaultExtension) throws IOException
{
return copyToTempFile(new File(template), defaultExtension);
}
/**
* Changes the permissions of the given file to the given POSIX permissions.
*
* @param file the file for which the permissions should be changed
* @param permissions POSIX permissions to be set
* @throws IOException if an I/O error occurs
*/
public static void chmod(File file, String permissions) throws IOException
{
chmod(file.getAbsolutePath(), permissions);
}
/**
* Changes the permissions of the given file to the given POSIX permissions. This method will be
* raised an exception, if the OS is not UNIX.
*
* @param path the absolute path of the file for which the permissions should be changed
* @param permissions POSIX permissions to be set
* @throws IOException if an I/O error occurs
*/
public static void chmod(String path, String permissions) throws IOException
{
// Perform UNIX
if (OsVersion.IS_UNIX)
{
String[] params = { "chmod", permissions, path};
String[] output = new String[2];
FileExecutor fe = new FileExecutor();
fe.executeCommand(params, output);
}
else
{
throw new IOException("Sorry, chmod not supported yet on " + OsVersion.OS_NAME + ".");
}
}
/**
* Returns the free (disk) space for the given path. If it is not ascertainable -1 returns.
*
* @param path path for which the free space should be detected
* @return the free space for the given path
*/
public static long getFreeSpace(String path)
{
long retval = -1;
if (OsVersion.IS_WINDOWS)
{
String command = "cmd.exe";
if (System.getProperty("os.name").toLowerCase().indexOf("windows 9") > -1) return (-1);
String[] params = { command, "/C", "\"dir /D /-C \"" + path + "\"\""};
String[] output = new String[2];
FileExecutor fe = new FileExecutor();
fe.executeCommand(params, output);
retval = extractLong(output[0], -3, 3, "%");
}
else if (OsVersion.IS_SUNOS)
{
String[] params = { "df", "-k", path};
String[] output = new String[2];
FileExecutor fe = new FileExecutor();
fe.executeCommand(params, output);
retval = extractLong(output[0], -3, 3, "%") * 1024;
}
else if (OsVersion.IS_HPUX)
{
String[] params = { "bdf", path };
String[] output = new String[2];
FileExecutor fe = new FileExecutor();
fe.executeCommand(params, output);
retval = extractLong(output[0], -3, 3, "%") * 1024;
}
else if (OsVersion.IS_UNIX)
{
String[] params = { "df", "-Pk", path};
String[] output = new String[2];
FileExecutor fe = new FileExecutor();
fe.executeCommand(params, output);
retval = extractLong(output[0], -3, 3, "%") * 1024;
}
return retval;
}
/**
* Returns whether the given method will be supported with the given environment. Some methods
* of this class are not supported on all operation systems.
*
* @param method name of the method
* @return true if the method will be supported with the current enivronment else false
* @throws RuntimeException if the given method name does not exist
*/
public static boolean supported(String method)
{
if (method.equals("getFreeSpace"))
{
if (OsVersion.IS_UNIX) return true;
if (OsVersion.IS_WINDOWS)
{ // getFreeSpace do not work on Windows 98.
if (System.getProperty("os.name").toLowerCase().indexOf("windows 9") > -1)
return (false);
return (true);
}
}
else if (method.equals("chmod"))
{
if (OsVersion.IS_UNIX) return true;
}
else if (method.equals("copyFile"))
{
return true;
}
else if (method.equals("getPrimaryGroup"))
{
if (OsVersion.IS_UNIX) return true;
}
else if (method.equals("getenv"))
{
return true;
}
else
{
throw new RuntimeException("method name " + method + "not supported by this method");
}
return false;
}
/**
* Returns the first existing parent directory in a path
*
* @param path path which should be scanned
* @return the first existing parent directory in a path
*/
public static File existingParent(File path)
{
File result = path;
while (!result.exists())
{
if (result.getParent() == null) return result;
result = result.getParentFile();
}
return result;
}
/**
* Extracts a long value from a string in a special manner. The string will be broken into
* tokens with a standard StringTokenizer. Arround the assumed place (with the given half range)
* the tokens are scaned reverse for a token which represents a long. if useNotIdentifier is not
* null, tokens which are contains this string will be ignored. The first founded long returns.
*
* @param in the string which should be parsed
* @param assumedPlace token number which should contain the value
* @param halfRange half range for detection range
* @param useNotIdentifier string which determines tokens which should be ignored
* @return founded long
*/
private static long extractLong(String in, int assumedPlace, int halfRange,
String useNotIdentifier)
{
long retval = -1;
StringTokenizer st = new StringTokenizer(in);
int length = st.countTokens();
int i;
int currentRange = 0;
String[] interestedEntries = new String[halfRange + halfRange];
for (i = 0; i < length - halfRange + assumedPlace; ++i)
st.nextToken(); // Forget this entries.
for (i = 0; i < halfRange + halfRange; ++i)
{ // Put the interesting Strings into an intermediaer array.
if (st.hasMoreTokens())
{
interestedEntries[i] = st.nextToken();
currentRange++;
}
}
for (i = currentRange - 1; i >= 0; --i)
{
if (useNotIdentifier != null && interestedEntries[i].indexOf(useNotIdentifier) > -1)
continue;
try
{
retval = Long.parseLong(interestedEntries[i]);
}
catch (NumberFormatException nfe)
{
continue;
}
break;
}
return retval;
}
/**
* Returns the primary group of the current user. This feature will be supported only on Unix.
* On other systems null returns.
*
* @return the primary group of the current user
*/
public static String getPrimaryGroup()
{
if (supported("getPrimaryGroup"))
{
if (OsVersion.IS_SUNOS)
{ // Standard id of SOLARIS do not support -gn.
String[] params = { "id"};
String[] output = new String[2];
FileExecutor fe = new FileExecutor();
fe.executeCommand(params, output);
// No we have "uid=%u(%s) gid=%u(%s)"
if (output[0] != null)
{
StringTokenizer st = new StringTokenizer(output[0], "()");
int length = st.countTokens();
if (length >= 4)
{
for (int i = 0; i < 3; ++i)
st.nextToken();
return (st.nextToken());
}
}
return (null);
}
else
{
String[] params = { "id", "-gn"};
String[] output = new String[2];
FileExecutor fe = new FileExecutor();
fe.executeCommand(params, output);
return output[0];
}
}
else
return null;
}
/**
* Returns a string resulting from replacing all occurrences of what in this string with with.
* In opposite to the String.replaceAll method this method do not use regular expression or
* other methods which are only available in JRE 1.4 and later. This method was special made to
* mask masked slashes to avert a conversion during path translation.
*
* @param destination string for which the replacing should be performed
* @param what what string should be replaced
* @param with with what string what should be replaced
* @return a new String object if what was found in the given string, else the given string self
*/
public static String replaceString(String destination, String what, String with)
{
if (destination.indexOf(what) >= 0)
{ // what found, with (placeholder) not included in destination ->
// perform changing.
StringBuffer buf = new StringBuffer();
int last = 0;
int current = destination.indexOf(what);
int whatLength = what.length();
while (current >= 0)
{ // Do not use Methods from JRE 1.4 and higher ...
if (current > 0) buf.append(destination.substring(last, current));
buf.append(with);
last = current + whatLength;
current = destination.indexOf(what, last);
}
if (destination.length() > last) buf.append(destination.substring(last));
return buf.toString();
}
return destination;
}
/**
* Translates a relative path to a local system path.
*
* @param destination The path to translate.
* @return The translated path.
*/
public static String translatePath(String destination, VariableSubstitutor vs)
{
// Parse for variables
destination = vs.substitute(destination, null);
// Convert the file separator characters
// destination = destination.replace('/', File.separatorChar);
// Undo the conversion if the slashes was masked with
// a backslash
// Not all occurencies of slashes are path separators. To differ
// between it we allow to mask a slash with a backslash infront.
// Unfortunately we cannot use String.replaceAll because it
// handles backslashes in the replacement string in a special way
// and the method exist only beginning with JRE 1.4.
// Therefore the little bit crude way following ...
if (destination.indexOf("\\/") >= 0 && destination.indexOf(MASKED_SLASH_PLACEHOLDER) < 0)
{ // Masked slash found, placeholder not included in destination ->
// perform masking.
destination = replaceString(destination, "\\/", MASKED_SLASH_PLACEHOLDER);
// Masked slashes changed to MASKED_SLASH_PLACEHOLDER.
// Replace unmasked slashes.
destination = destination.replace('/', File.separatorChar);
// Replace the MASKED_SLASH_PLACEHOLDER to slashes; masking
// backslashes will
// be removed.
destination = replaceString(destination, MASKED_SLASH_PLACEHOLDER, "/");
}
else
destination = destination.replace('/', File.separatorChar);
return destination;
}
/**
* Returns the value of the environment variable given by key. This method is a work around for
* VM versions which do not support getenv in an other way. At the first call all environment
* variables will be loaded via an exec. On Windows keys are not case sensitive.
*
* @param key variable name for which the value should be resolved
* @return the value of the environment variable given by key
*/
public static String getenv(String key)
{
if (envVars == null) loadEnv();
if (envVars == null) return (null);
if (OsVersion.IS_WINDOWS) key = key.toUpperCase();
return (String) (envVars.get(key));
}
/**
* Loads all environment variables via an exec.
*/
private static void loadEnv()
{
String[] output = new String[2];
String[] params;
if (OsVersion.IS_WINDOWS)
{
String command = "cmd.exe";
if (System.getProperty("os.name").toLowerCase().indexOf("windows 9") > -1)
command = "command.com";
String[] paramst = { command, "/C", "set"};
params = paramst;
}
else
{
String[] paramst = { "env"};
params = paramst;
}
FileExecutor fe = new FileExecutor();
fe.executeCommand(params, output);
if (output[0].length() <= 0) return;
String lineSep = System.getProperty("line.separator");
StringTokenizer st = new StringTokenizer(output[0], lineSep);
envVars = new Properties();
String var = null;
while (st.hasMoreTokens())
{
String line = st.nextToken();
if (line.indexOf('=') == -1)
{ // May be a env var with a new line in it.
if (var == null)
{
var = lineSep + line;
}
else
{
var += lineSep + line;
}
}
else
{ // New var, perform the previous one.
setEnvVar(var);
var = line;
}
}
setEnvVar(var);
}
/**
* Extracts key and value from the given string var. The key should be separated from the value
* by a sign. On Windows all chars of the key are translated to upper case.
*
* @param var
*/
private static void setEnvVar(String var)
{
if (var == null) return;
int index = var.indexOf('=');
if (index < 0) return;
String key = var.substring(0, index);
// On windows change all key chars to upper.
if (OsVersion.IS_WINDOWS) key = key.toUpperCase();
envVars.setProperty(key, var.substring(index + 1));
}
}
| src/lib/com/izforge/izpack/util/IoHelper.java | /*
* IzPack - Copyright 2001-2005 Julien Ponge, All Rights Reserved.
*
* http://www.izforge.com/izpack/
* http://developer.berlios.de/projects/izpack/
*
* Copyright 2004 Elmar Klaus Bartz
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.izforge.izpack.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.StringTokenizer;
/**
* <p>
* Class with some IO related helper.
* </p>
*
*/
public class IoHelper
{
// This class uses the same values for family and flavor as
// TargetFactory. But this class should not depends on TargetFactory,
// because it is possible that TargetFactory is not bound. Therefore
// the definition here again.
// ------------------------------------------------------------------------
// Constant Definitions
// ------------------------------------------------------------------------
/** Placeholder during translatePath computing */
private static final String MASKED_SLASH_PLACEHOLDER = "~&_&~";
private static Properties envVars = null;
/**
* Default constructor
*/
private IoHelper()
{
}
/**
* Copies the contents of inFile into outFile.
*
* @param inFile path of file which should be copied
* @param outFile path of file to create and copy the contents of inFile into
*/
public static void copyFile(String inFile, String outFile) throws IOException
{
copyFile(new File(inFile), new File(outFile));
}
/**
* Creates an in- and output stream for the given File objects and copies all the data from the
* specified input to the specified output.
*
* @param inFile File object for input
* @param outFile File object for output
* @exception IOException if an I/O error occurs
*/
public static void copyFile(File inFile, File outFile) throws IOException
{
copyFile(inFile, outFile, null, null);
}
/**
* Creates an in- and output stream for the given File objects and copies all the data from the
* specified input to the specified output. If permissions is not null, a chmod will be done on
* the output file.
*
* @param inFile File object for input
* @param outFile File object for output
* @param permissions permissions for the output file
* @exception IOException if an I/O error occurs
*/
public static void copyFile(File inFile, File outFile, String permissions) throws IOException
{
copyFile(inFile, outFile, permissions, null);
}
/**
* Creates an in- and output stream for the given File objects and copies all the data from the
* specified input to the specified output. If the VariableSubstitutor is not null, a substition
* will be done during copy.
*
* @param inFile File object for input
* @param outFile File object for output
* @param vss substitutor which is used during copying
* @exception IOException if an I/O error occurs
*/
public static void copyFile(File inFile, File outFile, VariableSubstitutor vss)
throws IOException
{
copyFile(inFile, outFile, null, vss);
}
/**
* Creates an in- and output stream for the given File objects and copies all the data from the
* specified input to the specified output. If the VariableSubstitutor is not null, a substition
* will be done during copy. If permissions is not null, a chmod will be done on the output
* file.
*
* @param inFile File object for input
* @param outFile File object for output
* @param permissions permissions for the output file
* @param vs substitutor which is used during copying
* @exception IOException if an I/O error occurs
*/
public static void copyFile(File inFile, File outFile, String permissions,
VariableSubstitutor vs) throws IOException
{
copyFile(inFile, outFile, permissions, vs, null);
}
/**
* Creates an in- and output stream for the given File objects and copies all the data from the
* specified input to the specified output. If the VariableSubstitutor is not null, a substition
* will be done during copy. If permissions is not null, a chmod will be done on the output
* file. If type is not null, that type is used as file type at substitution.
*
* @param inFile File object for input
* @param outFile File object for output
* @param permissions permissions for the output file
* @param vs substitutor which is used during copying
* @param type file type for the substitutor
* @exception IOException if an I/O error occurs
*/
public static void copyFile(File inFile, File outFile, String permissions,
VariableSubstitutor vs, String type) throws IOException
{
FileOutputStream out = new FileOutputStream(outFile);
FileInputStream in = new FileInputStream(inFile);
if (vs == null)
{
byte[] buffer = new byte[5120];
long bytesCopied = 0;
int bytesInBuffer;
while ((bytesInBuffer = in.read(buffer)) != -1)
{
out.write(buffer, 0, bytesInBuffer);
bytesCopied += bytesInBuffer;
}
in.close();
out.close();
}
else
{
BufferedInputStream bin = new BufferedInputStream(in, 5120);
BufferedOutputStream bout = new BufferedOutputStream(out, 5120);
vs.substitute(bin, bout, type, null);
bin.close();
bout.close();
}
if (permissions != null && IoHelper.supported("chmod"))
{
chmod(outFile.getAbsolutePath(), permissions);
}
}
/**
* Creates a temp file with delete on exit rule. The extension is extracted from the template if
* possible, else the default extension is used. The contents of template will be copied into
* the temporary file.
*
* @param template file to copy from and define file extension
* @param defaultExtension file extension if no is contained in template
* @return newly created and filled temporary file
* @throws IOException
*/
public static File copyToTempFile(File template, String defaultExtension) throws IOException
{
return copyToTempFile(template, defaultExtension, null);
}
/**
* Creates a temp file with delete on exit rule. The extension is extracted from the template if
* possible, else the default extension is used. The contents of template will be copied into
* the temporary file. If the variable substitutor is not null, variables will be replaced
* during copying.
*
* @param template file to copy from and define file extension
* @param defaultExtension file extension if no is contained in template
* @param vss substitutor which is used during copying
* @return newly created and filled temporary file
* @throws IOException
*/
public static File copyToTempFile(File template, String defaultExtension,
VariableSubstitutor vss) throws IOException
{
String path = template.getCanonicalPath();
int pos = path.lastIndexOf('.');
String ext = path.substring(pos);
if (ext == null) ext = defaultExtension;
File tmpFile = File.createTempFile("izpack_io", ext);
tmpFile.deleteOnExit();
IoHelper.copyFile(template, tmpFile, vss);
return tmpFile;
}
/**
* Creates a temp file with delete on exit rule. The extension is extracted from the template if
* possible, else the default extension is used. The contents of template will be copied into
* the temporary file.
*
* @param template file to copy from and define file extension
* @param defaultExtension file extension if no is contained in template
* @return newly created and filled temporary file
* @throws IOException
*/
public static File copyToTempFile(String template, String defaultExtension) throws IOException
{
return copyToTempFile(new File(template), defaultExtension);
}
/**
* Changes the permissions of the given file to the given POSIX permissions.
*
* @param file the file for which the permissions should be changed
* @param permissions POSIX permissions to be set
* @throws IOException if an I/O error occurs
*/
public static void chmod(File file, String permissions) throws IOException
{
chmod(file.getAbsolutePath(), permissions);
}
/**
* Changes the permissions of the given file to the given POSIX permissions. This method will be
* raised an exception, if the OS is not UNIX.
*
* @param path the absolute path of the file for which the permissions should be changed
* @param permissions POSIX permissions to be set
* @throws IOException if an I/O error occurs
*/
public static void chmod(String path, String permissions) throws IOException
{
// Perform UNIX
if (OsVersion.IS_UNIX)
{
String[] params = { "chmod", permissions, path};
String[] output = new String[2];
FileExecutor fe = new FileExecutor();
fe.executeCommand(params, output);
}
else
{
throw new IOException("Sorry, chmod not supported yet on " + OsVersion.OS_NAME + ".");
}
}
/**
* Returns the free (disk) space for the given path. If it is not ascertainable -1 returns.
*
* @param path path for which the free space should be detected
* @return the free space for the given path
*/
public static long getFreeSpace(String path)
{
long retval = -1;
if (OsVersion.IS_WINDOWS)
{
String command = "cmd.exe";
if (System.getProperty("os.name").toLowerCase().indexOf("windows 9") > -1) return (-1);
String[] params = { command, "/C", "\"dir /D /-C \"" + path + "\"\""};
String[] output = new String[2];
FileExecutor fe = new FileExecutor();
fe.executeCommand(params, output);
retval = extractLong(output[0], -3, 3, "%");
}
else if (OsVersion.IS_SUNOS)
{
String[] params = { "df", "-k", path};
String[] output = new String[2];
FileExecutor fe = new FileExecutor();
fe.executeCommand(params, output);
retval = extractLong(output[0], -3, 3, "%") * 1024;
}
else if (OsVersion.IS_TRU64)
{
String[] params = { "bdf", path };
String[] output = new String[2];
FileExecutor fe = new FileExecutor();
fe.executeCommand(params, output);
retval = extractLong(output[0], -3, 3, "%") * 1024;
}
else if (OsVersion.IS_UNIX)
{
String[] params = { "df", "-Pk", path};
String[] output = new String[2];
FileExecutor fe = new FileExecutor();
fe.executeCommand(params, output);
retval = extractLong(output[0], -3, 3, "%") * 1024;
}
return retval;
}
/**
* Returns whether the given method will be supported with the given environment. Some methods
* of this class are not supported on all operation systems.
*
* @param method name of the method
* @return true if the method will be supported with the current enivronment else false
* @throws RuntimeException if the given method name does not exist
*/
public static boolean supported(String method)
{
if (method.equals("getFreeSpace"))
{
if (OsVersion.IS_UNIX) return true;
if (OsVersion.IS_WINDOWS)
{ // getFreeSpace do not work on Windows 98.
if (System.getProperty("os.name").toLowerCase().indexOf("windows 9") > -1)
return (false);
return (true);
}
}
else if (method.equals("chmod"))
{
if (OsVersion.IS_UNIX) return true;
}
else if (method.equals("copyFile"))
{
return true;
}
else if (method.equals("getPrimaryGroup"))
{
if (OsVersion.IS_UNIX) return true;
}
else if (method.equals("getenv"))
{
return true;
}
else
{
throw new RuntimeException("method name " + method + "not supported by this method");
}
return false;
}
/**
* Returns the first existing parent directory in a path
*
* @param path path which should be scanned
* @return the first existing parent directory in a path
*/
public static File existingParent(File path)
{
File result = path;
while (!result.exists())
{
if (result.getParent() == null) return result;
result = result.getParentFile();
}
return result;
}
/**
* Extracts a long value from a string in a special manner. The string will be broken into
* tokens with a standard StringTokenizer. Arround the assumed place (with the given half range)
* the tokens are scaned reverse for a token which represents a long. if useNotIdentifier is not
* null, tokens which are contains this string will be ignored. The first founded long returns.
*
* @param in the string which should be parsed
* @param assumedPlace token number which should contain the value
* @param halfRange half range for detection range
* @param useNotIdentifier string which determines tokens which should be ignored
* @return founded long
*/
private static long extractLong(String in, int assumedPlace, int halfRange,
String useNotIdentifier)
{
long retval = -1;
StringTokenizer st = new StringTokenizer(in);
int length = st.countTokens();
int i;
int currentRange = 0;
String[] interestedEntries = new String[halfRange + halfRange];
for (i = 0; i < length - halfRange + assumedPlace; ++i)
st.nextToken(); // Forget this entries.
for (i = 0; i < halfRange + halfRange; ++i)
{ // Put the interesting Strings into an intermediaer array.
if (st.hasMoreTokens())
{
interestedEntries[i] = st.nextToken();
currentRange++;
}
}
for (i = currentRange - 1; i >= 0; --i)
{
if (useNotIdentifier != null && interestedEntries[i].indexOf(useNotIdentifier) > -1)
continue;
try
{
retval = Long.parseLong(interestedEntries[i]);
}
catch (NumberFormatException nfe)
{
continue;
}
break;
}
return retval;
}
/**
* Returns the primary group of the current user. This feature will be supported only on Unix.
* On other systems null returns.
*
* @return the primary group of the current user
*/
public static String getPrimaryGroup()
{
if (supported("getPrimaryGroup"))
{
if (OsVersion.IS_SUNOS)
{ // Standard id of SOLARIS do not support -gn.
String[] params = { "id"};
String[] output = new String[2];
FileExecutor fe = new FileExecutor();
fe.executeCommand(params, output);
// No we have "uid=%u(%s) gid=%u(%s)"
if (output[0] != null)
{
StringTokenizer st = new StringTokenizer(output[0], "()");
int length = st.countTokens();
if (length >= 4)
{
for (int i = 0; i < 3; ++i)
st.nextToken();
return (st.nextToken());
}
}
return (null);
}
else
{
String[] params = { "id", "-gn"};
String[] output = new String[2];
FileExecutor fe = new FileExecutor();
fe.executeCommand(params, output);
return output[0];
}
}
else
return null;
}
/**
* Returns a string resulting from replacing all occurrences of what in this string with with.
* In opposite to the String.replaceAll method this method do not use regular expression or
* other methods which are only available in JRE 1.4 and later. This method was special made to
* mask masked slashes to avert a conversion during path translation.
*
* @param destination string for which the replacing should be performed
* @param what what string should be replaced
* @param with with what string what should be replaced
* @return a new String object if what was found in the given string, else the given string self
*/
public static String replaceString(String destination, String what, String with)
{
if (destination.indexOf(what) >= 0)
{ // what found, with (placeholder) not included in destination ->
// perform changing.
StringBuffer buf = new StringBuffer();
int last = 0;
int current = destination.indexOf(what);
int whatLength = what.length();
while (current >= 0)
{ // Do not use Methods from JRE 1.4 and higher ...
if (current > 0) buf.append(destination.substring(last, current));
buf.append(with);
last = current + whatLength;
current = destination.indexOf(what, last);
}
if (destination.length() > last) buf.append(destination.substring(last));
return buf.toString();
}
return destination;
}
/**
* Translates a relative path to a local system path.
*
* @param destination The path to translate.
* @return The translated path.
*/
public static String translatePath(String destination, VariableSubstitutor vs)
{
// Parse for variables
destination = vs.substitute(destination, null);
// Convert the file separator characters
// destination = destination.replace('/', File.separatorChar);
// Undo the conversion if the slashes was masked with
// a backslash
// Not all occurencies of slashes are path separators. To differ
// between it we allow to mask a slash with a backslash infront.
// Unfortunately we cannot use String.replaceAll because it
// handles backslashes in the replacement string in a special way
// and the method exist only beginning with JRE 1.4.
// Therefore the little bit crude way following ...
if (destination.indexOf("\\/") >= 0 && destination.indexOf(MASKED_SLASH_PLACEHOLDER) < 0)
{ // Masked slash found, placeholder not included in destination ->
// perform masking.
destination = replaceString(destination, "\\/", MASKED_SLASH_PLACEHOLDER);
// Masked slashes changed to MASKED_SLASH_PLACEHOLDER.
// Replace unmasked slashes.
destination = destination.replace('/', File.separatorChar);
// Replace the MASKED_SLASH_PLACEHOLDER to slashes; masking
// backslashes will
// be removed.
destination = replaceString(destination, MASKED_SLASH_PLACEHOLDER, "/");
}
else
destination = destination.replace('/', File.separatorChar);
return destination;
}
/**
* Returns the value of the environment variable given by key. This method is a work around for
* VM versions which do not support getenv in an other way. At the first call all environment
* variables will be loaded via an exec. On Windows keys are not case sensitive.
*
* @param key variable name for which the value should be resolved
* @return the value of the environment variable given by key
*/
public static String getenv(String key)
{
if (envVars == null) loadEnv();
if (envVars == null) return (null);
if (OsVersion.IS_WINDOWS) key = key.toUpperCase();
return (String) (envVars.get(key));
}
/**
* Loads all environment variables via an exec.
*/
private static void loadEnv()
{
String[] output = new String[2];
String[] params;
if (OsVersion.IS_WINDOWS)
{
String command = "cmd.exe";
if (System.getProperty("os.name").toLowerCase().indexOf("windows 9") > -1)
command = "command.com";
String[] paramst = { command, "/C", "set"};
params = paramst;
}
else
{
String[] paramst = { "env"};
params = paramst;
}
FileExecutor fe = new FileExecutor();
fe.executeCommand(params, output);
if (output[0].length() <= 0) return;
String lineSep = System.getProperty("line.separator");
StringTokenizer st = new StringTokenizer(output[0], lineSep);
envVars = new Properties();
String var = null;
while (st.hasMoreTokens())
{
String line = st.nextToken();
if (line.indexOf('=') == -1)
{ // May be a env var with a new line in it.
if (var == null)
{
var = lineSep + line;
}
else
{
var += lineSep + line;
}
}
else
{ // New var, perform the previous one.
setEnvVar(var);
var = line;
}
}
setEnvVar(var);
}
/**
* Extracts key and value from the given string var. The key should be separated from the value
* by a sign. On Windows all chars of the key are translated to upper case.
*
* @param var
*/
private static void setEnvVar(String var)
{
if (var == null) return;
int index = var.indexOf('=');
if (index < 0) return;
String key = var.substring(0, index);
// On windows change all key chars to upper.
if (OsVersion.IS_WINDOWS) key = key.toUpperCase();
envVars.setProperty(key, var.substring(index + 1));
}
}
| Fixed detection of getFreeSpace() not for tru64 but HP-UX
git-svn-id: 408af81b9e4f0a5eaad229a6d9eed76d614c4af6@1415 7d736ef5-cfd4-0310-9c9a-b52d5c14b761
| src/lib/com/izforge/izpack/util/IoHelper.java | Fixed detection of getFreeSpace() not for tru64 but HP-UX | <ide><path>rc/lib/com/izforge/izpack/util/IoHelper.java
<ide> fe.executeCommand(params, output);
<ide> retval = extractLong(output[0], -3, 3, "%") * 1024;
<ide> }
<del> else if (OsVersion.IS_TRU64)
<add> else if (OsVersion.IS_HPUX)
<ide> {
<ide> String[] params = { "bdf", path };
<ide> String[] output = new String[2]; |
|
JavaScript | mit | fa3da3b6d6e0ac308d5d6de621392a11296716af | 0 | CptPie/telegram-shipit-bot,CptPie/telegram-shipit-bot | const TelegramBot = require('node-telegram-bot-api');
const request = require('request');
const token = '<YOUR TOKEN>'
const bot = new TelegramBot(token, {polling: true})
bot.onText(/\/greet (.+)/, (msg, input) => {
const chatId = msg.chat.id;
var blub = input[1];
var resp ='Hello, '+blub;
bot.sendMessage(chatId, resp);
});
var loremSettings = {
url: 'http://lorempixel.com/400/200',
encoding: null
};
bot.onText(/\/lorem/||/\/lorem (.*)/, (msg) =>{
const chatId = msg.chat.id;
request(loremSettings, function (error, response, buffer) {
if (!error && response.statusCode == 200){
bot.sendPhoto(chatId, buffer);
}
})
});
var doit = [
'http://i.imgur.com/RPbK0fZ.png',
'http://i.imgur.com/TgUQfNI.jpg',
'http://i.imgur.com/WSm116p.jpg',
]
bot.onText(/\/doit/,(msg) =>{
const chatId = msg.chat.id;
bot.sendPhoto(chatId, doit[Math.floor(Math.random()*doit.length)]);
});
var ship = [
'http://i.imgur.com/b7bzy0C.png',
'http://i.imgur.com/hse69ui.jpg',
'http://i.imgur.com/pyjpvhM.gif',
'http://i.imgur.com/66j50Xz.jpg',
'http://i.imgur.com/tCiQSlg.jpg',
'http://i.imgur.com/DDLLoL8.gif',
'http://i.imgur.com/LDzcDY3.jpg',
'http://i.imgur.com/nkeMpLe.jpg',
'http://i.imgur.com/ACaARFw.jpg',
'http://i.imgur.com/aJkhUrE.jpg',
'http://i.imgur.com/YBdJsaS.jpg',
'http://i.imgur.com/KmZrtgd.jpg',
'http://i.imgur.com/rmgCY2Q.jpg',
'http://i.imgur.com/g00lVs9.gif',
'http://i.imgur.com/LIIXWmD.png',
'http://i.imgur.com/c6K9rP3.jpg',
'http://i.imgur.com/2M8iyPt.jpg',
'http://i.imgur.com/7XxnrTu.jpg',
'http://i.imgur.com/AJN04yl.jpg',
'http://i.imgur.com/rcIMpM0.gif',
'http://i.imgur.com/60u8kye.jpg',
'http://i.imgur.com/yUypmaC.jpg',
'http://i.imgur.com/IflZleY.jpg',
'http://i.imgur.com/h3mlvCq.png',
'http://i.imgur.com/dXzZETc.png',
'https://media.giphy.com/media/143vPc6b08locw/giphy.gif',
'https://media0.giphy.com/media/14tFXhhNurdGp2/giphy.gif',
'https://media4.giphy.com/media/ta83CqOoRwfwQ/giphy.gif',
'https://media2.giphy.com/media/tDafHUBVrRKtq/giphy.gif',
'https://media2.giphy.com/media/tDafHUBVrRKtq/giphy.gif',
]
bot.onText(/\/ship/,(msg) =>{
const chatId = msg.chat.id;
bot.sendMessage(chatId, ship[Math.floor(Math.random()*ship.length)]);
});
var merge = [
'https://i.imgur.com/X9zNSkM.gif',
'https://cdn.meme.am/cache/instances/folder86/500x/64007086/disaster-girl-push-rejected-rebase-or-merge-git-push-force.jpg',
'https://www.mememaker.net/static/images/memes/3629643.jpg',
'http://s.quickmeme.com/img/58/58cdc50dcb04a16438e9759f2db7a0ac23442e718f69af7b2ac0a3761915e92a.jpg',
'https://i.stack.imgur.com/nEfIm.jpg',
]
bot.onText(/\/merge/,(msg) => {
const chatId = msg.chat.id;
bot.sendMessage(chatId, merge[Math.floor(Math.random()*merge.length)]);
});
| bot.js | const TelegramBot = require('node-telegram-bot-api');
const request = require('request');
const token = '438965853:AAGwB7Y5g8KqM3OVjkQilBuOrvCh8s9ZqmM'
const bot = new TelegramBot(token, {polling: true})
bot.onText(/\/greet (.+)/, (msg, input) => {
const chatId = msg.chat.id;
var blub = input[1];
var resp ='Hello, '+blub;
bot.sendMessage(chatId, resp);
});
var loremSettings = {
url: 'http://lorempixel.com/400/200',
encoding: null
};
bot.onText(/\/lorem/||/\/lorem (.*)/, (msg) =>{
const chatId = msg.chat.id;
request(loremSettings, function (error, response, buffer) {
if (!error && response.statusCode == 200){
bot.sendPhoto(chatId, buffer);
}
})
});
var doit = [
'http://i.imgur.com/RPbK0fZ.png',
'http://i.imgur.com/TgUQfNI.jpg',
'http://i.imgur.com/WSm116p.jpg',
]
bot.onText(/\/doit/,(msg) =>{
const chatId = msg.chat.id;
bot.sendPhoto(chatId, doit[Math.floor(Math.random()*doit.length)]);
});
var ship = [
'http://i.imgur.com/b7bzy0C.png',
'http://i.imgur.com/hse69ui.jpg',
'http://i.imgur.com/pyjpvhM.gif',
'http://i.imgur.com/66j50Xz.jpg',
'http://i.imgur.com/tCiQSlg.jpg',
'http://i.imgur.com/DDLLoL8.gif',
'http://i.imgur.com/LDzcDY3.jpg',
'http://i.imgur.com/nkeMpLe.jpg',
'http://i.imgur.com/ACaARFw.jpg',
'http://i.imgur.com/aJkhUrE.jpg',
'http://i.imgur.com/YBdJsaS.jpg',
'http://i.imgur.com/KmZrtgd.jpg',
'http://i.imgur.com/rmgCY2Q.jpg',
'http://i.imgur.com/g00lVs9.gif',
'http://i.imgur.com/LIIXWmD.png',
'http://i.imgur.com/c6K9rP3.jpg',
'http://i.imgur.com/2M8iyPt.jpg',
'http://i.imgur.com/7XxnrTu.jpg',
'http://i.imgur.com/AJN04yl.jpg',
'http://i.imgur.com/rcIMpM0.gif',
'http://i.imgur.com/60u8kye.jpg',
'http://i.imgur.com/yUypmaC.jpg',
'http://i.imgur.com/IflZleY.jpg',
'http://i.imgur.com/h3mlvCq.png',
'http://i.imgur.com/dXzZETc.png',
'https://media.giphy.com/media/143vPc6b08locw/giphy.gif',
'https://media0.giphy.com/media/14tFXhhNurdGp2/giphy.gif',
'https://media4.giphy.com/media/ta83CqOoRwfwQ/giphy.gif',
'https://media2.giphy.com/media/tDafHUBVrRKtq/giphy.gif',
'https://media2.giphy.com/media/tDafHUBVrRKtq/giphy.gif',
]
bot.onText(/\/ship/,(msg) =>{
const chatId = msg.chat.id;
bot.sendMessage(chatId, ship[Math.floor(Math.random()*ship.length)]);
});
var merge = [
'https://i.imgur.com/X9zNSkM.gif',
'https://cdn.meme.am/cache/instances/folder86/500x/64007086/disaster-girl-push-rejected-rebase-or-merge-git-push-force.jpg',
'https://www.mememaker.net/static/images/memes/3629643.jpg',
'http://s.quickmeme.com/img/58/58cdc50dcb04a16438e9759f2db7a0ac23442e718f69af7b2ac0a3761915e92a.jpg',
'https://i.stack.imgur.com/nEfIm.jpg',
]
bot.onText(/\/merge/,(msg) => {
const chatId = msg.chat.id;
bot.sendMessage(chatId, merge[Math.floor(Math.random()*merge.length)]);
});
| removed my bot token for security reasons
| bot.js | removed my bot token for security reasons | <ide><path>ot.js
<ide> const TelegramBot = require('node-telegram-bot-api');
<ide> const request = require('request');
<ide>
<del>const token = '438965853:AAGwB7Y5g8KqM3OVjkQilBuOrvCh8s9ZqmM'
<add>const token = '<YOUR TOKEN>'
<ide> const bot = new TelegramBot(token, {polling: true})
<ide>
<ide> bot.onText(/\/greet (.+)/, (msg, input) => { |
|
Java | apache-2.0 | f02762aabfbb12397c7a54cec0ef72d00a0d0cdd | 0 | ispras/binnavi,nihilus/binnavi,google/binnavi,mayl8822/binnavi,ant4g0nist/binnavi,noikiy/binnavi,noikiy/binnavi,bmihaila/binnavi,AmesianX/binnavi,firebitsbr/binnavi,hoangcuongflp/binnavi,AmesianX/binnavi,ispras/binnavi,noikiy/binnavi,bmihaila/binnavi,ant4g0nist/binnavi,chubbymaggie/binnavi,google/binnavi,ant4g0nist/binnavi,hoangcuongflp/binnavi,ispras/binnavi,firebitsbr/binnavi,mayl8822/binnavi,bmihaila/binnavi,ant4g0nist/binnavi,firebitsbr/binnavi,bmihaila/binnavi,hoangcuongflp/binnavi,nihilus/binnavi,firebitsbr/binnavi,AmesianX/binnavi,nihilus/binnavi,mayl8822/binnavi,bmihaila/binnavi,hoangcuongflp/binnavi,nihilus/binnavi,ispras/binnavi,mayl8822/binnavi,mayl8822/binnavi,firebitsbr/binnavi,chubbymaggie/binnavi,noikiy/binnavi,ispras/binnavi,google/binnavi,ant4g0nist/binnavi,AmesianX/binnavi,noikiy/binnavi,hoangcuongflp/binnavi,AmesianX/binnavi,chubbymaggie/binnavi,google/binnavi,nihilus/binnavi,chubbymaggie/binnavi,google/binnavi,chubbymaggie/binnavi,chubbymaggie/binnavi,ispras/binnavi,google/binnavi | /*
Copyright 2015 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.security.zynamics.zylib.net;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
public class WebsiteReader {
public static String read(final String url) throws IOException {
// Create a URL for the desired page
final URL url_ = new URL(url);
final BufferedReader in = new BufferedReader(new InputStreamReader(url_.openStream()));
final StringBuilder sb = new StringBuilder();
String str;
while ((str = in.readLine()) != null) {
sb.append(str);
}
in.close();
return sb.toString();
}
public static String sendPost(final String urlString, final String encodedData)
throws IOException {
final URL url = new URL(urlString);
final URLConnection conn = url.openConnection();
conn.setDoOutput(true);
try (OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream())) {
wr.write(encodedData);
wr.flush();
}
// Get the response
final StringBuilder ret = new StringBuilder();
String line;
try (BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
while ((line = rd.readLine()) != null) {
ret.append(line);
}
}
return ret.toString();
}
}
| src/main/java/com/google/security/zynamics/zylib/net/WebsiteReader.java | /*
Copyright 2015 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.security.zynamics.zylib.net;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
public class WebsiteReader {
public static String read(final String url) throws IOException {
// Create a URL for the desired page
final URL url_ = new URL(url);
final BufferedReader in = new BufferedReader(new InputStreamReader(url_.openStream()));
final StringBuilder sb = new StringBuilder();
String str;
while ((str = in.readLine()) != null) {
sb.append(str);
}
in.close();
return sb.toString();
}
public static String sendPost(final String urlString, final String encodedData)
throws IOException {
final URL url = new URL(urlString);
final URLConnection conn = url.openConnection();
conn.setDoOutput(true);
final OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
try {
wr.write(encodedData);
wr.flush();
} finally {
wr.close();
}
// Get the response
final BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
final StringBuilder ret = new StringBuilder();
String line;
try {
while ((line = rd.readLine()) != null) {
ret.append(line);
}
} finally {
rd.close();
}
return ret.toString();
}
}
| Update WebsiteReader.java | src/main/java/com/google/security/zynamics/zylib/net/WebsiteReader.java | Update WebsiteReader.java | <ide><path>rc/main/java/com/google/security/zynamics/zylib/net/WebsiteReader.java
<ide>
<ide> conn.setDoOutput(true);
<ide>
<del> final OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
<del> try {
<add> try (OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream())) {
<ide> wr.write(encodedData);
<ide> wr.flush();
<del> } finally {
<del> wr.close();
<ide> }
<ide>
<ide> // Get the response
<del> final BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
<del>
<ide> final StringBuilder ret = new StringBuilder();
<del>
<ide> String line;
<ide>
<del> try {
<add> try (BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
<ide> while ((line = rd.readLine()) != null) {
<ide> ret.append(line);
<ide> }
<del> } finally {
<del> rd.close();
<ide> }
<ide>
<ide> return ret.toString(); |
|
JavaScript | isc | b60bfc91f2b95cb7fc071ed1c107e808a5b20daf | 0 | wilsonianb/ripple-lib,wilsonianb/ripple-lib,darkdarkdragon/ripple-lib,ripple/ripple-lib,ripple/ripple-lib,darkdarkdragon/ripple-lib,darkdarkdragon/ripple-lib,ripple/ripple-lib,ripple/ripple-lib,wilsonianb/ripple-lib | // Represent Ripple amounts and currencies.
// - Numbers in hex are big-endian.
var sjcl = require('./sjcl/core.js');
var bn = require('./sjcl/core.js').bn;
var utils = require('./utils.js');
var jsbn = require('./jsbn.js');
var BigInteger = jsbn.BigInteger;
var nbi = jsbn.nbi;
var alphabets = {
'ripple' : "rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz",
'bitcoin' : "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
};
var consts = exports.consts = {
'address_xns' : "rrrrrrrrrrrrrrrrrrrrrhoLvTp",
'address_one' : "rrrrrrrrrrrrrrrrrrrrBZbvji",
'currency_xns' : 0,
'currency_one' : 1,
'uint160_xns' : utils.hexToString("0000000000000000000000000000000000000000"),
'uint160_one' : utils.hexToString("0000000000000000000000000000000000000001"),
'hex_xns' : "0000000000000000000000000000000000000000",
'hex_one' : "0000000000000000000000000000000000000001",
'xns_precision' : 6,
// BigInteger values prefixed with bi_.
'bi_10' : new BigInteger('10'),
'bi_man_max_value' : new BigInteger('9999999999999999'),
'bi_man_min_value' : new BigInteger('1000000000000000'),
'bi_xns_max' : new BigInteger("9000000000000000000"), // Json wire limit.
'bi_xns_min' : new BigInteger("-9000000000000000000"), // Json wire limit.
'bi_xns_unit' : new BigInteger('1000000'),
};
// --> input: big-endian array of bytes.
// <-- string at least as long as input.
var encode_base = function (input, alphabet) {
var alphabet = alphabets[alphabet || 'ripple'];
var bi_base = new BigInteger(String(alphabet.length));
var bi_q = nbi();
var bi_r = nbi();
var bi_value = new BigInteger(input);
var buffer = [];
while (bi_value.compareTo(BigInteger.ZERO) > 0)
{
bi_value.divRemTo(bi_base, bi_q, bi_r);
bi_q.copyTo(bi_value);
buffer.push(alphabet[bi_r.intValue()]);
}
var i;
for (i = 0; i != input.length && !input[i]; i += 1) {
buffer.push(alphabet[0]);
}
return buffer.reverse().join("");
};
// --> input: String
// <-- array of bytes or undefined.
var decode_base = function (input, alphabet) {
var alphabet = alphabets[alphabet || 'ripple'];
var bi_base = new BigInteger(String(alphabet.length));
var bi_value = nbi();
var i;
for (i = 0; i != input.length && input[i] === alphabet[0]; i += 1)
;
for (; i != input.length; i += 1) {
var v = alphabet.indexOf(input[i]);
if (v < 0)
return undefined;
var r = nbi();
r.fromInt(v);
bi_value = bi_value.multiply(bi_base).add(r);
}
// toByteArray:
// - Returns leading zeros!
// - Returns signed bytes!
var bytes = bi_value.toByteArray().map(function (b) { return b ? b < 0 ? 256+b : b : 0});
var extra = 0;
while (extra != bytes.length && !bytes[extra])
extra += 1;
if (extra)
bytes = bytes.slice(extra);
var zeros = 0;
while (zeros !== input.length && input[zeros] === alphabet[0])
zeros += 1;
return [].concat(utils.arraySet(zeros, 0), bytes);
};
var sha256 = function (bytes) {
return sjcl.codec.bytes.fromBits(sjcl.hash.sha256.hash(sjcl.codec.bytes.toBits(bytes)));
};
var sha256hash = function (bytes) {
return sha256(sha256(bytes));
};
// --> input: Array
// <-- String
var encode_base_check = function (version, input, alphabet) {
var buffer = [].concat(version, input);
var check = sha256(sha256(buffer)).slice(0, 4);
return encode_base([].concat(buffer, check), alphabet);
}
// --> input : String
// <-- NaN || BigInteger
var decode_base_check = function (version, input, alphabet) {
var buffer = decode_base(input, alphabet);
if (!buffer || buffer[0] !== version || buffer.length < 5)
return NaN;
var computed = sha256hash(buffer.slice(0, -4)).slice(0, 4);
var checksum = buffer.slice(-4);
var i;
for (i = 0; i != 4; i += 1)
if (computed[i] !== checksum[i])
return NaN;
return new BigInteger(buffer.slice(1, -4));
}
var UInt160 = function () {
// Internal form: NaN or BigInteger
this._value = NaN;
};
UInt160.json_rewrite = function (j) {
return UInt160.from_json(j).to_json();
};
// Return a new UInt160 from j.
UInt160.from_json = function (j) {
return 'string' === typeof j
? (new UInt160()).parse_json(j)
: j.clone();
};
UInt160.is_valid = function (j) {
return UInt160.from_json(j).is_valid();
};
UInt160.prototype.clone = function() {
return this.copyTo(new UInt160());
};
// Returns copy.
UInt160.prototype.copyTo = function(d) {
d._value = this._value;
return d;
};
UInt160.prototype.equals = function(d) {
return isNaN(this._value) || isNaN(d._value) ? false : this._value.equals(d._value);
};
// value = NaN on error.
UInt160.prototype.parse_json = function (j) {
// Canonicalize and validate
if (exports.config.accounts && j in exports.config.accounts)
j = exports.config.accounts[j].account;
switch (j) {
case undefined:
case "0":
case consts.address_xns:
case consts.uint160_xns:
case consts.hex_xns:
this._value = nbi();
break;
case "1":
case consts.address_one:
case consts.uint160_one:
case consts.hex_one:
this._value = new BigInteger([1]);
break;
default:
if ('string' !== typeof j) {
this._value = NaN;
}
else if (20 === j.length) {
this._value = new BigInteger(utils.stringToArray(j), 256);
}
else if (40 === j.length) {
// XXX Check char set!
this._value = new BigInteger(j, 16);
}
else if (j[0] === "r") {
this._value = decode_base_check(0, j);
}
else {
this._value = NaN;
}
}
return this;
};
// Convert from internal form.
// XXX Json form should allow 0 and 1, C++ doesn't currently allow it.
UInt160.prototype.to_json = function () {
if (isNaN(this._value))
return NaN;
var bytes = this._value.toByteArray().map(function (b) { return b ? b < 0 ? 256+b : b : 0});
var target = 20;
// XXX Make sure only trim off leading zeros.
var array = bytes.length < target
? bytes.length
? [].concat(utils.arraySet(target - bytes.length, 0), bytes)
: utils.arraySet(target, 0)
: bytes.slice(target - bytes.length);
var output = encode_base_check(0, array);
return output;
};
UInt160.prototype.is_valid = function () {
return !isNaN(this._value);
};
// XXX Internal form should be UInt160.
var Currency = function () {
// Internal form: 0 = XRP. 3 letter-code.
// XXX Internal should be 0 or hex with three letter annotation when valid.
// Json form:
// '', 'XRP', '0': 0
// 3-letter code: ...
// XXX Should support hex, C++ doesn't currently allow it.
this._value = NaN;
}
// Given "USD" return the json.
Currency.json_rewrite = function(j) {
return Currency.from_json(j).to_json();
};
Currency.from_json = function (j) {
return 'string' === typeof j
? (new Currency()).parse_json(j)
: j.clone();
};
Currency.is_valid = function (j) {
return currency.from_json(j).is_valid();
};
Currency.prototype.clone = function() {
return this.copyTo(new Currency());
};
// Returns copy.
Currency.prototype.copyTo = function(d) {
d._value = this._value;
return d;
};
Currency.prototype.equals = function(d) {
return ('string' !== typeof this._value && isNaN(this._value))
|| ('string' !== typeof d._value && isNaN(d._value)) ? false : this._value === d._value;
}
// this._value = NaN on error.
Currency.prototype.parse_json = function(j) {
if ("" === j || "0" === j || "XRP" === j) {
this._value = 0;
}
else if ('string' != typeof j || 3 !== j.length) {
this._value = NaN;
}
else {
this._value = j;
}
return this;
};
Currency.prototype.is_valid = function () {
return !isNaN(this._value);
};
Currency.prototype.to_json = function () {
return this._value ? this._value : "XRP";
};
Currency.prototype.to_human = function() {
return this._value ? this._value : "XRP";
};
var Amount = function () {
// Json format:
// integer : XRP
// { 'value' : ..., 'currency' : ..., 'issuer' : ...}
this._value = new BigInteger(); // NaN for bad value. Always positive for non-XRP.
this._offset = undefined; // For non-XRP.
this._is_native = true; // Default to XRP. Only valid if value is not NaN.
this._is_negative = undefined; // For non-XRP. Undefined for XRP.
this._currency = new Currency();
this._issuer = new UInt160();
};
// Given "100/USD/mtgox" return the a string with mtgox remapped.
Amount.text_full_rewrite = function (j) {
return Amount.from_json(j).to_text_full();
}
// Given "100/USD/mtgox" return the json.
Amount.json_rewrite = function(j) {
return Amount.from_json(j).to_json();
};
Amount.from_json = function(j) {
return (new Amount()).parse_json(j);
};
Amount.from_human = function(j) {
return (new Amount()).parse_human(j);
};
Amount.is_valid = function (j) {
return Amount.from_json(j).is_valid();
};
Amount.is_valid_full = function (j) {
return Amount.from_json(j).is_valid_full();
};
Amount.prototype.clone = function(negate) {
return this.copyTo(new Amount(), negate);
};
// Returns copy.
Amount.prototype.copyTo = function(d, negate) {
if ('object' === typeof this._value)
{
if (this._is_native && negate)
this._value.negate().copyTo(d._value);
else
this._value.copyTo(d._value);
}
else
{
d._value = this._value;
}
d._offset = this._offset;
d._is_native = this._is_native;
d._is_negative = this._is_native
? undefined // Native sign in BigInteger.
: negate
? !this._is_negative // Negating.
: this._is_negative; // Just copying.
this._currency.copyTo(d._currency);
this._issuer.copyTo(d._issuer);
return d;
};
Amount.prototype.currency = function() {
return this._currency;
};
Amount.prototype.set_currency = function(c) {
if ('string' === typeof c) {
this._currency.parse_json(c);
}
else
{
c.copyTo(this._currency);
}
return this;
};
Amount.prototype.set_issuer = function (issuer) {
if (issuer instanceof UInt160) {
issuer.copyTo(this._issuer);
} else {
this._issuer.parse_json(issuer);
}
return this;
};
// Only checks the value. Not the currency and issuer.
Amount.prototype.is_valid = function() {
return !isNaN(this._value);
};
Amount.prototype.is_valid_full = function() {
return this.is_valid() && this._currency.is_valid() && this._issuer.is_valid();
};
Amount.prototype.issuer = function() {
return this._issuer;
};
Amount.prototype.to_number = function(allow_nan) {
var s = this.to_text(allow_nan);
return ('string' === typeof s) ? Number(s) : s;
}
// Convert only value to JSON wire format.
Amount.prototype.to_text = function(allow_nan) {
if (isNaN(this._value)) {
// Never should happen.
return allow_nan ? NaN : "0";
}
else if (this._is_native) {
if (this._value.compareTo(consts.bi_xns_max) > 0 || this._value.compareTo(consts.bi_xns_min) < 0)
{
// Never should happen.
return allow_nan ? NaN : "0";
}
else
{
return this._value.toString();
}
}
else if (this._value.equals(BigInteger.ZERO))
{
return "0";
}
else if (this._offset < -25 || this._offset > -5)
{
// Use e notation.
// XXX Clamp output.
return (this._is_negative ? "-" : "") + this._value.toString() + "e" + this._offset;
}
else
{
var val = "000000000000000000000000000" + this._value.toString() + "00000000000000000000000";
var pre = val.substring(0, this._offset + 43);
var post = val.substring(this._offset + 43);
var s_pre = pre.match(/[1-9].*$/); // Everything but leading zeros.
var s_post = post.match(/[1-9]0*$/); // Last non-zero plus trailing zeros.
return (this._is_negative ? "-" : "")
+ (s_pre ? s_pre[0] : "0")
+ (s_post ? "." + post.substring(0, 1+post.length-s_post[0].length) : "");
}
};
/**
* Format only value in a human-readable format.
*
* @example
* var pretty = amount.to_human({precision: 2});
*
* @param opts Options for formatter.
* @param opts.precision {Number} Max. number of digits after decimal point.
* @param opts.group_sep {Boolean|String} Whether to show a separator every n
* digits, if a string, that value will be used as the separator. Default: ","
* @param opts.group_width {Number} How many numbers will be grouped together,
* default: 3.
* @param opts.signed {Boolean|String} Whether negative numbers will have a
* prefix. If String, that string will be used as the prefix. Default: "-"
*/
Amount.prototype.to_human = function (opts)
{
opts = opts || {};
// Default options
if ("undefined" === typeof opts.signed) opts.signed = true;
if ("undefined" === typeof opts.group_sep) opts.group_sep = true;
opts.group_width = opts.group_width || 3;
var order = this._is_native ? consts.xns_precision : -this._offset;
var denominator = consts.bi_10.clone().pow(order);
var int_part = this._value.divide(denominator).toString(10);
var fraction_part = this._value.mod(denominator).toString(10);
// Add leading zeros to fraction
while (fraction_part.length < order) {
fraction_part = "0" + fraction_part;
}
int_part = int_part.replace(/^0*/, '');
fraction_part = fraction_part.replace(/0*$/, '');
if ("number" === typeof opts.precision) {
fraction_part = fraction_part.slice(0, opts.precision);
}
if (opts.group_sep) {
if ("string" !== typeof opts.group_sep) {
opts.group_sep = ',';
}
int_part = utils.chunkString(int_part, opts.group_width, true).join(opts.group_sep);
}
var formatted = '';
if (opts.signed && this._is_negative) {
if ("string" !== typeof opts.signed) {
opts.signed = '-';
}
formatted += opts.signed;
}
formatted += int_part.length ? int_part : '0';
formatted += fraction_part.length ? '.'+fraction_part : '';
return formatted;
};
Amount.prototype.canonicalize = function() {
if (isNaN(this._value) || !this._currency) {
// nothing
}
else if (this._value.equals(BigInteger.ZERO)) {
this._offset = -100;
this._is_negative = false;
}
else
{
while (this._value.compareTo(consts.bi_man_min_value) < 0) {
this._value = this._value.multiply(consts.bi_10);
this._offset -= 1;
}
while (this._value.compareTo(consts.bi_man_max_value) > 0) {
this._value = this._value.divide(consts.bi_10);
this._offset += 1;
}
}
return this;
};
Amount.prototype.is_native = function () {
return this._is_native;
};
// Return a new value.
Amount.prototype.negate = function () {
return this.clone('NEGATE');
};
Amount.prototype.to_json = function() {
if (this._is_native) {
return this.to_text();
}
else
{
var amount_json = {
'value' : this.to_text(),
'currency' : this._currency.to_json()
};
if (this._issuer.is_valid()) {
amount_json.issuer = this._issuer.to_json();
}
return amount_json;
}
};
Amount.prototype.to_text_full = function() {
return isNaN(this._value)
? NaN
: this._is_native
? this.to_text() + "/XRP"
: this.to_text() + "/" + this._currency.to_json() + "/" + this._issuer.to_json();
};
/**
* Tries to correctly interpret an amount as entered by a user.
*
* Examples:
*
* XRP 250 => 250000000/XRP
* 25.2 XRP => 25200000/XRP
* USD 100.40 => 100.4/USD/?
* 100 => 100000000/XRP
*/
Amount.prototype.parse_human = function(j) {
// Cast to string
j = ""+j;
// Parse
var m = j.match(/^\s*([a-z]{3})?\s*(-)?(\d+)(?:\.(\d*))?\s*([a-z]{3})?\s*$/i);
if (m) {
var currency = m[1] || m[5] || "XRP",
integer = m[3] || "0",
fraction = m[4] || "",
precision = null;
currency = currency.toUpperCase();
this._value = new BigInteger(integer);
this.set_currency(currency);
// XRP have exactly six digits of precision
if (currency === 'XRP') {
fraction = fraction.slice(0, 6);
while (fraction.length < 6) {
fraction += "0";
}
this._is_native = true;
this._value = this._value.multiply(consts.bi_xns_unit).add(new BigInteger(fraction));
}
// Other currencies have arbitrary precision
else {
while (fraction[fraction.length - 1] === "0") {
fraction = fraction.slice(0, fraction.length - 1);
}
precision = fraction.length;
this._is_native = false;
var multiplier = consts.bi_10.clone().pow(precision);
this._value = this._value.multiply(multiplier).add(new BigInteger(fraction));
this._offset = -precision;
this.canonicalize();
}
this._is_negative = !!m[2];
} else {
this._value = NaN;
}
return this;
};
// Parse a XRP value from untrusted input.
// - integer = raw units
// - float = with precision 6
// XXX Improvements: disallow leading zeros.
Amount.prototype.parse_native = function(j) {
var m;
if ('string' === typeof j)
m = j.match(/^(-?)(\d+)(\.\d{0,6})?$/);
if (m) {
if (undefined === m[3]) {
// Integer notation
this._value = new BigInteger(m[2]);
}
else {
// Float notation : values multiplied by 1,000,000.
var int_part = (new BigInteger(m[2])).multiply(consts.bi_xns_unit);
var fraction_part = (new BigInteger(m[3])).multiply(new BigInteger(String(Math.pow(10, 1+consts.xns_precision-m[3].length))));
this._value = int_part.add(fraction_part);
}
if (m[1])
this._value = this._value.negate();
this._is_native = true;
this._offset = undefined;
this._is_negative = undefined;
if (this._value.compareTo(consts.bi_xns_max) > 0 || this._value.compareTo(consts.bi_xns_min) < 0)
{
this._value = NaN;
}
}
else {
this._value = NaN;
}
return this;
};
// Parse a non-native value for the json wire format.
// Requires _currency to be set!
Amount.prototype.parse_value = function(j) {
this._is_native = false;
if ('number' === typeof j) {
this._is_negative = j < 0;
if (this._is_negative) j = -j;
this._value = new BigInteger(j);
this._offset = 0;
this.canonicalize();
}
else if ('string' === typeof j) {
var i = j.match(/^(-?)(\d+)$/);
var d = !i && j.match(/^(-?)(\d+)\.(\d*)$/);
var e = !e && j.match(/^(-?)(\d+)e(\d+)$/);
if (e) {
// e notation
this._value = new BigInteger(e[2]);
this._offset = parseInt(e[3]);
this._is_negative = !!e[1];
this.canonicalize();
}
else if (d) {
// float notation
var integer = new BigInteger(d[2]);
var fraction = new BigInteger(d[3]);
var precision = d[3].length;
this._value = integer.multiply(consts.bi_10.clone().pow(precision)).add(fraction);
this._offset = -precision;
this._is_negative = !!d[1];
this.canonicalize();
}
else if (i) {
// integer notation
this._value = new BigInteger(i[2]);
this._offset = 0;
this._is_negative = !!i[1];
this.canonicalize();
}
else {
this._value = NaN;
}
}
else if (j.constructor == BigInteger) {
this._value = j.clone();
}
else {
this._value = NaN;
}
return this;
};
// <-> j
Amount.prototype.parse_json = function(j) {
if ('string' === typeof j) {
// .../.../... notation is not a wire format. But allowed for easier testing.
var m = j.match(/^(.+)\/(...)\/(.+)$/);
if (m) {
this._currency = Currency.from_json(m[2]);
this._issuer = UInt160.from_json(m[3]);
this.parse_value(m[1]);
}
else {
this.parse_native(j);
this._currency = new Currency();
this._issuer = new UInt160();
}
}
else if ('object' === typeof j && j.constructor == Amount) {
j.copyTo(this);
}
else if ('object' === typeof j && 'value' in j) {
// Parse the passed value to sanitize and copy it.
this._currency.parse_json(j.currency); // Never XRP.
if ("string" === typeof j.issuer) this._issuer.parse_json(j.issuer);
this.parse_value(j.value);
}
else {
this._value = NaN;
}
return this;
};
Amount.prototype.parse_issuer = function (issuer) {
this._issuer.parse_json(issuer);
return this;
};
Amount.prototype.is_negative = function () {
return this._is_negative;
};
// Check BigInteger NaN
// Checks currency, does not check issuer.
Amount.prototype.equals = function (d) {
return 'string' === typeof (d)
? this.equals(Amount.from_json(d))
: this === d
|| (d.constructor === Amount
&& this._is_native === d._is_native
&& (this._is_native
? this._value.equals(d._value)
: this._currency.equals(d._currency)
? this._is_negative === d._is_negative
? this._value.equals(d._value)
: this._value.equals(BigInteger.ZERO) && d._value.equals(BigInteger.ZERO)
: false));
};
Amount.prototype.not_equals_why = function (d) {
return 'string' === typeof (d)
? this.not_equals_why(Amount.from_json(d))
: this === d
? false
: d.constructor === Amount
? this._is_native === d._is_native
? this._is_native
? this._value.equals(d._value)
? false
: "XRP value differs."
: this._currency.equals(d._currency)
? this._is_negative === d._is_negative
? this._value.equals(d._value)
? false
: this._value.equals(BigInteger.ZERO) && d._value.equals(BigInteger.ZERO)
? false
: "Non-XRP value differs."
: "Non-XRP sign differs."
: "Non-XRP currency differs (" + JSON.stringify(this._currency) + "/" + JSON.stringify(d._currency) + ")"
: "Native mismatch"
: "Wrong constructor."
};
exports.Amount = Amount;
exports.Currency = Currency;
exports.UInt160 = UInt160;
exports.config = {};
// vim:sw=2:sts=2:ts=8:et
| src/js/amount.js | // Represent Ripple amounts and currencies.
// - Numbers in hex are big-endian.
var sjcl = require('./sjcl/core.js');
var bn = require('./sjcl/core.js').bn;
var utils = require('./utils.js');
var jsbn = require('./jsbn.js');
var BigInteger = jsbn.BigInteger;
var nbi = jsbn.nbi;
var alphabets = {
'ripple' : "rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz",
'bitcoin' : "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
};
var consts = exports.consts = {
'address_xns' : "rrrrrrrrrrrrrrrrrrrrrhoLvTp",
'address_one' : "rrrrrrrrrrrrrrrrrrrrBZbvji",
'currency_xns' : 0,
'currency_one' : 1,
'uint160_xns' : utils.hexToString("0000000000000000000000000000000000000000"),
'uint160_one' : utils.hexToString("0000000000000000000000000000000000000001"),
'hex_xns' : "0000000000000000000000000000000000000000",
'hex_one' : "0000000000000000000000000000000000000001",
'xns_precision' : 6,
// BigInteger values prefixed with bi_.
'bi_10' : new BigInteger('10'),
'bi_man_max_value' : new BigInteger('9999999999999999'),
'bi_man_min_value' : new BigInteger('1000000000000000'),
'bi_xns_max' : new BigInteger("9000000000000000000"), // Json wire limit.
'bi_xns_min' : new BigInteger("-9000000000000000000"), // Json wire limit.
'bi_xns_unit' : new BigInteger('1000000'),
};
// --> input: big-endian array of bytes.
// <-- string at least as long as input.
var encode_base = function (input, alphabet) {
var alphabet = alphabets[alphabet || 'ripple'];
var bi_base = new BigInteger(String(alphabet.length));
var bi_q = nbi();
var bi_r = nbi();
var bi_value = new BigInteger(input);
var buffer = [];
while (bi_value.compareTo(BigInteger.ZERO) > 0)
{
bi_value.divRemTo(bi_base, bi_q, bi_r);
bi_q.copyTo(bi_value);
buffer.push(alphabet[bi_r.intValue()]);
}
var i;
for (i = 0; i != input.length && !input[i]; i += 1) {
buffer.push(alphabet[0]);
}
return buffer.reverse().join("");
};
// --> input: String
// <-- array of bytes or undefined.
var decode_base = function (input, alphabet) {
var alphabet = alphabets[alphabet || 'ripple'];
var bi_base = new BigInteger(String(alphabet.length));
var bi_value = nbi();
var i;
for (i = 0; i != input.length && input[i] === alphabet[0]; i += 1)
;
for (; i != input.length; i += 1) {
var v = alphabet.indexOf(input[i]);
if (v < 0)
return undefined;
var r = nbi();
r.fromInt(v);
bi_value = bi_value.multiply(bi_base).add(r);
}
// toByteArray:
// - Returns leading zeros!
// - Returns signed bytes!
var bytes = bi_value.toByteArray().map(function (b) { return b ? b < 0 ? 256+b : b : 0});
var extra = 0;
while (extra != bytes.length && !bytes[extra])
extra += 1;
if (extra)
bytes = bytes.slice(extra);
var zeros = 0;
while (zeros !== input.length && input[zeros] === alphabet[0])
zeros += 1;
return [].concat(utils.arraySet(zeros, 0), bytes);
};
var sha256 = function (bytes) {
return sjcl.codec.bytes.fromBits(sjcl.hash.sha256.hash(sjcl.codec.bytes.toBits(bytes)));
};
var sha256hash = function (bytes) {
return sha256(sha256(bytes));
};
// --> input: Array
// <-- String
var encode_base_check = function (version, input, alphabet) {
var buffer = [].concat(version, input);
var check = sha256(sha256(buffer)).slice(0, 4);
return encode_base([].concat(buffer, check), alphabet);
}
// --> input : String
// <-- NaN || BigInteger
var decode_base_check = function (version, input, alphabet) {
var buffer = decode_base(input, alphabet);
if (!buffer || buffer[0] !== version || buffer.length < 5)
return NaN;
var computed = sha256hash(buffer.slice(0, -4)).slice(0, 4);
var checksum = buffer.slice(-4);
var i;
for (i = 0; i != 4; i += 1)
if (computed[i] !== checksum[i])
return NaN;
return new BigInteger(buffer.slice(1, -4));
}
var UInt160 = function () {
// Internal form: NaN or BigInteger
this._value = NaN;
};
UInt160.json_rewrite = function (j) {
return UInt160.from_json(j).to_json();
};
// Return a new UInt160 from j.
UInt160.from_json = function (j) {
return 'string' === typeof j
? (new UInt160()).parse_json(j)
: j.clone();
};
UInt160.is_valid = function (j) {
return UInt160.from_json(j).is_valid();
};
UInt160.prototype.clone = function() {
return this.copyTo(new UInt160());
};
// Returns copy.
UInt160.prototype.copyTo = function(d) {
d._value = this._value;
return d;
};
UInt160.prototype.equals = function(d) {
return isNaN(this._value) || isNaN(d._value) ? false : this._value.equals(d._value);
};
// value = NaN on error.
UInt160.prototype.parse_json = function (j) {
// Canonicalize and validate
if (exports.config.accounts && j in exports.config.accounts)
j = exports.config.accounts[j].account;
switch (j) {
case undefined:
case "0":
case consts.address_xns:
case consts.uint160_xns:
case consts.hex_xns:
this._value = nbi();
break;
case "1":
case consts.address_one:
case consts.uint160_one:
case consts.hex_one:
this._value = new BigInteger([1]);
break;
default:
if ('string' !== typeof j) {
this._value = NaN;
}
else if (20 === j.length) {
this._value = new BigInteger(utils.stringToArray(j), 256);
}
else if (40 === j.length) {
// XXX Check char set!
this._value = new BigInteger(j, 16);
}
else if (j[0] === "r") {
this._value = decode_base_check(0, j);
}
else {
this._value = NaN;
}
}
return this;
};
// Convert from internal form.
// XXX Json form should allow 0 and 1, C++ doesn't currently allow it.
UInt160.prototype.to_json = function () {
if (isNaN(this._value))
return NaN;
var bytes = this._value.toByteArray().map(function (b) { return b ? b < 0 ? 256+b : b : 0});
var target = 20;
// XXX Make sure only trim off leading zeros.
var array = bytes.length < target
? bytes.length
? [].concat(utils.arraySet(target - bytes.length, 0), bytes)
: utils.arraySet(target, 0)
: bytes.slice(target - bytes.length);
var output = encode_base_check(0, array);
return output;
};
UInt160.prototype.is_valid = function () {
return !isNaN(this._value);
};
// XXX Internal form should be UInt160.
var Currency = function () {
// Internal form: 0 = XRP. 3 letter-code.
// XXX Internal should be 0 or hex with three letter annotation when valid.
// Json form:
// '', 'XRP', '0': 0
// 3-letter code: ...
// XXX Should support hex, C++ doesn't currently allow it.
this._value = NaN;
}
// Given "USD" return the json.
Currency.json_rewrite = function(j) {
return Currency.from_json(j).to_json();
};
Currency.from_json = function (j) {
return 'string' === typeof j
? (new Currency()).parse_json(j)
: j.clone();
};
Currency.is_valid = function (j) {
return currency.from_json(j).is_valid();
};
Currency.prototype.clone = function() {
return this.copyTo(new Currency());
};
// Returns copy.
Currency.prototype.copyTo = function(d) {
d._value = this._value;
return d;
};
Currency.prototype.equals = function(d) {
return ('string' !== typeof this._value && isNaN(this._value))
|| ('string' !== typeof d._value && isNaN(d._value)) ? false : this._value === d._value;
}
// this._value = NaN on error.
Currency.prototype.parse_json = function(j) {
if ("" === j || "0" === j || "XRP" === j) {
this._value = 0;
}
else if ('string' != typeof j || 3 !== j.length) {
this._value = NaN;
}
else {
this._value = j;
}
return this;
};
Currency.prototype.is_valid = function () {
return !isNaN(this._value);
};
Currency.prototype.to_json = function () {
return this._value ? this._value : "XRP";
};
Currency.prototype.to_human = function() {
return this._value ? this._value : "XRP";
};
var Amount = function () {
// Json format:
// integer : XRP
// { 'value' : ..., 'currency' : ..., 'issuer' : ...}
this._value = new BigInteger(); // NaN for bad value. Always positive for non-XRP.
this._offset = undefined; // For non-XRP.
this._is_native = true; // Default to XRP. Only valid if value is not NaN.
this._is_negative = undefined; // For non-XRP. Undefined for XRP.
this._currency = new Currency();
this._issuer = new UInt160();
};
// Given "100/USD/mtgox" return the a string with mtgox remapped.
Amount.text_full_rewrite = function (j) {
return Amount.from_json(j).to_text_full();
}
// Given "100/USD/mtgox" return the json.
Amount.json_rewrite = function(j) {
return Amount.from_json(j).to_json();
};
Amount.from_json = function(j) {
return (new Amount()).parse_json(j);
};
Amount.from_human = function(j) {
return (new Amount()).parse_human(j);
};
Amount.is_valid = function (j) {
return Amount.from_json(j).is_valid();
};
Amount.is_valid_full = function (j) {
return Amount.from_json(j).is_valid_full();
};
Amount.prototype.clone = function(negate) {
return this.copyTo(new Amount(), negate);
};
// Returns copy.
Amount.prototype.copyTo = function(d, negate) {
if ('object' === typeof this._value)
{
if (this._is_native && negate)
this._value.negate().copyTo(d._value);
else
this._value.copyTo(d._value);
}
else
{
d._value = this._value;
}
d._offset = this._offset;
d._is_native = this._is_native;
d._is_negative = this._is_native
? undefined // Native sign in BigInteger.
: negate
? !this._is_negative // Negating.
: this._is_negative; // Just copying.
this._currency.copyTo(d._currency);
this._issuer.copyTo(d._issuer);
return d;
};
Amount.prototype.currency = function() {
return this._currency;
};
Amount.prototype.set_currency = function(c) {
if ('string' === typeof c) {
this._currency.parse_json(c);
}
else
{
c.copyTo(this._currency);
}
return this;
};
Amount.prototype.set_issuer = function (issuer) {
if (issuer instanceof UInt160) {
issuer.copyTo(this._issuer);
} else {
this._issuer.parse_json(issuer);
}
return this;
};
// Only checks the value. Not the currency and issuer.
Amount.prototype.is_valid = function() {
return !isNaN(this._value);
};
Amount.prototype.is_valid_full = function() {
return this.is_valid() && this._currency.is_valid() && this._issuer.is_valid();
};
Amount.prototype.issuer = function() {
return this._issuer;
};
Amount.prototype.to_number = function(allow_nan) {
var s = this.to_text(allow_nan);
return ('string' === typeof s) ? Number(s) : s;
}
// Convert only value to JSON wire format.
Amount.prototype.to_text = function(allow_nan) {
if (isNaN(this._value)) {
// Never should happen.
return allow_nan ? NaN : "0";
}
else if (this._is_native) {
if (this._value.compareTo(consts.bi_xns_max) > 0 || this._value.compareTo(consts.bi_xns_min) < 0)
{
// Never should happen.
return allow_nan ? NaN : "0";
}
else
{
return this._value.toString();
}
}
else if (this._value.equals(BigInteger.ZERO))
{
return "0";
}
else if (this._offset < -25 || this._offset > -5)
{
// Use e notation.
// XXX Clamp output.
return (this._is_negative ? "-" : "") + this._value.toString() + "e" + this._offset;
}
else
{
var val = "000000000000000000000000000" + this._value.toString() + "00000000000000000000000";
var pre = val.substring(0, this._offset + 43);
var post = val.substring(this._offset + 43);
var s_pre = pre.match(/[1-9].*$/); // Everything but leading zeros.
var s_post = post.match(/[1-9]0*$/); // Last non-zero plus trailing zeros.
return (this._is_negative ? "-" : "")
+ (s_pre ? s_pre[0] : "0")
+ (s_post ? "." + post.substring(0, 1+post.length-s_post[0].length) : "");
}
};
/**
* Format only value in a human-readable format.
*
* @example
* var pretty = amount.to_human({precision: 2});
*
* @param opts Options for formatter.
* @param opts.precision {Number} Max. number of digits after decimal point.
* @param opts.group_sep {Boolean|String} Whether to show a separator every n
* digits, if a string, that value will be used as the separator. Default: ","
* @param opts.group_width {Number} How many numbers will be grouped together,
* default: 3.
* @param opts.signed {Boolean|String} Whether negative numbers will have a
* prefix. If String, that string will be used as the prefix. Default: "-"
*/
Amount.prototype.to_human = function (opts)
{
opts = opts || {};
// Default options
if ("undefined" === typeof opts.signed) opts.signed = true;
if ("undefined" === typeof opts.group_sep) opts.group_sep = true;
opts.group_width = opts.group_width || 3;
var denominator = this._is_native ?
consts.bi_xns_unit :
consts.bi_10.clone().pow(-this._offset);
var int_part = this._value.divide(denominator).toString(10);
var fraction_part = this._value.mod(denominator).toString(10);
int_part = int_part.replace(/^0*/, '');
fraction_part = fraction_part.replace(/0*$/, '');
if ("number" === typeof opts.precision) {
fraction_part = fraction_part.slice(0, opts.precision);
}
if (opts.group_sep) {
if ("string" !== typeof opts.group_sep) {
opts.group_sep = ',';
}
int_part = utils.chunkString(int_part, opts.group_width, true).join(opts.group_sep);
}
var formatted = '';
if (opts.signed && this._is_negative) {
if ("string" !== typeof opts.signed) {
opts.signed = '-';
}
formatted += opts.signed;
}
formatted += int_part.length ? int_part : '0';
formatted += fraction_part.length ? '.'+fraction_part : '';
return formatted;
};
Amount.prototype.canonicalize = function() {
if (isNaN(this._value) || !this._currency) {
// nothing
}
else if (this._value.equals(BigInteger.ZERO)) {
this._offset = -100;
this._is_negative = false;
}
else
{
while (this._value.compareTo(consts.bi_man_min_value) < 0) {
this._value = this._value.multiply(consts.bi_10);
this._offset -= 1;
}
while (this._value.compareTo(consts.bi_man_max_value) > 0) {
this._value = this._value.divide(consts.bi_10);
this._offset += 1;
}
}
return this;
};
Amount.prototype.is_native = function () {
return this._is_native;
};
// Return a new value.
Amount.prototype.negate = function () {
return this.clone('NEGATE');
};
Amount.prototype.to_json = function() {
if (this._is_native) {
return this.to_text();
}
else
{
var amount_json = {
'value' : this.to_text(),
'currency' : this._currency.to_json()
};
if (this._issuer.is_valid()) {
amount_json.issuer = this._issuer.to_json();
}
return amount_json;
}
};
Amount.prototype.to_text_full = function() {
return isNaN(this._value)
? NaN
: this._is_native
? this.to_text() + "/XRP"
: this.to_text() + "/" + this._currency.to_json() + "/" + this._issuer.to_json();
};
/**
* Tries to correctly interpret an amount as entered by a user.
*
* Examples:
*
* XRP 250 => 250000000/XRP
* 25.2 XRP => 25200000/XRP
* USD 100.40 => 100.4/USD/?
* 100 => 100000000/XRP
*/
Amount.prototype.parse_human = function(j) {
// Cast to string
j = ""+j;
// Parse
var m = j.match(/^\s*([a-z]{3})?\s*(-)?(\d+)(?:\.(\d*))?\s*([a-z]{3})?\s*$/i);
if (m) {
var currency = m[1] || m[5] || "XRP",
integer = m[3] || "0",
fraction = m[4] || "",
precision = null;
currency = currency.toUpperCase();
this._value = new BigInteger(integer);
this.set_currency(currency);
// XRP have exactly six digits of precision
if (currency === 'XRP') {
fraction = fraction.slice(0, 6);
while (fraction.length < 6) {
fraction += "0";
}
this._is_native = true;
this._value = this._value.multiply(consts.bi_xns_unit).add(new BigInteger(fraction));
}
// Other currencies have arbitrary precision
else {
while (fraction[fraction.length - 1] === "0") {
fraction = fraction.slice(0, fraction.length - 1);
}
precision = fraction.length;
this._is_native = false;
var multiplier = consts.bi_10.clone().pow(precision);
this._value = this._value.multiply(multiplier).add(new BigInteger(fraction));
this._offset = -precision;
this.canonicalize();
}
this._is_negative = !!m[2];
} else {
this._value = NaN;
}
return this;
};
// Parse a XRP value from untrusted input.
// - integer = raw units
// - float = with precision 6
// XXX Improvements: disallow leading zeros.
Amount.prototype.parse_native = function(j) {
var m;
if ('string' === typeof j)
m = j.match(/^(-?)(\d+)(\.\d{0,6})?$/);
if (m) {
if (undefined === m[3]) {
// Integer notation
this._value = new BigInteger(m[2]);
}
else {
// Float notation : values multiplied by 1,000,000.
var int_part = (new BigInteger(m[2])).multiply(consts.bi_xns_unit);
var fraction_part = (new BigInteger(m[3])).multiply(new BigInteger(String(Math.pow(10, 1+consts.xns_precision-m[3].length))));
this._value = int_part.add(fraction_part);
}
if (m[1])
this._value = this._value.negate();
this._is_native = true;
this._offset = undefined;
this._is_negative = undefined;
if (this._value.compareTo(consts.bi_xns_max) > 0 || this._value.compareTo(consts.bi_xns_min) < 0)
{
this._value = NaN;
}
}
else {
this._value = NaN;
}
return this;
};
// Parse a non-native value for the json wire format.
// Requires _currency to be set!
Amount.prototype.parse_value = function(j) {
this._is_native = false;
if ('number' === typeof j) {
this._is_negative = j < 0;
if (this._is_negative) j = -j;
this._value = new BigInteger(j);
this._offset = 0;
this.canonicalize();
}
else if ('string' === typeof j) {
var i = j.match(/^(-?)(\d+)$/);
var d = !i && j.match(/^(-?)(\d+)\.(\d*)$/);
var e = !e && j.match(/^(-?)(\d+)e(\d+)$/);
if (e) {
// e notation
this._value = new BigInteger(e[2]);
this._offset = parseInt(e[3]);
this._is_negative = !!e[1];
this.canonicalize();
}
else if (d) {
// float notation
var integer = new BigInteger(d[2]);
var fraction = new BigInteger(d[3]);
var precision = d[3].length;
this._value = integer.multiply(consts.bi_10.clone().pow(precision)).add(fraction);
this._offset = -precision;
this._is_negative = !!d[1];
this.canonicalize();
}
else if (i) {
// integer notation
this._value = new BigInteger(i[2]);
this._offset = 0;
this._is_negative = !!i[1];
this.canonicalize();
}
else {
this._value = NaN;
}
}
else if (j.constructor == BigInteger) {
this._value = j.clone();
}
else {
this._value = NaN;
}
return this;
};
// <-> j
Amount.prototype.parse_json = function(j) {
if ('string' === typeof j) {
// .../.../... notation is not a wire format. But allowed for easier testing.
var m = j.match(/^(.+)\/(...)\/(.+)$/);
if (m) {
this._currency = Currency.from_json(m[2]);
this._issuer = UInt160.from_json(m[3]);
this.parse_value(m[1]);
}
else {
this.parse_native(j);
this._currency = new Currency();
this._issuer = new UInt160();
}
}
else if ('object' === typeof j && j.constructor == Amount) {
j.copyTo(this);
}
else if ('object' === typeof j && 'value' in j) {
// Parse the passed value to sanitize and copy it.
this._currency.parse_json(j.currency); // Never XRP.
if ("string" === typeof j.issuer) this._issuer.parse_json(j.issuer);
this.parse_value(j.value);
}
else {
this._value = NaN;
}
return this;
};
Amount.prototype.parse_issuer = function (issuer) {
this._issuer.parse_json(issuer);
return this;
};
Amount.prototype.is_negative = function () {
return this._is_negative;
};
// Check BigInteger NaN
// Checks currency, does not check issuer.
Amount.prototype.equals = function (d) {
return 'string' === typeof (d)
? this.equals(Amount.from_json(d))
: this === d
|| (d.constructor === Amount
&& this._is_native === d._is_native
&& (this._is_native
? this._value.equals(d._value)
: this._currency.equals(d._currency)
? this._is_negative === d._is_negative
? this._value.equals(d._value)
: this._value.equals(BigInteger.ZERO) && d._value.equals(BigInteger.ZERO)
: false));
};
Amount.prototype.not_equals_why = function (d) {
return 'string' === typeof (d)
? this.not_equals_why(Amount.from_json(d))
: this === d
? false
: d.constructor === Amount
? this._is_native === d._is_native
? this._is_native
? this._value.equals(d._value)
? false
: "XRP value differs."
: this._currency.equals(d._currency)
? this._is_negative === d._is_negative
? this._value.equals(d._value)
? false
: this._value.equals(BigInteger.ZERO) && d._value.equals(BigInteger.ZERO)
? false
: "Non-XRP value differs."
: "Non-XRP sign differs."
: "Non-XRP currency differs (" + JSON.stringify(this._currency) + "/" + JSON.stringify(d._currency) + ")"
: "Native mismatch"
: "Wrong constructor."
};
exports.Amount = Amount;
exports.Currency = Currency;
exports.UInt160 = UInt160;
exports.config = {};
// vim:sw=2:sts=2:ts=8:et
| Fix fractional part in to_human().
| src/js/amount.js | Fix fractional part in to_human(). | <ide><path>rc/js/amount.js
<ide> if ("undefined" === typeof opts.group_sep) opts.group_sep = true;
<ide> opts.group_width = opts.group_width || 3;
<ide>
<del> var denominator = this._is_native ?
<del> consts.bi_xns_unit :
<del> consts.bi_10.clone().pow(-this._offset);
<add> var order = this._is_native ? consts.xns_precision : -this._offset;
<add> var denominator = consts.bi_10.clone().pow(order);
<ide> var int_part = this._value.divide(denominator).toString(10);
<ide> var fraction_part = this._value.mod(denominator).toString(10);
<add>
<add> // Add leading zeros to fraction
<add> while (fraction_part.length < order) {
<add> fraction_part = "0" + fraction_part;
<add> }
<ide>
<ide> int_part = int_part.replace(/^0*/, '');
<ide> fraction_part = fraction_part.replace(/0*$/, ''); |
|
Java | apache-2.0 | bb4c491be49d13280ff3a4d9d1e31f43dad6693f | 0 | lepdou/apollo,ctripcorp/apollo,lepdou/apollo,yiming187/apollo,bulletqi/netposa-config,anycrane/apollo,nobodyiam/apollo,ctripcorp/apollo,bulletqi/netposa-config,ctripcorp/apollo,timothynode/apollo,lepdou/apollo,timothynode/apollo,ctripcorp/apollo,nobodyiam/apollo,yiming187/apollo,nobodyiam/apollo,yiming187/apollo,bulletqi/netposa-config,anycrane/apollo,anycrane/apollo,nobodyiam/apollo,timothynode/apollo,timothynode/apollo,anycrane/apollo,bulletqi/netposa-config,yiming187/apollo,lepdou/apollo | package com.ctrip.framework.apollo.portal.controller;
import com.ctrip.framework.apollo.common.entity.AppNamespace;
import com.ctrip.framework.apollo.core.dto.NamespaceDTO;
import com.ctrip.framework.apollo.core.enums.Env;
import com.ctrip.framework.apollo.core.utils.StringUtils;
import com.ctrip.framework.apollo.portal.auth.UserInfoHolder;
import com.ctrip.framework.apollo.portal.entity.form.NamespaceCreationModel;
import com.ctrip.framework.apollo.portal.entity.vo.NamespaceVO;
import com.ctrip.framework.apollo.portal.listener.AppNamespaceCreationEvent;
import com.ctrip.framework.apollo.portal.service.NamespaceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import static com.ctrip.framework.apollo.portal.util.RequestPrecondition.checkArgument;
import static com.ctrip.framework.apollo.portal.util.RequestPrecondition.checkModel;
@RestController
public class NamespaceController {
Logger logger = LoggerFactory.getLogger(NamespaceController.class);
@Autowired
private ApplicationEventPublisher publisher;
@Autowired
private UserInfoHolder userInfoHolder;
@Autowired
private NamespaceService namespaceService;
@RequestMapping("/appnamespaces/public")
public List<AppNamespace> findPublicAppNamespaces() {
return namespaceService.findPublicAppNamespaces();
}
@PreAuthorize(value = "@permissionValidator.hasCreateNamespacePermission(#appId)")
@RequestMapping(value = "/apps/{appId}/namespaces", method = RequestMethod.POST)
public ResponseEntity<Void> createNamespace(@PathVariable String appId, @RequestBody List<NamespaceCreationModel> models) {
checkModel(!CollectionUtils.isEmpty(models));
for (NamespaceCreationModel model : models) {
NamespaceDTO namespace = model.getNamespace();
checkArgument(model.getEnv(), namespace.getAppId(), namespace.getClusterName(), namespace.getNamespaceName());
try {
// TODO: 16/6/17 某些环境创建失败,统一处理这种场景
namespaceService.createNamespace(Env.valueOf(model.getEnv()), namespace);
} catch (Exception e) {
logger.error("create namespace error.", e);
}
}
return ResponseEntity.ok().build();
}
@RequestMapping(value = "/apps/{appId}/appnamespaces", method = RequestMethod.POST)
public void createAppNamespace(@PathVariable String appId, @RequestBody AppNamespace appNamespace) {
checkArgument(appNamespace.getAppId(), appNamespace.getName());
String operator = userInfoHolder.getUser().getUserId();
if (StringUtils.isEmpty(appNamespace.getDataChangeCreatedBy())) {
appNamespace.setDataChangeCreatedBy(operator);
}
appNamespace.setDataChangeLastModifiedBy(operator);
AppNamespace createdAppNamespace = namespaceService.createAppNamespaceInLocal(appNamespace);
publisher.publishEvent(new AppNamespaceCreationEvent(createdAppNamespace));
}
@RequestMapping("/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces")
public List<NamespaceVO> findNamespaces(@PathVariable String appId, @PathVariable String env,
@PathVariable String clusterName) {
return namespaceService.findNampspaces(appId, Env.valueOf(env), clusterName);
}
}
| apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/controller/NamespaceController.java | package com.ctrip.framework.apollo.portal.controller;
import com.ctrip.framework.apollo.common.entity.AppNamespace;
import com.ctrip.framework.apollo.core.dto.NamespaceDTO;
import com.ctrip.framework.apollo.core.enums.Env;
import com.ctrip.framework.apollo.core.utils.StringUtils;
import com.ctrip.framework.apollo.portal.auth.UserInfoHolder;
import com.ctrip.framework.apollo.portal.entity.form.NamespaceCreationModel;
import com.ctrip.framework.apollo.portal.entity.vo.NamespaceVO;
import com.ctrip.framework.apollo.portal.listener.AppNamespaceCreationEvent;
import com.ctrip.framework.apollo.portal.service.NamespaceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import static com.ctrip.framework.apollo.portal.util.RequestPrecondition.checkArgument;
import static com.ctrip.framework.apollo.portal.util.RequestPrecondition.checkModel;
@RestController
public class NamespaceController {
Logger logger = LoggerFactory.getLogger(NamespaceController.class);
@Autowired
private ApplicationEventPublisher publisher;
@Autowired
private UserInfoHolder userInfoHolder;
@Autowired
private NamespaceService namespaceService;
@RequestMapping("/appnamespaces/public")
public List<AppNamespace> findPublicAppNamespaces() {
return namespaceService.findPublicAppNamespaces();
}
@PreAuthorize(value = "@permissionValidator.hasCreateNamespacePermission(#appId)")
@RequestMapping(value = "/apps/{appId}/namespaces", method = RequestMethod.POST)
public ResponseEntity<Void> createNamespace(@PathVariable String appId, @RequestBody List<NamespaceCreationModel> models) {
checkModel(!CollectionUtils.isEmpty(models));
for (NamespaceCreationModel model : models) {
NamespaceDTO namespace = model.getNamespace();
checkArgument(model.getEnv(), namespace.getAppId(), namespace.getClusterName(), namespace.getNamespaceName());
try {
namespaceService.createNamespace(Env.valueOf(model.getEnv()), namespace);
} catch (Exception e) {
logger.error("create namespace error.", e);
}
}
return ResponseEntity.ok().build();
}
@RequestMapping(value = "/apps/{appId}/appnamespaces", method = RequestMethod.POST)
public void createAppNamespace(@PathVariable String appId, @RequestBody AppNamespace appNamespace) {
checkArgument(appNamespace.getAppId(), appNamespace.getName());
String operator = userInfoHolder.getUser().getUserId();
if (StringUtils.isEmpty(appNamespace.getDataChangeCreatedBy())) {
appNamespace.setDataChangeCreatedBy(operator);
}
appNamespace.setDataChangeLastModifiedBy(operator);
AppNamespace createdAppNamespace = namespaceService.createAppNamespaceInLocal(appNamespace);
publisher.publishEvent(new AppNamespaceCreationEvent(createdAppNamespace));
}
@RequestMapping("/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces")
public List<NamespaceVO> findNamespaces(@PathVariable String appId, @PathVariable String env,
@PathVariable String clusterName) {
return namespaceService.findNampspaces(appId, Env.valueOf(env), clusterName);
}
}
| update
| apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/controller/NamespaceController.java | update | <ide><path>pollo-portal/src/main/java/com/ctrip/framework/apollo/portal/controller/NamespaceController.java
<ide> checkArgument(model.getEnv(), namespace.getAppId(), namespace.getClusterName(), namespace.getNamespaceName());
<ide>
<ide> try {
<add> // TODO: 16/6/17 某些环境创建失败,统一处理这种场景
<ide> namespaceService.createNamespace(Env.valueOf(model.getEnv()), namespace);
<ide> } catch (Exception e) {
<ide> logger.error("create namespace error.", e); |
|
JavaScript | apache-2.0 | 14fbb4c6471f142fcd700c13a1661d7a6e173a2d | 0 | jrios6/GreenNav,Greennav/greennav,jrios6/GreenNav,Greennav/greennav,Greennav/greennav | import React, { Component, PropTypes } from 'react';
import ol from 'openlayers';
import AutoComplete from 'material-ui/AutoComplete';
import Slider from 'material-ui/Slider';
import RaisedButton from 'material-ui/RaisedButton';
import FontIcon from 'material-ui/FontIcon';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';
import TextField from 'material-ui/TextField';
import { green700 } from 'material-ui/styles/colors';
import config from '../config';
const styles = {
menu: {
margin: '10px 20px 30px'
},
reachabilitySlider: {
marginBottom: '0px'
},
batteryLevel: {
display: 'flex',
justifyContent: 'space-between'
},
batteryLevelValue: {
fontWeight: 'bold',
color: green700,
fontSize: '14px'
},
autoCompleteWrapper: {
position: 'relative',
display: 'flex'
},
rangeTextField: {
display: 'inherit',
position: 'relative',
marginBottom: '25px'
},
buttonDiv: {
display: 'flex',
},
displayButton: {
marginRight: '18px'
}
};
export default class ReachabilityTab extends Component {
constructor(props) {
super(props);
this.state = {
dataSource: [],
};
window.google.load('maps', '3', {
other_params: `key=${config.GOOGLE_MAP_KEY}&libraries=places`
});
window.google.setOnLoadCallback(this.initialize);
}
getCoordinateFromPlaceId = id => new Promise((resolve) => {
this.state.placesService.getDetails({ placeId: id }, (results, status) => {
if (status === window.google.maps.places.PlacesServiceStatus.OK) {
resolve([results.geometry.location.lng(), results.geometry.location.lat()]);
}
});
})
initialize = () => {
const map = new window.google.maps.Map(document.getElementById('gmap'));
this.setState({
autocompleteService: new window.google.maps.places.AutocompleteService(),
placesService: new window.google.maps.places.PlacesService(map),
});
}
handleToRequest = (chosenRequest) => {
this.getCoordinateFromPlaceId(chosenRequest.value).then((coord) => {
this.props.setRangePolygonDestination(ol.proj.transform(coord, 'EPSG:4326', 'EPSG:3857'));
});
}
handleFromRequest = (chosenRequest) => {
this.getCoordinateFromPlaceId(chosenRequest.value).then((coord) => {
this.props.setRangePolygonOrigin(ol.proj.transform(coord, 'EPSG:4326', 'EPSG:3857'));
});
}
updateFromInput = (value) => {
this.props.updateRangeFromField(value);
if (value.length > 0) {
this.updateAutocomplete(value);
}
};
updateToInput = (value) => {
this.props.updateRangeToField(value);
if (value.length > 0) {
this.updateAutocomplete(value);
}
};
updateAutocomplete = (value) => {
this.state.autocompleteService.getQueryPredictions({ input: value }, (predictions, status) => {
if (status === window.google.maps.places.PlacesServiceStatus.OK) {
const results = [];
predictions.forEach((prediction) => {
if (prediction.description && prediction.place_id) {
results.push({
text: prediction.description,
value: prediction.place_id,
});
}
});
this.setState({ dataSource: results });
}
else {
this.setState({ dataSource: [] });
}
});
};
render() {
return (
<div style={styles.menu}>
<div style={styles.autoCompleteWrapper}>
<AutoComplete
searchText={this.props.rangeFromField}
floatingLabelText="From"
onClick={() => this.props.updateRangeFromSelected(true)}
onNewRequest={this.handleFromRequest}
onUpdateInput={this.updateFromInput}
dataSource={this.state.dataSource}
filter={AutoComplete.noFilter}
fullWidth
/>
</div>
<div style={styles.autoCompleteWrapper}>
<AutoComplete
searchText={this.props.rangeToField}
floatingLabelText="To"
onClick={() => this.props.updateRangeToSelected(true)}
onNewRequest={this.handleToRequest}
onUpdateInput={this.updateToInput}
dataSource={this.state.dataSource}
filter={AutoComplete.noFilter}
fullWidth
/>
</div>
<SelectField
floatingLabelText="Vehicle"
value={this.props.vehicle}
onChange={this.props.vehicleChange}
maxHeight={210}
fullWidth
>
{this.props.getVehicles().map((vehicle, index) => (
<MenuItem key={vehicle} value={index} primaryText={vehicle} />
))}
</SelectField>
<p style={styles.batteryLevel}>
<span>Battery Level</span>
<span
style={styles.batteryLevelValue}
ref={node => (this.batteryLevel = node)}
>
{`${this.props.batteryPecentage}%`}
</span>
</p>
<Slider
onChange={this.props.updateBatterySlider}
value={this.props.batteryLevel}
sliderStyle={styles.reachabilitySlider}
/>
<TextField
onChange={this.props.updateRemainingRange}
style={styles.rangeTextField}
floatingLabelText="Remaining Range"
value={Math.round(this.props.remainingRange * 100) / 100 || ''}
/>
<div
style={styles.buttonDiv}
>
<RaisedButton
label="Display"
onClick={this.props.getRangeVisualisation}
icon={<FontIcon className="material-icons">map</FontIcon>}
style={styles.displayButton}
/>
{this.props.rangePolygonVisible ?
<RaisedButton
label="Hide"
onClick={this.props.hideRangeVisualisation}
icon={<FontIcon className="material-icons">map</FontIcon>}
/> : null}
</div>
</div>
);
}
}
ReachabilityTab.propTypes = {
vehicle: PropTypes.number.isRequired,
batteryLevel: PropTypes.number.isRequired,
batteryPecentage: PropTypes.number.isRequired,
updateBatterySlider: PropTypes.func.isRequired,
rangePolygonVisible: PropTypes.bool.isRequired,
remainingRange: PropTypes.number.isRequired,
updateRemainingRange: PropTypes.func.isRequired,
getVehicles: PropTypes.func.isRequired,
vehicleChange: PropTypes.func.isRequired,
getRangeVisualisation: PropTypes.func.isRequired,
hideRangeVisualisation: PropTypes.func.isRequired,
rangeFromField: PropTypes.string.isRequired,
updateRangeFromField: PropTypes.func.isRequired,
updateRangeFromSelected: PropTypes.func.isRequired,
rangeToField: PropTypes.string.isRequired,
updateRangeToField: PropTypes.func.isRequired,
updateRangeToSelected: PropTypes.func.isRequired,
setRangePolygonOrigin: PropTypes.func.isRequired,
setRangePolygonDestination: PropTypes.func.isRequired,
};
| src/components/ReachabilityTab.js | import React, { Component, PropTypes } from 'react';
import ol from 'openlayers';
import AutoComplete from 'material-ui/AutoComplete';
import Slider from 'material-ui/Slider';
import RaisedButton from 'material-ui/RaisedButton';
import FontIcon from 'material-ui/FontIcon';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';
import TextField from 'material-ui/TextField';
import { green700 } from 'material-ui/styles/colors';
import config from '../config';
const styles = {
menu: {
margin: '10px 20px 30px'
},
reachabilitySlider: {
marginBottom: '0px'
},
batteryLevel: {
display: 'flex',
justifyContent: 'space-between'
},
batteryLevelValue: {
fontWeight: 'bold',
color: green700,
fontSize: '14px'
},
autoCompleteWrapper: {
position: 'relative',
display: 'flex'
},
rangeTextField: {
display: 'inherit',
position: 'relative',
marginBottom: '25px'
},
buttonDiv: {
display: 'flex',
},
displayButton: {
marginRight: '18px'
}
};
export default class ReachabilityTab extends Component {
constructor(props) {
super(props);
this.state = {
dataSource: [],
};
window.google.load('maps', '3', {
other_params: `key=${config.GOOGLE_MAP_KEY}&libraries=places`
});
window.google.setOnLoadCallback(this.initialize);
}
getCoordinateFromPlaceId = id => new Promise((resolve) => {
this.state.placesService.getDetails({ placeId: id }, (results, status) => {
if (status === window.google.maps.places.PlacesServiceStatus.OK) {
resolve([results.geometry.location.lng(), results.geometry.location.lat()]);
}
});
})
initialize = () => {
const map = new window.google.maps.Map(document.getElementById('gmap'));
this.setState({
autocompleteService: new window.google.maps.places.AutocompleteService(),
placesService: new window.google.maps.places.PlacesService(map),
});
}
handleToRequest = (chosenRequest) => {
this.getCoordinateFromPlaceId(chosenRequest.value).then((coord) => {
this.props.setRangePolygonDestination(ol.proj.transform(coord, 'EPSG:4326', 'EPSG:3857'));
});
}
handleFromRequest = (chosenRequest) => {
this.getCoordinateFromPlaceId(chosenRequest.value).then((coord) => {
this.props.setRangePolygonOrigin(ol.proj.transform(coord, 'EPSG:4326', 'EPSG:3857'));
});
}
updateFromInput = (value) => {
this.props.updateRangeFromField(value);
this.updateAutocomplete(value);
};
updateToInput = (value) => {
this.props.updateRangeToField(value);
this.updateAutocomplete(value);
};
updateAutocomplete = (value) => {
this.state.autocompleteService.getQueryPredictions({ input: value }, (predictions, status) => {
if (status === window.google.maps.places.PlacesServiceStatus.OK) {
const results = [];
predictions.forEach((prediction) => {
results.push({
text: prediction.description,
value: prediction.place_id,
});
});
this.setState({ dataSource: results });
}
});
};
render() {
return (
<div style={styles.menu}>
<div style={styles.autoCompleteWrapper}>
<AutoComplete
searchText={this.props.rangeFromField}
floatingLabelText="From"
onClick={() => this.props.updateRangeFromSelected(true)}
onNewRequest={this.handleFromRequest}
onUpdateInput={this.updateFromInput}
dataSource={this.state.dataSource}
filter={AutoComplete.noFilter}
fullWidth
/>
</div>
<div style={styles.autoCompleteWrapper}>
<AutoComplete
searchText={this.props.rangeToField}
floatingLabelText="To"
onClick={() => this.props.updateRangeToSelected(true)}
onNewRequest={this.handleToRequest}
onUpdateInput={this.updateToInput}
dataSource={this.state.dataSource}
filter={AutoComplete.noFilter}
fullWidth
/>
</div>
<SelectField
floatingLabelText="Vehicle"
value={this.props.vehicle}
onChange={this.props.vehicleChange}
maxHeight={210}
fullWidth
>
{this.props.getVehicles().map((vehicle, index) => (
<MenuItem key={vehicle} value={index} primaryText={vehicle} />
))}
</SelectField>
<p style={styles.batteryLevel}>
<span>Battery Level</span>
<span
style={styles.batteryLevelValue}
ref={node => (this.batteryLevel = node)}
>
{`${this.props.batteryPecentage}%`}
</span>
</p>
<Slider
onChange={this.props.updateBatterySlider}
value={this.props.batteryLevel}
sliderStyle={styles.reachabilitySlider}
/>
<TextField
onChange={this.props.updateRemainingRange}
style={styles.rangeTextField}
floatingLabelText="Remaining Range"
value={Math.round(this.props.remainingRange * 100) / 100 || ''}
/>
<div
style={styles.buttonDiv}
>
<RaisedButton
label="Display"
onClick={this.props.getRangeVisualisation}
icon={<FontIcon className="material-icons">map</FontIcon>}
style={styles.displayButton}
/>
{this.props.rangePolygonVisible ?
<RaisedButton
label="Hide"
onClick={this.props.hideRangeVisualisation}
icon={<FontIcon className="material-icons">map</FontIcon>}
/> : null}
</div>
</div>
);
}
}
ReachabilityTab.propTypes = {
vehicle: PropTypes.number.isRequired,
batteryLevel: PropTypes.number.isRequired,
batteryPecentage: PropTypes.number.isRequired,
updateBatterySlider: PropTypes.func.isRequired,
rangePolygonVisible: PropTypes.bool.isRequired,
remainingRange: PropTypes.number.isRequired,
updateRemainingRange: PropTypes.func.isRequired,
getVehicles: PropTypes.func.isRequired,
vehicleChange: PropTypes.func.isRequired,
getRangeVisualisation: PropTypes.func.isRequired,
hideRangeVisualisation: PropTypes.func.isRequired,
rangeFromField: PropTypes.string.isRequired,
updateRangeFromField: PropTypes.func.isRequired,
updateRangeFromSelected: PropTypes.func.isRequired,
rangeToField: PropTypes.string.isRequired,
updateRangeToField: PropTypes.func.isRequired,
updateRangeToSelected: PropTypes.func.isRequired,
setRangePolygonOrigin: PropTypes.func.isRequired,
setRangePolygonDestination: PropTypes.func.isRequired,
};
| Fix AutoComplete: Cannot read property 'type' of undefined
| src/components/ReachabilityTab.js | Fix AutoComplete: Cannot read property 'type' of undefined | <ide><path>rc/components/ReachabilityTab.js
<ide>
<ide> updateFromInput = (value) => {
<ide> this.props.updateRangeFromField(value);
<del> this.updateAutocomplete(value);
<add> if (value.length > 0) {
<add> this.updateAutocomplete(value);
<add> }
<ide> };
<ide>
<ide> updateToInput = (value) => {
<ide> this.props.updateRangeToField(value);
<del> this.updateAutocomplete(value);
<add> if (value.length > 0) {
<add> this.updateAutocomplete(value);
<add> }
<ide> };
<ide>
<ide> updateAutocomplete = (value) => {
<ide> if (status === window.google.maps.places.PlacesServiceStatus.OK) {
<ide> const results = [];
<ide> predictions.forEach((prediction) => {
<del> results.push({
<del> text: prediction.description,
<del> value: prediction.place_id,
<del> });
<add> if (prediction.description && prediction.place_id) {
<add> results.push({
<add> text: prediction.description,
<add> value: prediction.place_id,
<add> });
<add> }
<ide> });
<ide> this.setState({ dataSource: results });
<add> }
<add> else {
<add> this.setState({ dataSource: [] });
<ide> }
<ide> });
<ide> }; |
|
Java | apache-2.0 | 66a5265e4892e959269e915d14f4351f608e84b1 | 0 | apache/commons-bcel,Maccimo/commons-bcel,typetools/commons-bcel,mohanaraosv/commons-bcel,tempbottle/commons-bcel,Maccimo/commons-bcel,Maccimo/commons-bcel,typetools/commons-bcel,apache/commons-bcel,mohanaraosv/commons-bcel,typetools/commons-bcel,apache/commons-bcel,tempbottle/commons-bcel,tempbottle/commons-bcel,mohanaraosv/commons-bcel | /*
* Copyright 2000-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.bcel.generic;
import java.util.HashMap;
import java.util.Map;
import org.apache.bcel.Constants;
import org.apache.bcel.classfile.Constant;
import org.apache.bcel.classfile.ConstantCP;
import org.apache.bcel.classfile.ConstantClass;
import org.apache.bcel.classfile.ConstantDouble;
import org.apache.bcel.classfile.ConstantFieldref;
import org.apache.bcel.classfile.ConstantFloat;
import org.apache.bcel.classfile.ConstantInteger;
import org.apache.bcel.classfile.ConstantInterfaceMethodref;
import org.apache.bcel.classfile.ConstantLong;
import org.apache.bcel.classfile.ConstantMethodref;
import org.apache.bcel.classfile.ConstantNameAndType;
import org.apache.bcel.classfile.ConstantPool;
import org.apache.bcel.classfile.ConstantString;
import org.apache.bcel.classfile.ConstantUtf8;
/**
* This class is used to build up a constant pool. The user adds
* constants via `addXXX' methods, `addString', `addClass',
* etc.. These methods return an index into the constant
* pool. Finally, `getFinalConstantPool()' returns the constant pool
* built up. Intermediate versions of the constant pool can be
* obtained with `getConstantPool()'. A constant pool has capacity for
* Constants.MAX_SHORT entries. Note that the first (0) is used by the
* JVM and that Double and Long constants need two slots.
*
* @version $Id$
* @author <A HREF="mailto:[email protected]">M. Dahm</A>
* @see Constant
*/
public class ConstantPoolGen implements java.io.Serializable {
protected int size = 1024; // Inital size, sufficient in most cases
protected Constant[] constants = new Constant[size];
protected int index = 1; // First entry (0) used by JVM
private static final String METHODREF_DELIM = ":";
private static final String IMETHODREF_DELIM = "#";
private static final String FIELDREF_DELIM = "&";
private static final String NAT_DELIM = "%";
private static class Index implements java.io.Serializable {
int index;
Index(int i) { index = i; }
}
/**
* Initialize with given array of constants.
*
* @param cs array of given constants, new ones will be appended
*/
public ConstantPoolGen(Constant[] cs) {
if(cs.length > size) {
size = cs.length;
constants = new Constant[size];
}
System.arraycopy(cs, 0, constants, 0, cs.length);
if(cs.length > 0)
index = cs.length;
for(int i=1; i < index; i++) {
Constant c = constants[i];
if(c instanceof ConstantString) {
ConstantString s = (ConstantString)c;
ConstantUtf8 u8 = (ConstantUtf8)constants[s.getStringIndex()];
String key = u8.getBytes();
if (!string_table.containsKey(key))
string_table.put(key, new Index(i));
} else if(c instanceof ConstantClass) {
ConstantClass s = (ConstantClass)c;
ConstantUtf8 u8 = (ConstantUtf8)constants[s.getNameIndex()];
String key = u8.getBytes();
if (!class_table.containsKey(key))
class_table.put(key, new Index(i));
} else if(c instanceof ConstantNameAndType) {
ConstantNameAndType n = (ConstantNameAndType)c;
ConstantUtf8 u8 = (ConstantUtf8)constants[n.getNameIndex()];
ConstantUtf8 u8_2 = (ConstantUtf8)constants[n.getSignatureIndex()];
String key = u8.getBytes() + NAT_DELIM + u8_2.getBytes();
if (!n_a_t_table.containsKey(key))
n_a_t_table.put(key, new Index(i));
} else if(c instanceof ConstantUtf8) {
ConstantUtf8 u = (ConstantUtf8)c;
String key = u.getBytes();
if (!utf8_table.containsKey(key))
utf8_table.put(key, new Index(i));
} else if(c instanceof ConstantCP) {
ConstantCP m = (ConstantCP)c;
ConstantClass clazz = (ConstantClass)constants[m.getClassIndex()];
ConstantNameAndType n = (ConstantNameAndType)constants[m.getNameAndTypeIndex()];
ConstantUtf8 u8 = (ConstantUtf8)constants[clazz.getNameIndex()];
String class_name = u8.getBytes().replace('/', '.');
u8 = (ConstantUtf8)constants[n.getNameIndex()];
String method_name = u8.getBytes();
u8 = (ConstantUtf8)constants[n.getSignatureIndex()];
String signature = u8.getBytes();
String delim = METHODREF_DELIM;
if(c instanceof ConstantInterfaceMethodref)
delim = IMETHODREF_DELIM;
else if(c instanceof ConstantFieldref)
delim = FIELDREF_DELIM;
String key = class_name + delim + method_name + delim + signature;
if (!cp_table.containsKey(key))
cp_table.put(key, new Index(i));
}
}
}
/**
* Initialize with given constant pool.
*/
public ConstantPoolGen(ConstantPool cp) {
this(cp.getConstantPool());
}
/**
* Create empty constant pool.
*/
public ConstantPoolGen() {}
/** Resize internal array of constants.
*/
protected void adjustSize() {
if(index + 3 >= size) {
Constant[] cs = constants;
size *= 2;
constants = new Constant[size];
System.arraycopy(cs, 0, constants, 0, index);
}
}
private Map string_table = new HashMap();
/**
* Look for ConstantString in ConstantPool containing String `str'.
*
* @param str String to search for
* @return index on success, -1 otherwise
*/
public int lookupString(String str) {
Index index = (Index)string_table.get(str);
return (index != null)? index.index : -1;
}
/**
* Add a new String constant to the ConstantPool, if it is not already in there.
*
* @param str String to add
* @return index of entry
*/
public int addString(String str) {
int ret;
if((ret = lookupString(str)) != -1)
return ret; // Already in CP
int utf8 = addUtf8(str);
adjustSize();
ConstantString s = new ConstantString(utf8);
ret = index;
constants[index++] = s;
if (!string_table.containsKey(str))
string_table.put(str, new Index(ret));
return ret;
}
private Map class_table = new HashMap();
/**
* Look for ConstantClass in ConstantPool named `str'.
*
* @param str String to search for
* @return index on success, -1 otherwise
*/
public int lookupClass(String str) {
Index index = (Index)class_table.get(str.replace('.', '/'));
return (index != null)? index.index : -1;
}
private int addClass_(String clazz) {
int ret;
if((ret = lookupClass(clazz)) != -1)
return ret; // Already in CP
adjustSize();
ConstantClass c = new ConstantClass(addUtf8(clazz));
ret = index;
constants[index++] = c;
if (!class_table.containsKey(clazz))
class_table.put(clazz, new Index(ret));
return ret;
}
/**
* Add a new Class reference to the ConstantPool, if it is not already in there.
*
* @param str Class to add
* @return index of entry
*/
public int addClass(String str) {
return addClass_(str.replace('.', '/'));
}
/**
* Add a new Class reference to the ConstantPool for a given type.
*
* @param type Class to add
* @return index of entry
*/
public int addClass(ObjectType type) {
return addClass(type.getClassName());
}
/**
* Add a reference to an array class (e.g. String[][]) as needed by MULTIANEWARRAY
* instruction, e.g. to the ConstantPool.
*
* @param type type of array class
* @return index of entry
*/
public int addArrayClass(ArrayType type) {
return addClass_(type.getSignature());
}
/**
* Look for ConstantInteger in ConstantPool.
*
* @param n integer number to look for
* @return index on success, -1 otherwise
*/
public int lookupInteger(int n) {
for(int i=1; i < index; i++) {
if(constants[i] instanceof ConstantInteger) {
ConstantInteger c = (ConstantInteger)constants[i];
if(c.getBytes() == n)
return i;
}
}
return -1;
}
/**
* Add a new Integer constant to the ConstantPool, if it is not already in there.
*
* @param n integer number to add
* @return index of entry
*/
public int addInteger(int n) {
int ret;
if((ret = lookupInteger(n)) != -1)
return ret; // Already in CP
adjustSize();
ret = index;
constants[index++] = new ConstantInteger(n);
return ret;
}
/**
* Look for ConstantFloat in ConstantPool.
*
* @param n Float number to look for
* @return index on success, -1 otherwise
*/
public int lookupFloat(float n) {
int bits = Float.floatToIntBits(n);
for(int i=1; i < index; i++) {
if(constants[i] instanceof ConstantFloat) {
ConstantFloat c = (ConstantFloat)constants[i];
if(Float.floatToIntBits(c.getBytes()) == bits)
return i;
}
}
return -1;
}
/**
* Add a new Float constant to the ConstantPool, if it is not already in there.
*
* @param n Float number to add
* @return index of entry
*/
public int addFloat(float n) {
int ret;
if((ret = lookupFloat(n)) != -1)
return ret; // Already in CP
adjustSize();
ret = index;
constants[index++] = new ConstantFloat(n);
return ret;
}
private Map utf8_table = new HashMap();
/**
* Look for ConstantUtf8 in ConstantPool.
*
* @param n Utf8 string to look for
* @return index on success, -1 otherwise
*/
public int lookupUtf8(String n) {
Index index = (Index)utf8_table.get(n);
return (index != null)? index.index : -1;
}
/**
* Add a new Utf8 constant to the ConstantPool, if it is not already in there.
*
* @param n Utf8 string to add
* @return index of entry
*/
public int addUtf8(String n) {
int ret;
if((ret = lookupUtf8(n)) != -1)
return ret; // Already in CP
adjustSize();
ret = index;
constants[index++] = new ConstantUtf8(n);
if (!utf8_table.containsKey(n))
utf8_table.put(n, new Index(ret));
return ret;
}
/**
* Look for ConstantLong in ConstantPool.
*
* @param n Long number to look for
* @return index on success, -1 otherwise
*/
public int lookupLong(long n) {
for(int i=1; i < index; i++) {
if(constants[i] instanceof ConstantLong) {
ConstantLong c = (ConstantLong)constants[i];
if(c.getBytes() == n)
return i;
}
}
return -1;
}
/**
* Add a new long constant to the ConstantPool, if it is not already in there.
*
* @param n Long number to add
* @return index of entry
*/
public int addLong(long n) {
int ret;
if((ret = lookupLong(n)) != -1)
return ret; // Already in CP
adjustSize();
ret = index;
constants[index] = new ConstantLong(n);
index += 2; // Wastes one entry according to spec
return ret;
}
/**
* Look for ConstantDouble in ConstantPool.
*
* @param n Double number to look for
* @return index on success, -1 otherwise
*/
public int lookupDouble(double n) {
long bits = Double.doubleToLongBits(n);
for(int i=1; i < index; i++) {
if(constants[i] instanceof ConstantDouble) {
ConstantDouble c = (ConstantDouble)constants[i];
if(Double.doubleToLongBits(c.getBytes()) == bits)
return i;
}
}
return -1;
}
/**
* Add a new double constant to the ConstantPool, if it is not already in there.
*
* @param n Double number to add
* @return index of entry
*/
public int addDouble(double n) {
int ret;
if((ret = lookupDouble(n)) != -1)
return ret; // Already in CP
adjustSize();
ret = index;
constants[index] = new ConstantDouble(n);
index += 2; // Wastes one entry according to spec
return ret;
}
private Map n_a_t_table = new HashMap();
/**
* Look for ConstantNameAndType in ConstantPool.
*
* @param name of variable/method
* @param signature of variable/method
* @return index on success, -1 otherwise
*/
public int lookupNameAndType(String name, String signature) {
Index _index = (Index)n_a_t_table.get(name + NAT_DELIM + signature);
return (_index != null)? _index.index : -1;
}
/**
* Add a new NameAndType constant to the ConstantPool if it is not already
* in there.
*
* @param name Name string to add
* @param signature signature string to add
* @return index of entry
*/
public int addNameAndType(String name, String signature) {
int ret;
int name_index, signature_index;
if((ret = lookupNameAndType(name, signature)) != -1)
return ret; // Already in CP
adjustSize();
name_index = addUtf8(name);
signature_index = addUtf8(signature);
ret = index;
constants[index++] = new ConstantNameAndType(name_index, signature_index);
String key = name + NAT_DELIM + signature;
if (!n_a_t_table.containsKey(key))
n_a_t_table.put(key, new Index(ret));
return ret;
}
private Map cp_table = new HashMap();
/**
* Look for ConstantMethodref in ConstantPool.
*
* @param class_name Where to find method
* @param method_name Guess what
* @param signature return and argument types
* @return index on success, -1 otherwise
*/
public int lookupMethodref(String class_name, String method_name, String signature) {
Index index = (Index)cp_table.get(class_name + METHODREF_DELIM + method_name +
METHODREF_DELIM + signature);
return (index != null)? index.index : -1;
}
public int lookupMethodref(MethodGen method) {
return lookupMethodref(method.getClassName(), method.getName(),
method.getSignature());
}
/**
* Add a new Methodref constant to the ConstantPool, if it is not already
* in there.
*
* @param class_name class name string to add
* @param method_name method name string to add
* @param signature method signature string to add
* @return index of entry
*/
public int addMethodref(String class_name, String method_name, String signature) {
int ret, class_index, name_and_type_index;
if((ret = lookupMethodref(class_name, method_name, signature)) != -1)
return ret; // Already in CP
adjustSize();
name_and_type_index = addNameAndType(method_name, signature);
class_index = addClass(class_name);
ret = index;
constants[index++] = new ConstantMethodref(class_index, name_and_type_index);
String key = class_name + METHODREF_DELIM + method_name + METHODREF_DELIM + signature;
if (!cp_table.containsKey(key))
cp_table.put(key, new Index(ret));
return ret;
}
public int addMethodref(MethodGen method) {
return addMethodref(method.getClassName(), method.getName(),
method.getSignature());
}
/**
* Look for ConstantInterfaceMethodref in ConstantPool.
*
* @param class_name Where to find method
* @param method_name Guess what
* @param signature return and argument types
* @return index on success, -1 otherwise
*/
public int lookupInterfaceMethodref(String class_name, String method_name, String signature) {
Index index = (Index)cp_table.get(class_name + IMETHODREF_DELIM + method_name +
IMETHODREF_DELIM + signature);
return (index != null)? index.index : -1;
}
public int lookupInterfaceMethodref(MethodGen method) {
return lookupInterfaceMethodref(method.getClassName(), method.getName(),
method.getSignature());
}
/**
* Add a new InterfaceMethodref constant to the ConstantPool, if it is not already
* in there.
*
* @param class_name class name string to add
* @param method_name method name string to add
* @param signature signature string to add
* @return index of entry
*/
public int addInterfaceMethodref(String class_name, String method_name, String signature) {
int ret, class_index, name_and_type_index;
if((ret = lookupInterfaceMethodref(class_name, method_name, signature)) != -1)
return ret; // Already in CP
adjustSize();
class_index = addClass(class_name);
name_and_type_index = addNameAndType(method_name, signature);
ret = index;
constants[index++] = new ConstantInterfaceMethodref(class_index, name_and_type_index);
String key = class_name + IMETHODREF_DELIM + method_name + IMETHODREF_DELIM + signature;
if (!cp_table.containsKey(key))
cp_table.put(key, new Index(ret));
return ret;
}
public int addInterfaceMethodref(MethodGen method) {
return addInterfaceMethodref(method.getClassName(), method.getName(),
method.getSignature());
}
/**
* Look for ConstantFieldref in ConstantPool.
*
* @param class_name Where to find method
* @param field_name Guess what
* @param signature return and argument types
* @return index on success, -1 otherwise
*/
public int lookupFieldref(String class_name, String field_name, String signature) {
Index index = (Index)cp_table.get(class_name + FIELDREF_DELIM + field_name +
FIELDREF_DELIM + signature);
return (index != null)? index.index : -1;
}
/**
* Add a new Fieldref constant to the ConstantPool, if it is not already
* in there.
*
* @param class_name class name string to add
* @param field_name field name string to add
* @param signature signature string to add
* @return index of entry
*/
public int addFieldref(String class_name, String field_name, String signature) {
int ret;
int class_index, name_and_type_index;
if((ret = lookupFieldref(class_name, field_name, signature)) != -1)
return ret; // Already in CP
adjustSize();
class_index = addClass(class_name);
name_and_type_index = addNameAndType(field_name, signature);
ret = index;
constants[index++] = new ConstantFieldref(class_index, name_and_type_index);
String key = class_name + FIELDREF_DELIM + field_name + FIELDREF_DELIM + signature;
if (!cp_table.containsKey(key))
cp_table.put(key, new Index(ret));
return ret;
}
/**
* @param i index in constant pool
* @return constant pool entry at index i
*/
public Constant getConstant(int i) { return constants[i]; }
/**
* Use with care!
*
* @param i index in constant pool
* @param c new constant pool entry at index i
*/
public void setConstant(int i, Constant c) { constants[i] = c; }
/**
* @return intermediate constant pool
*/
public ConstantPool getConstantPool() {
return new ConstantPool(constants);
}
/**
* @return current size of constant pool
*/
public int getSize() {
return index;
}
/**
* @return constant pool with proper length
*/
public ConstantPool getFinalConstantPool() {
Constant[] cs = new Constant[index];
System.arraycopy(constants, 0, cs, 0, index);
return new ConstantPool(cs);
}
/**
* @return String representation.
*/
public String toString() {
StringBuffer buf = new StringBuffer();
for(int i=1; i < index; i++)
buf.append(i).append(")").append(constants[i]).append("\n");
return buf.toString();
}
/** Import constant from another ConstantPool and return new index.
*/
public int addConstant(Constant c, ConstantPoolGen cp) {
Constant[] constants = cp.getConstantPool().getConstantPool();
switch(c.getTag()) {
case Constants.CONSTANT_String: {
ConstantString s = (ConstantString)c;
ConstantUtf8 u8 = (ConstantUtf8)constants[s.getStringIndex()];
return addString(u8.getBytes());
}
case Constants.CONSTANT_Class: {
ConstantClass s = (ConstantClass)c;
ConstantUtf8 u8 = (ConstantUtf8)constants[s.getNameIndex()];
return addClass(u8.getBytes());
}
case Constants.CONSTANT_NameAndType: {
ConstantNameAndType n = (ConstantNameAndType)c;
ConstantUtf8 u8 = (ConstantUtf8)constants[n.getNameIndex()];
ConstantUtf8 u8_2 = (ConstantUtf8)constants[n.getSignatureIndex()];
return addNameAndType(u8.getBytes(), u8_2.getBytes());
}
case Constants.CONSTANT_Utf8:
return addUtf8(((ConstantUtf8)c).getBytes());
case Constants.CONSTANT_Double:
return addDouble(((ConstantDouble)c).getBytes());
case Constants.CONSTANT_Float:
return addFloat(((ConstantFloat)c).getBytes());
case Constants.CONSTANT_Long:
return addLong(((ConstantLong)c).getBytes());
case Constants.CONSTANT_Integer:
return addInteger(((ConstantInteger)c).getBytes());
case Constants.CONSTANT_InterfaceMethodref: case Constants.CONSTANT_Methodref:
case Constants.CONSTANT_Fieldref: {
ConstantCP m = (ConstantCP)c;
ConstantClass clazz = (ConstantClass)constants[m.getClassIndex()];
ConstantNameAndType n = (ConstantNameAndType)constants[m.getNameAndTypeIndex()];
ConstantUtf8 u8 = (ConstantUtf8)constants[clazz.getNameIndex()];
String class_name = u8.getBytes().replace('/', '.');
u8 = (ConstantUtf8)constants[n.getNameIndex()];
String name = u8.getBytes();
u8 = (ConstantUtf8)constants[n.getSignatureIndex()];
String signature = u8.getBytes();
switch(c.getTag()) {
case Constants.CONSTANT_InterfaceMethodref:
return addInterfaceMethodref(class_name, name, signature);
case Constants.CONSTANT_Methodref:
return addMethodref(class_name, name, signature);
case Constants.CONSTANT_Fieldref:
return addFieldref(class_name, name, signature);
default: // Never reached
throw new RuntimeException("Unknown constant type " + c);
}
}
default: // Never reached
throw new RuntimeException("Unknown constant type " + c);
}
}
}
| src/java/org/apache/bcel/generic/ConstantPoolGen.java | /*
* Copyright 2000-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.bcel.generic;
import java.util.HashMap;
import java.util.Map;
import org.apache.bcel.Constants;
import org.apache.bcel.classfile.Constant;
import org.apache.bcel.classfile.ConstantCP;
import org.apache.bcel.classfile.ConstantClass;
import org.apache.bcel.classfile.ConstantDouble;
import org.apache.bcel.classfile.ConstantFieldref;
import org.apache.bcel.classfile.ConstantFloat;
import org.apache.bcel.classfile.ConstantInteger;
import org.apache.bcel.classfile.ConstantInterfaceMethodref;
import org.apache.bcel.classfile.ConstantLong;
import org.apache.bcel.classfile.ConstantMethodref;
import org.apache.bcel.classfile.ConstantNameAndType;
import org.apache.bcel.classfile.ConstantPool;
import org.apache.bcel.classfile.ConstantString;
import org.apache.bcel.classfile.ConstantUtf8;
/**
* This class is used to build up a constant pool. The user adds
* constants via `addXXX' methods, `addString', `addClass',
* etc.. These methods return an index into the constant
* pool. Finally, `getFinalConstantPool()' returns the constant pool
* built up. Intermediate versions of the constant pool can be
* obtained with `getConstantPool()'. A constant pool has capacity for
* Constants.MAX_SHORT entries. Note that the first (0) is used by the
* JVM and that Double and Long constants need two slots.
*
* @version $Id$
* @author <A HREF="mailto:[email protected]">M. Dahm</A>
* @see Constant
*/
public class ConstantPoolGen implements java.io.Serializable {
protected int size = 1024; // Inital size, sufficient in most cases
protected Constant[] constants = new Constant[size];
protected int index = 1; // First entry (0) used by JVM
private static final String METHODREF_DELIM = ":";
private static final String IMETHODREF_DELIM = "#";
private static final String FIELDREF_DELIM = "&";
private static final String NAT_DELIM = "%";
private static class Index implements java.io.Serializable {
int index;
Index(int i) { index = i; }
}
/**
* Initialize with given array of constants.
*
* @param cs array of given constants, new ones will be appended
*/
public ConstantPoolGen(Constant[] cs) {
if(cs.length > size) {
size = cs.length;
constants = new Constant[size];
}
System.arraycopy(cs, 0, constants, 0, cs.length);
if(cs.length > 0)
index = cs.length;
for(int i=1; i < index; i++) {
Constant c = constants[i];
if(c instanceof ConstantString) {
ConstantString s = (ConstantString)c;
ConstantUtf8 u8 = (ConstantUtf8)constants[s.getStringIndex()];
String key = u8.getBytes();
if (!string_table.containsKey(key))
string_table.put(key, new Index(i));
} else if(c instanceof ConstantClass) {
ConstantClass s = (ConstantClass)c;
ConstantUtf8 u8 = (ConstantUtf8)constants[s.getNameIndex()];
String key = u8.getBytes();
if (!class_table.containsKey(key))
class_table.put(key, new Index(i));
} else if(c instanceof ConstantNameAndType) {
ConstantNameAndType n = (ConstantNameAndType)c;
ConstantUtf8 u8 = (ConstantUtf8)constants[n.getNameIndex()];
ConstantUtf8 u8_2 = (ConstantUtf8)constants[n.getSignatureIndex()];
String key = u8.getBytes() + NAT_DELIM + u8_2.getBytes();
if (!n_a_t_table.containsKey(key))
n_a_t_table.put(key, new Index(i));
} else if(c instanceof ConstantUtf8) {
ConstantUtf8 u = (ConstantUtf8)c;
String key = u.getBytes();
if (!utf8_table.containsKey(key))
utf8_table.put(key, new Index(i));
} else if(c instanceof ConstantCP) {
ConstantCP m = (ConstantCP)c;
ConstantClass clazz = (ConstantClass)constants[m.getClassIndex()];
ConstantNameAndType n = (ConstantNameAndType)constants[m.getNameAndTypeIndex()];
ConstantUtf8 u8 = (ConstantUtf8)constants[clazz.getNameIndex()];
String class_name = u8.getBytes().replace('/', '.');
u8 = (ConstantUtf8)constants[n.getNameIndex()];
String method_name = u8.getBytes();
u8 = (ConstantUtf8)constants[n.getSignatureIndex()];
String signature = u8.getBytes();
String delim = METHODREF_DELIM;
if(c instanceof ConstantInterfaceMethodref)
delim = IMETHODREF_DELIM;
else if(c instanceof ConstantFieldref)
delim = FIELDREF_DELIM;
cp_table.put(class_name + delim + method_name + delim + signature, new Index(i));
}
}
}
/**
* Initialize with given constant pool.
*/
public ConstantPoolGen(ConstantPool cp) {
this(cp.getConstantPool());
}
/**
* Create empty constant pool.
*/
public ConstantPoolGen() {}
/** Resize internal array of constants.
*/
protected void adjustSize() {
if(index + 3 >= size) {
Constant[] cs = constants;
size *= 2;
constants = new Constant[size];
System.arraycopy(cs, 0, constants, 0, index);
}
}
private Map string_table = new HashMap();
/**
* Look for ConstantString in ConstantPool containing String `str'.
*
* @param str String to search for
* @return index on success, -1 otherwise
*/
public int lookupString(String str) {
Index index = (Index)string_table.get(str);
return (index != null)? index.index : -1;
}
/**
* Add a new String constant to the ConstantPool, if it is not already in there.
*
* @param str String to add
* @return index of entry
*/
public int addString(String str) {
int ret;
if((ret = lookupString(str)) != -1)
return ret; // Already in CP
int utf8 = addUtf8(str);
adjustSize();
ConstantString s = new ConstantString(utf8);
ret = index;
constants[index++] = s;
if (!string_table.containsKey(str))
string_table.put(str, new Index(ret));
return ret;
}
private Map class_table = new HashMap();
/**
* Look for ConstantClass in ConstantPool named `str'.
*
* @param str String to search for
* @return index on success, -1 otherwise
*/
public int lookupClass(String str) {
Index index = (Index)class_table.get(str.replace('.', '/'));
return (index != null)? index.index : -1;
}
private int addClass_(String clazz) {
int ret;
if((ret = lookupClass(clazz)) != -1)
return ret; // Already in CP
adjustSize();
ConstantClass c = new ConstantClass(addUtf8(clazz));
ret = index;
constants[index++] = c;
if (!class_table.containsKey(clazz))
class_table.put(clazz, new Index(ret));
return ret;
}
/**
* Add a new Class reference to the ConstantPool, if it is not already in there.
*
* @param str Class to add
* @return index of entry
*/
public int addClass(String str) {
return addClass_(str.replace('.', '/'));
}
/**
* Add a new Class reference to the ConstantPool for a given type.
*
* @param type Class to add
* @return index of entry
*/
public int addClass(ObjectType type) {
return addClass(type.getClassName());
}
/**
* Add a reference to an array class (e.g. String[][]) as needed by MULTIANEWARRAY
* instruction, e.g. to the ConstantPool.
*
* @param type type of array class
* @return index of entry
*/
public int addArrayClass(ArrayType type) {
return addClass_(type.getSignature());
}
/**
* Look for ConstantInteger in ConstantPool.
*
* @param n integer number to look for
* @return index on success, -1 otherwise
*/
public int lookupInteger(int n) {
for(int i=1; i < index; i++) {
if(constants[i] instanceof ConstantInteger) {
ConstantInteger c = (ConstantInteger)constants[i];
if(c.getBytes() == n)
return i;
}
}
return -1;
}
/**
* Add a new Integer constant to the ConstantPool, if it is not already in there.
*
* @param n integer number to add
* @return index of entry
*/
public int addInteger(int n) {
int ret;
if((ret = lookupInteger(n)) != -1)
return ret; // Already in CP
adjustSize();
ret = index;
constants[index++] = new ConstantInteger(n);
return ret;
}
/**
* Look for ConstantFloat in ConstantPool.
*
* @param n Float number to look for
* @return index on success, -1 otherwise
*/
public int lookupFloat(float n) {
int bits = Float.floatToIntBits(n);
for(int i=1; i < index; i++) {
if(constants[i] instanceof ConstantFloat) {
ConstantFloat c = (ConstantFloat)constants[i];
if(Float.floatToIntBits(c.getBytes()) == bits)
return i;
}
}
return -1;
}
/**
* Add a new Float constant to the ConstantPool, if it is not already in there.
*
* @param n Float number to add
* @return index of entry
*/
public int addFloat(float n) {
int ret;
if((ret = lookupFloat(n)) != -1)
return ret; // Already in CP
adjustSize();
ret = index;
constants[index++] = new ConstantFloat(n);
return ret;
}
private Map utf8_table = new HashMap();
/**
* Look for ConstantUtf8 in ConstantPool.
*
* @param n Utf8 string to look for
* @return index on success, -1 otherwise
*/
public int lookupUtf8(String n) {
Index index = (Index)utf8_table.get(n);
return (index != null)? index.index : -1;
}
/**
* Add a new Utf8 constant to the ConstantPool, if it is not already in there.
*
* @param n Utf8 string to add
* @return index of entry
*/
public int addUtf8(String n) {
int ret;
if((ret = lookupUtf8(n)) != -1)
return ret; // Already in CP
adjustSize();
ret = index;
constants[index++] = new ConstantUtf8(n);
if (!utf8_table.containsKey(n))
utf8_table.put(n, new Index(ret));
return ret;
}
/**
* Look for ConstantLong in ConstantPool.
*
* @param n Long number to look for
* @return index on success, -1 otherwise
*/
public int lookupLong(long n) {
for(int i=1; i < index; i++) {
if(constants[i] instanceof ConstantLong) {
ConstantLong c = (ConstantLong)constants[i];
if(c.getBytes() == n)
return i;
}
}
return -1;
}
/**
* Add a new long constant to the ConstantPool, if it is not already in there.
*
* @param n Long number to add
* @return index of entry
*/
public int addLong(long n) {
int ret;
if((ret = lookupLong(n)) != -1)
return ret; // Already in CP
adjustSize();
ret = index;
constants[index] = new ConstantLong(n);
index += 2; // Wastes one entry according to spec
return ret;
}
/**
* Look for ConstantDouble in ConstantPool.
*
* @param n Double number to look for
* @return index on success, -1 otherwise
*/
public int lookupDouble(double n) {
long bits = Double.doubleToLongBits(n);
for(int i=1; i < index; i++) {
if(constants[i] instanceof ConstantDouble) {
ConstantDouble c = (ConstantDouble)constants[i];
if(Double.doubleToLongBits(c.getBytes()) == bits)
return i;
}
}
return -1;
}
/**
* Add a new double constant to the ConstantPool, if it is not already in there.
*
* @param n Double number to add
* @return index of entry
*/
public int addDouble(double n) {
int ret;
if((ret = lookupDouble(n)) != -1)
return ret; // Already in CP
adjustSize();
ret = index;
constants[index] = new ConstantDouble(n);
index += 2; // Wastes one entry according to spec
return ret;
}
private Map n_a_t_table = new HashMap();
/**
* Look for ConstantNameAndType in ConstantPool.
*
* @param name of variable/method
* @param signature of variable/method
* @return index on success, -1 otherwise
*/
public int lookupNameAndType(String name, String signature) {
Index _index = (Index)n_a_t_table.get(name + NAT_DELIM + signature);
return (_index != null)? _index.index : -1;
}
/**
* Add a new NameAndType constant to the ConstantPool if it is not already
* in there.
*
* @param name Name string to add
* @param signature signature string to add
* @return index of entry
*/
public int addNameAndType(String name, String signature) {
int ret;
int name_index, signature_index;
if((ret = lookupNameAndType(name, signature)) != -1)
return ret; // Already in CP
adjustSize();
name_index = addUtf8(name);
signature_index = addUtf8(signature);
ret = index;
constants[index++] = new ConstantNameAndType(name_index, signature_index);
String key = name + NAT_DELIM + signature;
if (!n_a_t_table.containsKey(key))
n_a_t_table.put(key, new Index(ret));
return ret;
}
private Map cp_table = new HashMap();
/**
* Look for ConstantMethodref in ConstantPool.
*
* @param class_name Where to find method
* @param method_name Guess what
* @param signature return and argument types
* @return index on success, -1 otherwise
*/
public int lookupMethodref(String class_name, String method_name, String signature) {
Index index = (Index)cp_table.get(class_name + METHODREF_DELIM + method_name +
METHODREF_DELIM + signature);
return (index != null)? index.index : -1;
}
public int lookupMethodref(MethodGen method) {
return lookupMethodref(method.getClassName(), method.getName(),
method.getSignature());
}
/**
* Add a new Methodref constant to the ConstantPool, if it is not already
* in there.
*
* @param class_name class name string to add
* @param method_name method name string to add
* @param signature method signature string to add
* @return index of entry
*/
public int addMethodref(String class_name, String method_name, String signature) {
int ret, class_index, name_and_type_index;
if((ret = lookupMethodref(class_name, method_name, signature)) != -1)
return ret; // Already in CP
adjustSize();
name_and_type_index = addNameAndType(method_name, signature);
class_index = addClass(class_name);
ret = index;
constants[index++] = new ConstantMethodref(class_index, name_and_type_index);
String key = class_name + METHODREF_DELIM + method_name + METHODREF_DELIM + signature;
if (!cp_table.containsKey(key))
cp_table.put(key, new Index(ret));
return ret;
}
public int addMethodref(MethodGen method) {
return addMethodref(method.getClassName(), method.getName(),
method.getSignature());
}
/**
* Look for ConstantInterfaceMethodref in ConstantPool.
*
* @param class_name Where to find method
* @param method_name Guess what
* @param signature return and argument types
* @return index on success, -1 otherwise
*/
public int lookupInterfaceMethodref(String class_name, String method_name, String signature) {
Index index = (Index)cp_table.get(class_name + IMETHODREF_DELIM + method_name +
IMETHODREF_DELIM + signature);
return (index != null)? index.index : -1;
}
public int lookupInterfaceMethodref(MethodGen method) {
return lookupInterfaceMethodref(method.getClassName(), method.getName(),
method.getSignature());
}
/**
* Add a new InterfaceMethodref constant to the ConstantPool, if it is not already
* in there.
*
* @param class_name class name string to add
* @param method_name method name string to add
* @param signature signature string to add
* @return index of entry
*/
public int addInterfaceMethodref(String class_name, String method_name, String signature) {
int ret, class_index, name_and_type_index;
if((ret = lookupInterfaceMethodref(class_name, method_name, signature)) != -1)
return ret; // Already in CP
adjustSize();
class_index = addClass(class_name);
name_and_type_index = addNameAndType(method_name, signature);
ret = index;
constants[index++] = new ConstantInterfaceMethodref(class_index, name_and_type_index);
String key = class_name + IMETHODREF_DELIM + method_name + IMETHODREF_DELIM + signature;
if (!cp_table.containsKey(key))
cp_table.put(key, new Index(ret));
return ret;
}
public int addInterfaceMethodref(MethodGen method) {
return addInterfaceMethodref(method.getClassName(), method.getName(),
method.getSignature());
}
/**
* Look for ConstantFieldref in ConstantPool.
*
* @param class_name Where to find method
* @param field_name Guess what
* @param signature return and argument types
* @return index on success, -1 otherwise
*/
public int lookupFieldref(String class_name, String field_name, String signature) {
Index index = (Index)cp_table.get(class_name + FIELDREF_DELIM + field_name +
FIELDREF_DELIM + signature);
return (index != null)? index.index : -1;
}
/**
* Add a new Fieldref constant to the ConstantPool, if it is not already
* in there.
*
* @param class_name class name string to add
* @param field_name field name string to add
* @param signature signature string to add
* @return index of entry
*/
public int addFieldref(String class_name, String field_name, String signature) {
int ret;
int class_index, name_and_type_index;
if((ret = lookupFieldref(class_name, field_name, signature)) != -1)
return ret; // Already in CP
adjustSize();
class_index = addClass(class_name);
name_and_type_index = addNameAndType(field_name, signature);
ret = index;
constants[index++] = new ConstantFieldref(class_index, name_and_type_index);
String key = class_name + FIELDREF_DELIM + field_name + FIELDREF_DELIM + signature;
if (!cp_table.containsKey(key))
cp_table.put(key, new Index(ret));
return ret;
}
/**
* @param i index in constant pool
* @return constant pool entry at index i
*/
public Constant getConstant(int i) { return constants[i]; }
/**
* Use with care!
*
* @param i index in constant pool
* @param c new constant pool entry at index i
*/
public void setConstant(int i, Constant c) { constants[i] = c; }
/**
* @return intermediate constant pool
*/
public ConstantPool getConstantPool() {
return new ConstantPool(constants);
}
/**
* @return current size of constant pool
*/
public int getSize() {
return index;
}
/**
* @return constant pool with proper length
*/
public ConstantPool getFinalConstantPool() {
Constant[] cs = new Constant[index];
System.arraycopy(constants, 0, cs, 0, index);
return new ConstantPool(cs);
}
/**
* @return String representation.
*/
public String toString() {
StringBuffer buf = new StringBuffer();
for(int i=1; i < index; i++)
buf.append(i).append(")").append(constants[i]).append("\n");
return buf.toString();
}
/** Import constant from another ConstantPool and return new index.
*/
public int addConstant(Constant c, ConstantPoolGen cp) {
Constant[] constants = cp.getConstantPool().getConstantPool();
switch(c.getTag()) {
case Constants.CONSTANT_String: {
ConstantString s = (ConstantString)c;
ConstantUtf8 u8 = (ConstantUtf8)constants[s.getStringIndex()];
return addString(u8.getBytes());
}
case Constants.CONSTANT_Class: {
ConstantClass s = (ConstantClass)c;
ConstantUtf8 u8 = (ConstantUtf8)constants[s.getNameIndex()];
return addClass(u8.getBytes());
}
case Constants.CONSTANT_NameAndType: {
ConstantNameAndType n = (ConstantNameAndType)c;
ConstantUtf8 u8 = (ConstantUtf8)constants[n.getNameIndex()];
ConstantUtf8 u8_2 = (ConstantUtf8)constants[n.getSignatureIndex()];
return addNameAndType(u8.getBytes(), u8_2.getBytes());
}
case Constants.CONSTANT_Utf8:
return addUtf8(((ConstantUtf8)c).getBytes());
case Constants.CONSTANT_Double:
return addDouble(((ConstantDouble)c).getBytes());
case Constants.CONSTANT_Float:
return addFloat(((ConstantFloat)c).getBytes());
case Constants.CONSTANT_Long:
return addLong(((ConstantLong)c).getBytes());
case Constants.CONSTANT_Integer:
return addInteger(((ConstantInteger)c).getBytes());
case Constants.CONSTANT_InterfaceMethodref: case Constants.CONSTANT_Methodref:
case Constants.CONSTANT_Fieldref: {
ConstantCP m = (ConstantCP)c;
ConstantClass clazz = (ConstantClass)constants[m.getClassIndex()];
ConstantNameAndType n = (ConstantNameAndType)constants[m.getNameAndTypeIndex()];
ConstantUtf8 u8 = (ConstantUtf8)constants[clazz.getNameIndex()];
String class_name = u8.getBytes().replace('/', '.');
u8 = (ConstantUtf8)constants[n.getNameIndex()];
String name = u8.getBytes();
u8 = (ConstantUtf8)constants[n.getSignatureIndex()];
String signature = u8.getBytes();
switch(c.getTag()) {
case Constants.CONSTANT_InterfaceMethodref:
return addInterfaceMethodref(class_name, name, signature);
case Constants.CONSTANT_Methodref:
return addMethodref(class_name, name, signature);
case Constants.CONSTANT_Fieldref:
return addFieldref(class_name, name, signature);
default: // Never reached
throw new RuntimeException("Unknown constant type " + c);
}
}
default: // Never reached
throw new RuntimeException("Unknown constant type " + c);
}
}
}
| forgot one
git-svn-id: 77ab32d24b47fe90dc24bcc15ad4d4ee91dcaedf@384784 13f79535-47bb-0310-9956-ffa450edef68
| src/java/org/apache/bcel/generic/ConstantPoolGen.java | forgot one | <ide><path>rc/java/org/apache/bcel/generic/ConstantPoolGen.java
<ide> else if(c instanceof ConstantFieldref)
<ide> delim = FIELDREF_DELIM;
<ide>
<del> cp_table.put(class_name + delim + method_name + delim + signature, new Index(i));
<add> String key = class_name + delim + method_name + delim + signature;
<add> if (!cp_table.containsKey(key))
<add> cp_table.put(key, new Index(i));
<ide> }
<ide> }
<ide> } |
|
JavaScript | isc | 9bcb223f9644441b259b0e90de31db1ad17ec3ab | 0 | LearnersGuild/icons | /* eslint-disable no-console, no-undef */
process.env.PORT = process.env.PORT || '8080'
import path from 'path'
import Express from 'express'
import serveStatic from 'serve-static'
import configureDevEnvironment from './configure-dev-environment'
import configureSwagger from './configure-swagger'
import generateIconsAndMetadata from './generateIconsAndMetadata'
const serverHost = process.env.APP_HOSTNAME || 'localhost'
const serverPort = parseInt(process.env.PORT, 10)
const baseUrl = `http://${serverHost}:${serverPort}`
const app = new Express()
if (__DEVELOPMENT__) {
configureDevEnvironment(app)
}
// Use this middleware to server up static files
app.use(serveStatic(path.join(__dirname, '../dist')))
app.use(serveStatic(path.join(__dirname, '../public')))
console.info('Generating icons and metadata ...')
generateIconsAndMetadata(baseUrl)
.then((/* response */) => {
console.info('... done generating icons and metadata.')
})
.catch((/* error */) => {
console.error('... ERROR generating icons and metadata.')
})
// Swagger middleware
configureSwagger(app, ()=> {
app.listen(serverPort, (error) => {
if (error) {
console.error(error)
} else {
console.info('�� Listening at http://%s:%d ', serverHost, serverPort)
}
})
})
| server/server.js | /* eslint-disable no-console, no-undef */
process.env.PORT = process.env.PORT || '8080'
import path from 'path'
import Express from 'express'
import serveStatic from 'serve-static'
import configureDevEnvironment from './configure-dev-environment'
import configureSwagger from './configure-swagger'
const serverHost = process.env.APP_HOSTNAME || 'localhost'
const serverPort = parseInt(process.env.PORT, 10)
const app = new Express()
if (__DEVELOPMENT__) {
configureDevEnvironment(app)
}
// Use this middleware to server up static files
app.use(serveStatic(path.join(__dirname, '../dist')))
app.use(serveStatic(path.join(__dirname, '../public')))
// Swagger middleware
configureSwagger(app, ()=> {
app.listen(serverPort, (error) => {
if (error) {
console.error(error)
} else {
console.info('�� Listening at http://%s:%d ', serverHost, serverPort)
}
})
})
| asynchronously generate icons and metadata on startup
| server/server.js | asynchronously generate icons and metadata on startup | <ide><path>erver/server.js
<ide>
<ide> import configureDevEnvironment from './configure-dev-environment'
<ide> import configureSwagger from './configure-swagger'
<add>import generateIconsAndMetadata from './generateIconsAndMetadata'
<ide>
<ide> const serverHost = process.env.APP_HOSTNAME || 'localhost'
<ide> const serverPort = parseInt(process.env.PORT, 10)
<add>const baseUrl = `http://${serverHost}:${serverPort}`
<ide>
<ide> const app = new Express()
<ide>
<ide> app.use(serveStatic(path.join(__dirname, '../dist')))
<ide> app.use(serveStatic(path.join(__dirname, '../public')))
<ide>
<add>console.info('Generating icons and metadata ...')
<add>generateIconsAndMetadata(baseUrl)
<add> .then((/* response */) => {
<add> console.info('... done generating icons and metadata.')
<add> })
<add> .catch((/* error */) => {
<add> console.error('... ERROR generating icons and metadata.')
<add> })
<add>
<ide> // Swagger middleware
<ide> configureSwagger(app, ()=> {
<ide> app.listen(serverPort, (error) => { |
|
Java | apache-2.0 | 73107c0c40f29596c6addfa396c8053698de2efa | 0 | EvilMcJerkface/presto,shixuan-fan/presto,electrum/presto,smartnews/presto,haozhun/presto,losipiuk/presto,arhimondr/presto,Praveen2112/presto,zzhao0/presto,ptkool/presto,nezihyigitbasi/presto,zzhao0/presto,arhimondr/presto,electrum/presto,haozhun/presto,twitter-forks/presto,electrum/presto,zzhao0/presto,dain/presto,youngwookim/presto,sopel39/presto,prestodb/presto,EvilMcJerkface/presto,Yaliang/presto,wyukawa/presto,arhimondr/presto,shixuan-fan/presto,miniway/presto,twitter-forks/presto,stewartpark/presto,twitter-forks/presto,nezihyigitbasi/presto,wyukawa/presto,raghavsethi/presto,sopel39/presto,prestodb/presto,Praveen2112/presto,erichwang/presto,erichwang/presto,mvp/presto,treasure-data/presto,mvp/presto,EvilMcJerkface/presto,electrum/presto,stewartpark/presto,treasure-data/presto,shixuan-fan/presto,martint/presto,twitter-forks/presto,Praveen2112/presto,smartnews/presto,raghavsethi/presto,miniway/presto,treasure-data/presto,facebook/presto,sopel39/presto,erichwang/presto,hgschmie/presto,ebyhr/presto,dain/presto,nezihyigitbasi/presto,prestodb/presto,smartnews/presto,EvilMcJerkface/presto,arhimondr/presto,ptkool/presto,prestodb/presto,electrum/presto,ebyhr/presto,dain/presto,ebyhr/presto,ebyhr/presto,stewartpark/presto,facebook/presto,erichwang/presto,raghavsethi/presto,EvilMcJerkface/presto,11xor6/presto,shixuan-fan/presto,twitter-forks/presto,facebook/presto,11xor6/presto,hgschmie/presto,martint/presto,facebook/presto,ptkool/presto,mvp/presto,prestodb/presto,smartnews/presto,zzhao0/presto,dain/presto,nezihyigitbasi/presto,losipiuk/presto,Praveen2112/presto,stewartpark/presto,losipiuk/presto,martint/presto,11xor6/presto,miniway/presto,haozhun/presto,losipiuk/presto,raghavsethi/presto,facebook/presto,hgschmie/presto,ptkool/presto,prestodb/presto,ebyhr/presto,erichwang/presto,raghavsethi/presto,Yaliang/presto,11xor6/presto,youngwookim/presto,treasure-data/presto,Praveen2112/presto,shixuan-fan/presto,11xor6/presto,sopel39/presto,arhimondr/presto,sopel39/presto,Yaliang/presto,Yaliang/presto,mvp/presto,haozhun/presto,wyukawa/presto,nezihyigitbasi/presto,wyukawa/presto,wyukawa/presto,martint/presto,hgschmie/presto,smartnews/presto,zzhao0/presto,miniway/presto,miniway/presto,youngwookim/presto,youngwookim/presto,ptkool/presto,stewartpark/presto,losipiuk/presto,Yaliang/presto,mvp/presto,hgschmie/presto,treasure-data/presto,dain/presto,youngwookim/presto,treasure-data/presto,haozhun/presto,martint/presto | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator.aggregation;
import com.facebook.presto.metadata.MetadataManager;
import com.facebook.presto.spi.Page;
import com.facebook.presto.spi.block.Block;
import com.facebook.presto.spi.block.BlockBuilder;
import com.facebook.presto.spi.type.Type;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import io.airlift.slice.Slice;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import static com.facebook.presto.spi.type.DoubleType.DOUBLE;
import static io.airlift.testing.Assertions.assertLessThan;
import static org.testng.Assert.assertEquals;
public abstract class AbstractTestApproximateCountDistinct
{
public abstract InternalAggregationFunction getAggregationFunction();
public abstract Type getValueType();
public abstract Object randomValue();
protected static final MetadataManager metadata = MetadataManager.createTestMetadataManager();
@DataProvider(name = "provideStandardErrors")
public Object[][] provideStandardErrors()
{
return new Object[][] {
{0.0230}, // 2k buckets
{0.0115}, // 8k buckets
};
}
@Test(dataProvider = "provideStandardErrors")
public void testNoPositions(double maxStandardError)
{
assertCount(ImmutableList.of(), maxStandardError, 0);
}
@Test(dataProvider = "provideStandardErrors")
public void testSinglePosition(double maxStandardError)
{
assertCount(ImmutableList.of(randomValue()), maxStandardError, 1);
}
@Test(dataProvider = "provideStandardErrors")
public void testAllPositionsNull(double maxStandardError)
{
assertCount(Collections.nCopies(100, null), maxStandardError, 0);
}
@Test(dataProvider = "provideStandardErrors")
public void testMixedNullsAndNonNulls(double maxStandardError)
{
List<Object> baseline = createRandomSample(10000, 15000);
// Randomly insert nulls
// We need to retain the preexisting order to ensure that the HLL can generate the same estimates.
Iterator<Object> iterator = baseline.iterator();
List<Object> mixed = new ArrayList<>();
while (iterator.hasNext()) {
mixed.add(ThreadLocalRandom.current().nextBoolean() ? null : iterator.next());
}
assertCount(mixed, maxStandardError, estimateGroupByCount(baseline, maxStandardError));
}
@Test(dataProvider = "provideStandardErrors")
public void testMultiplePositions(double maxStandardError)
{
DescriptiveStatistics stats = new DescriptiveStatistics();
for (int i = 0; i < 500; ++i) {
int uniques = ThreadLocalRandom.current().nextInt(20000) + 1;
List<Object> values = createRandomSample(uniques, (int) (uniques * 1.5));
long actual = estimateGroupByCount(values, maxStandardError);
double error = (actual - uniques) * 1.0 / uniques;
stats.addValue(error);
}
assertLessThan(stats.getMean(), 1.0e-2);
assertLessThan(stats.getStandardDeviation(), 1.0e-2 + maxStandardError);
}
@Test(dataProvider = "provideStandardErrors")
public void testMultiplePositionsPartial(double maxStandardError)
{
for (int i = 0; i < 100; ++i) {
int uniques = ThreadLocalRandom.current().nextInt(20000) + 1;
List<Object> values = createRandomSample(uniques, (int) (uniques * 1.5));
assertEquals(estimateCountPartial(values, maxStandardError), estimateGroupByCount(values, maxStandardError));
}
}
private void assertCount(List<Object> values, double maxStandardError, long expectedCount)
{
if (!values.isEmpty()) {
assertEquals(estimateGroupByCount(values, maxStandardError), expectedCount);
}
assertEquals(estimateCount(values, maxStandardError), expectedCount);
assertEquals(estimateCountPartial(values, maxStandardError), expectedCount);
}
private long estimateGroupByCount(List<Object> values, double maxStandardError)
{
Object result = AggregationTestUtils.groupedAggregation(getAggregationFunction(), createPage(values, maxStandardError));
return (long) result;
}
private long estimateCount(List<Object> values, double maxStandardError)
{
Object result = AggregationTestUtils.aggregation(getAggregationFunction(), createPage(values, maxStandardError));
return (long) result;
}
private long estimateCountPartial(List<Object> values, double maxStandardError)
{
Object result = AggregationTestUtils.partialAggregation(getAggregationFunction(), createPage(values, maxStandardError));
return (long) result;
}
private Page createPage(List<Object> values, double maxStandardError)
{
if (values.isEmpty()) {
return new Page(0);
}
else {
return new Page(values.size(),
createBlock(getValueType(), values),
createBlock(DOUBLE, ImmutableList.copyOf(Collections.nCopies(values.size(), maxStandardError))));
}
}
/**
* Produce a block with the given values in the last field.
*/
private static Block createBlock(Type type, List<Object> values)
{
BlockBuilder blockBuilder = type.createBlockBuilder(null, values.size());
for (Object value : values) {
Class<?> javaType = type.getJavaType();
if (value == null) {
blockBuilder.appendNull();
}
else if (javaType == boolean.class) {
type.writeBoolean(blockBuilder, (Boolean) value);
}
else if (javaType == long.class) {
type.writeLong(blockBuilder, (Long) value);
}
else if (javaType == double.class) {
type.writeDouble(blockBuilder, (Double) value);
}
else if (javaType == Slice.class) {
Slice slice = (Slice) value;
type.writeSlice(blockBuilder, slice, 0, slice.length());
}
else {
throw new UnsupportedOperationException("not yet implemented: " + javaType);
}
}
return blockBuilder.build();
}
private List<Object> createRandomSample(int uniques, int total)
{
Preconditions.checkArgument(uniques <= total, "uniques (%s) must be <= total (%s)", uniques, total);
List<Object> result = new ArrayList<>(total);
result.addAll(makeRandomSet(uniques));
Random random = ThreadLocalRandom.current();
while (result.size() < total) {
int index = random.nextInt(result.size());
result.add(result.get(index));
}
return result;
}
private Set<Object> makeRandomSet(int count)
{
Set<Object> result = new HashSet<>();
while (result.size() < count) {
result.add(randomValue());
}
return result;
}
}
| presto-main/src/test/java/com/facebook/presto/operator/aggregation/AbstractTestApproximateCountDistinct.java | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator.aggregation;
import com.facebook.presto.metadata.MetadataManager;
import com.facebook.presto.spi.Page;
import com.facebook.presto.spi.block.Block;
import com.facebook.presto.spi.block.BlockBuilder;
import com.facebook.presto.spi.type.Type;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import io.airlift.slice.Slice;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import static com.facebook.presto.spi.type.DoubleType.DOUBLE;
import static io.airlift.testing.Assertions.assertLessThan;
import static org.testng.Assert.assertEquals;
public abstract class AbstractTestApproximateCountDistinct
{
public abstract InternalAggregationFunction getAggregationFunction();
public abstract Type getValueType();
public abstract Object randomValue();
protected static final MetadataManager metadata = MetadataManager.createTestMetadataManager();
@DataProvider(name = "provideStandardErrors")
public Object[][] provideStandardErrors()
{
return new Object[][] {
{0.0230}, // 2k buckets
{0.0115}, // 8k buckets
};
}
@Test(dataProvider = "provideStandardErrors")
public void testNoPositions(double maxStandardError)
{
assertCount(ImmutableList.of(), maxStandardError, 0);
}
@Test(dataProvider = "provideStandardErrors")
public void testSinglePosition(double maxStandardError)
{
assertCount(ImmutableList.of(randomValue()), maxStandardError, 1);
}
@Test(dataProvider = "provideStandardErrors")
public void testAllPositionsNull(double maxStandardError)
{
assertCount(Collections.nCopies(100, null), maxStandardError, 0);
}
@Test(dataProvider = "provideStandardErrors")
public void testMixedNullsAndNonNulls(double maxStandardError)
{
List<Object> baseline = createRandomSample(10000, 15000);
// Randomly insert nulls
// We need to retain the preexisting order to ensure that the HLL can generate the same estimates.
Iterator<Object> iterator = baseline.iterator();
List<Object> mixed = new ArrayList<>();
while (iterator.hasNext()) {
mixed.add(ThreadLocalRandom.current().nextBoolean() ? null : iterator.next());
}
assertCount(mixed, maxStandardError, estimateGroupByCount(baseline, maxStandardError));
}
@Test(dataProvider = "provideStandardErrors")
public void testMultiplePositions(double maxStandardError)
{
DescriptiveStatistics stats = new DescriptiveStatistics();
for (int i = 0; i < 500; ++i) {
int uniques = ThreadLocalRandom.current().nextInt(20000) + 1;
List<Object> values = createRandomSample(uniques, (int) (uniques * 1.5));
long actual = estimateGroupByCount(values, maxStandardError);
double error = (actual - uniques) * 1.0 / uniques;
stats.addValue(error);
}
assertLessThan(stats.getMean(), 1.0e-2);
assertLessThan(Math.abs(stats.getStandardDeviation() - maxStandardError), 1.0e-2);
}
@Test(dataProvider = "provideStandardErrors")
public void testMultiplePositionsPartial(double maxStandardError)
{
for (int i = 0; i < 100; ++i) {
int uniques = ThreadLocalRandom.current().nextInt(20000) + 1;
List<Object> values = createRandomSample(uniques, (int) (uniques * 1.5));
assertEquals(estimateCountPartial(values, maxStandardError), estimateGroupByCount(values, maxStandardError));
}
}
private void assertCount(List<Object> values, double maxStandardError, long expectedCount)
{
if (!values.isEmpty()) {
assertEquals(estimateGroupByCount(values, maxStandardError), expectedCount);
}
assertEquals(estimateCount(values, maxStandardError), expectedCount);
assertEquals(estimateCountPartial(values, maxStandardError), expectedCount);
}
private long estimateGroupByCount(List<Object> values, double maxStandardError)
{
Object result = AggregationTestUtils.groupedAggregation(getAggregationFunction(), createPage(values, maxStandardError));
return (long) result;
}
private long estimateCount(List<Object> values, double maxStandardError)
{
Object result = AggregationTestUtils.aggregation(getAggregationFunction(), createPage(values, maxStandardError));
return (long) result;
}
private long estimateCountPartial(List<Object> values, double maxStandardError)
{
Object result = AggregationTestUtils.partialAggregation(getAggregationFunction(), createPage(values, maxStandardError));
return (long) result;
}
private Page createPage(List<Object> values, double maxStandardError)
{
if (values.isEmpty()) {
return new Page(0);
}
else {
return new Page(values.size(),
createBlock(getValueType(), values),
createBlock(DOUBLE, ImmutableList.copyOf(Collections.nCopies(values.size(), maxStandardError))));
}
}
/**
* Produce a block with the given values in the last field.
*/
private static Block createBlock(Type type, List<Object> values)
{
BlockBuilder blockBuilder = type.createBlockBuilder(null, values.size());
for (Object value : values) {
Class<?> javaType = type.getJavaType();
if (value == null) {
blockBuilder.appendNull();
}
else if (javaType == boolean.class) {
type.writeBoolean(blockBuilder, (Boolean) value);
}
else if (javaType == long.class) {
type.writeLong(blockBuilder, (Long) value);
}
else if (javaType == double.class) {
type.writeDouble(blockBuilder, (Double) value);
}
else if (javaType == Slice.class) {
Slice slice = (Slice) value;
type.writeSlice(blockBuilder, slice, 0, slice.length());
}
else {
throw new UnsupportedOperationException("not yet implemented: " + javaType);
}
}
return blockBuilder.build();
}
private List<Object> createRandomSample(int uniques, int total)
{
Preconditions.checkArgument(uniques <= total, "uniques (%s) must be <= total (%s)", uniques, total);
List<Object> result = new ArrayList<>(total);
result.addAll(makeRandomSet(uniques));
Random random = ThreadLocalRandom.current();
while (result.size() < total) {
int index = random.nextInt(result.size());
result.add(result.get(index));
}
return result;
}
private Set<Object> makeRandomSet(int count)
{
Set<Object> result = new HashSet<>();
while (result.size() < count) {
result.add(randomValue());
}
return result;
}
}
| Minor fix to standard error check in approx_distinct test
For types with small value sets (e.g. TINYINT), standard deviation
can be small or even zero. This will fail the current check since it
asserts the standard deviation is within a range of maxStandardError.
| presto-main/src/test/java/com/facebook/presto/operator/aggregation/AbstractTestApproximateCountDistinct.java | Minor fix to standard error check in approx_distinct test | <ide><path>resto-main/src/test/java/com/facebook/presto/operator/aggregation/AbstractTestApproximateCountDistinct.java
<ide> }
<ide>
<ide> assertLessThan(stats.getMean(), 1.0e-2);
<del> assertLessThan(Math.abs(stats.getStandardDeviation() - maxStandardError), 1.0e-2);
<add> assertLessThan(stats.getStandardDeviation(), 1.0e-2 + maxStandardError);
<ide> }
<ide>
<ide> @Test(dataProvider = "provideStandardErrors") |
|
Java | apache-2.0 | 703c09ae258ded75f44fc331083f24667f85436d | 0 | DeveloperLiberationFront/Pdf-Reviewer,DeveloperLiberationFront/Pdf-Reviewer,DeveloperLiberationFront/Pdf-Reviewer | package src.main.servlet;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.DatatypeConverter;
import com.google.appengine.api.taskqueue.DeferredTask;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.eclipse.egit.github.core.Issue;
import org.eclipse.egit.github.core.Label;
import org.eclipse.egit.github.core.Repository;
import org.eclipse.egit.github.core.RepositoryContents;
import org.eclipse.egit.github.core.User;
import org.eclipse.egit.github.core.client.GitHubClient;
import org.eclipse.egit.github.core.service.ContentsService;
import org.eclipse.egit.github.core.service.IssueService;
import org.eclipse.egit.github.core.service.RepositoryService;
import org.eclipse.egit.github.core.service.UserService;
import org.json.JSONException;
import org.json.JSONObject;
import src.main.model.Pdf;
import src.main.model.PdfComment;
import src.main.model.PdfComment.Tag;
public class ReviewSubmitServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private transient HttpClient httpClient = HttpClients.createDefault();
private String repoName;
private String writerLogin;
private String accessToken;
private transient GitHubClient client;
@Override
protected void doPost(final HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
final ServletFileUpload upload = new ServletFileUpload();
this.repoName = req.getParameter("repoName");
this.writerLogin = req.getParameter("writer");
this.accessToken = req.getParameter("access_token");
System.out.println("Hello " + repoName + " " + writerLogin);
if (repoName == null || writerLogin == null || accessToken == null) {
System.out.println("Something blank");
resp.sendError(500);
return;
}
SubmitTask task = new SubmitTask();
String pdfUrl = "";
try {
FileItemIterator iter = upload.getItemIterator(req);
FileItemStream file = iter.next();
Pdf pdf = new Pdf(file.openStream());
this.client = new GitHubClient();
client.setOAuth2Token(accessToken);
UserService userService = new UserService(client);
User reviewer = userService.getUser();
List<String> comments = updatePdf(pdf);
pdfUrl = addPdfToRepo(pdf, reviewer);
task.setter(comments, accessToken, writerLogin, repoName);
pdf.close();
} catch (FileUploadException e) {
e.printStackTrace();
resp.sendError(500, "There has been an error uploading your Pdf.");
}
resp.getWriter().write(pdfUrl);
Queue taskQueue = QueueFactory.getDefaultQueue();
taskQueue.add(TaskOptions.Builder.withPayload(task));
}
public void createIssue(GitHubClient client, String writerLogin, String repoName, PdfComment comment) throws IOException {
IssueService issueService = new IssueService(client);
// If the issue does not already exist
if(comment.getIssueNumber() == 0) {
Issue issue = new Issue();
issue.setTitle(comment.getTitle());
issue.setBody(comment.getComment());
List<Label> labels = new ArrayList<>();
for(Tag tag : comment.getTags()) {
Label label = new Label();
label.setName(tag.name());
labels.add(label);
}
issue.setLabels(labels);
//creates an issue remotely
issue = issueService.createIssue(writerLogin, repoName, issue);
comment.setIssueNumber(issue.getNumber());
}
// If the issue already exists
else {
Issue issue = issueService.getIssue(writerLogin, repoName, comment.getIssueNumber());
String issueText = comment.getComment();
if(!issue.getBody().equals(issueText)) {
issueService.createComment(writerLogin, repoName, comment.getIssueNumber(), issueText);
}
List<Label> existingLabels = issue.getLabels();
List<Label> labels = new ArrayList<>();
for(Tag tag : comment.getTags()) {
Label l = new Label();
l.setName(tag.name());
labels.add(l);
}
boolean updateLabels = labels.size() != existingLabels.size();
if(!updateLabels) {
for(Label l1 : labels) {
updateLabels = true;
for(Label l2 : existingLabels) {
if(l1.getName().equals(l2.getName())) {
updateLabels = false;
break;
}
}
if(updateLabels)
break;
}
}
if(updateLabels) {
issue.setLabels(labels);
issueService.editIssue(writerLogin, repoName, issue);
}
}
}
public void createIssues(GitHubClient client, String writerLogin, String repoName, List<PdfComment> comments) throws IOException {
for(PdfComment comment : comments) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
createIssue(client, writerLogin, repoName, comment);
}
}
public List<String> updatePdf(Pdf pdf) throws IOException {
List<String> comments = pdf.getComments();
if(!comments.isEmpty()) {
List<PdfComment> pdfComments = PdfComment.getComments(comments);
// Set the issue numbers
int issueNumber = getNumTotalIssues() + 1;
for(PdfComment com : pdfComments) {
if(com.getIssueNumber() == 0) {
com.setIssueNumber(issueNumber++);
}
}
// Update the comments
pdf.updateComments(pdfComments, this.writerLogin, this.repoName);
}
return comments;
}
@SuppressWarnings("unused")
private static void main(String[] args) throws IOException {
Pdf pdf = new Pdf(new FileInputStream("C:\\Users\\KevinLubick\\Downloads\\test_anno.pdf"));
ReviewSubmitServlet servlet = new ReviewSubmitServlet();
List<String> comments = pdf.getComments();
List<PdfComment> pdfComments = PdfComment.getComments(comments);
// Set the issue numbers
int issueNumber = 1;
for (PdfComment com : pdfComments) {
if (com.getIssueNumber() == 0) {
com.setIssueNumber(issueNumber++);
}
}
// Update the comments
pdf.updateComments(pdfComments, servlet.writerLogin, servlet.repoName);
pdf.getDoc().save("C:\\Users\\KevinLubick\\Downloads\\test_anno_1.pdf");
pdf.close();
}
private int getNumTotalIssues() throws IOException {
IssueService issueService = new IssueService(client);
Map<String, String> prefs = new HashMap<String, String>();
//By default, only open issues are shown
prefs.put(IssueService.FILTER_STATE, "all");
//get all issus for this repo
List<Issue> issues = issueService.getIssues(getRepo(client), prefs);
return issues.size();
}
public static void closeReviewIssue(GitHubClient client, String writerLogin, String repoName, String reviewer, String comment) throws IOException {
IssueService issueService = new IssueService(client);
for(Issue issue : issueService.getIssues(writerLogin, repoName, null)) {
if(issue.getAssignee() != null) {
if(issue.getTitle().startsWith("Reviewer - ") && issue.getAssignee().getLogin().equals(reviewer)) {
issueService.createComment(writerLogin, repoName, issue.getNumber(), comment);
issue.setState("closed");
issueService.editIssue(writerLogin, repoName, issue);
}
}
}
}
public String addPdfToRepo(Pdf pdf, User reviewer) throws IOException {
String filePath = "reviews/" + reviewer.getLogin() + ".pdf";
String sha = null;
ContentsService contents = new ContentsService(client);
Repository repo = getRepo(client);
try {
//list all the files in reviews. We can't just fetch our paper, because it might be
//bigger than 1MB which breaks this API call
List<RepositoryContents> files = contents.getContents(repo, "reviews/");
for(RepositoryContents file: files) {
if (file.getName().equals(reviewer.getLogin()+".pdf")) {
sha = file.getSha();
}
}
} catch(IOException e) {
e.printStackTrace();
}
HttpPut request = new HttpPut(buildURIForFileUpload(accessToken, writerLogin, repoName, filePath));
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
pdf.getDoc().save(output);
String content = DatatypeConverter.printBase64Binary(output.toByteArray());
JSONObject json = new JSONObject();
if (sha == null) {
//if we are uploading the review for the first time
json.put("message", reviewer.getLogin() + " has submitted their review.");
} else {
//updating review
json.put("message", reviewer.getLogin() + " has updated their review.");
json.put("sha", sha);
}
json.put("path", filePath);
json.put("content", content);
StringEntity entity = new StringEntity(json.toString());
entity.setContentType("application/json");
request.setEntity(entity);
httpClient.execute(request);
} catch(JSONException e) {
e.printStackTrace();
} finally {
request.releaseConnection();
}
return filePath;
}
private Repository getRepo(GitHubClient client) throws IOException {
RepositoryService repoService = new RepositoryService(client);
Repository repo = repoService.getRepository(writerLogin, repoName);
return repo;
}
private void readObject(ObjectInputStream inputStream) throws IOException, ClassNotFoundException
{
inputStream.defaultReadObject();
//reinstantiate our transient variables.
this.httpClient = HttpClients.createDefault();
this.client = new GitHubClient();
client.setOAuth2Token(accessToken);
}
private URI buildURIForFileUpload(String accessToken, String writerLogin, String repoName, String filePath) throws IOException {
try {
URIBuilder builder = new URIBuilder("https://api.github.com/repos/" + writerLogin + "/" + repoName + "/contents/" + filePath);
builder.addParameter("access_token", accessToken);
URI build = builder.build();
return build;
} catch (URISyntaxException e) {
throw new IOException("Could not build uri", e);
}
}
private final class SubmitTask implements DeferredTask {
private static final long serialVersionUID = -603761725725342674L;
private String accessToken;
private List<String> commentStrs;
private String writerLogin;
private String repoName;
public void setter(List<String> comments, String accessToken, String writerLogin, String repoName) {
this.commentStrs = comments;
this.accessToken = accessToken;
this.writerLogin = writerLogin;
this.repoName = repoName;
}
@Override
public void run() {
try {
GitHubClient client = new GitHubClient();
client.setOAuth2Token(accessToken);
UserService userService = new UserService(client);
User reviewer = userService.getUser();
List<PdfComment> comments = PdfComment.getComments(commentStrs);
createIssues(client, writerLogin, repoName, comments);
String closeComment = "@" + reviewer.getLogin() + " has reviewed this paper.";
closeReviewIssue(client, writerLogin, repoName, reviewer.getLogin(), closeComment);
ReviewRequestServlet.removeReviewFromDatastore(reviewer.getLogin(), writerLogin, repoName);
} catch(IOException e) {
e.printStackTrace();
System.err.println("Error processing Pdf.");
}
}
}
}
| src/main/java/src/main/servlet/ReviewSubmitServlet.java | package src.main.servlet;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.DatatypeConverter;
import com.google.appengine.api.taskqueue.DeferredTask;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.eclipse.egit.github.core.Issue;
import org.eclipse.egit.github.core.Label;
import org.eclipse.egit.github.core.Repository;
import org.eclipse.egit.github.core.RepositoryContents;
import org.eclipse.egit.github.core.User;
import org.eclipse.egit.github.core.client.GitHubClient;
import org.eclipse.egit.github.core.service.ContentsService;
import org.eclipse.egit.github.core.service.IssueService;
import org.eclipse.egit.github.core.service.RepositoryService;
import org.eclipse.egit.github.core.service.UserService;
import org.json.JSONException;
import org.json.JSONObject;
import src.main.model.Pdf;
import src.main.model.PdfComment;
import src.main.model.PdfComment.Tag;
public class ReviewSubmitServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private transient HttpClient httpClient = HttpClients.createDefault();
private String repoName;
private String writerLogin;
private String accessToken;
private transient GitHubClient client;
@Override
protected void doPost(final HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
final ServletFileUpload upload = new ServletFileUpload();
this.repoName = req.getParameter("repoName");
this.writerLogin = req.getParameter("writer");
this.accessToken = req.getParameter("access_token");
System.out.println("Hello "+repoName+" "+writerLogin);
if(repoName == null || writerLogin == null || accessToken == null) {
System.out.println("Something blank");
resp.sendError(500);
return;
}
SubmitTask task = new SubmitTask();
String pdfUrl = "";
try {
FileItemIterator iter = upload.getItemIterator(req);
FileItemStream file = iter.next();
Pdf pdf = new Pdf(file.openStream());
this.client = new GitHubClient();
client.setOAuth2Token(accessToken);
UserService userService = new UserService(client);
User reviewer = userService.getUser();
List<String> comments = updatePdf(pdf);
pdfUrl = addPdfToRepo(pdf, reviewer);
task.setter(comments, accessToken, writerLogin, repoName);
pdf.close();
} catch(FileUploadException e) {
e.printStackTrace();
resp.sendError(500, "There has been an error uploading your Pdf.");
}
resp.getWriter().write(pdfUrl);
Queue taskQueue = QueueFactory.getDefaultQueue();
taskQueue.add(TaskOptions.Builder.withPayload(task));
}
public void createIssue(GitHubClient client, String writerLogin, String repoName, PdfComment comment) throws IOException {
IssueService issueService = new IssueService(client);
// If the issue does not already exist
if(comment.getIssueNumber() == 0) {
Issue issue = new Issue();
issue.setTitle(comment.getTitle());
issue.setBody(comment.getComment());
List<Label> labels = new ArrayList<>();
for(Tag tag : comment.getTags()) {
Label label = new Label();
label.setName(tag.name());
labels.add(label);
}
issue.setLabels(labels);
//creates an issue remotely
issue = issueService.createIssue(writerLogin, repoName, issue);
comment.setIssueNumber(issue.getNumber());
}
// If the issue already exists
else {
Issue issue = issueService.getIssue(writerLogin, repoName, comment.getIssueNumber());
String issueText = comment.getComment();
if(!issue.getBody().equals(issueText)) {
issueService.createComment(writerLogin, repoName, comment.getIssueNumber(), issueText);
}
List<Label> existingLabels = issue.getLabels();
List<Label> labels = new ArrayList<>();
for(Tag tag : comment.getTags()) {
Label l = new Label();
l.setName(tag.name());
labels.add(l);
}
boolean updateLabels = labels.size() != existingLabels.size();
if(!updateLabels) {
for(Label l1 : labels) {
updateLabels = true;
for(Label l2 : existingLabels) {
if(l1.getName().equals(l2.getName())) {
updateLabels = false;
break;
}
}
if(updateLabels)
break;
}
}
if(updateLabels) {
issue.setLabels(labels);
issueService.editIssue(writerLogin, repoName, issue);
}
}
}
public void createIssues(GitHubClient client, String writerLogin, String repoName, List<PdfComment> comments) throws IOException {
for(PdfComment comment : comments) {
createIssue(client, writerLogin, repoName, comment);
}
}
public List<String> updatePdf(Pdf pdf) throws IOException {
List<String> comments = pdf.getComments();
if(!comments.isEmpty()) {
List<PdfComment> pdfComments = PdfComment.getComments(comments);
// Set the issue numbers
int issueNumber = getNumTotalIssues() + 1;
for(PdfComment com : pdfComments) {
if(com.getIssueNumber() == 0) {
System.out.println(com.getIssueNumber());
com.setIssueNumber(issueNumber++);
}
}
// Update the comments
pdf.updateComments(pdfComments, this.writerLogin, this.repoName);
}
return comments;
}
@SuppressWarnings("unused")
private static void main(String[] args) throws IOException {
Pdf pdf = new Pdf(new FileInputStream("C:\\Users\\KevinLubick\\Downloads\\test_anno.pdf"));
ReviewSubmitServlet servlet = new ReviewSubmitServlet();
List<String> comments = pdf.getComments();
List<PdfComment> pdfComments = PdfComment.getComments(comments);
// Set the issue numbers
int issueNumber = 1;
for (PdfComment com : pdfComments) {
if (com.getIssueNumber() == 0) {
System.out.println(com.getIssueNumber());
com.setIssueNumber(issueNumber++);
}
}
// Update the comments
pdf.updateComments(pdfComments, servlet.writerLogin, servlet.repoName);
pdf.getDoc().save("C:\\Users\\KevinLubick\\Downloads\\test_anno_1.pdf");
pdf.close();
}
private int getNumTotalIssues() throws IOException {
IssueService issueService = new IssueService(client);
Map<String, String> prefs = new HashMap<String, String>();
//By default, only open issues are shown
prefs.put(IssueService.FILTER_STATE, "all");
//get all issus for this repo
List<Issue> issues = issueService.getIssues(getRepo(client), prefs);
return issues.size();
}
public static void closeReviewIssue(GitHubClient client, String writerLogin, String repoName, String reviewer, String comment) throws IOException {
IssueService issueService = new IssueService(client);
for(Issue issue : issueService.getIssues(writerLogin, repoName, null)) {
if(issue.getAssignee() != null) {
if(issue.getTitle().startsWith("Reviewer - ") && issue.getAssignee().getLogin().equals(reviewer)) {
issueService.createComment(writerLogin, repoName, issue.getNumber(), comment);
issue.setState("closed");
issueService.editIssue(writerLogin, repoName, issue);
}
}
}
}
public String addPdfToRepo(Pdf pdf, User reviewer) throws IOException {
String filePath = "reviews/" + reviewer.getLogin() + ".pdf";
String sha = null;
ContentsService contents = new ContentsService(client);
Repository repo = getRepo(client);
try {
//list all the files in reviews. We can't just fetch our paper, because it might be
//bigger than 1MB which breaks this API call
List<RepositoryContents> files = contents.getContents(repo, "reviews/");
for(RepositoryContents file: files) {
if (file.getName().equals(reviewer.getLogin()+".pdf")) {
sha = file.getSha();
}
}
} catch(IOException e) {
e.printStackTrace();
}
HttpPut request = new HttpPut(buildURIForFileUpload(accessToken, writerLogin, repoName, filePath));
try {
ByteArrayOutputStream output = new ByteArrayOutputStream();
pdf.getDoc().save(output);
String content = DatatypeConverter.printBase64Binary(output.toByteArray());
JSONObject json = new JSONObject();
if (sha == null) {
//if we are uploading the review for the first time
json.put("message", reviewer.getLogin() + " has submitted their review.");
} else {
//updating review
json.put("message", reviewer.getLogin() + " has updated their review.");
json.put("sha", sha);
}
json.put("path", filePath);
json.put("content", content);
StringEntity entity = new StringEntity(json.toString());
entity.setContentType("application/json");
request.setEntity(entity);
httpClient.execute(request);
} catch(JSONException e) {
e.printStackTrace();
} finally {
request.releaseConnection();
}
return filePath;
}
private Repository getRepo(GitHubClient client) throws IOException {
RepositoryService repoService = new RepositoryService(client);
Repository repo = repoService.getRepository(writerLogin, repoName);
return repo;
}
private void readObject(ObjectInputStream inputStream) throws IOException, ClassNotFoundException
{
inputStream.defaultReadObject();
//reinstantiate our transient variables.
this.httpClient = HttpClients.createDefault();
this.client = new GitHubClient();
client.setOAuth2Token(accessToken);
}
private URI buildURIForFileUpload(String accessToken, String writerLogin, String repoName, String filePath) throws IOException {
try {
URIBuilder builder = new URIBuilder("https://api.github.com/repos/" + writerLogin + "/" + repoName + "/contents/" + filePath);
builder.addParameter("access_token", accessToken);
URI build = builder.build();
return build;
} catch (URISyntaxException e) {
throw new IOException("Could not build uri", e);
}
}
private final class SubmitTask implements DeferredTask {
private static final long serialVersionUID = -603761725725342674L;
private String accessToken;
private List<String> commentStrs;
private String writerLogin;
private String repoName;
public void setter(List<String> comments, String accessToken, String writerLogin, String repoName) {
this.commentStrs = comments;
this.accessToken = accessToken;
this.writerLogin = writerLogin;
this.repoName = repoName;
}
@Override
public void run() {
try {
GitHubClient client = new GitHubClient();
client.setOAuth2Token(accessToken);
UserService userService = new UserService(client);
User reviewer = userService.getUser();
List<PdfComment> comments = PdfComment.getComments(commentStrs);
createIssues(client, writerLogin, repoName, comments);
String closeComment = "@" + reviewer.getLogin() + " has reviewed this paper.";
closeReviewIssue(client, writerLogin, repoName, reviewer.getLogin(), closeComment);
ReviewRequestServlet.removeReviewFromDatastore(reviewer.getLogin(), writerLogin, repoName);
} catch(IOException e) {
e.printStackTrace();
System.err.println("Error processing Pdf.");
}
}
}
}
| Adds some rate limiting on creating issues
To hopefully avoid the 403 abuse exception
| src/main/java/src/main/servlet/ReviewSubmitServlet.java | Adds some rate limiting on creating issues | <ide><path>rc/main/java/src/main/servlet/ReviewSubmitServlet.java
<ide>
<ide> private transient GitHubClient client;
<ide>
<del> @Override
<del> protected void doPost(final HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
<del> final ServletFileUpload upload = new ServletFileUpload();
<del>
<del> this.repoName = req.getParameter("repoName");
<del> this.writerLogin = req.getParameter("writer");
<del> this.accessToken = req.getParameter("access_token");
<del> System.out.println("Hello "+repoName+" "+writerLogin);
<del>
<del> if(repoName == null || writerLogin == null || accessToken == null) {
<del> System.out.println("Something blank");
<del> resp.sendError(500);
<del> return;
<del> }
<del>
<del> SubmitTask task = new SubmitTask();
<del> String pdfUrl = "";
<del>
<del> try {
<del> FileItemIterator iter = upload.getItemIterator(req);
<del> FileItemStream file = iter.next();
<del> Pdf pdf = new Pdf(file.openStream());
<del>
<del>
<del>
<del> this.client = new GitHubClient();
<del> client.setOAuth2Token(accessToken);
<del> UserService userService = new UserService(client);
<del> User reviewer = userService.getUser();
<del>
<del>
<del> List<String> comments = updatePdf(pdf);
<del> pdfUrl = addPdfToRepo(pdf, reviewer);
<del> task.setter(comments, accessToken, writerLogin, repoName);
<del>
<del> pdf.close();
<del> } catch(FileUploadException e) {
<del> e.printStackTrace();
<del> resp.sendError(500, "There has been an error uploading your Pdf.");
<del> }
<del>
<del> resp.getWriter().write(pdfUrl);
<del>
<del> Queue taskQueue = QueueFactory.getDefaultQueue();
<del> taskQueue.add(TaskOptions.Builder.withPayload(task));
<del> }
<add> @Override
<add> protected void doPost(final HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
<add> final ServletFileUpload upload = new ServletFileUpload();
<add>
<add> this.repoName = req.getParameter("repoName");
<add> this.writerLogin = req.getParameter("writer");
<add> this.accessToken = req.getParameter("access_token");
<add> System.out.println("Hello " + repoName + " " + writerLogin);
<add>
<add> if (repoName == null || writerLogin == null || accessToken == null) {
<add> System.out.println("Something blank");
<add> resp.sendError(500);
<add> return;
<add> }
<add>
<add> SubmitTask task = new SubmitTask();
<add> String pdfUrl = "";
<add>
<add> try {
<add> FileItemIterator iter = upload.getItemIterator(req);
<add> FileItemStream file = iter.next();
<add> Pdf pdf = new Pdf(file.openStream());
<add>
<add> this.client = new GitHubClient();
<add> client.setOAuth2Token(accessToken);
<add> UserService userService = new UserService(client);
<add> User reviewer = userService.getUser();
<add>
<add> List<String> comments = updatePdf(pdf);
<add> pdfUrl = addPdfToRepo(pdf, reviewer);
<add> task.setter(comments, accessToken, writerLogin, repoName);
<add>
<add> pdf.close();
<add> } catch (FileUploadException e) {
<add> e.printStackTrace();
<add> resp.sendError(500, "There has been an error uploading your Pdf.");
<add> }
<add>
<add> resp.getWriter().write(pdfUrl);
<add>
<add> Queue taskQueue = QueueFactory.getDefaultQueue();
<add> taskQueue.add(TaskOptions.Builder.withPayload(task));
<add> }
<ide>
<ide> public void createIssue(GitHubClient client, String writerLogin, String repoName, PdfComment comment) throws IOException {
<ide> IssueService issueService = new IssueService(client);
<ide>
<ide> public void createIssues(GitHubClient client, String writerLogin, String repoName, List<PdfComment> comments) throws IOException {
<ide> for(PdfComment comment : comments) {
<add> try {
<add> Thread.sleep(2000);
<add> } catch (InterruptedException e) {
<add> e.printStackTrace();
<add> }
<ide> createIssue(client, writerLogin, repoName, comment);
<ide> }
<ide> }
<ide> int issueNumber = getNumTotalIssues() + 1;
<ide> for(PdfComment com : pdfComments) {
<ide> if(com.getIssueNumber() == 0) {
<del> System.out.println(com.getIssueNumber());
<ide> com.setIssueNumber(issueNumber++);
<ide> }
<ide> }
<ide> int issueNumber = 1;
<ide> for (PdfComment com : pdfComments) {
<ide> if (com.getIssueNumber() == 0) {
<del> System.out.println(com.getIssueNumber());
<ide> com.setIssueNumber(issueNumber++);
<ide> }
<ide> } |
|
Java | mit | error: pathspec 'cinderella-core/src/test/java/de/neofonie/cinderella/core/CinderellaServiceImplTest2.java' did not match any file(s) known to git
| 9e9ef782c6bf7d25a57892df4e78fb0b18f08814 | 1 | Neofonie/cinderella | /*
*
* The MIT License (MIT)
* Copyright (c) 2016 Neofonie GmbH
* 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.
*
*/
package de.neofonie.cinderella.core;
import de.neofonie.cinderella.core.config.CinderellaConfig;
import de.neofonie.cinderella.core.config.loader.CinderellaXmlConfigLoader;
import de.neofonie.cinderella.core.config.xml.IdentifierType;
import de.neofonie.cinderella.core.config.xml.Rule;
import de.neofonie.cinderella.core.counter.Counter;
import org.easymock.EasyMock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
import static org.testng.Assert.*;
@ContextConfiguration(classes = CinderellaServiceImplTest2.Config.class)
public class CinderellaServiceImplTest2 extends AbstractTestNGSpringContextTests {
@Autowired
private CinderellaServiceImpl ddosService;
@Autowired
private Counter counter;
@Autowired
private CinderellaXmlConfigLoader cinderellaXmlConfigLoader;
private static final Rule rule = new Rule(new ArrayList<>(), "id", IdentifierType.IP, 2, 5);
@Test
public void testWhitelistSession() throws Exception {
CinderellaConfig cinderellaConfig = EasyMock.createMock(CinderellaConfig.class);
MockHttpServletRequest request = createMockHttpServletRequest();
//Init
EasyMock.expect(counter.isWhitelisted("SESSION_ID")).andReturn(true);
//Test
EasyMock.replay(cinderellaConfig, cinderellaXmlConfigLoader, counter);
assertFalse(ddosService.isDdos(request));
EasyMock.verify(cinderellaConfig, cinderellaXmlConfigLoader, counter);
EasyMock.reset(cinderellaConfig, cinderellaXmlConfigLoader, counter);
}
@Test
public void testChecksBlacklistSession() throws Exception {
CinderellaConfig cinderellaConfig = EasyMock.createMock(CinderellaConfig.class);
MockHttpServletRequest request = createMockHttpServletRequest();
//Init
EasyMock.expect(counter.isWhitelisted("SESSION_ID")).andReturn(false);
EasyMock.expect(counter.isBlacklisted("SESSION_ID")).andReturn(true);
//Test
EasyMock.replay(cinderellaConfig, cinderellaXmlConfigLoader, counter);
assertTrue(ddosService.isDdos(request));
EasyMock.verify(cinderellaConfig, cinderellaXmlConfigLoader, counter);
EasyMock.reset(cinderellaConfig, cinderellaXmlConfigLoader, counter);
}
@Test
public void testChecksBlacklistIP() throws Exception {
CinderellaConfig cinderellaConfig = EasyMock.createMock(CinderellaConfig.class);
MockHttpServletRequest request = createMockHttpServletRequest();
//Init
EasyMock.expect(counter.isWhitelisted("SESSION_ID")).andReturn(false);
EasyMock.expect(counter.isBlacklisted("SESSION_ID")).andReturn(false);
EasyMock.expect(counter.isBlacklisted("127.0.0.1")).andReturn(true);
//Test
EasyMock.replay(cinderellaConfig, cinderellaXmlConfigLoader, counter);
assertTrue(ddosService.isDdos(request));
EasyMock.verify(cinderellaConfig, cinderellaXmlConfigLoader, counter);
EasyMock.reset(cinderellaConfig, cinderellaXmlConfigLoader, counter);
}
@Test
public void testNoConfig() throws Exception {
CinderellaConfig cinderellaConfig = EasyMock.createMock(CinderellaConfig.class);
MockHttpServletRequest request = createMockHttpServletRequest();
//Init
EasyMock.expect(counter.isWhitelisted("SESSION_ID")).andReturn(false);
EasyMock.expect(counter.isBlacklisted("SESSION_ID")).andReturn(false);
EasyMock.expect(counter.isBlacklisted("127.0.0.1")).andReturn(false);
EasyMock.expect(cinderellaXmlConfigLoader.getCinderellaConfig()).andReturn(null);
//Test
EasyMock.replay(cinderellaConfig, cinderellaXmlConfigLoader, counter);
assertFalse(ddosService.isDdos(request));
EasyMock.verify(cinderellaConfig, cinderellaXmlConfigLoader, counter);
EasyMock.reset(cinderellaConfig, cinderellaXmlConfigLoader, counter);
}
@Test
public void testConfigException() throws Exception {
CinderellaConfig cinderellaConfig = EasyMock.createMock(CinderellaConfig.class);
MockHttpServletRequest request = createMockHttpServletRequest();
//Init
EasyMock.expect(counter.isWhitelisted("SESSION_ID")).andReturn(false);
EasyMock.expect(counter.isBlacklisted("SESSION_ID")).andReturn(false);
EasyMock.expect(counter.isBlacklisted("127.0.0.1")).andReturn(false);
EasyMock.expect(cinderellaXmlConfigLoader.getCinderellaConfig()).andThrow(new IOException());
//Test
EasyMock.replay(cinderellaConfig, cinderellaXmlConfigLoader, counter);
assertFalse(ddosService.isDdos(request));
EasyMock.verify(cinderellaConfig, cinderellaXmlConfigLoader, counter);
EasyMock.reset(cinderellaConfig, cinderellaXmlConfigLoader, counter);
}
@Test
public void testNoMatch() throws Exception {
CinderellaConfig cinderellaConfig = EasyMock.createMock(CinderellaConfig.class);
MockHttpServletRequest request = createMockHttpServletRequest();
//Init
EasyMock.expect(counter.isWhitelisted("SESSION_ID")).andReturn(false);
EasyMock.expect(counter.isBlacklisted("SESSION_ID")).andReturn(false);
EasyMock.expect(counter.isBlacklisted("127.0.0.1")).andReturn(false);
EasyMock.expect(cinderellaXmlConfigLoader.getCinderellaConfig()).andReturn(cinderellaConfig);
EasyMock.expect(cinderellaConfig.getMatches(request)).andReturn(Collections.emptyList());
//Test
EasyMock.replay(cinderellaConfig, cinderellaXmlConfigLoader, counter);
assertFalse(ddosService.isDdos(request));
EasyMock.verify(cinderellaConfig, cinderellaXmlConfigLoader, counter);
EasyMock.reset(cinderellaConfig, cinderellaXmlConfigLoader, counter);
}
@Test
public void testNoDDos() throws Exception {
CinderellaConfig cinderellaConfig = EasyMock.createMock(CinderellaConfig.class);
MockHttpServletRequest request = createMockHttpServletRequest();
assertEquals("SESSION_ID", request.getSession().getId());
//Init
EasyMock.expect(counter.isWhitelisted("SESSION_ID")).andReturn(false);
EasyMock.expect(counter.isBlacklisted("SESSION_ID")).andReturn(false);
EasyMock.expect(counter.isBlacklisted("127.0.0.1")).andReturn(false);
EasyMock.expect(cinderellaXmlConfigLoader.getCinderellaConfig()).andReturn(cinderellaConfig);
EasyMock.expect(cinderellaConfig.getMatches(request)).andReturn(Arrays.asList(rule));
EasyMock.expect(counter.checkCount("127.0.0.1_id", 2, TimeUnit.MINUTES, 5)).andReturn(false);
//Test
EasyMock.replay(cinderellaConfig, cinderellaXmlConfigLoader, counter);
assertFalse(ddosService.isDdos(request));
EasyMock.verify(cinderellaConfig, cinderellaXmlConfigLoader, counter);
EasyMock.reset(cinderellaConfig, cinderellaXmlConfigLoader, counter);
}
@Test
public void testSetBlacklist() throws Exception {
CinderellaConfig cinderellaConfig = EasyMock.createMock(CinderellaConfig.class);
MockHttpServletRequest request = createMockHttpServletRequest();
//Init
EasyMock.expect(cinderellaConfig.getBlacklistMinutes()).andReturn(1L);
EasyMock.expect(counter.isWhitelisted("SESSION_ID")).andReturn(false);
EasyMock.expect(counter.isBlacklisted("SESSION_ID")).andReturn(false);
EasyMock.expect(counter.isBlacklisted("127.0.0.1")).andReturn(false);
EasyMock.expect(cinderellaXmlConfigLoader.getCinderellaConfig()).andReturn(cinderellaConfig);
EasyMock.expect(cinderellaConfig.getMatches(request)).andReturn(Arrays.asList(rule));
EasyMock.expect(counter.checkCount("127.0.0.1_id", 2, TimeUnit.MINUTES, 5)).andReturn(true);
counter.blacklist("127.0.0.1", TimeUnit.MINUTES, 1);
//Test
EasyMock.replay(cinderellaConfig, cinderellaXmlConfigLoader, counter);
assertTrue(ddosService.isDdos(request));
EasyMock.verify(cinderellaConfig, cinderellaXmlConfigLoader, counter);
EasyMock.reset(cinderellaConfig, cinderellaXmlConfigLoader, counter);
}
private MockHttpServletRequest createMockHttpServletRequest() {
MockHttpSession session = new MockHttpSession(null, "SESSION_ID");
MockHttpServletRequest request = new MockHttpServletRequest();
request.setSession(session);
return request;
}
@BeforeMethod
public void setUp() throws Exception {
EasyMock.reset(cinderellaXmlConfigLoader, counter);
}
@Configuration
static class Config {
@Bean
CinderellaServiceImpl ddosService() {
return new CinderellaServiceImpl();
}
@Bean
CinderellaXmlConfigLoader ddosXmlConfigLoader() {
return EasyMock.createMock(CinderellaXmlConfigLoader.class);
}
@Bean
Counter counter() {
return EasyMock.createMock(Counter.class);
}
}
} | cinderella-core/src/test/java/de/neofonie/cinderella/core/CinderellaServiceImplTest2.java | add Test
| cinderella-core/src/test/java/de/neofonie/cinderella/core/CinderellaServiceImplTest2.java | add Test | <ide><path>inderella-core/src/test/java/de/neofonie/cinderella/core/CinderellaServiceImplTest2.java
<add>/*
<add> *
<add> * The MIT License (MIT)
<add> * Copyright (c) 2016 Neofonie GmbH
<add> * Permission is hereby granted, free of charge, to any person obtaining a copy
<add> * of this software and associated documentation files (the "Software"), to deal
<add> * in the Software without restriction, including without limitation the rights
<add> * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
<add> * copies of the Software, and to permit persons to whom the Software is
<add> * furnished to do so, subject to the following conditions:
<add> * The above copyright notice and this permission notice shall be included in all
<add> * copies or substantial portions of the Software.
<add> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
<add> * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
<add> * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
<add> * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
<add> * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
<add> * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
<add> * SOFTWARE.
<add> *
<add> */
<add>
<add>package de.neofonie.cinderella.core;
<add>
<add>import de.neofonie.cinderella.core.config.CinderellaConfig;
<add>import de.neofonie.cinderella.core.config.loader.CinderellaXmlConfigLoader;
<add>import de.neofonie.cinderella.core.config.xml.IdentifierType;
<add>import de.neofonie.cinderella.core.config.xml.Rule;
<add>import de.neofonie.cinderella.core.counter.Counter;
<add>import org.easymock.EasyMock;
<add>import org.springframework.beans.factory.annotation.Autowired;
<add>import org.springframework.context.annotation.Bean;
<add>import org.springframework.context.annotation.Configuration;
<add>import org.springframework.mock.web.MockHttpServletRequest;
<add>import org.springframework.mock.web.MockHttpSession;
<add>import org.springframework.test.context.ContextConfiguration;
<add>import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
<add>import org.testng.annotations.BeforeMethod;
<add>import org.testng.annotations.Test;
<add>
<add>import java.io.IOException;
<add>import java.util.ArrayList;
<add>import java.util.Arrays;
<add>import java.util.Collections;
<add>import java.util.concurrent.TimeUnit;
<add>
<add>import static org.testng.Assert.*;
<add>
<add>@ContextConfiguration(classes = CinderellaServiceImplTest2.Config.class)
<add>public class CinderellaServiceImplTest2 extends AbstractTestNGSpringContextTests {
<add>
<add> @Autowired
<add> private CinderellaServiceImpl ddosService;
<add> @Autowired
<add> private Counter counter;
<add> @Autowired
<add> private CinderellaXmlConfigLoader cinderellaXmlConfigLoader;
<add> private static final Rule rule = new Rule(new ArrayList<>(), "id", IdentifierType.IP, 2, 5);
<add>
<add> @Test
<add> public void testWhitelistSession() throws Exception {
<add>
<add> CinderellaConfig cinderellaConfig = EasyMock.createMock(CinderellaConfig.class);
<add> MockHttpServletRequest request = createMockHttpServletRequest();
<add>
<add> //Init
<add> EasyMock.expect(counter.isWhitelisted("SESSION_ID")).andReturn(true);
<add>
<add> //Test
<add> EasyMock.replay(cinderellaConfig, cinderellaXmlConfigLoader, counter);
<add> assertFalse(ddosService.isDdos(request));
<add> EasyMock.verify(cinderellaConfig, cinderellaXmlConfigLoader, counter);
<add> EasyMock.reset(cinderellaConfig, cinderellaXmlConfigLoader, counter);
<add> }
<add>
<add> @Test
<add> public void testChecksBlacklistSession() throws Exception {
<add>
<add> CinderellaConfig cinderellaConfig = EasyMock.createMock(CinderellaConfig.class);
<add> MockHttpServletRequest request = createMockHttpServletRequest();
<add>
<add> //Init
<add> EasyMock.expect(counter.isWhitelisted("SESSION_ID")).andReturn(false);
<add> EasyMock.expect(counter.isBlacklisted("SESSION_ID")).andReturn(true);
<add>
<add> //Test
<add> EasyMock.replay(cinderellaConfig, cinderellaXmlConfigLoader, counter);
<add> assertTrue(ddosService.isDdos(request));
<add> EasyMock.verify(cinderellaConfig, cinderellaXmlConfigLoader, counter);
<add> EasyMock.reset(cinderellaConfig, cinderellaXmlConfigLoader, counter);
<add>
<add> }
<add>
<add> @Test
<add> public void testChecksBlacklistIP() throws Exception {
<add>
<add> CinderellaConfig cinderellaConfig = EasyMock.createMock(CinderellaConfig.class);
<add> MockHttpServletRequest request = createMockHttpServletRequest();
<add>
<add> //Init
<add> EasyMock.expect(counter.isWhitelisted("SESSION_ID")).andReturn(false);
<add> EasyMock.expect(counter.isBlacklisted("SESSION_ID")).andReturn(false);
<add> EasyMock.expect(counter.isBlacklisted("127.0.0.1")).andReturn(true);
<add>
<add> //Test
<add> EasyMock.replay(cinderellaConfig, cinderellaXmlConfigLoader, counter);
<add> assertTrue(ddosService.isDdos(request));
<add> EasyMock.verify(cinderellaConfig, cinderellaXmlConfigLoader, counter);
<add> EasyMock.reset(cinderellaConfig, cinderellaXmlConfigLoader, counter);
<add> }
<add>
<add> @Test
<add> public void testNoConfig() throws Exception {
<add>
<add> CinderellaConfig cinderellaConfig = EasyMock.createMock(CinderellaConfig.class);
<add> MockHttpServletRequest request = createMockHttpServletRequest();
<add>
<add> //Init
<add> EasyMock.expect(counter.isWhitelisted("SESSION_ID")).andReturn(false);
<add> EasyMock.expect(counter.isBlacklisted("SESSION_ID")).andReturn(false);
<add> EasyMock.expect(counter.isBlacklisted("127.0.0.1")).andReturn(false);
<add> EasyMock.expect(cinderellaXmlConfigLoader.getCinderellaConfig()).andReturn(null);
<add>
<add> //Test
<add> EasyMock.replay(cinderellaConfig, cinderellaXmlConfigLoader, counter);
<add> assertFalse(ddosService.isDdos(request));
<add> EasyMock.verify(cinderellaConfig, cinderellaXmlConfigLoader, counter);
<add> EasyMock.reset(cinderellaConfig, cinderellaXmlConfigLoader, counter);
<add> }
<add>
<add> @Test
<add> public void testConfigException() throws Exception {
<add>
<add> CinderellaConfig cinderellaConfig = EasyMock.createMock(CinderellaConfig.class);
<add> MockHttpServletRequest request = createMockHttpServletRequest();
<add>
<add> //Init
<add> EasyMock.expect(counter.isWhitelisted("SESSION_ID")).andReturn(false);
<add> EasyMock.expect(counter.isBlacklisted("SESSION_ID")).andReturn(false);
<add> EasyMock.expect(counter.isBlacklisted("127.0.0.1")).andReturn(false);
<add> EasyMock.expect(cinderellaXmlConfigLoader.getCinderellaConfig()).andThrow(new IOException());
<add>
<add> //Test
<add> EasyMock.replay(cinderellaConfig, cinderellaXmlConfigLoader, counter);
<add> assertFalse(ddosService.isDdos(request));
<add> EasyMock.verify(cinderellaConfig, cinderellaXmlConfigLoader, counter);
<add> EasyMock.reset(cinderellaConfig, cinderellaXmlConfigLoader, counter);
<add> }
<add>
<add> @Test
<add> public void testNoMatch() throws Exception {
<add>
<add> CinderellaConfig cinderellaConfig = EasyMock.createMock(CinderellaConfig.class);
<add> MockHttpServletRequest request = createMockHttpServletRequest();
<add>
<add> //Init
<add> EasyMock.expect(counter.isWhitelisted("SESSION_ID")).andReturn(false);
<add> EasyMock.expect(counter.isBlacklisted("SESSION_ID")).andReturn(false);
<add> EasyMock.expect(counter.isBlacklisted("127.0.0.1")).andReturn(false);
<add> EasyMock.expect(cinderellaXmlConfigLoader.getCinderellaConfig()).andReturn(cinderellaConfig);
<add> EasyMock.expect(cinderellaConfig.getMatches(request)).andReturn(Collections.emptyList());
<add>
<add> //Test
<add> EasyMock.replay(cinderellaConfig, cinderellaXmlConfigLoader, counter);
<add> assertFalse(ddosService.isDdos(request));
<add> EasyMock.verify(cinderellaConfig, cinderellaXmlConfigLoader, counter);
<add> EasyMock.reset(cinderellaConfig, cinderellaXmlConfigLoader, counter);
<add> }
<add>
<add> @Test
<add> public void testNoDDos() throws Exception {
<add>
<add> CinderellaConfig cinderellaConfig = EasyMock.createMock(CinderellaConfig.class);
<add> MockHttpServletRequest request = createMockHttpServletRequest();
<add> assertEquals("SESSION_ID", request.getSession().getId());
<add>
<add> //Init
<add> EasyMock.expect(counter.isWhitelisted("SESSION_ID")).andReturn(false);
<add> EasyMock.expect(counter.isBlacklisted("SESSION_ID")).andReturn(false);
<add> EasyMock.expect(counter.isBlacklisted("127.0.0.1")).andReturn(false);
<add> EasyMock.expect(cinderellaXmlConfigLoader.getCinderellaConfig()).andReturn(cinderellaConfig);
<add> EasyMock.expect(cinderellaConfig.getMatches(request)).andReturn(Arrays.asList(rule));
<add> EasyMock.expect(counter.checkCount("127.0.0.1_id", 2, TimeUnit.MINUTES, 5)).andReturn(false);
<add>
<add> //Test
<add> EasyMock.replay(cinderellaConfig, cinderellaXmlConfigLoader, counter);
<add> assertFalse(ddosService.isDdos(request));
<add> EasyMock.verify(cinderellaConfig, cinderellaXmlConfigLoader, counter);
<add> EasyMock.reset(cinderellaConfig, cinderellaXmlConfigLoader, counter);
<add> }
<add>
<add> @Test
<add> public void testSetBlacklist() throws Exception {
<add>
<add> CinderellaConfig cinderellaConfig = EasyMock.createMock(CinderellaConfig.class);
<add> MockHttpServletRequest request = createMockHttpServletRequest();
<add>
<add> //Init
<add> EasyMock.expect(cinderellaConfig.getBlacklistMinutes()).andReturn(1L);
<add>
<add> EasyMock.expect(counter.isWhitelisted("SESSION_ID")).andReturn(false);
<add> EasyMock.expect(counter.isBlacklisted("SESSION_ID")).andReturn(false);
<add> EasyMock.expect(counter.isBlacklisted("127.0.0.1")).andReturn(false);
<add> EasyMock.expect(cinderellaXmlConfigLoader.getCinderellaConfig()).andReturn(cinderellaConfig);
<add> EasyMock.expect(cinderellaConfig.getMatches(request)).andReturn(Arrays.asList(rule));
<add> EasyMock.expect(counter.checkCount("127.0.0.1_id", 2, TimeUnit.MINUTES, 5)).andReturn(true);
<add> counter.blacklist("127.0.0.1", TimeUnit.MINUTES, 1);
<add>
<add> //Test
<add> EasyMock.replay(cinderellaConfig, cinderellaXmlConfigLoader, counter);
<add> assertTrue(ddosService.isDdos(request));
<add> EasyMock.verify(cinderellaConfig, cinderellaXmlConfigLoader, counter);
<add> EasyMock.reset(cinderellaConfig, cinderellaXmlConfigLoader, counter);
<add> }
<add>
<add> private MockHttpServletRequest createMockHttpServletRequest() {
<add> MockHttpSession session = new MockHttpSession(null, "SESSION_ID");
<add>
<add> MockHttpServletRequest request = new MockHttpServletRequest();
<add> request.setSession(session);
<add> return request;
<add> }
<add>
<add> @BeforeMethod
<add> public void setUp() throws Exception {
<add> EasyMock.reset(cinderellaXmlConfigLoader, counter);
<add> }
<add>
<add> @Configuration
<add> static class Config {
<add>
<add> @Bean
<add> CinderellaServiceImpl ddosService() {
<add> return new CinderellaServiceImpl();
<add> }
<add>
<add> @Bean
<add> CinderellaXmlConfigLoader ddosXmlConfigLoader() {
<add> return EasyMock.createMock(CinderellaXmlConfigLoader.class);
<add> }
<add>
<add> @Bean
<add> Counter counter() {
<add> return EasyMock.createMock(Counter.class);
<add> }
<add> }
<add>} |
|
Java | apache-2.0 | b7f9a4b864f0e093618f1791de5b626db5e6a3cf | 0 | apache/syncope,apache/syncope,apache/syncope,ilgrosso/syncope,apache/syncope,ilgrosso/syncope,ilgrosso/syncope,ilgrosso/syncope | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.syncope.client.console.wizards.any;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.syncope.client.console.SyncopeConsoleSession;
import org.apache.syncope.client.console.commons.SchemaUtils;
import org.apache.syncope.client.console.wicket.ajax.markup.html.LabelInfo;
import org.apache.syncope.client.console.wicket.markup.html.bootstrap.tabs.Accordion;
import org.apache.syncope.client.console.wicket.markup.html.form.AbstractFieldPanel;
import org.apache.syncope.client.console.wicket.markup.html.form.AjaxCheckBoxPanel;
import org.apache.syncope.client.console.wicket.markup.html.form.AjaxDropDownChoicePanel;
import org.apache.syncope.client.console.wicket.markup.html.form.AjaxSpinnerFieldPanel;
import org.apache.syncope.client.console.wicket.markup.html.form.AjaxTextFieldPanel;
import org.apache.syncope.client.console.wicket.markup.html.form.BinaryFieldPanel;
import org.apache.syncope.client.console.wicket.markup.html.form.AjaxDateFieldPanel;
import org.apache.syncope.client.console.wicket.markup.html.form.AjaxDateTimeFieldPanel;
import org.apache.syncope.client.console.wicket.markup.html.form.EncryptedFieldPanel;
import org.apache.syncope.client.console.wicket.markup.html.form.FieldPanel;
import org.apache.syncope.client.console.wicket.markup.html.form.MultiFieldPanel;
import org.apache.syncope.client.console.wizards.AjaxWizard;
import org.apache.syncope.common.lib.EntityTOUtils;
import org.apache.syncope.common.lib.SyncopeConstants;
import org.apache.syncope.common.lib.to.AnyObjectTO;
import org.apache.syncope.common.lib.to.AnyTO;
import org.apache.syncope.common.lib.to.AttrTO;
import org.apache.syncope.common.lib.to.GroupTO;
import org.apache.syncope.common.lib.to.GroupableRelatableTO;
import org.apache.syncope.common.lib.to.MembershipTO;
import org.apache.syncope.common.lib.to.PlainSchemaTO;
import org.apache.syncope.common.lib.to.UserTO;
import org.apache.syncope.common.lib.types.AttrSchemaType;
import org.apache.syncope.common.lib.types.SchemaType;
import org.apache.wicket.PageReference;
import org.apache.wicket.extensions.markup.html.tabs.AbstractTab;
import org.apache.wicket.extensions.markup.html.tabs.ITab;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.IChoiceRenderer;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.model.StringResourceModel;
import org.apache.wicket.model.util.ListModel;
public class PlainAttrs extends AbstractAttrs<PlainSchemaTO> {
private static final long serialVersionUID = 552437609667518888L;
protected final AjaxWizard.Mode mode;
protected final AnyTO previousObject;
protected String fileKey = "";
public <T extends AnyTO> PlainAttrs(
final AnyWrapper<T> modelObject,
final Form<?> form,
final AjaxWizard.Mode mode,
final List<String> anyTypeClasses,
final List<String> whichPlainAttrs) throws IllegalArgumentException {
super(modelObject, anyTypeClasses, whichPlainAttrs);
this.mode = mode;
if (modelObject.getInnerObject() instanceof UserTO) {
fileKey = UserTO.class.cast(modelObject.getInnerObject()).getUsername();
} else if (modelObject.getInnerObject() instanceof GroupTO) {
fileKey = GroupTO.class.cast(modelObject.getInnerObject()).getName();
} else if (modelObject.getInnerObject() instanceof AnyObjectTO) {
fileKey = AnyObjectTO.class.cast(modelObject.getInnerObject()).getName();
}
if (modelObject instanceof UserWrapper) {
previousObject = UserWrapper.class.cast(modelObject).getPreviousUserTO();
} else {
previousObject = null;
}
setTitleModel(new ResourceModel("attributes.plain"));
add(new Accordion("plainSchemas", Collections.<ITab>singletonList(new AbstractTab(
new ResourceModel("attributes.accordion", "Plain Attributes")) {
private static final long serialVersionUID = 1037272333056449378L;
@Override
public WebMarkupContainer getPanel(final String panelId) {
return new PlainSchemas(panelId, schemas, attrTOs);
}
}), Model.of(0)).setOutputMarkupId(true));
add(new ListView<MembershipTO>("membershipsPlainSchemas", membershipTOs) {
private static final long serialVersionUID = 1L;
@Override
protected void populateItem(final ListItem<MembershipTO> item) {
final MembershipTO membershipTO = item.getModelObject();
item.add(new Accordion("membershipPlainSchemas", Collections.<ITab>singletonList(new AbstractTab(
new StringResourceModel(
"attributes.membership.accordion",
PlainAttrs.this,
Model.of(membershipTO))) {
private static final long serialVersionUID = 1037272333056449378L;
@Override
public WebMarkupContainer getPanel(final String panelId) {
return new PlainSchemas(
panelId,
membershipSchemas.get(membershipTO.getGroupKey()),
new ListModel<>(getAttrsFromTO(membershipTO)));
}
}), Model.of(-1)).setOutputMarkupId(true));
}
});
}
@Override
protected SchemaType getSchemaType() {
return SchemaType.PLAIN;
}
@Override
protected boolean reoderSchemas() {
return super.reoderSchemas() && mode != AjaxWizard.Mode.TEMPLATE;
}
@Override
protected List<AttrTO> getAttrsFromTO() {
return anyTO.getPlainAttrs().stream().sorted(attrComparator).collect(Collectors.toList());
}
@Override
protected List<AttrTO> getAttrsFromTO(final MembershipTO membershipTO) {
return membershipTO.getPlainAttrs().stream().sorted(attrComparator).collect(Collectors.toList());
}
@Override
protected void setAttrs() {
List<AttrTO> attrs = new ArrayList<>();
Map<String, AttrTO> attrMap = EntityTOUtils.buildAttrMap(anyTO.getPlainAttrs());
attrs.addAll(schemas.values().stream().map(schema -> {
AttrTO attrTO = new AttrTO();
attrTO.setSchema(schema.getKey());
if (attrMap.get(schema.getKey()) == null || attrMap.get(schema.getKey()).getValues().isEmpty()) {
attrTO.getValues().add("");
} else {
attrTO = attrMap.get(schema.getKey());
}
return attrTO;
}).collect(Collectors.toList()));
anyTO.getPlainAttrs().clear();
anyTO.getPlainAttrs().addAll(attrs);
}
@Override
protected void setAttrs(final MembershipTO membershipTO) {
List<AttrTO> attrs = new ArrayList<>();
final Map<String, AttrTO> attrMap;
if (GroupableRelatableTO.class.cast(anyTO).getMembership(membershipTO.getGroupKey()).isPresent()) {
attrMap = EntityTOUtils.buildAttrMap(GroupableRelatableTO.class.cast(anyTO)
.getMembership(membershipTO.getGroupKey()).get().getPlainAttrs());
} else {
attrMap = new HashMap<>();
}
attrs.addAll(membershipSchemas.get(membershipTO.getGroupKey()).values().stream().
map(schema -> {
AttrTO attrTO = new AttrTO();
attrTO.setSchema(schema.getKey());
if (attrMap.get(schema.getKey()) == null || attrMap.get(schema.getKey()).getValues().isEmpty()) {
attrTO.getValues().add(StringUtils.EMPTY);
} else {
attrTO.getValues().addAll(attrMap.get(schema.getKey()).getValues());
}
return attrTO;
}).collect(Collectors.toList()));
membershipTO.getPlainAttrs().clear();
membershipTO.getPlainAttrs().addAll(attrs);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
protected FieldPanel getFieldPanel(final PlainSchemaTO schemaTO) {
final boolean required;
final boolean readOnly;
final AttrSchemaType type;
final boolean jexlHelp;
if (mode == AjaxWizard.Mode.TEMPLATE) {
required = false;
readOnly = false;
type = AttrSchemaType.String;
jexlHelp = true;
} else {
required = schemaTO.getMandatoryCondition().equalsIgnoreCase("true");
readOnly = schemaTO.isReadonly();
type = schemaTO.getType();
jexlHelp = false;
}
FieldPanel panel;
switch (type) {
case Boolean:
panel = new AjaxCheckBoxPanel(
"panel",
schemaTO.getLabel(SyncopeConsoleSession.get().getLocale()),
new Model<>(),
true);
panel.setRequired(required);
break;
case Date:
String datePattern = schemaTO.getConversionPattern() == null
? SyncopeConstants.DEFAULT_DATE_PATTERN
: schemaTO.getConversionPattern();
if (datePattern.contains("H")) {
panel = new AjaxDateTimeFieldPanel(
"panel",
schemaTO.getLabel(SyncopeConsoleSession.get().getLocale()),
new Model<>(),
datePattern);
} else {
panel = new AjaxDateFieldPanel(
"panel",
schemaTO.getLabel(SyncopeConsoleSession.get().getLocale()),
new Model<>(),
datePattern);
}
if (required) {
panel.addRequiredLabel();
}
break;
case Enum:
panel = new AjaxDropDownChoicePanel<>("panel",
schemaTO.getLabel(SyncopeConsoleSession.get().getLocale()), new Model<>(), true);
((AjaxDropDownChoicePanel<String>) panel).setChoices(SchemaUtils.getEnumeratedValues(schemaTO));
if (StringUtils.isNotBlank(schemaTO.getEnumerationKeys())) {
((AjaxDropDownChoicePanel) panel).setChoiceRenderer(new IChoiceRenderer<String>() {
private static final long serialVersionUID = -3724971416312135885L;
private final Map<String, String> valueMap = SchemaUtils.getEnumeratedKeyValues(schemaTO);
@Override
public String getDisplayValue(final String value) {
return valueMap.get(value) == null ? value : valueMap.get(value);
}
@Override
public String getIdValue(final String value, final int i) {
return value;
}
@Override
public String getObject(
final String id, final IModel<? extends List<? extends String>> choices) {
return id;
}
});
}
if (required) {
panel.addRequiredLabel();
}
break;
case Long:
panel = new AjaxSpinnerFieldPanel.Builder<Long>().enableOnChange().build(
"panel",
schemaTO.getLabel(SyncopeConsoleSession.get().getLocale()),
Long.class,
new Model<>());
if (required) {
panel.addRequiredLabel();
}
break;
case Double:
panel = new AjaxSpinnerFieldPanel.Builder<Double>().enableOnChange().step(0.1).build(
"panel",
schemaTO.getLabel(SyncopeConsoleSession.get().getLocale()),
Double.class,
new Model<>());
if (required) {
panel.addRequiredLabel();
}
break;
case Binary:
final PageReference pageRef = getPageReference();
panel = new BinaryFieldPanel(
"panel",
schemaTO.getLabel(SyncopeConsoleSession.get().getLocale()),
new Model<>(),
schemaTO.getMimeType(),
fileKey) {
private static final long serialVersionUID = -3268213909514986831L;
@Override
protected PageReference getPageReference() {
return pageRef;
}
};
if (required) {
panel.addRequiredLabel();
}
break;
case Encrypted:
panel = new EncryptedFieldPanel("panel",
schemaTO.getLabel(SyncopeConsoleSession.get().getLocale()), new Model<>(), true);
if (required) {
panel.addRequiredLabel();
}
break;
default:
panel = new AjaxTextFieldPanel("panel",
schemaTO.getLabel(SyncopeConsoleSession.get().getLocale()), new Model<>(), true);
if (jexlHelp) {
AjaxTextFieldPanel.class.cast(panel).enableJexlHelp();
}
if (required) {
panel.addRequiredLabel();
}
}
panel.setReadOnly(readOnly);
return panel;
}
public class PlainSchemas extends Schemas {
private static final long serialVersionUID = -4730563859116024676L;
public PlainSchemas(
final String id,
final Map<String, PlainSchemaTO> schemas,
final IModel<List<AttrTO>> attrTOs) {
super(id);
add(new ListView<AttrTO>("schemas", attrTOs) {
private static final long serialVersionUID = 9101744072914090143L;
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
protected void populateItem(final ListItem<AttrTO> item) {
AttrTO attrTO = item.getModelObject();
AbstractFieldPanel<?> panel = getFieldPanel(schemas.get(attrTO.getSchema()));
if (mode == AjaxWizard.Mode.TEMPLATE
|| !schemas.get(attrTO.getSchema()).isMultivalue()) {
FieldPanel.class.cast(panel).setNewModel(attrTO.getValues());
} else {
panel = new MultiFieldPanel.Builder<>(
new PropertyModel<>(attrTO, "values")).build(
"panel",
attrTO.getSchema(),
FieldPanel.class.cast(panel));
// SYNCOPE-1215 the entire multifield panel must be readonly, not only its field
((MultiFieldPanel) panel).setReadOnly(schemas.get(attrTO.getSchema()).isReadonly());
}
item.add(panel);
Optional<AttrTO> previousPlainAttr = previousObject.getPlainAttr(attrTO.getSchema());
if (previousObject != null
&& ((!previousPlainAttr.isPresent() && !isEmptyOrBlank(attrTO.getValues()))
|| (previousPlainAttr.isPresent() && !ListUtils.isEqualList(
ListUtils.select(previousPlainAttr.get().getValues(),
object -> StringUtils.isNotEmpty(object)),
ListUtils.select(attrTO.getValues(), object -> StringUtils.isNotEmpty(object)))))) {
List<String> oldValues = !previousPlainAttr.isPresent()
? Collections.<String>emptyList()
: previousPlainAttr.get().getValues();
panel.showExternAction(new LabelInfo("externalAction", oldValues));
}
}
protected boolean isEmptyOrBlank(final List<String> values) {
return values.stream().allMatch(value -> StringUtils.isBlank(value));
}
});
}
}
}
| client/console/src/main/java/org/apache/syncope/client/console/wizards/any/PlainAttrs.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.syncope.client.console.wizards.any;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.syncope.client.console.SyncopeConsoleSession;
import org.apache.syncope.client.console.commons.SchemaUtils;
import org.apache.syncope.client.console.wicket.ajax.markup.html.LabelInfo;
import org.apache.syncope.client.console.wicket.markup.html.bootstrap.tabs.Accordion;
import org.apache.syncope.client.console.wicket.markup.html.form.AbstractFieldPanel;
import org.apache.syncope.client.console.wicket.markup.html.form.AjaxCheckBoxPanel;
import org.apache.syncope.client.console.wicket.markup.html.form.AjaxDropDownChoicePanel;
import org.apache.syncope.client.console.wicket.markup.html.form.AjaxSpinnerFieldPanel;
import org.apache.syncope.client.console.wicket.markup.html.form.AjaxTextFieldPanel;
import org.apache.syncope.client.console.wicket.markup.html.form.BinaryFieldPanel;
import org.apache.syncope.client.console.wicket.markup.html.form.AjaxDateFieldPanel;
import org.apache.syncope.client.console.wicket.markup.html.form.AjaxDateTimeFieldPanel;
import org.apache.syncope.client.console.wicket.markup.html.form.EncryptedFieldPanel;
import org.apache.syncope.client.console.wicket.markup.html.form.FieldPanel;
import org.apache.syncope.client.console.wicket.markup.html.form.MultiFieldPanel;
import org.apache.syncope.client.console.wizards.AjaxWizard;
import org.apache.syncope.common.lib.EntityTOUtils;
import org.apache.syncope.common.lib.SyncopeConstants;
import org.apache.syncope.common.lib.to.AnyObjectTO;
import org.apache.syncope.common.lib.to.AnyTO;
import org.apache.syncope.common.lib.to.AttrTO;
import org.apache.syncope.common.lib.to.GroupTO;
import org.apache.syncope.common.lib.to.GroupableRelatableTO;
import org.apache.syncope.common.lib.to.MembershipTO;
import org.apache.syncope.common.lib.to.PlainSchemaTO;
import org.apache.syncope.common.lib.to.UserTO;
import org.apache.syncope.common.lib.types.AttrSchemaType;
import org.apache.syncope.common.lib.types.SchemaType;
import org.apache.wicket.PageReference;
import org.apache.wicket.extensions.markup.html.tabs.AbstractTab;
import org.apache.wicket.extensions.markup.html.tabs.ITab;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.IChoiceRenderer;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.model.StringResourceModel;
import org.apache.wicket.model.util.ListModel;
public class PlainAttrs extends AbstractAttrs<PlainSchemaTO> {
private static final long serialVersionUID = 552437609667518888L;
protected final AjaxWizard.Mode mode;
protected final AnyTO previousObject;
protected String fileKey = "";
public <T extends AnyTO> PlainAttrs(
final AnyWrapper<T> modelObject,
final Form<?> form,
final AjaxWizard.Mode mode,
final List<String> anyTypeClasses,
final List<String> whichPlainAttrs) throws IllegalArgumentException {
super(modelObject, anyTypeClasses, whichPlainAttrs);
this.mode = mode;
if (modelObject.getInnerObject() instanceof UserTO) {
fileKey = UserTO.class.cast(modelObject.getInnerObject()).getUsername();
} else if (modelObject.getInnerObject() instanceof GroupTO) {
fileKey = GroupTO.class.cast(modelObject.getInnerObject()).getName();
} else if (modelObject.getInnerObject() instanceof AnyObjectTO) {
fileKey = AnyObjectTO.class.cast(modelObject.getInnerObject()).getName();
}
if (modelObject instanceof UserWrapper) {
previousObject = UserWrapper.class.cast(modelObject).getPreviousUserTO();
} else {
previousObject = null;
}
setTitleModel(new ResourceModel("attributes.plain"));
add(new Accordion("plainSchemas", Collections.<ITab>singletonList(new AbstractTab(
new ResourceModel("attributes.accordion", "Plain Attributes")) {
private static final long serialVersionUID = 1037272333056449378L;
@Override
public WebMarkupContainer getPanel(final String panelId) {
return new PlainSchemas(panelId, schemas, attrTOs);
}
}), Model.of(0)).setOutputMarkupId(true));
add(new ListView<MembershipTO>("membershipsPlainSchemas", membershipTOs) {
private static final long serialVersionUID = 1L;
@Override
protected void populateItem(final ListItem<MembershipTO> item) {
final MembershipTO membershipTO = item.getModelObject();
item.add(new Accordion("membershipPlainSchemas", Collections.<ITab>singletonList(new AbstractTab(
new StringResourceModel(
"attributes.membership.accordion",
PlainAttrs.this,
Model.of(membershipTO))) {
private static final long serialVersionUID = 1037272333056449378L;
@Override
public WebMarkupContainer getPanel(final String panelId) {
return new PlainSchemas(
panelId,
membershipSchemas.get(membershipTO.getGroupKey()),
new ListModel<>(getAttrsFromTO(membershipTO)));
}
}), Model.of(-1)).setOutputMarkupId(true));
}
});
}
@Override
protected SchemaType getSchemaType() {
return SchemaType.PLAIN;
}
@Override
protected boolean reoderSchemas() {
return super.reoderSchemas() && mode != AjaxWizard.Mode.TEMPLATE;
}
@Override
protected List<AttrTO> getAttrsFromTO() {
return anyTO.getPlainAttrs().stream().sorted(attrComparator).collect(Collectors.toList());
}
@Override
protected List<AttrTO> getAttrsFromTO(final MembershipTO membershipTO) {
return membershipTO.getPlainAttrs().stream().sorted(attrComparator).collect(Collectors.toList());
}
@Override
protected void setAttrs() {
List<AttrTO> attrs = new ArrayList<>();
Map<String, AttrTO> attrMap = EntityTOUtils.buildAttrMap(anyTO.getPlainAttrs());
attrs.addAll(schemas.values().stream().map(schema -> {
AttrTO attrTO = new AttrTO();
attrTO.setSchema(schema.getKey());
if (attrMap.get(schema.getKey()) == null || attrMap.get(schema.getKey()).getValues().isEmpty()) {
attrTO.getValues().add("");
} else {
attrTO = attrMap.get(schema.getKey());
}
return attrTO;
}).collect(Collectors.toList()));
anyTO.getPlainAttrs().clear();
anyTO.getPlainAttrs().addAll(attrs);
}
@Override
protected void setAttrs(final MembershipTO membershipTO) {
List<AttrTO> attrs = new ArrayList<>();
final Map<String, AttrTO> attrMap;
if (GroupableRelatableTO.class.cast(anyTO).getMembership(membershipTO.getGroupKey()).isPresent()) {
attrMap = EntityTOUtils.buildAttrMap(GroupableRelatableTO.class.cast(anyTO)
.getMembership(membershipTO.getGroupKey()).get().getPlainAttrs());
} else {
attrMap = new HashMap<>();
}
attrs.addAll(membershipSchemas.get(membershipTO.getGroupKey()).values().stream().
map(schema -> {
AttrTO attrTO = new AttrTO();
attrTO.setSchema(schema.getKey());
if (attrMap.get(schema.getKey()) == null || attrMap.get(schema.getKey()).getValues().isEmpty()) {
attrTO.getValues().add(StringUtils.EMPTY);
} else {
attrTO.getValues().addAll(attrMap.get(schema.getKey()).getValues());
}
return attrTO;
}).collect(Collectors.toList()));
membershipTO.getPlainAttrs().clear();
membershipTO.getPlainAttrs().addAll(attrs);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
protected FieldPanel getFieldPanel(final PlainSchemaTO schemaTO) {
final boolean required;
final boolean readOnly;
final AttrSchemaType type;
final boolean jexlHelp;
if (mode == AjaxWizard.Mode.TEMPLATE) {
required = false;
readOnly = false;
type = AttrSchemaType.String;
jexlHelp = true;
} else {
required = schemaTO.getMandatoryCondition().equalsIgnoreCase("true");
readOnly = schemaTO.isReadonly();
type = schemaTO.getType();
jexlHelp = false;
}
FieldPanel panel;
switch (type) {
case Boolean:
panel = new AjaxCheckBoxPanel(
"panel",
schemaTO.getLabel(SyncopeConsoleSession.get().getLocale()),
new Model<>(),
true);
panel.setRequired(required);
break;
case Date:
String datePattern = schemaTO.getConversionPattern() == null
? SyncopeConstants.DEFAULT_DATE_PATTERN
: schemaTO.getConversionPattern();
if (datePattern.contains("H")) {
panel = new AjaxDateTimeFieldPanel(
"panel",
schemaTO.getLabel(SyncopeConsoleSession.get().getLocale()),
new Model<>(),
datePattern);
} else {
panel = new AjaxDateFieldPanel(
"panel",
schemaTO.getLabel(SyncopeConsoleSession.get().getLocale()),
new Model<>(),
datePattern);
}
if (required) {
panel.addRequiredLabel();
}
break;
case Enum:
panel = new AjaxDropDownChoicePanel<>("panel",
schemaTO.getLabel(SyncopeConsoleSession.get().getLocale()), new Model<>(), true);
((AjaxDropDownChoicePanel<String>) panel).setChoices(SchemaUtils.getEnumeratedValues(schemaTO));
if (StringUtils.isNotBlank(schemaTO.getEnumerationKeys())) {
((AjaxDropDownChoicePanel) panel).setChoiceRenderer(new IChoiceRenderer<String>() {
private static final long serialVersionUID = -3724971416312135885L;
private final Map<String, String> valueMap = SchemaUtils.getEnumeratedKeyValues(schemaTO);
@Override
public String getDisplayValue(final String value) {
return valueMap.get(value) == null ? value : valueMap.get(value);
}
@Override
public String getIdValue(final String value, final int i) {
return value;
}
@Override
public String getObject(
final String id, final IModel<? extends List<? extends String>> choices) {
return id;
}
});
}
if (required) {
panel.addRequiredLabel();
}
break;
case Long:
panel = new AjaxSpinnerFieldPanel.Builder<Long>().enableOnChange().build(
"panel",
schemaTO.getLabel(SyncopeConsoleSession.get().getLocale()),
Long.class,
new Model<>());
if (required) {
panel.addRequiredLabel();
}
break;
case Double:
panel = new AjaxSpinnerFieldPanel.Builder<Double>().enableOnChange().step(0.1).build(
"panel",
schemaTO.getLabel(SyncopeConsoleSession.get().getLocale()),
Double.class,
new Model<>());
if (required) {
panel.addRequiredLabel();
}
break;
case Binary:
final PageReference pageRef = getPageReference();
panel = new BinaryFieldPanel(
"panel",
schemaTO.getLabel(SyncopeConsoleSession.get().getLocale()),
new Model<>(),
schemaTO.getMimeType(),
fileKey) {
private static final long serialVersionUID = -3268213909514986831L;
@Override
protected PageReference getPageReference() {
return pageRef;
}
};
if (required) {
panel.addRequiredLabel();
}
break;
case Encrypted:
panel = new EncryptedFieldPanel("panel",
schemaTO.getLabel(SyncopeConsoleSession.get().getLocale()), new Model<>(), true);
if (required) {
panel.addRequiredLabel();
}
break;
default:
panel = new AjaxTextFieldPanel("panel",
schemaTO.getLabel(SyncopeConsoleSession.get().getLocale()), new Model<>(), true);
if (jexlHelp) {
AjaxTextFieldPanel.class.cast(panel).enableJexlHelp();
}
if (required) {
panel.addRequiredLabel();
}
}
panel.setReadOnly(readOnly);
return panel;
}
public class PlainSchemas extends Schemas {
private static final long serialVersionUID = -4730563859116024676L;
public PlainSchemas(
final String id,
final Map<String, PlainSchemaTO> schemas,
final IModel<List<AttrTO>> attrTOs) {
super(id);
add(new ListView<AttrTO>("schemas", attrTOs) {
private static final long serialVersionUID = 9101744072914090143L;
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
protected void populateItem(final ListItem<AttrTO> item) {
AttrTO attrTO = item.getModelObject();
AbstractFieldPanel<?> panel = getFieldPanel(schemas.get(attrTO.getSchema()));
if (mode == AjaxWizard.Mode.TEMPLATE
|| !schemas.get(attrTO.getSchema()).isMultivalue()) {
FieldPanel.class.cast(panel).setNewModel(attrTO.getValues());
} else {
panel = new MultiFieldPanel.Builder<>(
new PropertyModel<>(attrTO, "values")).build(
"panel",
attrTO.getSchema(),
FieldPanel.class.cast(panel));
// SYNCOPE-1215 the entire multifield panel must be readonly, not only its field
((MultiFieldPanel) panel).setReadOnly(schemas.get(attrTO.getSchema()).isReadonly());
}
item.add(panel);
if (previousObject != null
&& (previousObject.getPlainAttr(attrTO.getSchema()) == null
|| !ListUtils.isEqualList(
ListUtils.select(previousObject.getPlainAttr(attrTO.getSchema()).get().getValues(),
object -> StringUtils.isNotEmpty(object)),
ListUtils.select(attrTO.getValues(), object -> StringUtils.isNotEmpty(object))))) {
List<String> oldValues = previousObject.getPlainAttr(attrTO.getSchema()) == null
? Collections.<String>emptyList()
: previousObject.getPlainAttr(attrTO.getSchema()).get().getValues();
panel.showExternAction(new LabelInfo("externalAction", oldValues));
}
}
});
}
}
}
| [SYNCOPE-1397] Now plain attributes are shown in approval, removed unwanted changed flags on empty attributes
| client/console/src/main/java/org/apache/syncope/client/console/wizards/any/PlainAttrs.java | [SYNCOPE-1397] Now plain attributes are shown in approval, removed unwanted changed flags on empty attributes | <ide><path>lient/console/src/main/java/org/apache/syncope/client/console/wizards/any/PlainAttrs.java
<ide> import java.util.HashMap;
<ide> import java.util.List;
<ide> import java.util.Map;
<add>import java.util.Optional;
<ide> import java.util.stream.Collectors;
<ide> import org.apache.commons.collections4.ListUtils;
<ide> import org.apache.commons.lang3.StringUtils;
<ide> ((MultiFieldPanel) panel).setReadOnly(schemas.get(attrTO.getSchema()).isReadonly());
<ide> }
<ide> item.add(panel);
<add> Optional<AttrTO> previousPlainAttr = previousObject.getPlainAttr(attrTO.getSchema());
<ide>
<ide> if (previousObject != null
<del> && (previousObject.getPlainAttr(attrTO.getSchema()) == null
<del> || !ListUtils.isEqualList(
<del> ListUtils.select(previousObject.getPlainAttr(attrTO.getSchema()).get().getValues(),
<del> object -> StringUtils.isNotEmpty(object)),
<del> ListUtils.select(attrTO.getValues(), object -> StringUtils.isNotEmpty(object))))) {
<del>
<del> List<String> oldValues = previousObject.getPlainAttr(attrTO.getSchema()) == null
<add> && ((!previousPlainAttr.isPresent() && !isEmptyOrBlank(attrTO.getValues()))
<add> || (previousPlainAttr.isPresent() && !ListUtils.isEqualList(
<add> ListUtils.select(previousPlainAttr.get().getValues(),
<add> object -> StringUtils.isNotEmpty(object)),
<add> ListUtils.select(attrTO.getValues(), object -> StringUtils.isNotEmpty(object)))))) {
<add>
<add> List<String> oldValues = !previousPlainAttr.isPresent()
<ide> ? Collections.<String>emptyList()
<del> : previousObject.getPlainAttr(attrTO.getSchema()).get().getValues();
<add> : previousPlainAttr.get().getValues();
<ide> panel.showExternAction(new LabelInfo("externalAction", oldValues));
<ide> }
<ide> }
<add>
<add> protected boolean isEmptyOrBlank(final List<String> values) {
<add> return values.stream().allMatch(value -> StringUtils.isBlank(value));
<add> }
<ide> });
<ide> }
<ide> } |
|
Java | mit | f30829e60dc7686e47dd4dc2c3aebbc07d8a93f3 | 0 | k-danna/backupbuddies,k-danna/backupbuddies | package backupbuddies.gui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
import java.io.File;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.HashMap;
import java.lang.*;
import backupbuddies.gui.ListModel;
import backupbuddies.shared.IInterface;
import static backupbuddies.Debug.*;
@SuppressWarnings("serial")
public class GuiMain extends JFrame {
//colors
//static final Color colorBlue = new Color(53, 129, 184);
static final Color colorBlue = new Color(80, 80, 80);
static final Color textColor = new Color(220, 220, 220);
static final Color buttonTextColor = new Color(40, 40, 40);
static final Color listColor = new Color(255, 255, 255);
static final Color backgroundColor = new Color(92, 146, 194);
static final Color colorGray = new Color(20, 20, 20);
static final Font font = new Font("Papyrus", Font.BOLD, 18);
//load assets, lists etc before creating the gui
static JFrame frame = new JFrame("BackupBuddies");
static JTextField saveDir = new JTextField();
static final DefaultListModel<String> userModel = new DefaultListModel<String>();
static final DefaultListModel<String> fileModel = new DefaultListModel<String>();
static final DefaultListModel<ListModel> files = new DefaultListModel<ListModel>();
static DefaultListModel<ListModel> filetest = new DefaultListModel<ListModel>();
static DefaultListModel<ListModel> usertest = new DefaultListModel<ListModel>();
static JList<ListModel> allFiles = new JList<ListModel>();
static JList<ListModel> allUsers = new JList<ListModel>();
//holds the all indices selected by the user
static DefaultListModel<String> lastFileState = new DefaultListModel<String>();
static DefaultListModel<String> lastUserState = new DefaultListModel<String>();
static DefaultListModel<ListModel> debug = new DefaultListModel<ListModel>();
static final JTextArea log = new JTextArea(6, 20);
static List<String> prevEvents = new ArrayList<>();
static ImageIcon statusRed = new ImageIcon("bin/backupbuddies/gui/assets/RedderCircle.png");
static ImageIcon statusYellow = new ImageIcon("bin/backupbuddies/backupbuddies/gui/assets/YellowerCircle.png");
static ImageIcon statusGreen = new ImageIcon("bin/backupbuddies/backupbuddies/gui/assets/GreenerCircle.png");
static JList<ListModel> userMap = fetchAndProcess("users");
static JList<ListModel> fileMap = fetchAndProcess("files");
static boolean firstSearch = false;
static String globalSearch = "";
//populate the window
static Container contentPane = frame.getContentPane();
static JPanel loginPanel = loginPanel();
static JPanel controlPanel = controlPanel();
static JScrollPane userListPanel = userListPanel();
static JScrollPane fileListPanel = fileListPanel("");
static JPanel selectUsersPanel = selectUsersPanel();
static JPanel selectFilesPanel = selectFilesPanel();
static JPanel searchPanel = searchPanel();
static JPanel varsPanel = varsPanel();
static JPanel storagePanel = storagePanel();
static JPanel logPanel = logPanel();
static JPanel namePanel = namePanel();
static Map<Component, List<Integer>> panelLocs = new HashMap<Component, List<Integer>>();
//process lists returned from networking
//NOTE: to speed this up we can just do it in the interface methods
//iteration already occurs there
public static JList<ListModel> fetchAndProcess(String type) {
//get data
JList<ListModel> map = new JList<ListModel>();
//debug = new DefaultListModel<>();
if (type.equals("users")) debug = IInterface.INSTANCE.fetchUserList();
else if (type.equals("files")) debug = IInterface.INSTANCE.fetchFileList();
return map;
}
//updates ui on interval
public static void startIntervals(int interval) {
ActionListener updateUI = new ActionListener() {
public void actionPerformed(ActionEvent e) {
IInterface.INSTANCE.saveNetwork();
userMap = fetchAndProcess("users");
fileMap = fetchAndProcess("files");
updateFileSelection();
updateUserSelection();
fileSearch(globalSearch);
if(firstSearch == false){
fileSearch("");
firstSearch = true;
}
int[] selected = new int[lastFileState.getSize()];
for(int i=0; i<lastFileState.getSize(); i++){
selected[i] = Integer.parseInt(lastFileState.getElementAt(i));
}
allFiles.setSelectedIndices(selected);
// fileSearch(globalSearch);
//FIXME: this gets slower as more events are added
//prevArray --> int (length of last returned array)
//change to check length of returned array
//append the last (len(events) - prevLength) elements to log
//if this is negative they cleared the event log
//only reset prevArraysize variable
List<String> events = IInterface.INSTANCE.getEventLog();
log.setText("");
for (String event : events) {
log.append(event + "\n");
log.setCaretPosition(log.getDocument().getLength());
}
prevEvents = events;
}
};
Timer timer = new Timer(interval, updateUI);
timer.setRepeats(true);
timer.start();
}
//user chooses directory to save to
public static void setSaveDir() {
JFileChooser browser = new JFileChooser();
browser.setDialogTitle("choose save location");
browser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
browser.setAcceptAllFileFilterUsed(false);
if (browser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
saveDir.setText(browser.getSelectedFile().toString());
IInterface.INSTANCE.setStoragePath(saveDir.getText());
}
}
//user selects a file and it uploads to network
public static void chooseAndUpload() {
JFileChooser browser = new JFileChooser();
browser.setMultiSelectionEnabled(true);
browser.setDialogTitle("choose files to upload");
if (browser.showOpenDialog(frame) ==
JFileChooser.APPROVE_OPTION) {
//File[] files = browser.getSelectedFiles();
//for (File f : files) {
// System.out.printf("%s\n", f.toPath());
//}
int[] selected = allUsers.getSelectedIndices();
for( int i=0; i<selected.length; i++){
IInterface.INSTANCE.uploadFile(browser.getSelectedFiles(),
allUsers.getModel().getElementAt(selected[i]).getName());
}
}
//fileSearch("");
}
//user downloads a file to save directory (and chooses if not set)
public static void setDirAndDownload() {
//FIXME: need to have a list of uploaded files to choose from
//String fileToGet = "test.txt";
if (saveDir.getText().equals("")) {
setSaveDir();
}
int[] selected = allFiles.getSelectedIndices();
for(int i=0; i<selected.length; i++){
//System.out.printf("Index: %d %s\n", i, hi.getModel().getElementAt(selected[i]).getName());
IInterface.INSTANCE.downloadFile(allFiles.getModel().getElementAt(selected[i]).getName(), saveDir.getText());
}
}
//upload, download, save control buttons
public static JPanel controlPanel() {
//create panel
JFrame failedUpload = new JFrame();
JPanel controlPanel = new JPanel();
GridLayout layout = new GridLayout(2, 1, 0, 10);
controlPanel.setLayout(layout);
//create components
JLabel fileLabel = new JLabel("backup your files");
JButton uploadButton = new JButton("upload");
JButton downloadButton = new JButton("download");
JButton pathButton = new JButton("save to...");
downloadButton.setForeground(buttonTextColor);
uploadButton.setForeground(buttonTextColor);
//set button colors
//uploadButton.setForeground(colorGreen); //text color
//uploadButton.setBackground(Color.GRAY);
//uploadButton.setContentAreaFilled(false);
//uploadButton.setOpaque(true);
//bind methods to buttons
uploadButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (allUsers.getSelectedIndex() == -1){
String upError = "Please select at least one user\n";
System.out.printf(upError);
JOptionPane.showMessageDialog(failedUpload, upError);
}else{
chooseAndUpload();
}
}
});
pathButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setSaveDir();
}
});
downloadButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setDirAndDownload();
}
});
//add components to panel and specify orientation
controlPanel.setPreferredSize(new Dimension(250, 150));
//controlPanel.add(fileLabel);
controlPanel.add(uploadButton);
controlPanel.add(downloadButton);
//controlPanel.add(pathButton);
//controlPanel.setComponentOrientation(
// ComponentOrientation.LEFT_TO_RIGHT);
return controlPanel;
}
//allows user to input ip and pass and connect to network
public static JPanel loginPanel() {
//create panel
final JPanel loginPanel = new JPanel();
BoxLayout layout = new BoxLayout(loginPanel, BoxLayout.Y_AXIS);
loginPanel.setLayout(layout);
//create components
final JLabel loginLabel = new JLabel("Join a Network:");
final JButton loginButton = new JButton("Join");
final JTextField ipField = new JTextField("network ip...", 21);
final JTextField passField = new JTextField("network password...");
ipField.setEnabled(false);
passField.setEnabled(false);
ipField.setBackground(listColor);
passField.setBackground(listColor);
loginButton.setForeground(buttonTextColor);
//bind methods to buttons
loginButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
IInterface.INSTANCE.login(ipField.getText(), passField.getText());
}
});
ipField.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
ipField.setText("");
ipField.setEnabled(true);
ipField.requestFocus();
}
});
passField.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
passField.setText("");
passField.setEnabled(true);
passField.requestFocus();
}
});
// loginButton.setBorder(new RoundedBorder(10));
//add components to panel and specify orientation
// loginButton.setOpaque(false);
// loginButton.setBorderPainted(false);
// loginButton.setFocusPainted(false);
//loginButton.setForeground(Color.BLUE);
//loginButton.setBorder(BorderFactory.createEmptyBorder(1,1,1,1));
loginLabel.setForeground(textColor);
loginLabel.setFont(font);
loginPanel.add(loginLabel);
loginPanel.add(ipField);
loginPanel.add(passField);
loginPanel.add(loginButton);
return loginPanel;
}
//list of peers in the network
//TODO: multiple selection
//TODO: renders images
public static JScrollPane userListPanel() {
usertest = (IInterface.INSTANCE.fetchUserList());
allUsers.setModel(usertest);
allUsers.addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent e){
int selectedItem = allUsers.getSelectedIndex();
lastUserState.addElement(Integer.toString(selectedItem));
}
});
allUsers.setCellRenderer(new ListRenderer());
JScrollPane pane = new JScrollPane(allUsers);
pane.setPreferredSize(new Dimension(250, 440));
//allUsers.setSelectionBackground(Color.green);
allUsers.setBackground(listColor);
return pane;
}
//list of files you can recover
//TODO: multiple selection
//TODO: renders images
public static JScrollPane fileListPanel(String search) {
filetest = (IInterface.INSTANCE.fetchFileList());
//allFiles.setModel(filetest);
allFiles.setModel(files);
for(int i=0; i< files.size(); i++){
System.out.printf("%s\n", files.getElementAt(i));
}
/*for(int i=0; i< filetest.size(); i++){
System.out.printf("%s\n", filetest.getElementAt(i));
}*/
allFiles.addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent e){
int selectedItem = allFiles.getSelectedIndex();
lastFileState.addElement(Integer.toString(selectedItem));
}
});
allFiles.setCellRenderer(new ListRenderer());
JScrollPane pane = new JScrollPane(allFiles);
pane.setPreferredSize(new Dimension(250, 440));
//allFiles.setSelectionBackground(Color.green);
allFiles.setBackground(listColor);
return pane;
}
public static void fileSearch(String search){
//int cap = debug.getSize();
int cap = filetest.getSize();
files.clear();
for(int i=0; i<cap; i++){
//ListModel model = debug.elementAt(i);
ListModel model = filetest.elementAt(i);
String name = model.getName();
if(name.indexOf(search) != -1){
ListModel add = new ListModel(model.getName(), model.getStatus());
//filetest.addElement(add);
files.addElement(add);;
}
}
}
public static JPanel searchPanel() {
JPanel panel = new JPanel();
JLabel label = new JLabel("Search:");
JTextField search = new JTextField("search...", 12);
search.setEnabled(false);
// fileSearch(search.getText());
search.setBackground(listColor);
search.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
search.setText("");
search.setEnabled(true);
search.requestFocus();
}
});
search.getDocument().addDocumentListener(new DocumentListener(){
@Override
public void changedUpdate(DocumentEvent arg0) {
System.out.printf("changed\n");
}
@Override
public void insertUpdate(DocumentEvent arg0) {
fileSearch(search.getText());
globalSearch = search.getText();
lastFileState.clear();
}
@Override
public void removeUpdate(DocumentEvent arg0) {
fileSearch(search.getText());
globalSearch = search.getText();
lastFileState.clear();
}
});
label.setForeground(textColor);
label.setFont(font);
panel.add(label);
panel.add(search);
return panel;
}
public static JPanel varsPanel() {
//create panel
final JPanel panel = new JPanel();
BoxLayout layout = new BoxLayout(panel, BoxLayout.Y_AXIS);
panel.setLayout(layout);
//create components
final JLabel varsPanelLabel = new JLabel("Enter Encryption Key:");
final JButton lockPassButton = new JButton("confirm key");
final JTextField keyField = new JTextField("key...",10);
keyField.setEnabled(false);
keyField.setBackground(listColor);
lockPassButton.setForeground(buttonTextColor);
//bind methods to buttons
lockPassButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
IInterface.INSTANCE.setEncryptKey(keyField.getText());
}
});
keyField.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
keyField.setText("");
keyField.setEnabled(true);
keyField.requestFocus();
}
});
//add components to panel and specify orientation
varsPanelLabel.setForeground(textColor);
varsPanelLabel.setFont(font);
panel.add(varsPanelLabel);
panel.add(keyField);
panel.add(lockPassButton);
panel.setComponentOrientation(
ComponentOrientation.LEFT_TO_RIGHT);
return panel;
}
public static JPanel storagePanel(){
JPanel panel = new JPanel();
GridLayout layout = new GridLayout(2, 2, 0, 0);
panel.setLayout(layout);
panel.setPreferredSize(new Dimension(280, 50));
int min = 0;
int max = 100;
int init = 1;
final JLabel sliderLabel = new JLabel("Storage:");
final JLabel positionLabel = new JLabel("");
sliderLabel.setForeground(textColor);
sliderLabel.setFont(font);
final JSlider slider = new JSlider(JSlider.HORIZONTAL, min, max, init);
slider.setPreferredSize(new Dimension(200, 30));
slider.setMajorTickSpacing(max / 10);
slider.setPaintTicks(true);
final JLabel currStorageLabel = new JLabel(String.valueOf(slider.getValue()) + " GB");
currStorageLabel.setForeground(textColor);
currStorageLabel.setFont(font);
slider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (!slider.getValueIsAdjusting()) {
currStorageLabel.setText(String.valueOf(slider.getValue()) + " GB");
IInterface.INSTANCE.setStorageSpace(slider.getValue());
}
}
});
panel.add(sliderLabel);
panel.add(positionLabel);
panel.add(slider);
panel.add(currStorageLabel);
panel.setComponentOrientation(
ComponentOrientation.LEFT_TO_RIGHT);
return panel;
}
public static JPanel selectUsersPanel() {
//create panel
final JPanel panel = new JPanel();
final JLabel selectUser = new JLabel("Select Peer: ");
final JButton selectAllButton = new JButton("all");
final JButton selectNoneButton = new JButton("none");
selectAllButton.setForeground(buttonTextColor);
selectNoneButton.setForeground(buttonTextColor);
//bind methods to buttons
selectAllButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.printf("[*] selecting all\n");
for(int i=0; i < (allUsers.getModel().getSize()); i++){
lastUserState.addElement(Integer.toString(i));
}
}
});
selectNoneButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.printf("[*] selecting none\n");
lastUserState.clear();
}
});
selectUser.setForeground(textColor);
selectUser.setFont(font);
panel.add(selectUser);
panel.add(selectAllButton);
panel.add(selectNoneButton);
return panel;
}
public static JPanel selectFilesPanel() {
//create panel
final JPanel panel = new JPanel();
final JLabel selectFiles = new JLabel("Select File: ");
final JButton selectAllButton = new JButton("all");
final JButton selectNoneButton = new JButton("none");
selectAllButton.setForeground(buttonTextColor);
selectNoneButton.setForeground(buttonTextColor);
//bind methods to buttons
selectAllButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.printf("[*] selecting all\n");
for(int i=0; i < (allFiles.getModel().getSize()); i++){
lastFileState.addElement(Integer.toString(i));
}
}
});
selectNoneButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.printf("[*] selecting none\n");
lastFileState.clear();
}
});
selectFiles.setForeground(textColor);
selectFiles.setFont(font);
panel.add(selectFiles);
panel.add(selectAllButton);
panel.add(selectNoneButton);
return panel;
}
public static void updateFileSelection(){
for(int i=0; i<lastFileState.getSize(); i++){
allFiles.addSelectionInterval(Integer.parseInt(lastFileState.elementAt(i)),
Integer.parseInt(lastFileState.elementAt(i)));
}
}
public static void updateUserSelection(){
for(int i=0; i<lastUserState.getSize(); i++){
allUsers.addSelectionInterval(Integer.parseInt(lastUserState.elementAt(i)),
Integer.parseInt(lastUserState.elementAt(i)));
}
}
public static JPanel logPanel() {
//create panel
final JPanel panel = new JPanel();
BoxLayout layout = new BoxLayout(panel, BoxLayout.Y_AXIS);
panel.setLayout(layout);
//create components
final JLabel logLabel = new JLabel("Event Log:");
logLabel.setForeground(textColor);
logLabel.setFont(font);
log.setEditable(false);
//log.append(text + newline)
log.setBackground(listColor);
panel.add(logLabel);
panel.add(new JScrollPane(log));
return panel;
}
public static SpringLayout frameLayout() {
SpringLayout layout = new SpringLayout();
//set locations for each panel
for (Component panel : panelLocs.keySet()) {
layout.putConstraint(SpringLayout.NORTH, panel,
panelLocs.get(panel).get(1), SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.WEST, panel,
panelLocs.get(panel).get(0), SpringLayout.WEST, contentPane);
}
return layout;
}
public static JPanel namePanel() {
//create panel
final JPanel panel = new JPanel();
//BoxLayout layout = new BoxLayout(panel, BoxLayout.Y_AXIS);
//panel.setLayout(layout);
//create components
final JLabel nameLabel = new JLabel("Enter Device Name: ");
final JButton lockNameButton = new JButton("set");
final JTextField nameField = new JTextField("name...",10);
nameField.setEnabled(false);
nameField.setBackground(listColor);
lockNameButton.setForeground(buttonTextColor);
//bind methods to buttons
lockNameButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
IInterface.INSTANCE.setDisplayName(nameField.getText());
}
});
nameField.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
nameField.setText("");
nameField.setEnabled(true);
nameField.requestFocus();
}
});
//add components to panel and specify orientation
nameLabel.setForeground(textColor);
nameLabel.setFont(font);
panel.add(nameLabel);
panel.add(nameField);
panel.add(lockNameButton);
panel.setComponentOrientation(
ComponentOrientation.LEFT_TO_RIGHT);
return panel;
}
public static JPanel leftColorPanel() {
JPanel panel = new JPanel();
panel.setBackground(colorBlue);
panel.setPreferredSize(new Dimension(310, 600));
return panel;
}
public static JPanel linePanel() {
JPanel panel = new JPanel();
panel.setBackground(colorGray);
panel.setPreferredSize(new Dimension(318, 600));
return panel;
}
public static JPanel topColorPanel() {
JPanel panel = new JPanel();
panel.setBackground(colorGray);
panel.setPreferredSize(new Dimension(1000, 100));
return panel;
}
//bind panels to frame and display the gui
public static void startGui() {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
//load network
IInterface.INSTANCE.loadNetwork();
//start those intervals
startIntervals(500);
//create the window and center it on screen
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
//left column locations
panelLocs.put(loginPanel, Arrays.asList(30, 10));
panelLocs.put(varsPanel, Arrays.asList(30, 120));
panelLocs.put(controlPanel, Arrays.asList(30, 210));
panelLocs.put(logPanel, Arrays.asList(30, 425));
panelLocs.put(storagePanel, Arrays.asList(30, 365));
//middle column locatinos
panelLocs.put(userListPanel, Arrays.asList(370, 80));
panelLocs.put(selectUsersPanel, Arrays.asList(350, 40));
//right column locations
panelLocs.put(searchPanel, Arrays.asList(650, 10));
panelLocs.put(selectFilesPanel, Arrays.asList(650, 40));
panelLocs.put(fileListPanel, Arrays.asList(670, 80));
panelLocs.put(namePanel, Arrays.asList(610, 540));
//confirm layout
contentPane.setLayout(frameLayout());
frame.setSize(1000, 600);
frame.setLocationRelativeTo(null);
for (Component panel : panelLocs.keySet()) {
contentPane.add(panel);
}
contentPane.add(leftColorPanel());
contentPane.add(linePanel());
//contentPane.add(topColorPanel());
//set background color
Color globalColor = colorBlue;
//background stuff
frame.getContentPane().setBackground(backgroundColor);
searchPanel.setBackground(backgroundColor);
selectFilesPanel.setBackground(backgroundColor);
selectUsersPanel.setBackground(backgroundColor);
namePanel.setBackground(backgroundColor);
//left panel stuff
loginPanel.setBackground(globalColor);
varsPanel.setBackground(globalColor);
storagePanel.setBackground(globalColor);
logPanel.setBackground(globalColor);
controlPanel.setBackground(globalColor);
//display the window
frame.validate();
frame.repaint();
frame.setVisible(true);
}
});
}
}
| backupbuddies/gui/GuiMain.java | package backupbuddies.gui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
import java.io.File;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.HashMap;
import java.lang.*;
import backupbuddies.gui.ListModel;
import backupbuddies.shared.IInterface;
import static backupbuddies.Debug.*;
@SuppressWarnings("serial")
public class GuiMain extends JFrame {
//colors
//static final Color colorBlue = new Color(53, 129, 184);
static final Color colorBlue = new Color(80, 80, 80);
static final Color textColor = new Color(220, 220, 220);
static final Color buttonTextColor = new Color(40, 40, 40);
static final Color listColor = new Color(255, 255, 255);
static final Color backgroundColor = new Color(92, 146, 194);
static final Color colorGray = new Color(20, 20, 20);
static final Font font = new Font("Papyrus", Font.BOLD, 18);
//load assets, lists etc before creating the gui
static JFrame frame = new JFrame("BackupBuddies");
static JTextField saveDir = new JTextField();
static final DefaultListModel<String> userModel = new DefaultListModel<String>();
static final DefaultListModel<String> fileModel = new DefaultListModel<String>();
static final DefaultListModel<ListModel> files = new DefaultListModel<ListModel>();
static DefaultListModel<ListModel> filetest = new DefaultListModel<ListModel>();
static DefaultListModel<ListModel> usertest = new DefaultListModel<ListModel>();
static JList<ListModel> allFiles = new JList<ListModel>();
static JList<ListModel> allUsers = new JList<ListModel>();
//holds the all indices selected by the user
static DefaultListModel<String> lastFileState = new DefaultListModel<String>();
static DefaultListModel<String> lastUserState = new DefaultListModel<String>();
static DefaultListModel<ListModel> debug = new DefaultListModel<ListModel>();
static final JTextArea log = new JTextArea(6, 20);
static List<String> prevEvents = new ArrayList<>();
static ImageIcon statusRed = new ImageIcon("bin/backupbuddies/gui/assets/RedderCircle.png");
static ImageIcon statusYellow = new ImageIcon("bin/backupbuddies/backupbuddies/gui/assets/YellowerCircle.png");
static ImageIcon statusGreen = new ImageIcon("bin/backupbuddies/backupbuddies/gui/assets/GreenerCircle.png");
static JList<ListModel> userMap = fetchAndProcess("users");
static JList<ListModel> fileMap = fetchAndProcess("files");
static boolean firstSearch = false;
static String globalSearch = "";
//populate the window
static Container contentPane = frame.getContentPane();
static JPanel loginPanel = loginPanel();
static JPanel controlPanel = controlPanel();
static JScrollPane userListPanel = userListPanel();
static JScrollPane fileListPanel = fileListPanel("");
static JPanel selectUsersPanel = selectUsersPanel();
static JPanel selectFilesPanel = selectFilesPanel();
static JPanel searchPanel = searchPanel();
static JPanel varsPanel = varsPanel();
static JPanel storagePanel = storagePanel();
static JPanel logPanel = logPanel();
static JPanel namePanel = namePanel();
static Map<Component, List<Integer>> panelLocs = new HashMap<Component, List<Integer>>();
//process lists returned from networking
//NOTE: to speed this up we can just do it in the interface methods
//iteration already occurs there
public static JList<ListModel> fetchAndProcess(String type) {
//get data
JList<ListModel> map = new JList<ListModel>();
//debug = new DefaultListModel<>();
if (type.equals("users")) debug = IInterface.INSTANCE.fetchUserList();
else if (type.equals("files")) debug = IInterface.INSTANCE.fetchFileList();
return map;
}
//updates ui on interval
public static void startIntervals(int interval) {
ActionListener updateUI = new ActionListener() {
public void actionPerformed(ActionEvent e) {
IInterface.INSTANCE.saveNetwork();
userMap = fetchAndProcess("users");
fileMap = fetchAndProcess("files");
updateFileSelection();
updateUserSelection();
fileSearch(globalSearch);
if(firstSearch == false){
fileSearch("");
firstSearch = true;
}
int[] selected = new int[lastFileState.getSize()];
for(int i=0; i<lastFileState.getSize(); i++){
selected[i] = Integer.parseInt(lastFileState.getElementAt(i));
}
allFiles.setSelectedIndices(selected);
// fileSearch(globalSearch);
//FIXME: this gets slower as more events are added
//prevArray --> int (length of last returned array)
//change to check length of returned array
//append the last (len(events) - prevLength) elements to log
//if this is negative they cleared the event log
//only reset prevArraysize variable
List<String> events = IInterface.INSTANCE.getEventLog();
log.setText("");
for (String event : events) {
log.append(event + "\n");
log.setCaretPosition(log.getDocument().getLength());
}
prevEvents = events;
}
};
Timer timer = new Timer(interval, updateUI);
timer.setRepeats(true);
timer.start();
}
//user chooses directory to save to
public static void setSaveDir() {
JFileChooser browser = new JFileChooser();
browser.setDialogTitle("choose save location");
browser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
browser.setAcceptAllFileFilterUsed(false);
if (browser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
saveDir.setText(browser.getSelectedFile().toString());
IInterface.INSTANCE.setStoragePath(saveDir.getText());
}
}
//user selects a file and it uploads to network
public static void chooseAndUpload() {
JFileChooser browser = new JFileChooser();
browser.setMultiSelectionEnabled(true);
browser.setDialogTitle("choose files to upload");
if (browser.showOpenDialog(frame) ==
JFileChooser.APPROVE_OPTION) {
//File[] files = browser.getSelectedFiles();
//for (File f : files) {
// System.out.printf("%s\n", f.toPath());
//}
int[] selected = allUsers.getSelectedIndices();
for( int i=0; i<selected.length; i++){
IInterface.INSTANCE.uploadFile(browser.getSelectedFiles(),
allUsers.getModel().getElementAt(selected[i]).getName());
}
}
//fileSearch("");
}
//user downloads a file to save directory (and chooses if not set)
public static void setDirAndDownload() {
//FIXME: need to have a list of uploaded files to choose from
//String fileToGet = "test.txt";
if (saveDir.getText().equals("")) {
setSaveDir();
}
int[] selected = allFiles.getSelectedIndices();
for(int i=0; i<selected.length; i++){
//System.out.printf("Index: %d %s\n", i, hi.getModel().getElementAt(selected[i]).getName());
IInterface.INSTANCE.downloadFile(allFiles.getModel().getElementAt(selected[i]).getName(), saveDir.getText());
}
}
//upload, download, save control buttons
public static JPanel controlPanel() {
//create panel
JFrame failedUpload = new JFrame();
JPanel controlPanel = new JPanel();
GridLayout layout = new GridLayout(2, 1, 0, 10);
controlPanel.setLayout(layout);
//create components
JLabel fileLabel = new JLabel("backup your files");
JButton uploadButton = new JButton("upload");
JButton downloadButton = new JButton("download");
JButton pathButton = new JButton("save to...");
downloadButton.setForeground(buttonTextColor);
uploadButton.setForeground(buttonTextColor);
//set button colors
//uploadButton.setForeground(colorGreen); //text color
//uploadButton.setBackground(Color.GRAY);
//uploadButton.setContentAreaFilled(false);
//uploadButton.setOpaque(true);
//bind methods to buttons
uploadButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (allUsers.getSelectedIndex() == -1){
String upError = "Please select at least one user\n";
System.out.printf(upError);
JOptionPane.showMessageDialog(failedUpload, upError);
}else{
chooseAndUpload();
}
}
});
pathButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setSaveDir();
}
});
downloadButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setDirAndDownload();
}
});
//add components to panel and specify orientation
controlPanel.setPreferredSize(new Dimension(250, 150));
//controlPanel.add(fileLabel);
controlPanel.add(uploadButton);
controlPanel.add(downloadButton);
//controlPanel.add(pathButton);
//controlPanel.setComponentOrientation(
// ComponentOrientation.LEFT_TO_RIGHT);
return controlPanel;
}
//allows user to input ip and pass and connect to network
public static JPanel loginPanel() {
//create panel
final JPanel loginPanel = new JPanel();
BoxLayout layout = new BoxLayout(loginPanel, BoxLayout.Y_AXIS);
loginPanel.setLayout(layout);
//create components
final JLabel loginLabel = new JLabel("Join a Network:");
final JButton loginButton = new JButton("Join");
final JTextField ipField = new JTextField("network ip...", 21);
final JTextField passField = new JTextField("network password...");
ipField.setEnabled(false);
passField.setEnabled(false);
ipField.setBackground(listColor);
passField.setBackground(listColor);
loginButton.setForeground(buttonTextColor);
//bind methods to buttons
loginButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
IInterface.INSTANCE.login(ipField.getText(), passField.getText());
}
});
ipField.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
ipField.setText("");
ipField.setEnabled(true);
ipField.requestFocus();
}
});
passField.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
passField.setText("");
passField.setEnabled(true);
passField.requestFocus();
}
});
// loginButton.setBorder(new RoundedBorder(10));
//add components to panel and specify orientation
// loginButton.setOpaque(false);
// loginButton.setBorderPainted(false);
// loginButton.setFocusPainted(false);
//loginButton.setForeground(Color.BLUE);
//loginButton.setBorder(BorderFactory.createEmptyBorder(1,1,1,1));
loginLabel.setForeground(textColor);
loginLabel.setFont(font);
loginPanel.add(loginLabel);
loginPanel.add(ipField);
loginPanel.add(passField);
loginPanel.add(loginButton);
return loginPanel;
}
//list of peers in the network
//TODO: multiple selection
//TODO: renders images
public static JScrollPane userListPanel() {
usertest = (IInterface.INSTANCE.fetchUserList());
allUsers.setModel(usertest);
allUsers.addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent e){
int selectedItem = allUsers.getSelectedIndex();
lastUserState.addElement(Integer.toString(selectedItem));
}
});
allUsers.setCellRenderer(new ListRenderer());
JScrollPane pane = new JScrollPane(allUsers);
pane.setPreferredSize(new Dimension(250, 440));
//allUsers.setSelectionBackground(Color.green);
allUsers.setBackground(listColor);
return pane;
}
//list of files you can recover
//TODO: multiple selection
//TODO: renders images
public static JScrollPane fileListPanel(String search) {
filetest = (IInterface.INSTANCE.fetchFileList());
//allFiles.setModel(filetest);
allFiles.setModel(files);
for(int i=0; i< files.size(); i++){
System.out.printf("%s\n", files.getElementAt(i));
}
/*for(int i=0; i< filetest.size(); i++){
System.out.printf("%s\n", filetest.getElementAt(i));
}*/
allFiles.addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent e){
int selectedItem = allFiles.getSelectedIndex();
lastFileState.addElement(Integer.toString(selectedItem));
}
});
allFiles.setCellRenderer(new ListRenderer());
JScrollPane pane = new JScrollPane(allFiles);
pane.setPreferredSize(new Dimension(250, 440));
//allFiles.setSelectionBackground(Color.green);
allFiles.setBackground(listColor);
return pane;
}
public static void fileSearch(String search){
//int cap = debug.getSize();
int cap = filetest.getSize();
files.clear();
for(int i=0; i<cap; i++){
//ListModel model = debug.elementAt(i);
ListModel model = filetest.elementAt(i);
String name = model.getName();
if(name.indexOf(search) != -1){
ListModel add = new ListModel(model.getName(), model.getStatus());
//filetest.addElement(add);
files.addElement(add);;
}
}
}
public static JPanel searchPanel() {
JPanel panel = new JPanel();
JLabel label = new JLabel("Search:");
JTextField search = new JTextField("search...", 12);
search.setEnabled(false);
// fileSearch(search.getText());
search.setBackground(listColor);
search.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
search.setText("");
search.setEnabled(true);
search.requestFocus();
}
});
search.getDocument().addDocumentListener(new DocumentListener(){
@Override
public void changedUpdate(DocumentEvent arg0) {
System.out.printf("changed\n");
}
@Override
public void insertUpdate(DocumentEvent arg0) {
fileSearch(search.getText());
globalSearch = search.getText();
}
@Override
public void removeUpdate(DocumentEvent arg0) {
fileSearch(search.getText());
globalSearch = search.getText();
}
});
label.setForeground(textColor);
label.setFont(font);
panel.add(label);
panel.add(search);
return panel;
}
public static JPanel varsPanel() {
//create panel
final JPanel panel = new JPanel();
BoxLayout layout = new BoxLayout(panel, BoxLayout.Y_AXIS);
panel.setLayout(layout);
//create components
final JLabel varsPanelLabel = new JLabel("Enter Encryption Key:");
final JButton lockPassButton = new JButton("confirm key");
final JTextField keyField = new JTextField("key...",10);
keyField.setEnabled(false);
keyField.setBackground(listColor);
lockPassButton.setForeground(buttonTextColor);
//bind methods to buttons
lockPassButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
IInterface.INSTANCE.setEncryptKey(keyField.getText());
}
});
keyField.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
keyField.setText("");
keyField.setEnabled(true);
keyField.requestFocus();
}
});
//add components to panel and specify orientation
varsPanelLabel.setForeground(textColor);
varsPanelLabel.setFont(font);
panel.add(varsPanelLabel);
panel.add(keyField);
panel.add(lockPassButton);
panel.setComponentOrientation(
ComponentOrientation.LEFT_TO_RIGHT);
return panel;
}
public static JPanel storagePanel(){
JPanel panel = new JPanel();
GridLayout layout = new GridLayout(2, 2, 0, 0);
panel.setLayout(layout);
panel.setPreferredSize(new Dimension(280, 50));
int min = 0;
int max = 100;
int init = 1;
final JLabel sliderLabel = new JLabel("Storage:");
final JLabel positionLabel = new JLabel("");
sliderLabel.setForeground(textColor);
sliderLabel.setFont(font);
final JSlider slider = new JSlider(JSlider.HORIZONTAL, min, max, init);
slider.setPreferredSize(new Dimension(200, 30));
slider.setMajorTickSpacing(max / 10);
slider.setPaintTicks(true);
final JLabel currStorageLabel = new JLabel(String.valueOf(slider.getValue()) + " GB");
currStorageLabel.setForeground(textColor);
currStorageLabel.setFont(font);
slider.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
if (!slider.getValueIsAdjusting()) {
currStorageLabel.setText(String.valueOf(slider.getValue()) + " GB");
IInterface.INSTANCE.setStorageSpace(slider.getValue());
}
}
});
panel.add(sliderLabel);
panel.add(positionLabel);
panel.add(slider);
panel.add(currStorageLabel);
panel.setComponentOrientation(
ComponentOrientation.LEFT_TO_RIGHT);
return panel;
}
public static JPanel selectUsersPanel() {
//create panel
final JPanel panel = new JPanel();
final JLabel selectUser = new JLabel("Select Peer: ");
final JButton selectAllButton = new JButton("all");
final JButton selectNoneButton = new JButton("none");
selectAllButton.setForeground(buttonTextColor);
selectNoneButton.setForeground(buttonTextColor);
//bind methods to buttons
selectAllButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.printf("[*] selecting all\n");
for(int i=0; i < (allUsers.getModel().getSize()); i++){
lastUserState.addElement(Integer.toString(i));
}
}
});
selectNoneButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.printf("[*] selecting none\n");
lastUserState.clear();
}
});
selectUser.setForeground(textColor);
selectUser.setFont(font);
panel.add(selectUser);
panel.add(selectAllButton);
panel.add(selectNoneButton);
return panel;
}
public static JPanel selectFilesPanel() {
//create panel
final JPanel panel = new JPanel();
final JLabel selectFiles = new JLabel("Select File: ");
final JButton selectAllButton = new JButton("all");
final JButton selectNoneButton = new JButton("none");
selectAllButton.setForeground(buttonTextColor);
selectNoneButton.setForeground(buttonTextColor);
//bind methods to buttons
selectAllButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.printf("[*] selecting all\n");
for(int i=0; i < (allFiles.getModel().getSize()); i++){
lastFileState.addElement(Integer.toString(i));
}
}
});
selectNoneButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.printf("[*] selecting none\n");
lastFileState.clear();
}
});
selectFiles.setForeground(textColor);
selectFiles.setFont(font);
panel.add(selectFiles);
panel.add(selectAllButton);
panel.add(selectNoneButton);
return panel;
}
public static void updateFileSelection(){
for(int i=0; i<lastFileState.getSize(); i++){
allFiles.addSelectionInterval(Integer.parseInt(lastFileState.elementAt(i)),
Integer.parseInt(lastFileState.elementAt(i)));
}
}
public static void updateUserSelection(){
for(int i=0; i<lastUserState.getSize(); i++){
allUsers.addSelectionInterval(Integer.parseInt(lastUserState.elementAt(i)),
Integer.parseInt(lastUserState.elementAt(i)));
}
}
public static JPanel logPanel() {
//create panel
final JPanel panel = new JPanel();
BoxLayout layout = new BoxLayout(panel, BoxLayout.Y_AXIS);
panel.setLayout(layout);
//create components
final JLabel logLabel = new JLabel("Event Log:");
logLabel.setForeground(textColor);
logLabel.setFont(font);
log.setEditable(false);
//log.append(text + newline)
log.setBackground(listColor);
panel.add(logLabel);
panel.add(new JScrollPane(log));
return panel;
}
public static SpringLayout frameLayout() {
SpringLayout layout = new SpringLayout();
//set locations for each panel
for (Component panel : panelLocs.keySet()) {
layout.putConstraint(SpringLayout.NORTH, panel,
panelLocs.get(panel).get(1), SpringLayout.NORTH, contentPane);
layout.putConstraint(SpringLayout.WEST, panel,
panelLocs.get(panel).get(0), SpringLayout.WEST, contentPane);
}
return layout;
}
public static JPanel namePanel() {
//create panel
final JPanel panel = new JPanel();
//BoxLayout layout = new BoxLayout(panel, BoxLayout.Y_AXIS);
//panel.setLayout(layout);
//create components
final JLabel nameLabel = new JLabel("Enter Device Name: ");
final JButton lockNameButton = new JButton("set");
final JTextField nameField = new JTextField("name...",10);
nameField.setEnabled(false);
nameField.setBackground(listColor);
lockNameButton.setForeground(buttonTextColor);
//bind methods to buttons
lockNameButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
IInterface.INSTANCE.setDisplayName(nameField.getText());
}
});
nameField.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
nameField.setText("");
nameField.setEnabled(true);
nameField.requestFocus();
}
});
//add components to panel and specify orientation
nameLabel.setForeground(textColor);
nameLabel.setFont(font);
panel.add(nameLabel);
panel.add(nameField);
panel.add(lockNameButton);
panel.setComponentOrientation(
ComponentOrientation.LEFT_TO_RIGHT);
return panel;
}
public static JPanel leftColorPanel() {
JPanel panel = new JPanel();
panel.setBackground(colorBlue);
panel.setPreferredSize(new Dimension(310, 600));
return panel;
}
public static JPanel linePanel() {
JPanel panel = new JPanel();
panel.setBackground(colorGray);
panel.setPreferredSize(new Dimension(318, 600));
return panel;
}
public static JPanel topColorPanel() {
JPanel panel = new JPanel();
panel.setBackground(colorGray);
panel.setPreferredSize(new Dimension(1000, 100));
return panel;
}
//bind panels to frame and display the gui
public static void startGui() {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
//load network
IInterface.INSTANCE.loadNetwork();
//start those intervals
startIntervals(500);
//create the window and center it on screen
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
//left column locations
panelLocs.put(loginPanel, Arrays.asList(30, 10));
panelLocs.put(varsPanel, Arrays.asList(30, 120));
panelLocs.put(controlPanel, Arrays.asList(30, 210));
panelLocs.put(logPanel, Arrays.asList(30, 425));
panelLocs.put(storagePanel, Arrays.asList(30, 365));
//middle column locatinos
panelLocs.put(userListPanel, Arrays.asList(370, 80));
panelLocs.put(selectUsersPanel, Arrays.asList(350, 40));
//right column locations
panelLocs.put(searchPanel, Arrays.asList(650, 10));
panelLocs.put(selectFilesPanel, Arrays.asList(650, 40));
panelLocs.put(fileListPanel, Arrays.asList(670, 80));
panelLocs.put(namePanel, Arrays.asList(610, 540));
//confirm layout
contentPane.setLayout(frameLayout());
frame.setSize(1000, 600);
frame.setLocationRelativeTo(null);
for (Component panel : panelLocs.keySet()) {
contentPane.add(panel);
}
contentPane.add(leftColorPanel());
contentPane.add(linePanel());
//contentPane.add(topColorPanel());
//set background color
Color globalColor = colorBlue;
//background stuff
frame.getContentPane().setBackground(backgroundColor);
searchPanel.setBackground(backgroundColor);
selectFilesPanel.setBackground(backgroundColor);
selectUsersPanel.setBackground(backgroundColor);
namePanel.setBackground(backgroundColor);
//left panel stuff
loginPanel.setBackground(globalColor);
varsPanel.setBackground(globalColor);
storagePanel.setBackground(globalColor);
logPanel.setBackground(globalColor);
controlPanel.setBackground(globalColor);
//display the window
frame.validate();
frame.repaint();
frame.setVisible(true);
}
});
}
}
| searching now resets the selected indices | backupbuddies/gui/GuiMain.java | searching now resets the selected indices | <ide><path>ackupbuddies/gui/GuiMain.java
<ide> public void insertUpdate(DocumentEvent arg0) {
<ide> fileSearch(search.getText());
<ide> globalSearch = search.getText();
<add> lastFileState.clear();
<ide> }
<ide>
<ide> @Override
<ide> public void removeUpdate(DocumentEvent arg0) {
<ide> fileSearch(search.getText());
<ide> globalSearch = search.getText();
<add> lastFileState.clear();
<ide> }
<ide> });
<ide> label.setForeground(textColor); |
|
Java | apache-2.0 | 6b4f302e2bea5f83f71635d3bd9dd93fe8f71a0d | 0 | SpineEventEngine/base,SpineEventEngine/base,SpineEventEngine/base | /*
* Copyright 2020, TeamDev. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.base;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import io.spine.annotation.Internal;
import io.spine.annotation.SPI;
import org.checkerframework.checker.nullness.qual.Nullable;
import static com.google.common.base.Preconditions.checkNotNull;
import static io.spine.reflect.Invokables.callParameterlessCtor;
import static io.spine.util.Exceptions.newIllegalStateException;
/**
* Provides information about the environment (current platform used, etc.).
*
* <h1>Environment Type Detection</h1>
*
* <p>Current implementation allows to {@linkplain #type() obtain the type} of the current
* environment, or to check whether current environment type {@linkplain #is(Class) matches
* another type}.
* Two environment types exist out of the box:
*
* <ul>
* <li><em>{@link Tests}</em> is detected if the current call stack has a reference to the unit
* testing framework.
*
* <li><em>{@link Production}</em> is set in all other cases.
* </ul>
*
* <p>The framework users may define their custom settings depending on the current environment
* type:
*
* <pre>
*
* public final class Application {
*
* private final EmailSender sender;
*
* private Application() {
* Environment environment = Environment.instance();
* if(environment.is(Tests.class)) {
* // Do not send out emails if in tests.
* this.sender = new MockEmailSender();
* } else {
* this.sender = EmailSender.withConfig("email_gateway.yml");
* }
* //...
* }
* }
* </pre>
*
* <h1>Custom environment types</h1>
*
* {@code Environment} allows to {@link #register(EnvironmentType) reguster custom types}.
* In this case the environment detection functionality iterates over all known types, starting
* with those registered by the framework user:
*
* <pre>
*
* public final class Application {
*
* static {
* Environment.instance()
* .register(new Staging())
* .register(new LoadTesting());
* }
*
* private final ConnectionPool pool;
*
* private Application() {
* Environment environment = Environment.instance();
* if (environment.is(Tests.class) {
* // Single connection is enough for tests.
* this.pool = new ConnectionPoolImpl(PoolCapacity.of(1));
* } else {
* if(environment.is(LoadTesting.class) {
* this.pool =
* new ConnectionPoolImpl(PoolCapacity.fromConfig("load_tests.yml"));
* } else {
* this.pool =
* new ConnectionPoolImpl(PoolCapacity.fromConfig("cloud_deployment.yml"));
* }
* }
* //...
* }
* }
* </pre>
*
* <h1>Caching</h1>
*
* <p>{@code Environment} caches the {@code EnvironmentType} once its calculated.
* This means that if one environment type has been found to be active, its instance is saved.
* If later it becomes logically inactive, e.g. the environment variable that's used to check the
* environment type changes, {@code Environment} is still going to return the cached value. To
* overwrite the value use {@link #setTo(EnvironmentType)}. Also, the value may be
* {@linkplain #reset}.
*
* For example:
* <pre>
* Environment environment = Environment.instance();
* EnvironmentType awsLambda = new AwsLambda();
* environment.register(awsLambda);
* assertThat(environment.is(AwsLambda.class)).isTrue();
*
* System.clearProperty(AwsLambda.AWS_ENV_VARIABLE);
*
* // Even though `AwsLambda` is not active, we have cached the value, and `is(AwsLambda.class)`
* // is `true`.
* assertThat(environment.is(AwsLambda.class)).isTrue();
*
* environment.reset();
*
* // When `reset` explicitly, cached value is erased.
* assertThat(environment.is(AwsLambda.class)).isFalse();
* </pre>
*
* <p><b>When registering custom types, please ensure</b> their mutual exclusivity.
* If two or more environment types {@linkplain EnvironmentType#enabled() consider themselves
* enabled} at the same time, the behaviour of {@link #is(Class)}} is undefined.
*
* @see EnvironmentType
* @see Tests
* @see Production
*/
@SPI
public final class Environment {
private static final ImmutableList<EnvironmentType> BASE_TYPES =
ImmutableList.of(new Tests(), new Production());
private static final Environment INSTANCE = new Environment();
private ImmutableList<EnvironmentType> knownEnvTypes;
private @Nullable Class<? extends EnvironmentType> currentEnvType;
private Environment() {
this.knownEnvTypes = BASE_TYPES;
}
/** Creates a new instance with the copy of the state of the passed environment. */
private Environment(Environment copy) {
this.knownEnvTypes = copy.knownEnvTypes;
this.currentEnvType = copy.currentEnvType;
}
/**
* Remembers the specified environment type, allowing {@linkplain #is(Class) to
* determine whether it's enabled} later.
*
* <p>Note that the default types are still present.
* When trying to determine which environment type is enabled, the user-defined types are
* checked first, in the first-registered to last-registered order.
*
* @param environmentType
* a user-defined environment type
* @return this instance of {@code Environment}
* @see Tests
* @see Production
*/
@CanIgnoreReturnValue
public Environment register(EnvironmentType environmentType) {
if (!knownEnvTypes.contains(environmentType)) {
knownEnvTypes = ImmutableList
.<EnvironmentType>builder()
.add(environmentType)
.addAll(INSTANCE.knownEnvTypes)
.build();
}
return this;
}
/**
* Remembers the specified environment type, allowing {@linkplain #is(Class) to
* determine whether it's enabled} later.
*
* <p>The specified {@code type} must have a parameterless constructor. The
* {@code EnvironmentType} is going to be instantiated using the parameterless constructor.
*
* @param type
* environment type to register
* @return this instance of {@code Environment}
*/
@Internal
@CanIgnoreReturnValue
Environment register(Class<? extends EnvironmentType> type) {
EnvironmentType envTypeInstance = callParameterlessCtor(type);
return register(envTypeInstance);
}
/** Returns the singleton instance. */
public static Environment instance() {
return INSTANCE;
}
/**
* Creates a copy of the instance so that it can be later
* restored via {@link #restoreFrom(Environment)} by cleanup in tests.
*/
@VisibleForTesting
public Environment createCopy() {
return new Environment(this);
}
/**
* Determines whether the current environment is the same as the specified one.
*
* <p>If {@linkplain #register(EnvironmentType) custom env types have been registered},
* goes through them in the latest-registered to earliest-registered order.
* Then, checks {@link Tests} and {@link Production}.
*
* <p>Please note that {@code is} follows assigment-compatibility:
* <pre>
* abstract class AppEngine extends EnvironmentType {
* ...
* }
*
* final class AppEngineStandard extends AppEngine {
* ...
* }
*
* Environment environment = Environment.instance();
*
* // Assuming we are under App Engine Standard
* assertThat(environment.is(AppEngine.class)).isTrue();
*
* </pre>
*
* @return whether the current environment type matches the specified one
*/
public boolean is(Class<? extends EnvironmentType> type) {
Class<? extends EnvironmentType> currentEnv = cachedOrCalculated();
boolean result = type.isAssignableFrom(currentEnv);
return result;
}
/** Returns the type of the current environment. */
public Class<? extends EnvironmentType> type() {
Class<? extends EnvironmentType> currentEnv = cachedOrCalculated();
return currentEnv;
}
/**
* Verifies if the code currently runs under a unit testing framework.
*
* @see Tests
* @deprecated use {@code Environment.instance().is(Tests.class)}
*/
@Deprecated
public boolean isTests() {
return is(Tests.class);
}
/**
* Verifies if the code runs in the production mode.
*
* <p>This method is opposite to {@link #isTests()}.
*
* @return {@code true} if the code runs in the production mode, {@code false} otherwise
* @see Production
* @deprecated use {@code Environment.instance().is(Production.class)}
*/
@Deprecated
public boolean isProduction() {
return !isTests();
}
/**
* Restores the state from the instance created by {@link #createCopy()}.
*
* <p>Call this method when cleaning up tests that modify {@code Environment}.
*/
@VisibleForTesting
public void restoreFrom(Environment copy) {
// Make sure this matches the set of fields copied in the copy constructor.
this.knownEnvTypes = copy.knownEnvTypes;
this.currentEnvType = copy.currentEnvType;
}
/**
* Sets the current environment type to {@code type.getClass()}. Overrides the current value.
*/
@VisibleForTesting
public void setTo(EnvironmentType type) {
checkNotNull(type);
register(type);
this.currentEnvType = type.getClass();
}
/**
* Sets the current environment type to the specified one. Overrides the current value.
*/
@Internal
@VisibleForTesting
public void setTo(Class<? extends EnvironmentType> type) {
checkNotNull(type);
register(type);
this.currentEnvType = type;
}
/**
* Turns the test mode on.
*
* <p>This method is opposite to {@link #setToProduction()}.
*
* @deprecated use {@link #setTo(Class)}
*/
@Deprecated
@VisibleForTesting
public void setToTests() {
this.currentEnvType = Tests.class;
Tests.enable();
}
/**
* Turns the production mode on.
*
* <p>This method is opposite to {@link #setToTests()}.
*
* @deprecated use {@link #setTo(Class)}
*/
@Deprecated
@VisibleForTesting
public void setToProduction() {
this.currentEnvType = Production.class;
Tests.clearTestingEnvVariable();
}
/**
* Resets the instance and clears the {@link Tests#ENV_KEY_TESTS} variable.
*
* <p>Erases all registered environment types, leaving only {@code Tests} and {@code
* Production}.
*/
@VisibleForTesting
public void reset() {
this.currentEnvType = null;
this.knownEnvTypes = BASE_TYPES;
Tests.clearTestingEnvVariable();
}
private Class<? extends EnvironmentType> cachedOrCalculated() {
Class<? extends EnvironmentType> result = currentEnvType != null
? currentEnvType
: currentType();
this.currentEnvType = result;
return result;
}
private Class<? extends EnvironmentType> currentType() {
for (EnvironmentType type : knownEnvTypes) {
if (type.enabled()) {
return type.getClass();
}
}
throw newIllegalStateException("`Environment` could not find an active environment type.");
}
}
| base/src/main/java/io/spine/base/Environment.java | /*
* Copyright 2020, TeamDev. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.base;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import io.spine.annotation.Internal;
import io.spine.annotation.SPI;
import org.checkerframework.checker.nullness.qual.Nullable;
import static com.google.common.base.Preconditions.checkNotNull;
import static io.spine.reflect.Invokables.callParameterlessCtor;
import static io.spine.util.Exceptions.newIllegalStateException;
/**
* Provides information about the environment (current platform used, etc.).
*
* <h1>Environment Type Detection</h1>
*
* <p>Current implementation allows to {@linkplain #type() obtain the type} of the current
* environment, or to check whether current environment type {@linkplain #is(Class) matches
* another type}.
* Two environment types exist out of the box:
*
* <ul>
* <li><em>{@link Tests}</em> is detected if the current call stack has a reference to the unit
* testing framework.
*
* <li><em>{@link Production}</em> is set in all other cases.
* </ul>
*
* <p>The framework users may define their custom settings depending on the current environment
* type:
*
* <pre>
*
* public final class Application {
*
* private final EmailSender sender;
*
* private Application() {
* Environment environment = Environment.instance();
* if(environment.is(Tests.class)) {
* // Do not send out emails if in tests.
* this.sender = new MockEmailSender();
* } else {
* this.sender = EmailSender.withConfig("email_gateway.yml");
* }
* //...
* }
* }
* </pre>
*
* <h1>Custom environment types</h1>
*
* {@code Environment} allows to {@link #register(EnvironmentType) reguster custom types}.
* In this case the environment detection functionality iterates over all known types, starting
* with those registered by the framework user:
*
* <pre>
*
* public final class Application {
*
* static {
* Environment.instance()
* .register(new Staging())
* .register(new LoadTesting());
* }
*
* private final ConnectionPool pool;
*
* private Application() {
* Environment environment = Environment.instance();
* if (environment.is(Tests.class) {
* // Single connection is enough for tests.
* this.pool = new ConnectionPoolImpl(PoolCapacity.of(1));
* } else {
* if(environment.is(LoadTesting.class) {
* this.pool =
* new ConnectionPoolImpl(PoolCapacity.fromConfig("load_tests.yml"));
* } else {
* this.pool =
* new ConnectionPoolImpl(PoolCapacity.fromConfig("cloud_deployment.yml"));
* }
* }
* //...
* }
* }
* </pre>
*
* <h1>Caching</h1>
*
* <p>{@code Environment} caches the {@code EnvironmentType} once its calculated.
* This means that if one environment type has been found to be active, its instance is saved.
* If later it becomes logically inactive, e.g. the environment variable that's used to check the
* environment type changes, {@code Environment} is still going to return the cached value. To
* overwrite the value use {@link #setTo(EnvironmentType)}. Also, the value may be
* {@link #reset}.
*
* For example:
* <pre>
* Environment environment = Environment.instance();
* EnvironmentType awsLambda = new AwsLambda();
* environment.register(awsLambda);
* assertThat(environment.is(AwsLambda.class)).isTrue();
*
* System.clearProperty(AwsLambda.AWS_ENV_VARIABLE);
*
* // Even though `AwsLambda` is not active, we have cached the value, and `is(AwsLambda.class)`
* // is `true`.
* assertThat(environment.is(AwsLambda.class)).isTrue();
*
* environment.reset();
*
* // When `reset` explicitly, cached value is erased.
* assertThat(environment.is(AwsLambda.class)).isFalse();
* </pre>
*
* <p><b>When registering custom types, please ensure</b> their mutual exclusivity.
* If two or more environment types {@linkplain EnvironmentType#enabled() consider themselves
* enabled} at the same time, the behaviour of {@link #is(Class)}} is undefined.
*
* @see EnvironmentType
* @see Tests
* @see Production
*/
@SPI
public final class Environment {
private static final ImmutableList<EnvironmentType> BASE_TYPES =
ImmutableList.of(new Tests(), new Production());
private static final Environment INSTANCE = new Environment();
private ImmutableList<EnvironmentType> knownEnvTypes;
private @Nullable Class<? extends EnvironmentType> currentEnvType;
private Environment() {
this.knownEnvTypes = BASE_TYPES;
}
/** Creates a new instance with the copy of the state of the passed environment. */
private Environment(Environment copy) {
this.knownEnvTypes = copy.knownEnvTypes;
this.currentEnvType = copy.currentEnvType;
}
/**
* Remembers the specified environment type, allowing {@linkplain #is(Class) to
* determine whether it's enabled} later.
*
* <p>Note that the default types are still present.
* When trying to determine which environment type is enabled, the user-defined types are
* checked first, in the first-registered to last-registered order.
*
* @param environmentType
* a user-defined environment type
* @return this instance of {@code Environment}
* @see Tests
* @see Production
*/
@CanIgnoreReturnValue
public Environment register(EnvironmentType environmentType) {
if (!knownEnvTypes.contains(environmentType)) {
knownEnvTypes = ImmutableList
.<EnvironmentType>builder()
.add(environmentType)
.addAll(INSTANCE.knownEnvTypes)
.build();
}
return this;
}
/**
* Remembers the specified environment type, allowing {@linkplain #is(Class) to
* determine whether it's enabled} later.
*
* <p>The specified {@code type} must have a parameterless constructor. The
* {@code EnvironmentType} is going to be instantiated using the parameterless constructor.
*
* @param type
* environment type to register
* @return this instance of {@code Environment}
*/
@Internal
@CanIgnoreReturnValue
Environment register(Class<? extends EnvironmentType> type) {
EnvironmentType envTypeInstance = callParameterlessCtor(type);
return register(envTypeInstance);
}
/** Returns the singleton instance. */
public static Environment instance() {
return INSTANCE;
}
/**
* Creates a copy of the instance so that it can be later
* restored via {@link #restoreFrom(Environment)} by cleanup in tests.
*/
@VisibleForTesting
public Environment createCopy() {
return new Environment(this);
}
/**
* Determines whether the current environment is the same as the specified one.
*
* <p>If {@linkplain #register(EnvironmentType) custom env types have been registered},
* goes through them in the latest-registered to earliest-registered order.
* Then, checks {@link Tests} and {@link Production}.
*
* <p>Please note that {@code is} follows assigment-compatibility:
* <pre>
* abstract class AppEngine extends EnvironmentType {
* ...
* }
*
* final class AppEngineStandard extends AppEngine {
* ...
* }
*
* Environment environment = Environment.instance();
*
* // Assuming we are under App Engine Standard
* assertThat(environment.is(AppEngine.class)).isTrue();
*
* </pre>
*
* @return whether the current environment type matches the specified one
*/
public boolean is(Class<? extends EnvironmentType> type) {
Class<? extends EnvironmentType> currentEnv = cachedOrCalculated();
boolean result = type.isAssignableFrom(currentEnv);
return result;
}
/** Returns the type of the current environment. */
public Class<? extends EnvironmentType> type() {
Class<? extends EnvironmentType> currentEnv = cachedOrCalculated();
return currentEnv;
}
/**
* Verifies if the code currently runs under a unit testing framework.
*
* @see Tests
* @deprecated use {@code Environment.instance().is(Tests.class)}
*/
@Deprecated
public boolean isTests() {
return is(Tests.class);
}
/**
* Verifies if the code runs in the production mode.
*
* <p>This method is opposite to {@link #isTests()}.
*
* @return {@code true} if the code runs in the production mode, {@code false} otherwise
* @see Production
* @deprecated use {@code Environment.instance().is(Production.class)}
*/
@Deprecated
public boolean isProduction() {
return !isTests();
}
/**
* Restores the state from the instance created by {@link #createCopy()}.
*
* <p>Call this method when cleaning up tests that modify {@code Environment}.
*/
@VisibleForTesting
public void restoreFrom(Environment copy) {
// Make sure this matches the set of fields copied in the copy constructor.
this.knownEnvTypes = copy.knownEnvTypes;
this.currentEnvType = copy.currentEnvType;
}
/**
* Sets the current environment type to {@code type.getClass()}. Overrides the current value.
*/
@VisibleForTesting
public void setTo(EnvironmentType type) {
this.currentEnvType = checkNotNull(type).getClass();
}
/**
* Sets the current environment type to the specified one. Overrides the current value.
*/
@Internal
@VisibleForTesting
public void setTo(Class<? extends EnvironmentType> type) {
checkNotNull(type);
this.currentEnvType = type;
}
/**
* Turns the test mode on.
*
* <p>This method is opposite to {@link #setToProduction()}.
*
* @deprecated use {@link #setTo(Class)}
*/
@Deprecated
@VisibleForTesting
public void setToTests() {
this.currentEnvType = Tests.class;
Tests.enable();
}
/**
* Turns the production mode on.
*
* <p>This method is opposite to {@link #setToTests()}.
*
* @deprecated use {@link #setTo(Class)}
*/
@Deprecated
@VisibleForTesting
public void setToProduction() {
this.currentEnvType = Production.class;
Tests.clearTestingEnvVariable();
}
/**
* Resets the instance and clears the {@link Tests#ENV_KEY_TESTS} variable.
*
* <p>Erases all registered environment types, leaving only {@code Tests} and {@code
* Production}.
*/
@VisibleForTesting
public void reset() {
this.currentEnvType = null;
this.knownEnvTypes = BASE_TYPES;
Tests.clearTestingEnvVariable();
}
private Class<? extends EnvironmentType> cachedOrCalculated() {
Class<? extends EnvironmentType> result = currentEnvType != null
? currentEnvType
: currentType();
this.currentEnvType = result;
return result;
}
private Class<? extends EnvironmentType> currentType() {
for (EnvironmentType type : knownEnvTypes) {
if (type.enabled()) {
return type.getClass();
}
}
throw newIllegalStateException("`Environment` could not find an active environment type.");
}
}
| `register` an env on `setTo`.
| base/src/main/java/io/spine/base/Environment.java | `register` an env on `setTo`. | <ide><path>ase/src/main/java/io/spine/base/Environment.java
<ide> * If later it becomes logically inactive, e.g. the environment variable that's used to check the
<ide> * environment type changes, {@code Environment} is still going to return the cached value. To
<ide> * overwrite the value use {@link #setTo(EnvironmentType)}. Also, the value may be
<del> * {@link #reset}.
<add> * {@linkplain #reset}.
<ide> *
<ide> * For example:
<ide> * <pre>
<ide> */
<ide> @VisibleForTesting
<ide> public void setTo(EnvironmentType type) {
<del> this.currentEnvType = checkNotNull(type).getClass();
<add> checkNotNull(type);
<add> register(type);
<add> this.currentEnvType = type.getClass();
<ide> }
<ide>
<ide> /**
<ide> @VisibleForTesting
<ide> public void setTo(Class<? extends EnvironmentType> type) {
<ide> checkNotNull(type);
<add> register(type);
<ide> this.currentEnvType = type;
<ide> }
<ide> |
|
Java | epl-1.0 | 2ed611fde09e694390c653074194cfa74615f8f1 | 0 | hansjoachim/fitnesse,rbevers/fitnesse,rbevers/fitnesse,rbevers/fitnesse,amolenaar/fitnesse,amolenaar/fitnesse,jdufner/fitnesse,hansjoachim/fitnesse,jdufner/fitnesse,amolenaar/fitnesse,hansjoachim/fitnesse,jdufner/fitnesse | // Copyright (C) 2003-2009 by Object Mentor, Inc. All rights reserved.
// Released under the terms of the CPL Common Public License version 1.0.
package fitnesse.responders.run;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import fitnesse.FitNesseContext;
import fitnesse.FitNesseVersion;
import fitnesse.authentication.SecureOperation;
import fitnesse.authentication.SecureResponder;
import fitnesse.authentication.SecureTestOperation;
import fitnesse.http.MockRequest;
import fitnesse.http.MockResponseSender;
import fitnesse.http.Response;
import fitnesse.testsystems.TestSummary;
import fitnesse.testutil.FitNesseUtil;
import fitnesse.wiki.PageData;
import fitnesse.wiki.PathParser;
import fitnesse.wiki.WikiPage;
import fitnesse.wiki.WikiPagePath;
import fitnesse.wiki.WikiPageProperties;
import fitnesse.wiki.WikiPageUtil;
import fitnesse.wiki.mem.InMemoryPage;
import fitnesse.wikitext.Utils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import util.Clock;
import util.DateAlteringClock;
import util.DateTimeUtil;
import util.FileUtil;
import util.XmlUtil;
import static fitnesse.responders.run.TestResponderTest.XmlTestUtilities.assertCounts;
import static fitnesse.responders.run.TestResponderTest.XmlTestUtilities.getXmlDocumentFromResults;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.*;
import static util.RegexTestCase.*;
import static util.XmlUtil.getElementByTagName;
public class TestResponderTest {
private static final String TEST_TIME = "12/5/2008 01:19:00";
private WikiPage root;
private MockRequest request;
private TestResponder responder;
private FitNesseContext context;
private Response response;
private MockResponseSender sender;
private WikiPage testPage;
private String results;
private WikiPage errorLogsParentPage;
private File xmlResultsFile;
private XmlChecker xmlChecker = new XmlChecker();
private boolean debug;
@Before
public void setUp() throws Exception {
debug = true;
File testDir = new File("TestDir");
testDir.mkdir();
Properties properties = new Properties();
root = InMemoryPage.makeRoot("Root", properties);
errorLogsParentPage = WikiPageUtil.addPage(root, PathParser.parse("ErrorLogs"));
request = new MockRequest();
responder = new TestResponder();
context = FitNesseUtil.makeTestContext(root);
properties.setProperty("FITNESSE_PORT", String.valueOf(context.port));
new DateAlteringClock(DateTimeUtil.getDateFromString(TEST_TIME)).advanceMillisOnEachQuery();
}
@After
public void tearDown() throws Exception {
FitNesseUtil.destroyTestContext();
Clock.restoreDefaultClock();
}
@Test
public void testIsValidHtml() throws Exception {
doSimpleRun(passFixtureTable());
assertSubString("<!DOCTYPE html>", results);
assertSubString("</html>", results);
//assertSubString("<base href=\"http://somehost.com:8080/\"", results);
assertSubString("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>", results);
//assertSubString("Command Line Test Results", html);
}
@Test
public void testHead() throws Exception {
doSimpleRun(passFixtureTable());
assertSubString("<div id=\"test-summary\"><div id=\"progressBar\">Preparing Tests ...</div></div>", results);
}
@Test
public void testSimpleRun() throws Exception {
doSimpleRun(passFixtureTable());
assertSubString(testPage.getName(), results);
assertSubString("Test Results", results);
assertSubString("class", results);
assertNotSubString("ClassNotFoundException", results);
}
private void doSimpleRun(String fixtureTable) throws Exception {
doSimpleRunWithTags(fixtureTable, null);
}
private void doSimpleRunWithTags(String fixtureTable, String tags) throws Exception {
if (debug) request.addInput("debug", "true");
String simpleRunPageName = "TestPage";
testPage = WikiPageUtil.addPage(root, PathParser.parse(simpleRunPageName), classpathWidgets() + fixtureTable);
if (tags != null) {
PageData pageData = testPage.getData();
pageData.setAttribute(PageData.PropertySUITES, tags);
testPage.commit(pageData);
}
request.setResource(testPage.getName());
response = responder.makeResponse(context, request);
sender = new MockResponseSender();
sender.doSending(response);
results = sender.sentData();
}
@Test
public void testEmptyTestPage() throws Exception {
PageData data = root.getData();
data.setContent(classpathWidgets());
root.commit(data);
testPage = WikiPageUtil.addPage(root, PathParser.parse("EmptyTestPage"), "");
request.setResource(testPage.getName());
response = responder.makeResponse(context, request);
sender = new MockResponseSender();
sender.doSending(response);
sender.sentData();
WikiPagePath errorLogPath = PathParser.parse("ErrorLogs.EmptyTestPage");
WikiPage errorLogPage = root.getPageCrawler().getPage(errorLogPath);
String errorLogContent = errorLogPage.getData().getContent();
assertNotSubString("Exception", errorLogContent);
}
@Test
public void testStandardOutput() throws Exception {
String content = classpathWidgets()
+ outputWritingTable("output1")
+ outputWritingTable("output2")
+ outputWritingTable("output3");
String errorLogContent = doRunAndGetErrorLog(content);
assertHasRegexp("output1", errorLogContent);
assertHasRegexp("output2", errorLogContent);
assertHasRegexp("output3", errorLogContent);
}
@Test
public void testErrorOutput() throws Exception {
String content = classpathWidgets()
+ errorWritingTable("error1")
+ errorWritingTable("error2")
+ errorWritingTable("error3");
String errorLogContent = doRunAndGetErrorLog(content);
assertHasRegexp("error1", errorLogContent);
assertHasRegexp("error2", errorLogContent);
assertHasRegexp("error3", errorLogContent);
}
private String doRunAndGetErrorLog(String content) throws Exception {
WikiPage testPage = WikiPageUtil.addPage(root, PathParser.parse("TestPage"), content);
request.setResource(testPage.getName());
Response response = responder.makeResponse(context, request);
MockResponseSender sender = new MockResponseSender();
sender.doSending(response);
String results = sender.sentData();
assertHasRegexp("ErrorLog", results);
WikiPage errorLog = errorLogsParentPage.getChildPage(testPage.getName());
return errorLog.getData().getContent();
}
@Test
public void testHasExitValueHeader() throws Exception {
WikiPage testPage = WikiPageUtil.addPage(root, PathParser.parse("TestPage"), classpathWidgets() + passFixtureTable());
request.setResource(testPage.getName());
Response response = responder.makeResponse(context, request);
MockResponseSender sender = new MockResponseSender();
sender.doSending(response);
String results = sender.sentData();
assertSubString("Exit-Code: 0", results);
}
@Test
public void exitCodeIsCountOfErrors() throws Exception {
doSimpleRun(failFixtureTable());
assertSubString("Exit-Code: 1", results);
}
@Test
public void pageHistoryLinkIsIncluded() throws Exception {
responder.turnOffChunking();
doSimpleRun(passFixtureTable());
assertSubString("href=\"TestPage?pageHistory\">", results);
assertSubString("Page History", results);
}
@Test
public void testFixtureThatCrashes() throws Exception {
WikiPage testPage = WikiPageUtil.addPage(root, PathParser.parse("TestPage"), classpathWidgets() + crashFixtureTable());
request.setResource(testPage.getName());
Response response = responder.makeResponse(context, request);
MockResponseSender sender = new MockResponseSender();
sender.doSending(response);
String results = sender.sentData();
assertSubString("ErrorLog", results);
}
@Test
public void testResultsIncludeActions() throws Exception {
doSimpleRun(passFixtureTable());
assertSubString("<nav>", results);
}
@Test
public void testResultsDoHaveHeaderAndFooter() throws Exception {
WikiPageUtil.addPage(root, PathParser.parse("PageHeader"), "HEADER");
WikiPageUtil.addPage(root, PathParser.parse("PageFooter"), "FOOTER");
doSimpleRun(passFixtureTable());
assertSubString("HEADER", results);
assertSubString("FOOTER", results);
}
@Test
public void testExecutionStatusAppears() throws Exception {
doSimpleRun(passFixtureTable());
assertHasRegexp("Tests Executed OK", results);
}
@Test
public void simpleXmlFormat() throws Exception {
responder.turnOffChunking();
request.addInput("format", "xml");
doSimpleRun(passFixtureTable());
xmlChecker.assertFitPassFixtureXmlReportIsCorrect();
}
@Test
public void noHistory_skipsHistoryFormatter() throws Exception{
ensureXmlResultFileDoesNotExist(new TestSummary(2, 0, 0, 0));
request.addInput("nohistory", "true");
doSimpleRun(simpleSlimDecisionTable());
assertFalse(xmlResultsFile.exists());
}
private String slimDecisionTable() {
return "!define TEST_SYSTEM {slim}\n" +
"|!-DT:fitnesse.slim.test.TestSlim-!|\n" +
"|string|get string arg?|\n" +
"|right|wrong|\n" +
"|wow|wow|\n";
}
@Test
public void slimXmlFormat() throws Exception {
responder.turnOffChunking();
request.addInput("format", "xml");
ensureXmlResultFileDoesNotExist(new TestSummary(0, 1, 0, 0));
doSimpleRunWithTags(slimDecisionTable(), "zoo");
Document xmlFromFile = getXmlFromFileAndDeleteFile();
xmlChecker.assertXmlReportOfSlimDecisionTableWithZooTagIsCorrect();
xmlChecker.assertXmlHeaderIsCorrect(xmlFromFile);
xmlChecker.assertXmlReportOfSlimDecisionTableWithZooTagIsCorrect();
}
@Test
public void slimXmlFormatGivesErrorCountAsExitCode() throws Exception {
request.addInput("format", "xml");
ensureXmlResultFileDoesNotExist(new TestSummary(0, 1, 0, 0));
doSimpleRunWithTags(slimDecisionTable(), "zoo");
getXmlFromFileAndDeleteFile();
assertSubString("Exit-Code: 1", results);
}
private void ensureXmlResultFileDoesNotExist(TestSummary counts) {
String resultsFileName = String.format("%s/TestPage/20081205011900_%d_%d_%d_%d.xml",
context.getTestHistoryDirectory(), counts.getRight(), counts.getWrong(), counts.getIgnores(), counts.getExceptions());
xmlResultsFile = new File(resultsFileName);
if (xmlResultsFile.exists())
FileUtil.deleteFile(xmlResultsFile);
}
private Document getXmlFromFileAndDeleteFile() throws Exception {
assertTrue(xmlResultsFile.getAbsolutePath(), xmlResultsFile.exists());
FileInputStream xmlResultsStream = new FileInputStream(xmlResultsFile);
Document xmlDoc = XmlUtil.newDocument(xmlResultsStream);
xmlResultsStream.close();
FileUtil.deleteFile(xmlResultsFile);
return xmlDoc;
}
@Test
public void slimScenarioXmlFormat() throws Exception {
responder.turnOffChunking();
request.addInput("format", "xml");
doSimpleRun(XmlChecker.slimScenarioTable);
xmlChecker.assertXmlReportOfSlimScenarioTableIsCorrect();
}
@Test
public void simpleTextFormatForPassingTest() throws Exception {
request.addInput("format", "text");
doSimpleRun(passFixtureTable());
assertEquals("text/text", response.getContentType());
assertTrue(results.contains("\n. "));
assertTrue(results.contains("R:1 W:0 I:0 E:0 TestPage\t(TestPage)"));
assertTrue(results.contains("1 Tests,\t0 Failures"));
}
@Test
public void simpleTextFormatForFailingTest() throws Exception {
request.addInput("format", "text");
doSimpleRun(failFixtureTable());
assertEquals("text/text", response.getContentType());
assertTrue(results.contains("\nF "));
assertTrue(results.contains("R:0 W:1 I:0 E:0 TestPage\t(TestPage)"));
assertTrue(results.contains("1 Tests,\t1 Failures"));
}
@Test
public void simpleTextFormatForErrorTest() throws Exception {
request.addInput("format", "text");
doSimpleRun(errorFixtureTable());
assertEquals("text/text", response.getContentType());
assertTrue(results.contains("\nX "));
assertTrue(results.contains("R:0 W:0 I:0 E:1 TestPage\t(TestPage)"));
assertTrue(results.contains("1 Tests,\t1 Failures"));
}
@Test
public void testExecutionStatusOk() throws Exception {
doSimpleRun(passFixtureTable());
assertTrue(results.contains(">Tests Executed OK<"));
assertTrue(results.contains("\\\"ok\\\""));
}
@Test
public void debugTest() throws Exception {
request.addInput("debug", "");
doSimpleRun(passFixtureTable());
assertTrue(results.contains(">Tests Executed OK<"));
assertTrue(results.contains("\\\"ok\\\""));
assertTrue("should be fast test", responder.isDebug());
}
@Test
public void testExecutionStatusOutputCaptured() throws Exception {
debug = false;
doSimpleRun(outputWritingTable("blah"));
assertTrue(results.contains(">Output Captured<"));
assertTrue(results.contains("\\\"output\\\""));
}
@Test
public void testExecutionStatusError() throws Exception {
debug = false;
doSimpleRun(crashFixtureTable());
assertTrue(results.contains(">Errors Occurred<"));
assertTrue(results.contains("\\\"error\\\""));
}
@Test
public void testExecutionStatusErrorHasPriority() throws Exception {
debug = false;
doSimpleRun(errorWritingTable("blah") + crashFixtureTable());
assertTrue(results.contains(">Errors Occurred<"));
}
@Test
public void testTestSummaryAppears() throws Exception {
doSimpleRun(passFixtureTable());
assertHasRegexp(divWithIdAndContent("test-summary", ".*?"), results);
}
@Test
public void testTestSummaryInformationAppears() throws Exception {
doSimpleRun(passFixtureTable());
assertHasRegexp("<script>.*?document\\.getElementById\\(\"test-summary\"\\)\\.innerHTML = \".*?Assertions:.*?\";.*?</script>", results);
assertHasRegexp("<script>.*?document\\.getElementById\\(\"test-summary\"\\)\\.className = \".*?\";.*?</script>", results);
}
@Test
public void testTestSummaryHasRightClass() throws Exception {
doSimpleRun(passFixtureTable());
assertHasRegexp("<script>.*?document\\.getElementById\\(\"test-summary\"\\)\\.className = \"pass\";.*?</script>", results);
}
@Test
public void testTestHasStopped() throws Exception {
String semaphoreName = "testTestHasStopped.semaphore";
File semaphore = new File(semaphoreName);
if (semaphore.exists())
semaphore.delete();
new Thread(makeStopTestsRunnable(semaphore)).start();
doSimpleRun(createAndWaitFixture(semaphoreName));
assertHasRegexp("Testing was interrupted", results);
semaphore.delete();
}
private String createAndWaitFixture(String semaphoreName) {
return "!define TEST_SYSTEM {slim}\n" +
"!|fitnesse.testutil.CreateFileAndWaitFixture|" + semaphoreName + "|\n";
}
private Runnable makeStopTestsRunnable(File semaphore) {
return new WaitForSemaphoreThenStopProcesses(semaphore);
}
private class WaitForSemaphoreThenStopProcesses implements Runnable {
private File semaphore;
public WaitForSemaphoreThenStopProcesses(File semaphore) {
this.semaphore = semaphore;
}
public void run() {
waitForSemaphore();
context.runningTestingTracker.stopAllProcesses();
}
private void waitForSemaphore() {
try {
int i = 1000;
while (!semaphore.exists()) {
if (--i <= 0)
break;
Thread.sleep(5);
}
} catch (InterruptedException e) {
}
}
}
@Test
public void testAuthentication_RequiresTestPermission() throws Exception {
assertTrue(responder instanceof SecureResponder);
SecureOperation operation = responder.getSecureOperation();
assertEquals(SecureTestOperation.class, operation.getClass());
}
@Test
public void testSuiteSetUpAndTearDownIsCalledIfSingleTestIsRun() throws Exception {
WikiPage suitePage = WikiPageUtil.addPage(root, PathParser.parse("TestSuite"), classpathWidgets());
WikiPage testPage = WikiPageUtil.addPage(suitePage, PathParser.parse("TestPage"), outputWritingTable("Output of TestPage"));
WikiPageUtil.addPage(suitePage, PathParser.parse(PageData.SUITE_SETUP_NAME), outputWritingTable("Output of SuiteSetUp"));
WikiPageUtil.addPage(suitePage, PathParser.parse(PageData.SUITE_TEARDOWN_NAME), outputWritingTable("Output of SuiteTearDown"));
PageData data = testPage.getData();
WikiPageProperties properties = data.getProperties();
properties.set(PageData.PropertySUITES, "Test Page tags");
testPage.commit(data);
WikiPagePath testPagePath = testPage.getPageCrawler().getFullPath();
String resource = PathParser.render(testPagePath);
request.setResource(resource);
Response response = responder.makeResponse(context, request);
MockResponseSender sender = new MockResponseSender();
sender.doSending(response);
results = sender.sentData();
assertTrue(results.contains(">Output Captured<"));
assertHasRegexp("ErrorLog", results);
assertSubString("Test Page tags", results);
WikiPage errorLog = errorLogsParentPage.getPageCrawler().getPage(testPagePath);
String errorLogContent = errorLog.getData().getContent();
assertHasRegexp("Output of SuiteSetUp", errorLogContent);
assertHasRegexp("Output of TestPage", errorLogContent);
assertHasRegexp("Output of SuiteTearDown", errorLogContent);
}
@Test
public void testSuiteSetUpDoesNotIncludeSetUp() throws Exception {
WikiPage suitePage = WikiPageUtil.addPage(root, PathParser.parse("TestSuite"), classpathWidgets());
WikiPage testPage = WikiPageUtil.addPage(suitePage, PathParser.parse("TestPage"), outputWritingTable("Output of TestPage"));
WikiPageUtil.addPage(suitePage, PathParser.parse(PageData.SUITE_SETUP_NAME), outputWritingTable("Output of SuiteSetUp"));
WikiPageUtil.addPage(suitePage, PathParser.parse("SetUp"), outputWritingTable("Output of SetUp"));
WikiPagePath testPagePath = testPage.getPageCrawler().getFullPath();
String resource = PathParser.render(testPagePath);
request.setResource(resource);
Response response = responder.makeResponse(context, request);
MockResponseSender sender = new MockResponseSender();
sender.doSending(response);
results = sender.sentData();
WikiPage errorLog = errorLogsParentPage.getPageCrawler().getPage(testPagePath);
String errorLogContent = errorLog.getData().getContent();
assertMessagesOccurInOrder(errorLogContent, "Output of SuiteSetUp", "Output of SetUp", "Output of TestPage");
assertMessageHasJustOneOccurrenceOf(errorLogContent, "Output of SetUp");
}
@Test
public void testSuiteTearDownDoesNotIncludeTearDown() throws Exception {
WikiPage suitePage = WikiPageUtil.addPage(root, PathParser.parse("TestSuite"), classpathWidgets());
WikiPage testPage = WikiPageUtil.addPage(suitePage, PathParser.parse("TestPage"), outputWritingTable("Output of TestPage"));
WikiPageUtil.addPage(suitePage, PathParser.parse(PageData.SUITE_TEARDOWN_NAME), outputWritingTable("Output of SuiteTearDown"));
WikiPageUtil.addPage(suitePage, PathParser.parse("TearDown"), outputWritingTable("Output of TearDown"));
WikiPagePath testPagePath = testPage.getPageCrawler().getFullPath();
String resource = PathParser.render(testPagePath);
request.setResource(resource);
Response response = responder.makeResponse(context, request);
MockResponseSender sender = new MockResponseSender();
sender.doSending(response);
results = sender.sentData();
WikiPage errorLog = errorLogsParentPage.getPageCrawler().getPage(testPagePath);
String errorLogContent = errorLog.getData().getContent();
assertMessagesOccurInOrder(errorLogContent, "Output of TestPage", "Output of TearDown", "Output of SuiteTearDown");
assertMessageHasJustOneOccurrenceOf(errorLogContent, "Output of TearDown");
}
@Test
public void testSuiteSetUpAndSuiteTearDownWithSetUpAndTearDown() throws Exception {
WikiPage suitePage = WikiPageUtil.addPage(root, PathParser.parse("TestSuite"), classpathWidgets());
WikiPage testPage = WikiPageUtil.addPage(suitePage, PathParser.parse("TestPage"), outputWritingTable("Output of TestPage"));
WikiPageUtil.addPage(suitePage, PathParser.parse(PageData.SUITE_SETUP_NAME), outputWritingTable("Output of SuiteSetUp"));
WikiPageUtil.addPage(suitePage, PathParser.parse("SetUp"), outputWritingTable("Output of SetUp"));
WikiPageUtil.addPage(suitePage, PathParser.parse(PageData.SUITE_TEARDOWN_NAME), outputWritingTable("Output of SuiteTearDown"));
WikiPageUtil.addPage(suitePage, PathParser.parse("TearDown"), outputWritingTable("Output of TearDown"));
WikiPagePath testPagePath = testPage.getPageCrawler().getFullPath();
String resource = PathParser.render(testPagePath);
request.setResource(resource);
Response response = responder.makeResponse(context, request);
MockResponseSender sender = new MockResponseSender();
sender.doSending(response);
results = sender.sentData();
WikiPage errorLog = errorLogsParentPage.getPageCrawler().getPage(testPagePath);
String errorLogContent = errorLog.getData().getContent();
assertMessagesOccurInOrder(errorLogContent, "Output of SuiteSetUp", "Output of SetUp", "Output of TestPage", "Output of TearDown", "Output of SuiteTearDown");
assertMessageHasJustOneOccurrenceOf(errorLogContent, "Output of SetUp");
}
private void assertMessageHasJustOneOccurrenceOf(String output, String regexp) {
Matcher match = Pattern.compile(regexp, Pattern.MULTILINE | Pattern.DOTALL).matcher(output);
match.find();
boolean found = match.find();
if (found)
fail("The regexp <" + regexp + "> was more than once in: " + output + ".");
}
private void assertMessagesOccurInOrder(String errorLogContent, String... messages) {
int previousIndex = 0, currentIndex = 0;
String previousMsg = "";
for (String msg: messages) {
currentIndex = errorLogContent.indexOf(msg);
assertTrue(String.format("\"%s\" should occur not before \"%s\", but did in \"%s\"", msg, previousMsg, errorLogContent), currentIndex > previousIndex);
previousIndex = currentIndex;
previousMsg = msg;
}
}
private String simpleSlimDecisionTable() {
return "!define TEST_SYSTEM {slim}\n" +
"|!-DT:fitnesse.slim.test.TestSlim-!|\n" +
"|string|get string arg?|\n" +
"|wow|wow|\n";
}
@Test
public void checkHistoryForSimpleSlimTable() throws Exception {
ensureXmlResultFileDoesNotExist(new TestSummary(1, 0, 0, 0));
doSimpleRun(simpleSlimDecisionTable());
Document xmlFromFile = getXmlFromFileAndDeleteFile();
xmlChecker.assertXmlHeaderIsCorrect(xmlFromFile);
assertHasRegexp("<td><span class=\"pass\">wow</span></td>", Utils.unescapeHTML(results));
}
private String errorWritingTable(String message) {
return "\n|!-fitnesse.testutil.ErrorWritingFixture-!|\n" +
"|" + message + "|\n\n";
}
private String outputWritingTable(String message) {
return "\n|!-fitnesse.testutil.OutputWritingFixture-!|\n" +
"|" + message + "|\n\n";
}
private String classpathWidgets() {
return "!path classes\n";
}
private String crashFixtureTable() {
return "|!-fitnesse.testutil.CrashFixture-!|\n";
}
private String passFixtureTable() {
return "|!-fitnesse.testutil.PassFixture-!|\n";
}
private String failFixtureTable() {
return "|!-fitnesse.testutil.FailFixture-!|\n";
}
private String errorFixtureTable() {
return "|!-fitnesse.testutil.ErrorFixture-!|\n";
}
class XmlChecker {
private Element testResultsElement;
public void assertXmlHeaderIsCorrect(Document testResultsDocument) throws Exception {
testResultsElement = testResultsDocument.getDocumentElement();
assertEquals("testResults", testResultsElement.getNodeName());
String version = XmlUtil.getTextValue(testResultsElement, "FitNesseVersion");
assertEquals(new FitNesseVersion().toString(), version);
}
public void assertFitPassFixtureXmlReportIsCorrect() throws Exception {
assertHeaderOfXmlDocumentsInResponseIsCorrect();
Element result = getElementByTagName(testResultsElement, "result");
Element counts = getElementByTagName(result, "counts");
assertCounts(counts, "1", "0", "0", "0");
String runTimeInMillis = XmlUtil.getTextValue(result, "runTimeInMillis");
assertThat(Long.parseLong(runTimeInMillis), is(not(0L)));
Element tags = getElementByTagName(result, "tags");
assertNull(tags);
String content = XmlUtil.getTextValue(result, "content");
assertSubString("PassFixture", content);
String relativePageName = XmlUtil.getTextValue(result, "relativePageName");
assertEquals("TestPage", relativePageName);
}
public void assertXmlReportOfSlimDecisionTableWithZooTagIsCorrect() throws Exception {
//String instructionContents[] = {"make", "table", "beginTable", "reset", "setString", "execute", "getStringArg", "reset", "setString", "execute", "getStringArg", "endTable"};
//String instructionResults[] = {"OK", "EXCEPTION", "EXCEPTION", "EXCEPTION", "VOID", "VOID", "right", "EXCEPTION", "VOID", "VOID", "wow", "EXCEPTION"};
String instructionContents[] = {"make", "setString", "getStringArg", "setString", "getStringArg"};
String instructionResults[] = {"pass(DT:fitnesse.slim.test.TestSlim)", null, "fail(a=right;e=wrong)", null, "pass(wow)"};
assertHeaderOfXmlDocumentsInResponseIsCorrect();
Element result = getElementByTagName(testResultsElement, "result");
Element counts = getElementByTagName(result, "counts");
assertCounts(counts, "1", "1", "0", "0");
String tags = XmlUtil.getTextValue(result, "tags");
assertEquals("zoo", tags);
Element instructions = getElementByTagName(result, "instructions");
NodeList instructionList = instructions.getElementsByTagName("instructionResult");
//assertEquals(instructionContents.length, instructionList.getLength());
for (int i = 0; i < instructionContents.length; i++) {
Element instructionElement = (Element) instructionList.item(i);
assertInstructionHas(instructionElement, instructionContents[i]);
}
for (int i = 0; i < instructionResults.length; i++) {
Element instructionElement = (Element) instructionList.item(i);
assertResultHas(instructionElement, instructionResults[i]);
}
checkExpectation(instructionList, 0, "decisionTable_0_0", "0", "0", "pass", "ConstructionExpectation", null, null, "DT:fitnesse.slim.test.TestSlim");
checkExpectation(instructionList, 4, "decisionTable_0_10", "1", "3", "pass", "ReturnedValueExpectation", null, null, "wow");
}
public final static String slimScenarioTable =
"!define TEST_SYSTEM {slim}\n" +
"\n" +
"!|scenario|f|a|\n" +
"|check|echo int|@a|@a|\n" +
"\n" +
"!|script|fitnesse.slim.test.TestSlim|\n" +
"\n" +
"!|f|\n" +
"|a|\n" +
"|1|\n" +
"|2|\n";
public void assertXmlReportOfSlimScenarioTableIsCorrect() throws Exception {
assertHeaderOfXmlDocumentsInResponseIsCorrect();
Element result = getElementByTagName(testResultsElement, "result");
Element counts = getElementByTagName(result, "counts");
assertCounts(counts, "2", "0", "0", "0");
String runTimeInMillis = XmlUtil.getTextValue(result, "runTimeInMillis");
assertThat(Long.parseLong(runTimeInMillis), is(not(0L)));
assertTablesInSlimScenarioAreCorrect(result);
assertInstructionsOfSlimScenarioTableAreCorrect(result);
}
private void assertInstructionsOfSlimScenarioTableAreCorrect(Element result) throws Exception {
Element instructions = getElementByTagName(result, "instructions");
NodeList instructionList = instructions.getElementsByTagName("instructionResult");
assertInstructionContentsOfSlimScenarioAreCorrect(instructionList);
assertInstructionResultsOfSlimScenarioAreCorrect(instructionList);
assertExpectationsOfSlimScenarioAreCorrect(instructionList);
}
private void assertExpectationsOfSlimScenarioAreCorrect(NodeList instructionList) throws Exception {
checkExpectation(instructionList, 0, "scriptTable_1_0", "1", "0", "pass", "ConstructionExpectation", null, null, "fitnesse.slim.test.TestSlim");
checkExpectation(instructionList, 1, "decisionTable_2_0/scriptTable_0_0", "3", "1", "pass", "ReturnedValueExpectation", null, null, "1");
checkExpectation(instructionList, 2, "decisionTable_2_1/scriptTable_0_0", "3", "1", "pass", "ReturnedValueExpectation", null, null, "2");
}
private void assertInstructionResultsOfSlimScenarioAreCorrect(NodeList instructionList) throws Exception {
String instructionResults[] = {"pass", "1", "2"};
for (int i = 0; i < instructionResults.length; i++) {
Element instructionElement = (Element) instructionList.item(i);
assertResultHas(instructionElement, instructionResults[i]);
}
}
private void assertInstructionContentsOfSlimScenarioAreCorrect(NodeList instructionList) throws Exception {
String instructionContents[] = {"make", "call", "call"};
assertEquals(instructionContents.length, instructionList.getLength());
for (int i = 0; i < instructionContents.length; i++) {
Element instructionElement = (Element) instructionList.item(i);
assertInstructionHas(instructionElement, instructionContents[i]);
}
}
private void assertTablesInSlimScenarioAreCorrect(Element result) throws Exception {
// Element tables = getElementByTagName(result, "tables");
// NodeList tableList = tables.getElementsByTagName("table");
// assertEquals(5, tableList.getLength());
//
// String tableNames[] = {"scenarioTable_0", "scriptTable_1", "decisionTable_2", "decisionTable_2_0/scriptTable_0", "decisionTable_2_1/scriptTable_0"};
// String tableValues[][][] = {
// {
// {"scenario", "f", "a"},
// {"check", "echo int", "@a", "@a"}
// },
// {
// {"script", "pass(fitnesse.slim.test.TestSlim)"}
// },
// {
// {"f"},
// {"a"},
// {"1", "pass(scenario:decisionTable_2_0/scriptTable_0)"},
// {"2", "pass(scenario:decisionTable_2_1/scriptTable_0)"}
// },
// {
// {"scenario", "f", "a"},
// {"check", "echo int", "1", "pass(1)"}
// },
// {
// {"scenario", "f", "a"},
// {"check", "echo int", "2", "pass(2)"}
// }
// };
//
// for (int tableIndex = 0; tableIndex < tableList.getLength(); tableIndex++) {
// assertEquals(tableNames[tableIndex], XmlUtil.getTextValue((Element) tableList.item(tableIndex), "name"));
//
// Element tableElement = (Element) tableList.item(tableIndex);
// NodeList rowList = tableElement.getElementsByTagName("row");
// for (int rowIndex = 0; rowIndex < rowList.getLength(); rowIndex++) {
// NodeList colList = ((Element) rowList.item(rowIndex)).getElementsByTagName("col");
// for (int colIndex = 0; colIndex < colList.getLength(); colIndex++)
// assertEquals(tableValues[tableIndex][rowIndex][colIndex], XmlUtil.getElementText((Element) colList.item(colIndex)));
// }
// }
}
private void checkExpectation(NodeList instructionList, int index, String id, String col, String row, String status, String type, String actual, String expected, String message) throws Exception {
Element instructionElement = (Element) instructionList.item(index);
Element expectation = getElementByTagName(instructionElement, "expectation");
assertEquals(id, XmlUtil.getTextValue(expectation, "instructionId"));
assertEquals(status, XmlUtil.getTextValue(expectation, "status"));
assertEquals(type, XmlUtil.getTextValue(expectation, "type"));
assertEquals(col, XmlUtil.getTextValue(expectation, "col"));
assertEquals(row, XmlUtil.getTextValue(expectation, "row"));
assertEquals(actual, XmlUtil.getTextValue(expectation, "actual"));
assertEquals(expected, XmlUtil.getTextValue(expectation, "expected"));
assertEquals(message, XmlUtil.getTextValue(expectation, "evaluationMessage"));
}
private void assertInstructionHas(Element instructionElement, String content) throws Exception {
String instruction = XmlUtil.getTextValue(instructionElement, "instruction");
assertTrue(String.format("instruction %s should contain: %s", instruction, content), instruction.contains(content));
}
private void assertResultHas(Element instructionElement, String content) throws Exception {
String result = XmlUtil.getTextValue(instructionElement, "slimResult");
assertTrue(String.format("result %s should contain: %s", result, content), (result == null && content == null) || result.contains(content));
}
private void assertHeaderOfXmlDocumentsInResponseIsCorrect() throws Exception {
assertEquals("text/xml", response.getContentType());
Document testResultsDocument = getXmlDocumentFromResults(results);
xmlChecker.assertXmlHeaderIsCorrect(testResultsDocument);
}
}
public static class XmlTestUtilities {
public static Document getXmlDocumentFromResults(String results) throws Exception {
String endOfXml = "</testResults>";
String startOfXml = "<?xml";
int xmlStartIndex = results.indexOf(startOfXml);
int xmlEndIndex = results.indexOf(endOfXml) + endOfXml.length();
String xmlString = results.substring(xmlStartIndex, xmlEndIndex);
return XmlUtil.newDocument(xmlString);
}
public static void assertCounts(Element counts, String right, String wrong, String ignores, String exceptions)
throws Exception {
assertEquals(right, XmlUtil.getTextValue(counts, "right"));
assertEquals(wrong, XmlUtil.getTextValue(counts, "wrong"));
assertEquals(ignores, XmlUtil.getTextValue(counts, "ignores"));
assertEquals(exceptions, XmlUtil.getTextValue(counts, "exceptions"));
}
}
}
| test/fitnesse/responders/run/TestResponderTest.java | // Copyright (C) 2003-2009 by Object Mentor, Inc. All rights reserved.
// Released under the terms of the CPL Common Public License version 1.0.
package fitnesse.responders.run;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import fitnesse.FitNesseContext;
import fitnesse.FitNesseVersion;
import fitnesse.authentication.SecureOperation;
import fitnesse.authentication.SecureResponder;
import fitnesse.authentication.SecureTestOperation;
import fitnesse.http.MockRequest;
import fitnesse.http.MockResponseSender;
import fitnesse.http.Response;
import fitnesse.testsystems.TestSummary;
import fitnesse.testutil.FitNesseUtil;
import fitnesse.wiki.PageData;
import fitnesse.wiki.PathParser;
import fitnesse.wiki.WikiPage;
import fitnesse.wiki.WikiPagePath;
import fitnesse.wiki.WikiPageProperties;
import fitnesse.wiki.WikiPageUtil;
import fitnesse.wiki.mem.InMemoryPage;
import fitnesse.wikitext.Utils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import util.Clock;
import util.DateAlteringClock;
import util.DateTimeUtil;
import util.FileUtil;
import util.XmlUtil;
import static fitnesse.responders.run.TestResponderTest.XmlTestUtilities.assertCounts;
import static fitnesse.responders.run.TestResponderTest.XmlTestUtilities.getXmlDocumentFromResults;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.*;
import static util.RegexTestCase.*;
import static util.XmlUtil.getElementByTagName;
public class TestResponderTest {
private static final String TEST_TIME = "12/5/2008 01:19:00";
private WikiPage root;
private MockRequest request;
private TestResponder responder;
private FitNesseContext context;
private Response response;
private MockResponseSender sender;
private WikiPage testPage;
private String results;
private WikiPage errorLogsParentPage;
private File xmlResultsFile;
private XmlChecker xmlChecker = new XmlChecker();
private boolean debug;
@Before
public void setUp() throws Exception {
debug = true;
File testDir = new File("TestDir");
testDir.mkdir();
Properties properties = new Properties();
root = InMemoryPage.makeRoot("Root", properties);
errorLogsParentPage = WikiPageUtil.addPage(root, PathParser.parse("ErrorLogs"));
request = new MockRequest();
responder = new TestResponder();
context = FitNesseUtil.makeTestContext(root);
properties.setProperty("FITNESSE_PORT", String.valueOf(context.port));
new DateAlteringClock(DateTimeUtil.getDateFromString(TEST_TIME)).advanceMillisOnEachQuery();
}
@After
public void tearDown() throws Exception {
FitNesseUtil.destroyTestContext();
Clock.restoreDefaultClock();
}
@Test
public void testIsValidHtml() throws Exception {
doSimpleRun(passFixtureTable());
assertSubString("<!DOCTYPE html>", results);
assertSubString("</html>", results);
//assertSubString("<base href=\"http://somehost.com:8080/\"", results);
assertSubString("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>", results);
//assertSubString("Command Line Test Results", html);
}
@Test
public void testHead() throws Exception {
doSimpleRun(passFixtureTable());
assertSubString("<div id=\"test-summary\">Running Tests ...</div>", results);
}
@Test
public void testSimpleRun() throws Exception {
doSimpleRun(passFixtureTable());
assertSubString(testPage.getName(), results);
assertSubString("Test Results", results);
assertSubString("class", results);
assertNotSubString("ClassNotFoundException", results);
}
private void doSimpleRun(String fixtureTable) throws Exception {
doSimpleRunWithTags(fixtureTable, null);
}
private void doSimpleRunWithTags(String fixtureTable, String tags) throws Exception {
if (debug) request.addInput("debug", "true");
String simpleRunPageName = "TestPage";
testPage = WikiPageUtil.addPage(root, PathParser.parse(simpleRunPageName), classpathWidgets() + fixtureTable);
if (tags != null) {
PageData pageData = testPage.getData();
pageData.setAttribute(PageData.PropertySUITES, tags);
testPage.commit(pageData);
}
request.setResource(testPage.getName());
response = responder.makeResponse(context, request);
sender = new MockResponseSender();
sender.doSending(response);
results = sender.sentData();
}
@Test
public void testEmptyTestPage() throws Exception {
PageData data = root.getData();
data.setContent(classpathWidgets());
root.commit(data);
testPage = WikiPageUtil.addPage(root, PathParser.parse("EmptyTestPage"), "");
request.setResource(testPage.getName());
response = responder.makeResponse(context, request);
sender = new MockResponseSender();
sender.doSending(response);
sender.sentData();
WikiPagePath errorLogPath = PathParser.parse("ErrorLogs.EmptyTestPage");
WikiPage errorLogPage = root.getPageCrawler().getPage(errorLogPath);
String errorLogContent = errorLogPage.getData().getContent();
assertNotSubString("Exception", errorLogContent);
}
@Test
public void testStandardOutput() throws Exception {
String content = classpathWidgets()
+ outputWritingTable("output1")
+ outputWritingTable("output2")
+ outputWritingTable("output3");
String errorLogContent = doRunAndGetErrorLog(content);
assertHasRegexp("output1", errorLogContent);
assertHasRegexp("output2", errorLogContent);
assertHasRegexp("output3", errorLogContent);
}
@Test
public void testErrorOutput() throws Exception {
String content = classpathWidgets()
+ errorWritingTable("error1")
+ errorWritingTable("error2")
+ errorWritingTable("error3");
String errorLogContent = doRunAndGetErrorLog(content);
assertHasRegexp("error1", errorLogContent);
assertHasRegexp("error2", errorLogContent);
assertHasRegexp("error3", errorLogContent);
}
private String doRunAndGetErrorLog(String content) throws Exception {
WikiPage testPage = WikiPageUtil.addPage(root, PathParser.parse("TestPage"), content);
request.setResource(testPage.getName());
Response response = responder.makeResponse(context, request);
MockResponseSender sender = new MockResponseSender();
sender.doSending(response);
String results = sender.sentData();
assertHasRegexp("ErrorLog", results);
WikiPage errorLog = errorLogsParentPage.getChildPage(testPage.getName());
return errorLog.getData().getContent();
}
@Test
public void testHasExitValueHeader() throws Exception {
WikiPage testPage = WikiPageUtil.addPage(root, PathParser.parse("TestPage"), classpathWidgets() + passFixtureTable());
request.setResource(testPage.getName());
Response response = responder.makeResponse(context, request);
MockResponseSender sender = new MockResponseSender();
sender.doSending(response);
String results = sender.sentData();
assertSubString("Exit-Code: 0", results);
}
@Test
public void exitCodeIsCountOfErrors() throws Exception {
doSimpleRun(failFixtureTable());
assertSubString("Exit-Code: 1", results);
}
@Test
public void pageHistoryLinkIsIncluded() throws Exception {
responder.turnOffChunking();
doSimpleRun(passFixtureTable());
assertSubString("href=\"TestPage?pageHistory\">", results);
assertSubString("Page History", results);
}
@Test
public void testFixtureThatCrashes() throws Exception {
WikiPage testPage = WikiPageUtil.addPage(root, PathParser.parse("TestPage"), classpathWidgets() + crashFixtureTable());
request.setResource(testPage.getName());
Response response = responder.makeResponse(context, request);
MockResponseSender sender = new MockResponseSender();
sender.doSending(response);
String results = sender.sentData();
assertSubString("ErrorLog", results);
}
@Test
public void testResultsIncludeActions() throws Exception {
doSimpleRun(passFixtureTable());
assertSubString("<nav>", results);
}
@Test
public void testResultsDoHaveHeaderAndFooter() throws Exception {
WikiPageUtil.addPage(root, PathParser.parse("PageHeader"), "HEADER");
WikiPageUtil.addPage(root, PathParser.parse("PageFooter"), "FOOTER");
doSimpleRun(passFixtureTable());
assertSubString("HEADER", results);
assertSubString("FOOTER", results);
}
@Test
public void testExecutionStatusAppears() throws Exception {
doSimpleRun(passFixtureTable());
assertHasRegexp("Tests Executed OK", results);
}
@Test
public void simpleXmlFormat() throws Exception {
responder.turnOffChunking();
request.addInput("format", "xml");
doSimpleRun(passFixtureTable());
xmlChecker.assertFitPassFixtureXmlReportIsCorrect();
}
@Test
public void noHistory_skipsHistoryFormatter() throws Exception{
ensureXmlResultFileDoesNotExist(new TestSummary(2, 0, 0, 0));
request.addInput("nohistory", "true");
doSimpleRun(simpleSlimDecisionTable());
assertFalse(xmlResultsFile.exists());
}
private String slimDecisionTable() {
return "!define TEST_SYSTEM {slim}\n" +
"|!-DT:fitnesse.slim.test.TestSlim-!|\n" +
"|string|get string arg?|\n" +
"|right|wrong|\n" +
"|wow|wow|\n";
}
@Test
public void slimXmlFormat() throws Exception {
responder.turnOffChunking();
request.addInput("format", "xml");
ensureXmlResultFileDoesNotExist(new TestSummary(0, 1, 0, 0));
doSimpleRunWithTags(slimDecisionTable(), "zoo");
Document xmlFromFile = getXmlFromFileAndDeleteFile();
xmlChecker.assertXmlReportOfSlimDecisionTableWithZooTagIsCorrect();
xmlChecker.assertXmlHeaderIsCorrect(xmlFromFile);
xmlChecker.assertXmlReportOfSlimDecisionTableWithZooTagIsCorrect();
}
@Test
public void slimXmlFormatGivesErrorCountAsExitCode() throws Exception {
request.addInput("format", "xml");
ensureXmlResultFileDoesNotExist(new TestSummary(0, 1, 0, 0));
doSimpleRunWithTags(slimDecisionTable(), "zoo");
getXmlFromFileAndDeleteFile();
assertSubString("Exit-Code: 1", results);
}
private void ensureXmlResultFileDoesNotExist(TestSummary counts) {
String resultsFileName = String.format("%s/TestPage/20081205011900_%d_%d_%d_%d.xml",
context.getTestHistoryDirectory(), counts.getRight(), counts.getWrong(), counts.getIgnores(), counts.getExceptions());
xmlResultsFile = new File(resultsFileName);
if (xmlResultsFile.exists())
FileUtil.deleteFile(xmlResultsFile);
}
private Document getXmlFromFileAndDeleteFile() throws Exception {
assertTrue(xmlResultsFile.getAbsolutePath(), xmlResultsFile.exists());
FileInputStream xmlResultsStream = new FileInputStream(xmlResultsFile);
Document xmlDoc = XmlUtil.newDocument(xmlResultsStream);
xmlResultsStream.close();
FileUtil.deleteFile(xmlResultsFile);
return xmlDoc;
}
@Test
public void slimScenarioXmlFormat() throws Exception {
responder.turnOffChunking();
request.addInput("format", "xml");
doSimpleRun(XmlChecker.slimScenarioTable);
xmlChecker.assertXmlReportOfSlimScenarioTableIsCorrect();
}
@Test
public void simpleTextFormatForPassingTest() throws Exception {
request.addInput("format", "text");
doSimpleRun(passFixtureTable());
assertEquals("text/text", response.getContentType());
assertTrue(results.contains("\n. "));
assertTrue(results.contains("R:1 W:0 I:0 E:0 TestPage\t(TestPage)"));
assertTrue(results.contains("1 Tests,\t0 Failures"));
}
@Test
public void simpleTextFormatForFailingTest() throws Exception {
request.addInput("format", "text");
doSimpleRun(failFixtureTable());
assertEquals("text/text", response.getContentType());
assertTrue(results.contains("\nF "));
assertTrue(results.contains("R:0 W:1 I:0 E:0 TestPage\t(TestPage)"));
assertTrue(results.contains("1 Tests,\t1 Failures"));
}
@Test
public void simpleTextFormatForErrorTest() throws Exception {
request.addInput("format", "text");
doSimpleRun(errorFixtureTable());
assertEquals("text/text", response.getContentType());
assertTrue(results.contains("\nX "));
assertTrue(results.contains("R:0 W:0 I:0 E:1 TestPage\t(TestPage)"));
assertTrue(results.contains("1 Tests,\t1 Failures"));
}
@Test
public void testExecutionStatusOk() throws Exception {
doSimpleRun(passFixtureTable());
assertTrue(results.contains(">Tests Executed OK<"));
assertTrue(results.contains("\\\"ok\\\""));
}
@Test
public void debugTest() throws Exception {
request.addInput("debug", "");
doSimpleRun(passFixtureTable());
assertTrue(results.contains(">Tests Executed OK<"));
assertTrue(results.contains("\\\"ok\\\""));
assertTrue("should be fast test", responder.isDebug());
}
@Test
public void testExecutionStatusOutputCaptured() throws Exception {
debug = false;
doSimpleRun(outputWritingTable("blah"));
assertTrue(results.contains(">Output Captured<"));
assertTrue(results.contains("\\\"output\\\""));
}
@Test
public void testExecutionStatusError() throws Exception {
debug = false;
doSimpleRun(crashFixtureTable());
assertTrue(results.contains(">Errors Occurred<"));
assertTrue(results.contains("\\\"error\\\""));
}
@Test
public void testExecutionStatusErrorHasPriority() throws Exception {
debug = false;
doSimpleRun(errorWritingTable("blah") + crashFixtureTable());
assertTrue(results.contains(">Errors Occurred<"));
}
@Test
public void testTestSummaryAppears() throws Exception {
doSimpleRun(passFixtureTable());
assertHasRegexp(divWithIdAndContent("test-summary", ".*?"), results);
}
@Test
public void testTestSummaryInformationAppears() throws Exception {
doSimpleRun(passFixtureTable());
assertHasRegexp("<script>.*?document\\.getElementById\\(\"test-summary\"\\)\\.innerHTML = \".*?Assertions:.*?\";.*?</script>", results);
assertHasRegexp("<script>.*?document\\.getElementById\\(\"test-summary\"\\)\\.className = \".*?\";.*?</script>", results);
}
@Test
public void testTestSummaryHasRightClass() throws Exception {
doSimpleRun(passFixtureTable());
assertHasRegexp("<script>.*?document\\.getElementById\\(\"test-summary\"\\)\\.className = \"pass\";.*?</script>", results);
}
@Test
public void testTestHasStopped() throws Exception {
String semaphoreName = "testTestHasStopped.semaphore";
File semaphore = new File(semaphoreName);
if (semaphore.exists())
semaphore.delete();
new Thread(makeStopTestsRunnable(semaphore)).start();
doSimpleRun(createAndWaitFixture(semaphoreName));
assertHasRegexp("Testing was interrupted", results);
semaphore.delete();
}
private String createAndWaitFixture(String semaphoreName) {
return "!define TEST_SYSTEM {slim}\n" +
"!|fitnesse.testutil.CreateFileAndWaitFixture|" + semaphoreName + "|\n";
}
private Runnable makeStopTestsRunnable(File semaphore) {
return new WaitForSemaphoreThenStopProcesses(semaphore);
}
private class WaitForSemaphoreThenStopProcesses implements Runnable {
private File semaphore;
public WaitForSemaphoreThenStopProcesses(File semaphore) {
this.semaphore = semaphore;
}
public void run() {
waitForSemaphore();
context.runningTestingTracker.stopAllProcesses();
}
private void waitForSemaphore() {
try {
int i = 1000;
while (!semaphore.exists()) {
if (--i <= 0)
break;
Thread.sleep(5);
}
} catch (InterruptedException e) {
}
}
}
@Test
public void testAuthentication_RequiresTestPermission() throws Exception {
assertTrue(responder instanceof SecureResponder);
SecureOperation operation = responder.getSecureOperation();
assertEquals(SecureTestOperation.class, operation.getClass());
}
@Test
public void testSuiteSetUpAndTearDownIsCalledIfSingleTestIsRun() throws Exception {
WikiPage suitePage = WikiPageUtil.addPage(root, PathParser.parse("TestSuite"), classpathWidgets());
WikiPage testPage = WikiPageUtil.addPage(suitePage, PathParser.parse("TestPage"), outputWritingTable("Output of TestPage"));
WikiPageUtil.addPage(suitePage, PathParser.parse(PageData.SUITE_SETUP_NAME), outputWritingTable("Output of SuiteSetUp"));
WikiPageUtil.addPage(suitePage, PathParser.parse(PageData.SUITE_TEARDOWN_NAME), outputWritingTable("Output of SuiteTearDown"));
PageData data = testPage.getData();
WikiPageProperties properties = data.getProperties();
properties.set(PageData.PropertySUITES, "Test Page tags");
testPage.commit(data);
WikiPagePath testPagePath = testPage.getPageCrawler().getFullPath();
String resource = PathParser.render(testPagePath);
request.setResource(resource);
Response response = responder.makeResponse(context, request);
MockResponseSender sender = new MockResponseSender();
sender.doSending(response);
results = sender.sentData();
assertTrue(results.contains(">Output Captured<"));
assertHasRegexp("ErrorLog", results);
assertSubString("Test Page tags", results);
WikiPage errorLog = errorLogsParentPage.getPageCrawler().getPage(testPagePath);
String errorLogContent = errorLog.getData().getContent();
assertHasRegexp("Output of SuiteSetUp", errorLogContent);
assertHasRegexp("Output of TestPage", errorLogContent);
assertHasRegexp("Output of SuiteTearDown", errorLogContent);
}
@Test
public void testSuiteSetUpDoesNotIncludeSetUp() throws Exception {
WikiPage suitePage = WikiPageUtil.addPage(root, PathParser.parse("TestSuite"), classpathWidgets());
WikiPage testPage = WikiPageUtil.addPage(suitePage, PathParser.parse("TestPage"), outputWritingTable("Output of TestPage"));
WikiPageUtil.addPage(suitePage, PathParser.parse(PageData.SUITE_SETUP_NAME), outputWritingTable("Output of SuiteSetUp"));
WikiPageUtil.addPage(suitePage, PathParser.parse("SetUp"), outputWritingTable("Output of SetUp"));
WikiPagePath testPagePath = testPage.getPageCrawler().getFullPath();
String resource = PathParser.render(testPagePath);
request.setResource(resource);
Response response = responder.makeResponse(context, request);
MockResponseSender sender = new MockResponseSender();
sender.doSending(response);
results = sender.sentData();
WikiPage errorLog = errorLogsParentPage.getPageCrawler().getPage(testPagePath);
String errorLogContent = errorLog.getData().getContent();
assertMessagesOccurInOrder(errorLogContent, "Output of SuiteSetUp", "Output of SetUp", "Output of TestPage");
assertMessageHasJustOneOccurrenceOf(errorLogContent, "Output of SetUp");
}
@Test
public void testSuiteTearDownDoesNotIncludeTearDown() throws Exception {
WikiPage suitePage = WikiPageUtil.addPage(root, PathParser.parse("TestSuite"), classpathWidgets());
WikiPage testPage = WikiPageUtil.addPage(suitePage, PathParser.parse("TestPage"), outputWritingTable("Output of TestPage"));
WikiPageUtil.addPage(suitePage, PathParser.parse(PageData.SUITE_TEARDOWN_NAME), outputWritingTable("Output of SuiteTearDown"));
WikiPageUtil.addPage(suitePage, PathParser.parse("TearDown"), outputWritingTable("Output of TearDown"));
WikiPagePath testPagePath = testPage.getPageCrawler().getFullPath();
String resource = PathParser.render(testPagePath);
request.setResource(resource);
Response response = responder.makeResponse(context, request);
MockResponseSender sender = new MockResponseSender();
sender.doSending(response);
results = sender.sentData();
WikiPage errorLog = errorLogsParentPage.getPageCrawler().getPage(testPagePath);
String errorLogContent = errorLog.getData().getContent();
assertMessagesOccurInOrder(errorLogContent, "Output of TestPage", "Output of TearDown", "Output of SuiteTearDown");
assertMessageHasJustOneOccurrenceOf(errorLogContent, "Output of TearDown");
}
@Test
public void testSuiteSetUpAndSuiteTearDownWithSetUpAndTearDown() throws Exception {
WikiPage suitePage = WikiPageUtil.addPage(root, PathParser.parse("TestSuite"), classpathWidgets());
WikiPage testPage = WikiPageUtil.addPage(suitePage, PathParser.parse("TestPage"), outputWritingTable("Output of TestPage"));
WikiPageUtil.addPage(suitePage, PathParser.parse(PageData.SUITE_SETUP_NAME), outputWritingTable("Output of SuiteSetUp"));
WikiPageUtil.addPage(suitePage, PathParser.parse("SetUp"), outputWritingTable("Output of SetUp"));
WikiPageUtil.addPage(suitePage, PathParser.parse(PageData.SUITE_TEARDOWN_NAME), outputWritingTable("Output of SuiteTearDown"));
WikiPageUtil.addPage(suitePage, PathParser.parse("TearDown"), outputWritingTable("Output of TearDown"));
WikiPagePath testPagePath = testPage.getPageCrawler().getFullPath();
String resource = PathParser.render(testPagePath);
request.setResource(resource);
Response response = responder.makeResponse(context, request);
MockResponseSender sender = new MockResponseSender();
sender.doSending(response);
results = sender.sentData();
WikiPage errorLog = errorLogsParentPage.getPageCrawler().getPage(testPagePath);
String errorLogContent = errorLog.getData().getContent();
assertMessagesOccurInOrder(errorLogContent, "Output of SuiteSetUp", "Output of SetUp", "Output of TestPage", "Output of TearDown", "Output of SuiteTearDown");
assertMessageHasJustOneOccurrenceOf(errorLogContent, "Output of SetUp");
}
private void assertMessageHasJustOneOccurrenceOf(String output, String regexp) {
Matcher match = Pattern.compile(regexp, Pattern.MULTILINE | Pattern.DOTALL).matcher(output);
match.find();
boolean found = match.find();
if (found)
fail("The regexp <" + regexp + "> was more than once in: " + output + ".");
}
private void assertMessagesOccurInOrder(String errorLogContent, String... messages) {
int previousIndex = 0, currentIndex = 0;
String previousMsg = "";
for (String msg: messages) {
currentIndex = errorLogContent.indexOf(msg);
assertTrue(String.format("\"%s\" should occur not before \"%s\", but did in \"%s\"", msg, previousMsg, errorLogContent), currentIndex > previousIndex);
previousIndex = currentIndex;
previousMsg = msg;
}
}
private String simpleSlimDecisionTable() {
return "!define TEST_SYSTEM {slim}\n" +
"|!-DT:fitnesse.slim.test.TestSlim-!|\n" +
"|string|get string arg?|\n" +
"|wow|wow|\n";
}
@Test
public void checkHistoryForSimpleSlimTable() throws Exception {
ensureXmlResultFileDoesNotExist(new TestSummary(1, 0, 0, 0));
doSimpleRun(simpleSlimDecisionTable());
Document xmlFromFile = getXmlFromFileAndDeleteFile();
xmlChecker.assertXmlHeaderIsCorrect(xmlFromFile);
assertHasRegexp("<td><span class=\"pass\">wow</span></td>", Utils.unescapeHTML(results));
}
private String errorWritingTable(String message) {
return "\n|!-fitnesse.testutil.ErrorWritingFixture-!|\n" +
"|" + message + "|\n\n";
}
private String outputWritingTable(String message) {
return "\n|!-fitnesse.testutil.OutputWritingFixture-!|\n" +
"|" + message + "|\n\n";
}
private String classpathWidgets() {
return "!path classes\n";
}
private String crashFixtureTable() {
return "|!-fitnesse.testutil.CrashFixture-!|\n";
}
private String passFixtureTable() {
return "|!-fitnesse.testutil.PassFixture-!|\n";
}
private String failFixtureTable() {
return "|!-fitnesse.testutil.FailFixture-!|\n";
}
private String errorFixtureTable() {
return "|!-fitnesse.testutil.ErrorFixture-!|\n";
}
class XmlChecker {
private Element testResultsElement;
public void assertXmlHeaderIsCorrect(Document testResultsDocument) throws Exception {
testResultsElement = testResultsDocument.getDocumentElement();
assertEquals("testResults", testResultsElement.getNodeName());
String version = XmlUtil.getTextValue(testResultsElement, "FitNesseVersion");
assertEquals(new FitNesseVersion().toString(), version);
}
public void assertFitPassFixtureXmlReportIsCorrect() throws Exception {
assertHeaderOfXmlDocumentsInResponseIsCorrect();
Element result = getElementByTagName(testResultsElement, "result");
Element counts = getElementByTagName(result, "counts");
assertCounts(counts, "1", "0", "0", "0");
String runTimeInMillis = XmlUtil.getTextValue(result, "runTimeInMillis");
assertThat(Long.parseLong(runTimeInMillis), is(not(0L)));
Element tags = getElementByTagName(result, "tags");
assertNull(tags);
String content = XmlUtil.getTextValue(result, "content");
assertSubString("PassFixture", content);
String relativePageName = XmlUtil.getTextValue(result, "relativePageName");
assertEquals("TestPage", relativePageName);
}
public void assertXmlReportOfSlimDecisionTableWithZooTagIsCorrect() throws Exception {
//String instructionContents[] = {"make", "table", "beginTable", "reset", "setString", "execute", "getStringArg", "reset", "setString", "execute", "getStringArg", "endTable"};
//String instructionResults[] = {"OK", "EXCEPTION", "EXCEPTION", "EXCEPTION", "VOID", "VOID", "right", "EXCEPTION", "VOID", "VOID", "wow", "EXCEPTION"};
String instructionContents[] = {"make", "setString", "getStringArg", "setString", "getStringArg"};
String instructionResults[] = {"pass(DT:fitnesse.slim.test.TestSlim)", null, "fail(a=right;e=wrong)", null, "pass(wow)"};
assertHeaderOfXmlDocumentsInResponseIsCorrect();
Element result = getElementByTagName(testResultsElement, "result");
Element counts = getElementByTagName(result, "counts");
assertCounts(counts, "1", "1", "0", "0");
String tags = XmlUtil.getTextValue(result, "tags");
assertEquals("zoo", tags);
Element instructions = getElementByTagName(result, "instructions");
NodeList instructionList = instructions.getElementsByTagName("instructionResult");
//assertEquals(instructionContents.length, instructionList.getLength());
for (int i = 0; i < instructionContents.length; i++) {
Element instructionElement = (Element) instructionList.item(i);
assertInstructionHas(instructionElement, instructionContents[i]);
}
for (int i = 0; i < instructionResults.length; i++) {
Element instructionElement = (Element) instructionList.item(i);
assertResultHas(instructionElement, instructionResults[i]);
}
checkExpectation(instructionList, 0, "decisionTable_0_0", "0", "0", "pass", "ConstructionExpectation", null, null, "DT:fitnesse.slim.test.TestSlim");
checkExpectation(instructionList, 4, "decisionTable_0_10", "1", "3", "pass", "ReturnedValueExpectation", null, null, "wow");
}
public final static String slimScenarioTable =
"!define TEST_SYSTEM {slim}\n" +
"\n" +
"!|scenario|f|a|\n" +
"|check|echo int|@a|@a|\n" +
"\n" +
"!|script|fitnesse.slim.test.TestSlim|\n" +
"\n" +
"!|f|\n" +
"|a|\n" +
"|1|\n" +
"|2|\n";
public void assertXmlReportOfSlimScenarioTableIsCorrect() throws Exception {
assertHeaderOfXmlDocumentsInResponseIsCorrect();
Element result = getElementByTagName(testResultsElement, "result");
Element counts = getElementByTagName(result, "counts");
assertCounts(counts, "2", "0", "0", "0");
String runTimeInMillis = XmlUtil.getTextValue(result, "runTimeInMillis");
assertThat(Long.parseLong(runTimeInMillis), is(not(0L)));
assertTablesInSlimScenarioAreCorrect(result);
assertInstructionsOfSlimScenarioTableAreCorrect(result);
}
private void assertInstructionsOfSlimScenarioTableAreCorrect(Element result) throws Exception {
Element instructions = getElementByTagName(result, "instructions");
NodeList instructionList = instructions.getElementsByTagName("instructionResult");
assertInstructionContentsOfSlimScenarioAreCorrect(instructionList);
assertInstructionResultsOfSlimScenarioAreCorrect(instructionList);
assertExpectationsOfSlimScenarioAreCorrect(instructionList);
}
private void assertExpectationsOfSlimScenarioAreCorrect(NodeList instructionList) throws Exception {
checkExpectation(instructionList, 0, "scriptTable_1_0", "1", "0", "pass", "ConstructionExpectation", null, null, "fitnesse.slim.test.TestSlim");
checkExpectation(instructionList, 1, "decisionTable_2_0/scriptTable_0_0", "3", "1", "pass", "ReturnedValueExpectation", null, null, "1");
checkExpectation(instructionList, 2, "decisionTable_2_1/scriptTable_0_0", "3", "1", "pass", "ReturnedValueExpectation", null, null, "2");
}
private void assertInstructionResultsOfSlimScenarioAreCorrect(NodeList instructionList) throws Exception {
String instructionResults[] = {"pass", "1", "2"};
for (int i = 0; i < instructionResults.length; i++) {
Element instructionElement = (Element) instructionList.item(i);
assertResultHas(instructionElement, instructionResults[i]);
}
}
private void assertInstructionContentsOfSlimScenarioAreCorrect(NodeList instructionList) throws Exception {
String instructionContents[] = {"make", "call", "call"};
assertEquals(instructionContents.length, instructionList.getLength());
for (int i = 0; i < instructionContents.length; i++) {
Element instructionElement = (Element) instructionList.item(i);
assertInstructionHas(instructionElement, instructionContents[i]);
}
}
private void assertTablesInSlimScenarioAreCorrect(Element result) throws Exception {
// Element tables = getElementByTagName(result, "tables");
// NodeList tableList = tables.getElementsByTagName("table");
// assertEquals(5, tableList.getLength());
//
// String tableNames[] = {"scenarioTable_0", "scriptTable_1", "decisionTable_2", "decisionTable_2_0/scriptTable_0", "decisionTable_2_1/scriptTable_0"};
// String tableValues[][][] = {
// {
// {"scenario", "f", "a"},
// {"check", "echo int", "@a", "@a"}
// },
// {
// {"script", "pass(fitnesse.slim.test.TestSlim)"}
// },
// {
// {"f"},
// {"a"},
// {"1", "pass(scenario:decisionTable_2_0/scriptTable_0)"},
// {"2", "pass(scenario:decisionTable_2_1/scriptTable_0)"}
// },
// {
// {"scenario", "f", "a"},
// {"check", "echo int", "1", "pass(1)"}
// },
// {
// {"scenario", "f", "a"},
// {"check", "echo int", "2", "pass(2)"}
// }
// };
//
// for (int tableIndex = 0; tableIndex < tableList.getLength(); tableIndex++) {
// assertEquals(tableNames[tableIndex], XmlUtil.getTextValue((Element) tableList.item(tableIndex), "name"));
//
// Element tableElement = (Element) tableList.item(tableIndex);
// NodeList rowList = tableElement.getElementsByTagName("row");
// for (int rowIndex = 0; rowIndex < rowList.getLength(); rowIndex++) {
// NodeList colList = ((Element) rowList.item(rowIndex)).getElementsByTagName("col");
// for (int colIndex = 0; colIndex < colList.getLength(); colIndex++)
// assertEquals(tableValues[tableIndex][rowIndex][colIndex], XmlUtil.getElementText((Element) colList.item(colIndex)));
// }
// }
}
private void checkExpectation(NodeList instructionList, int index, String id, String col, String row, String status, String type, String actual, String expected, String message) throws Exception {
Element instructionElement = (Element) instructionList.item(index);
Element expectation = getElementByTagName(instructionElement, "expectation");
assertEquals(id, XmlUtil.getTextValue(expectation, "instructionId"));
assertEquals(status, XmlUtil.getTextValue(expectation, "status"));
assertEquals(type, XmlUtil.getTextValue(expectation, "type"));
assertEquals(col, XmlUtil.getTextValue(expectation, "col"));
assertEquals(row, XmlUtil.getTextValue(expectation, "row"));
assertEquals(actual, XmlUtil.getTextValue(expectation, "actual"));
assertEquals(expected, XmlUtil.getTextValue(expectation, "expected"));
assertEquals(message, XmlUtil.getTextValue(expectation, "evaluationMessage"));
}
private void assertInstructionHas(Element instructionElement, String content) throws Exception {
String instruction = XmlUtil.getTextValue(instructionElement, "instruction");
assertTrue(String.format("instruction %s should contain: %s", instruction, content), instruction.contains(content));
}
private void assertResultHas(Element instructionElement, String content) throws Exception {
String result = XmlUtil.getTextValue(instructionElement, "slimResult");
assertTrue(String.format("result %s should contain: %s", result, content), (result == null && content == null) || result.contains(content));
}
private void assertHeaderOfXmlDocumentsInResponseIsCorrect() throws Exception {
assertEquals("text/xml", response.getContentType());
Document testResultsDocument = getXmlDocumentFromResults(results);
xmlChecker.assertXmlHeaderIsCorrect(testResultsDocument);
}
}
public static class XmlTestUtilities {
public static Document getXmlDocumentFromResults(String results) throws Exception {
String endOfXml = "</testResults>";
String startOfXml = "<?xml";
int xmlStartIndex = results.indexOf(startOfXml);
int xmlEndIndex = results.indexOf(endOfXml) + endOfXml.length();
String xmlString = results.substring(xmlStartIndex, xmlEndIndex);
return XmlUtil.newDocument(xmlString);
}
public static void assertCounts(Element counts, String right, String wrong, String ignores, String exceptions)
throws Exception {
assertEquals(right, XmlUtil.getTextValue(counts, "right"));
assertEquals(wrong, XmlUtil.getTextValue(counts, "wrong"));
assertEquals(ignores, XmlUtil.getTextValue(counts, "ignores"));
assertEquals(exceptions, XmlUtil.getTextValue(counts, "exceptions"));
}
}
}
| Whoops. Should have run the tests first...
| test/fitnesse/responders/run/TestResponderTest.java | Whoops. Should have run the tests first... | <ide><path>est/fitnesse/responders/run/TestResponderTest.java
<ide> @Test
<ide> public void testHead() throws Exception {
<ide> doSimpleRun(passFixtureTable());
<del> assertSubString("<div id=\"test-summary\">Running Tests ...</div>", results);
<add> assertSubString("<div id=\"test-summary\"><div id=\"progressBar\">Preparing Tests ...</div></div>", results);
<ide> }
<ide>
<ide> @Test |
|
Java | mit | f4ddac10838ba1fb5a17933d9fdd30163a1af79b | 0 | Krasnyanskiy/jenkins,christ66/jenkins,tastatur/jenkins,bpzhang/jenkins,intelchen/jenkins,my7seven/jenkins,batmat/jenkins,lordofthejars/jenkins,olivergondza/jenkins,varmenise/jenkins,MarkEWaite/jenkins,mattclark/jenkins,kzantow/jenkins,jenkinsci/jenkins,kzantow/jenkins,ErikVerheul/jenkins,liupugong/jenkins,protazy/jenkins,SenolOzer/jenkins,liorhson/jenkins,morficus/jenkins,kohsuke/hudson,seanlin816/jenkins,tastatur/jenkins,mdonohue/jenkins,damianszczepanik/jenkins,tastatur/jenkins,luoqii/jenkins,FTG-003/jenkins,mcanthony/jenkins,everyonce/jenkins,arcivanov/jenkins,dbroady1/jenkins,vjuranek/jenkins,SebastienGllmt/jenkins,ChrisA89/jenkins,aduprat/jenkins,AustinKwang/jenkins,olivergondza/jenkins,lilyJi/jenkins,scoheb/jenkins,ndeloof/jenkins,fbelzunc/jenkins,msrb/jenkins,wuwen5/jenkins,ajshastri/jenkins,jpbriend/jenkins,jhoblitt/jenkins,stephenc/jenkins,huybrechts/hudson,msrb/jenkins,Jimilian/jenkins,andresrc/jenkins,recena/jenkins,andresrc/jenkins,scoheb/jenkins,bpzhang/jenkins,wuwen5/jenkins,seanlin816/jenkins,v1v/jenkins,evernat/jenkins,AustinKwang/jenkins,dariver/jenkins,liupugong/jenkins,v1v/jenkins,mattclark/jenkins,christ66/jenkins,iqstack/jenkins,luoqii/jenkins,gorcz/jenkins,rsandell/jenkins,pselle/jenkins,svanoort/jenkins,daniel-beck/jenkins,guoxu0514/jenkins,amruthsoft9/Jenkis,recena/jenkins,NehemiahMi/jenkins,kohsuke/hudson,aduprat/jenkins,1and1/jenkins,dariver/jenkins,lindzh/jenkins,gitaccountforprashant/gittest,akshayabd/jenkins,albers/jenkins,jglick/jenkins,gusreiber/jenkins,gorcz/jenkins,pjanouse/jenkins,wuwen5/jenkins,dennisjlee/jenkins,ndeloof/jenkins,rsandell/jenkins,huybrechts/hudson,morficus/jenkins,Krasnyanskiy/jenkins,guoxu0514/jenkins,fbelzunc/jenkins,rsandell/jenkins,my7seven/jenkins,lilyJi/jenkins,daniel-beck/jenkins,vlajos/jenkins,lordofthejars/jenkins,duzifang/my-jenkins,protazy/jenkins,Jochen-A-Fuerbacher/jenkins,gorcz/jenkins,CodeShane/jenkins,sathiya-mit/jenkins,292388900/jenkins,kzantow/jenkins,MarkEWaite/jenkins,FTG-003/jenkins,azweb76/jenkins,jcsirot/jenkins,fbelzunc/jenkins,amruthsoft9/Jenkis,AustinKwang/jenkins,v1v/jenkins,pselle/jenkins,mdonohue/jenkins,jcsirot/jenkins,DanielWeber/jenkins,mattclark/jenkins,FarmGeek4Life/jenkins,aduprat/jenkins,hemantojhaa/jenkins,samatdav/jenkins,evernat/jenkins,viqueen/jenkins,mdonohue/jenkins,samatdav/jenkins,elkingtonmcb/jenkins,mattclark/jenkins,iqstack/jenkins,godfath3r/jenkins,albers/jenkins,brunocvcunha/jenkins,bkmeneguello/jenkins,mrooney/jenkins,v1v/jenkins,ydubreuil/jenkins,pjanouse/jenkins,soenter/jenkins,brunocvcunha/jenkins,paulwellnerbou/jenkins,rashmikanta-1984/jenkins,Jimilian/jenkins,ChrisA89/jenkins,FTG-003/jenkins,khmarbaise/jenkins,jhoblitt/jenkins,jglick/jenkins,MarkEWaite/jenkins,jglick/jenkins,yonglehou/jenkins,lordofthejars/jenkins,evernat/jenkins,MarkEWaite/jenkins,ajshastri/jenkins,gusreiber/jenkins,jglick/jenkins,liorhson/jenkins,rlugojr/jenkins,damianszczepanik/jenkins,andresrc/jenkins,varmenise/jenkins,ikedam/jenkins,verbitan/jenkins,tfennelly/jenkins,azweb76/jenkins,MarkEWaite/jenkins,amuniz/jenkins,NehemiahMi/jenkins,christ66/jenkins,mattclark/jenkins,ChrisA89/jenkins,morficus/jenkins,brunocvcunha/jenkins,ns163/jenkins,sathiya-mit/jenkins,aldaris/jenkins,albers/jenkins,ikedam/jenkins,intelchen/jenkins,Vlatombe/jenkins,hemantojhaa/jenkins,rashmikanta-1984/jenkins,v1v/jenkins,liupugong/jenkins,vijayto/jenkins,stephenc/jenkins,varmenise/jenkins,DanielWeber/jenkins,lordofthejars/jenkins,SebastienGllmt/jenkins,scoheb/jenkins,Jochen-A-Fuerbacher/jenkins,recena/jenkins,ikedam/jenkins,khmarbaise/jenkins,rashmikanta-1984/jenkins,batmat/jenkins,KostyaSha/jenkins,SebastienGllmt/jenkins,protazy/jenkins,sathiya-mit/jenkins,aquarellian/jenkins,paulmillar/jenkins,escoem/jenkins,bpzhang/jenkins,Ykus/jenkins,Jochen-A-Fuerbacher/jenkins,noikiy/jenkins,Jochen-A-Fuerbacher/jenkins,vlajos/jenkins,mdonohue/jenkins,vijayto/jenkins,yonglehou/jenkins,morficus/jenkins,mrooney/jenkins,ajshastri/jenkins,Krasnyanskiy/jenkins,batmat/jenkins,liorhson/jenkins,amuniz/jenkins,SenolOzer/jenkins,jpederzolli/jenkins-1,rsandell/jenkins,mdonohue/jenkins,chbiel/jenkins,CodeShane/jenkins,DanielWeber/jenkins,petermarcoen/jenkins,luoqii/jenkins,morficus/jenkins,lindzh/jenkins,luoqii/jenkins,kohsuke/hudson,ErikVerheul/jenkins,mcanthony/jenkins,svanoort/jenkins,duzifang/my-jenkins,protazy/jenkins,vlajos/jenkins,rsandell/jenkins,pselle/jenkins,csimons/jenkins,csimons/jenkins,vjuranek/jenkins,escoem/jenkins,6WIND/jenkins,hashar/jenkins,khmarbaise/jenkins,Jimilian/jenkins,paulwellnerbou/jenkins,ChrisA89/jenkins,patbos/jenkins,MarkEWaite/jenkins,DanielWeber/jenkins,ajshastri/jenkins,sathiya-mit/jenkins,svanoort/jenkins,dbroady1/jenkins,samatdav/jenkins,ajshastri/jenkins,1and1/jenkins,patbos/jenkins,Jimilian/jenkins,noikiy/jenkins,my7seven/jenkins,aquarellian/jenkins,singh88/jenkins,jenkinsci/jenkins,gorcz/jenkins,patbos/jenkins,khmarbaise/jenkins,tfennelly/jenkins,292388900/jenkins,olivergondza/jenkins,liupugong/jenkins,lindzh/jenkins,hashar/jenkins,wuwen5/jenkins,tfennelly/jenkins,csimons/jenkins,ndeloof/jenkins,huybrechts/hudson,Vlatombe/jenkins,akshayabd/jenkins,bkmeneguello/jenkins,mcanthony/jenkins,iqstack/jenkins,6WIND/jenkins,viqueen/jenkins,gitaccountforprashant/gittest,petermarcoen/jenkins,samatdav/jenkins,paulwellnerbou/jenkins,liorhson/jenkins,1and1/jenkins,SebastienGllmt/jenkins,292388900/jenkins,daniel-beck/jenkins,pjanouse/jenkins,duzifang/my-jenkins,seanlin816/jenkins,MichaelPranovich/jenkins_sc,wangyikai/jenkins,1and1/jenkins,NehemiahMi/jenkins,FarmGeek4Life/jenkins,hashar/jenkins,vijayto/jenkins,dariver/jenkins,gorcz/jenkins,lilyJi/jenkins,verbitan/jenkins,292388900/jenkins,daniel-beck/jenkins,liorhson/jenkins,ns163/jenkins,liupugong/jenkins,lindzh/jenkins,my7seven/jenkins,everyonce/jenkins,seanlin816/jenkins,KostyaSha/jenkins,jhoblitt/jenkins,dariver/jenkins,ChrisA89/jenkins,ns163/jenkins,huybrechts/hudson,petermarcoen/jenkins,mcanthony/jenkins,patbos/jenkins,andresrc/jenkins,ikedam/jenkins,everyonce/jenkins,MichaelPranovich/jenkins_sc,morficus/jenkins,amuniz/jenkins,mcanthony/jenkins,batmat/jenkins,ErikVerheul/jenkins,rlugojr/jenkins,elkingtonmcb/jenkins,Ykus/jenkins,6WIND/jenkins,jhoblitt/jenkins,viqueen/jenkins,vjuranek/jenkins,ns163/jenkins,alvarolobato/jenkins,samatdav/jenkins,pselle/jenkins,jpbriend/jenkins,KostyaSha/jenkins,tangkun75/jenkins,gitaccountforprashant/gittest,stephenc/jenkins,brunocvcunha/jenkins,olivergondza/jenkins,duzifang/my-jenkins,Ykus/jenkins,SenolOzer/jenkins,vlajos/jenkins,hemantojhaa/jenkins,singh88/jenkins,292388900/jenkins,bpzhang/jenkins,guoxu0514/jenkins,aldaris/jenkins,ErikVerheul/jenkins,ajshastri/jenkins,petermarcoen/jenkins,DanielWeber/jenkins,batmat/jenkins,FTG-003/jenkins,mrooney/jenkins,kohsuke/hudson,mrooney/jenkins,Vlatombe/jenkins,amruthsoft9/Jenkis,azweb76/jenkins,bkmeneguello/jenkins,verbitan/jenkins,ChrisA89/jenkins,msrb/jenkins,khmarbaise/jenkins,gusreiber/jenkins,albers/jenkins,arunsingh/jenkins,jpederzolli/jenkins-1,brunocvcunha/jenkins,guoxu0514/jenkins,arunsingh/jenkins,godfath3r/jenkins,CodeShane/jenkins,amuniz/jenkins,MichaelPranovich/jenkins_sc,rlugojr/jenkins,azweb76/jenkins,brunocvcunha/jenkins,noikiy/jenkins,ndeloof/jenkins,Jochen-A-Fuerbacher/jenkins,Vlatombe/jenkins,mdonohue/jenkins,mdonohue/jenkins,rashmikanta-1984/jenkins,fbelzunc/jenkins,my7seven/jenkins,292388900/jenkins,amuniz/jenkins,rlugojr/jenkins,guoxu0514/jenkins,mattclark/jenkins,MichaelPranovich/jenkins_sc,hplatou/jenkins,arunsingh/jenkins,KostyaSha/jenkins,verbitan/jenkins,damianszczepanik/jenkins,yonglehou/jenkins,verbitan/jenkins,amruthsoft9/Jenkis,wuwen5/jenkins,guoxu0514/jenkins,jk47/jenkins,Ykus/jenkins,ErikVerheul/jenkins,DanielWeber/jenkins,jenkinsci/jenkins,dariver/jenkins,escoem/jenkins,6WIND/jenkins,escoem/jenkins,MichaelPranovich/jenkins_sc,FarmGeek4Life/jenkins,intelchen/jenkins,6WIND/jenkins,my7seven/jenkins,lindzh/jenkins,varmenise/jenkins,wangyikai/jenkins,Vlatombe/jenkins,chbiel/jenkins,kohsuke/hudson,dariver/jenkins,bkmeneguello/jenkins,luoqii/jenkins,damianszczepanik/jenkins,292388900/jenkins,jk47/jenkins,msrb/jenkins,varmenise/jenkins,rsandell/jenkins,wangyikai/jenkins,varmenise/jenkins,rlugojr/jenkins,alvarolobato/jenkins,huybrechts/hudson,lindzh/jenkins,kohsuke/hudson,lilyJi/jenkins,msrb/jenkins,liupugong/jenkins,oleg-nenashev/jenkins,bpzhang/jenkins,jpederzolli/jenkins-1,jpbriend/jenkins,msrb/jenkins,jenkinsci/jenkins,fbelzunc/jenkins,Ykus/jenkins,jpbriend/jenkins,christ66/jenkins,oleg-nenashev/jenkins,vlajos/jenkins,arcivanov/jenkins,SebastienGllmt/jenkins,stephenc/jenkins,ErikVerheul/jenkins,andresrc/jenkins,arcivanov/jenkins,evernat/jenkins,intelchen/jenkins,arunsingh/jenkins,vvv444/jenkins,chbiel/jenkins,jcsirot/jenkins,Krasnyanskiy/jenkins,tastatur/jenkins,hplatou/jenkins,paulwellnerbou/jenkins,arunsingh/jenkins,everyonce/jenkins,gusreiber/jenkins,csimons/jenkins,Krasnyanskiy/jenkins,amruthsoft9/Jenkis,godfath3r/jenkins,everyonce/jenkins,escoem/jenkins,daniel-beck/jenkins,hplatou/jenkins,Jimilian/jenkins,gusreiber/jenkins,batmat/jenkins,vijayto/jenkins,wangyikai/jenkins,vijayto/jenkins,csimons/jenkins,kzantow/jenkins,mrooney/jenkins,jk47/jenkins,alvarolobato/jenkins,godfath3r/jenkins,pjanouse/jenkins,AustinKwang/jenkins,tfennelly/jenkins,paulmillar/jenkins,andresrc/jenkins,KostyaSha/jenkins,NehemiahMi/jenkins,arcivanov/jenkins,msrb/jenkins,verbitan/jenkins,pjanouse/jenkins,ndeloof/jenkins,ikedam/jenkins,olivergondza/jenkins,aquarellian/jenkins,jk47/jenkins,aduprat/jenkins,bkmeneguello/jenkins,jhoblitt/jenkins,iqstack/jenkins,gitaccountforprashant/gittest,tangkun75/jenkins,rsandell/jenkins,SenolOzer/jenkins,oleg-nenashev/jenkins,jpederzolli/jenkins-1,KostyaSha/jenkins,paulmillar/jenkins,hemantojhaa/jenkins,SebastienGllmt/jenkins,pselle/jenkins,tastatur/jenkins,FTG-003/jenkins,amruthsoft9/Jenkis,vlajos/jenkins,christ66/jenkins,damianszczepanik/jenkins,Ykus/jenkins,jhoblitt/jenkins,yonglehou/jenkins,liupugong/jenkins,SenolOzer/jenkins,noikiy/jenkins,paulmillar/jenkins,gusreiber/jenkins,alvarolobato/jenkins,lilyJi/jenkins,recena/jenkins,csimons/jenkins,soenter/jenkins,soenter/jenkins,mcanthony/jenkins,vvv444/jenkins,jenkinsci/jenkins,amruthsoft9/Jenkis,damianszczepanik/jenkins,Krasnyanskiy/jenkins,wuwen5/jenkins,hashar/jenkins,noikiy/jenkins,vvv444/jenkins,aldaris/jenkins,gorcz/jenkins,godfath3r/jenkins,soenter/jenkins,albers/jenkins,khmarbaise/jenkins,rsandell/jenkins,jcsirot/jenkins,yonglehou/jenkins,amuniz/jenkins,lindzh/jenkins,ndeloof/jenkins,duzifang/my-jenkins,seanlin816/jenkins,mattclark/jenkins,duzifang/my-jenkins,aldaris/jenkins,paulmillar/jenkins,petermarcoen/jenkins,luoqii/jenkins,fbelzunc/jenkins,jenkinsci/jenkins,aldaris/jenkins,tfennelly/jenkins,rashmikanta-1984/jenkins,rlugojr/jenkins,Vlatombe/jenkins,jcsirot/jenkins,sathiya-mit/jenkins,scoheb/jenkins,daniel-beck/jenkins,patbos/jenkins,vvv444/jenkins,dennisjlee/jenkins,alvarolobato/jenkins,amuniz/jenkins,CodeShane/jenkins,dennisjlee/jenkins,paulwellnerbou/jenkins,hemantojhaa/jenkins,sathiya-mit/jenkins,KostyaSha/jenkins,dennisjlee/jenkins,NehemiahMi/jenkins,dennisjlee/jenkins,hplatou/jenkins,MichaelPranovich/jenkins_sc,bpzhang/jenkins,svanoort/jenkins,svanoort/jenkins,iqstack/jenkins,vlajos/jenkins,FarmGeek4Life/jenkins,AustinKwang/jenkins,alvarolobato/jenkins,gitaccountforprashant/gittest,dbroady1/jenkins,FarmGeek4Life/jenkins,jcsirot/jenkins,sathiya-mit/jenkins,hplatou/jenkins,ErikVerheul/jenkins,lilyJi/jenkins,dbroady1/jenkins,dbroady1/jenkins,stephenc/jenkins,svanoort/jenkins,SebastienGllmt/jenkins,ajshastri/jenkins,rlugojr/jenkins,chbiel/jenkins,SenolOzer/jenkins,recena/jenkins,huybrechts/hudson,dariver/jenkins,daniel-beck/jenkins,vvv444/jenkins,jglick/jenkins,AustinKwang/jenkins,wangyikai/jenkins,protazy/jenkins,tangkun75/jenkins,1and1/jenkins,my7seven/jenkins,v1v/jenkins,akshayabd/jenkins,elkingtonmcb/jenkins,KostyaSha/jenkins,soenter/jenkins,bpzhang/jenkins,vvv444/jenkins,oleg-nenashev/jenkins,ndeloof/jenkins,christ66/jenkins,mrooney/jenkins,aldaris/jenkins,kzantow/jenkins,patbos/jenkins,gitaccountforprashant/gittest,daniel-beck/jenkins,v1v/jenkins,mcanthony/jenkins,tangkun75/jenkins,liorhson/jenkins,everyonce/jenkins,pjanouse/jenkins,6WIND/jenkins,jcsirot/jenkins,evernat/jenkins,fbelzunc/jenkins,ydubreuil/jenkins,samatdav/jenkins,seanlin816/jenkins,chbiel/jenkins,mrooney/jenkins,tastatur/jenkins,jpederzolli/jenkins-1,elkingtonmcb/jenkins,yonglehou/jenkins,evernat/jenkins,singh88/jenkins,bkmeneguello/jenkins,godfath3r/jenkins,jk47/jenkins,khmarbaise/jenkins,Jochen-A-Fuerbacher/jenkins,vijayto/jenkins,ChrisA89/jenkins,azweb76/jenkins,NehemiahMi/jenkins,jpbriend/jenkins,pjanouse/jenkins,6WIND/jenkins,vjuranek/jenkins,soenter/jenkins,hashar/jenkins,CodeShane/jenkins,tangkun75/jenkins,guoxu0514/jenkins,recena/jenkins,ikedam/jenkins,samatdav/jenkins,vjuranek/jenkins,hplatou/jenkins,albers/jenkins,akshayabd/jenkins,singh88/jenkins,ydubreuil/jenkins,olivergondza/jenkins,viqueen/jenkins,patbos/jenkins,andresrc/jenkins,damianszczepanik/jenkins,stephenc/jenkins,gorcz/jenkins,wangyikai/jenkins,singh88/jenkins,protazy/jenkins,lilyJi/jenkins,batmat/jenkins,kzantow/jenkins,bkmeneguello/jenkins,1and1/jenkins,vjuranek/jenkins,tfennelly/jenkins,singh88/jenkins,gorcz/jenkins,intelchen/jenkins,chbiel/jenkins,elkingtonmcb/jenkins,tastatur/jenkins,viqueen/jenkins,Ykus/jenkins,intelchen/jenkins,kohsuke/hudson,aduprat/jenkins,noikiy/jenkins,huybrechts/hudson,rashmikanta-1984/jenkins,arcivanov/jenkins,NehemiahMi/jenkins,gusreiber/jenkins,iqstack/jenkins,arunsingh/jenkins,petermarcoen/jenkins,soenter/jenkins,alvarolobato/jenkins,pselle/jenkins,noikiy/jenkins,1and1/jenkins,lordofthejars/jenkins,recena/jenkins,MarkEWaite/jenkins,luoqii/jenkins,tangkun75/jenkins,rashmikanta-1984/jenkins,MichaelPranovich/jenkins_sc,singh88/jenkins,lordofthejars/jenkins,oleg-nenashev/jenkins,jhoblitt/jenkins,hemantojhaa/jenkins,jenkinsci/jenkins,aquarellian/jenkins,CodeShane/jenkins,tangkun75/jenkins,ydubreuil/jenkins,elkingtonmcb/jenkins,akshayabd/jenkins,aduprat/jenkins,dbroady1/jenkins,hashar/jenkins,Jochen-A-Fuerbacher/jenkins,ns163/jenkins,FTG-003/jenkins,FarmGeek4Life/jenkins,scoheb/jenkins,Vlatombe/jenkins,lordofthejars/jenkins,dbroady1/jenkins,jk47/jenkins,ns163/jenkins,varmenise/jenkins,MarkEWaite/jenkins,svanoort/jenkins,hashar/jenkins,tfennelly/jenkins,akshayabd/jenkins,jglick/jenkins,aquarellian/jenkins,escoem/jenkins,ydubreuil/jenkins,vvv444/jenkins,duzifang/my-jenkins,dennisjlee/jenkins,Jimilian/jenkins,oleg-nenashev/jenkins,olivergondza/jenkins,wuwen5/jenkins,elkingtonmcb/jenkins,FarmGeek4Life/jenkins,paulwellnerbou/jenkins,viqueen/jenkins,scoheb/jenkins,pselle/jenkins,iqstack/jenkins,arcivanov/jenkins,hplatou/jenkins,verbitan/jenkins,damianszczepanik/jenkins,jpederzolli/jenkins-1,Krasnyanskiy/jenkins,yonglehou/jenkins,DanielWeber/jenkins,SenolOzer/jenkins,intelchen/jenkins,ns163/jenkins,protazy/jenkins,jpederzolli/jenkins-1,ydubreuil/jenkins,morficus/jenkins,ydubreuil/jenkins,CodeShane/jenkins,jk47/jenkins,brunocvcunha/jenkins,ikedam/jenkins,jglick/jenkins,arcivanov/jenkins,aquarellian/jenkins,evernat/jenkins,everyonce/jenkins,hemantojhaa/jenkins,Jimilian/jenkins,jpbriend/jenkins,jenkinsci/jenkins,AustinKwang/jenkins,ikedam/jenkins,vijayto/jenkins,arunsingh/jenkins,viqueen/jenkins,seanlin816/jenkins,aquarellian/jenkins,akshayabd/jenkins,csimons/jenkins,petermarcoen/jenkins,paulmillar/jenkins,oleg-nenashev/jenkins,aduprat/jenkins,azweb76/jenkins,escoem/jenkins,jpbriend/jenkins,chbiel/jenkins,paulmillar/jenkins,FTG-003/jenkins,paulwellnerbou/jenkins,vjuranek/jenkins,dennisjlee/jenkins,scoheb/jenkins,kohsuke/hudson,albers/jenkins,stephenc/jenkins,wangyikai/jenkins,gitaccountforprashant/gittest,christ66/jenkins,aldaris/jenkins,godfath3r/jenkins,liorhson/jenkins,azweb76/jenkins,kzantow/jenkins | /*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Stephen Connolly, Thomas J. Black
*
* 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.
*/
package hudson.model;
import hudson.BulkChange;
import hudson.DescriptorExtensionList;
import hudson.Extension;
import hudson.Util;
import hudson.XmlFile;
import hudson.init.Initializer;
import hudson.model.Descriptor.FormException;
import hudson.model.listeners.SaveableListener;
import hudson.node_monitors.NodeMonitor;
import hudson.slaves.NodeDescriptor;
import hudson.triggers.SafeTimerTask;
import hudson.util.DescribableList;
import hudson.util.FormApply;
import hudson.util.FormValidation;
import jenkins.model.Jenkins;
import jenkins.model.ModelObjectWithChildren;
import jenkins.model.ModelObjectWithContextMenu.ContextMenu;
import jenkins.util.Timer;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.stapler.interceptor.RequirePOST;
import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sf.json.JSONObject;
import static hudson.init.InitMilestone.JOB_LOADED;
/**
* Serves as the top of {@link Computer}s in the URL hierarchy.
* <p>
* Getter methods are prefixed with '_' to avoid collision with computer names.
*
* @author Kohsuke Kawaguchi
*/
@ExportedBean
public final class ComputerSet extends AbstractModelObject implements Describable<ComputerSet>, ModelObjectWithChildren {
/**
* This is the owner that persists {@link #monitors}.
*/
private static final Saveable MONITORS_OWNER = new Saveable() {
public void save() throws IOException {
getConfigFile().write(monitors);
SaveableListener.fireOnChange(this, getConfigFile());
}
};
private static final DescribableList<NodeMonitor,Descriptor<NodeMonitor>> monitors
= new DescribableList<NodeMonitor, Descriptor<NodeMonitor>>(MONITORS_OWNER);
@Exported
public String getDisplayName() {
return Messages.ComputerSet_DisplayName();
}
/**
* @deprecated as of 1.301
* Use {@link #getMonitors()}.
*/
public static List<NodeMonitor> get_monitors() {
return monitors.toList();
}
@Exported(name="computer",inline=true)
public Computer[] get_all() {
return Jenkins.getInstance().getComputers();
}
public ContextMenu doChildrenContextMenu(StaplerRequest request, StaplerResponse response) throws Exception {
ContextMenu m = new ContextMenu();
for (Computer c : get_all()) {
m.add(c);
}
return m;
}
/**
* Exposing {@link NodeMonitor#all()} for Jelly binding.
*/
public DescriptorExtensionList<NodeMonitor,Descriptor<NodeMonitor>> getNodeMonitorDescriptors() {
return NodeMonitor.all();
}
public static DescribableList<NodeMonitor,Descriptor<NodeMonitor>> getMonitors() {
return monitors;
}
/**
* Returns a subset pf {@link #getMonitors()} that are {@linkplain NodeMonitor#isIgnored() not ignored}.
*/
public static Map<Descriptor<NodeMonitor>,NodeMonitor> getNonIgnoredMonitors() {
Map<Descriptor<NodeMonitor>,NodeMonitor> r = new HashMap<Descriptor<NodeMonitor>, NodeMonitor>();
for (NodeMonitor m : monitors) {
if(!m.isIgnored())
r.put(m.getDescriptor(),m);
}
return r;
}
/**
* Gets all the slave names.
*/
public List<String> get_slaveNames() {
return new AbstractList<String>() {
final List<Node> nodes = Jenkins.getInstance().getNodes();
public String get(int index) {
return nodes.get(index).getNodeName();
}
public int size() {
return nodes.size();
}
};
}
/**
* Number of total {@link Executor}s that belong to this label that are functioning.
* <p>
* This excludes executors that belong to offline nodes.
*/
@Exported
public int getTotalExecutors() {
int r=0;
for (Computer c : get_all()) {
if(c.isOnline())
r += c.countExecutors();
}
return r;
}
/**
* Number of busy {@link Executor}s that are carrying out some work right now.
*/
@Exported
public int getBusyExecutors() {
int r=0;
for (Computer c : get_all()) {
if(c.isOnline())
r += c.countBusy();
}
return r;
}
/**
* {@code getTotalExecutors()-getBusyExecutors()}, plus executors that are being brought online.
*/
public int getIdleExecutors() {
int r=0;
for (Computer c : get_all())
if((c.isOnline() || c.isConnecting()) && c.isAcceptingTasks())
r += c.countIdle();
return r;
}
public String getSearchUrl() {
return "/computers/";
}
public Computer getDynamic(String token, StaplerRequest req, StaplerResponse rsp) {
return Jenkins.getInstance().getComputer(token);
}
public void do_launchAll(StaplerRequest req, StaplerResponse rsp) throws IOException {
Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
for(Computer c : get_all()) {
if(c.isLaunchSupported())
c.connect(true);
}
rsp.sendRedirect(".");
}
/**
* Triggers the schedule update now.
*
* TODO: ajax on the client side to wait until the update completion might be nice.
*/
public void doUpdateNow( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
for (NodeMonitor nodeMonitor : NodeMonitor.getAll()) {
Thread t = nodeMonitor.triggerUpdate();
String columnCaption = nodeMonitor.getColumnCaption();
if (columnCaption != null) {
t.setName(columnCaption);
}
}
rsp.forwardToPreviousPage(req);
}
/**
* First check point in creating a new slave.
*/
public synchronized void doCreateItem( StaplerRequest req, StaplerResponse rsp,
@QueryParameter String name, @QueryParameter String mode,
@QueryParameter String from ) throws IOException, ServletException {
final Jenkins app = Jenkins.getInstance();
app.checkPermission(Computer.CREATE);
if(mode!=null && mode.equals("copy")) {
name = checkName(name);
Node src = app.getNode(from);
if(src==null) {
if (Util.fixEmpty(from) == null) {
throw new Failure(Messages.ComputerSet_SpecifySlaveToCopy());
} else {
throw new Failure(Messages.ComputerSet_NoSuchSlave(from));
}
}
// copy through XStream
String xml = Jenkins.XSTREAM.toXML(src);
Node result = (Node) Jenkins.XSTREAM.fromXML(xml);
result.setNodeName(name);
if(result instanceof Slave){ //change userId too
User user = User.current();
((Slave)result).setUserId(user==null ? "anonymous" : user.getId());
}
result.holdOffLaunchUntilSave = true;
app.addNode(result);
// send the browser to the config page
rsp.sendRedirect2(result.getNodeName()+"/configure");
} else {
// proceed to step 2
if (mode == null) {
throw new Failure("No mode given");
}
NodeDescriptor d = NodeDescriptor.all().findByName(mode);
if (d == null) {
throw new Failure("No node type ‘" + mode + "’ is known");
}
d.handleNewNodePage(this,name,req,rsp);
}
}
/**
* Really creates a new slave.
*/
public synchronized void doDoCreateItem( StaplerRequest req, StaplerResponse rsp,
@QueryParameter String name,
@QueryParameter String type ) throws IOException, ServletException, FormException {
final Jenkins app = Jenkins.getInstance();
app.checkPermission(Computer.CREATE);
String fixedName = Util.fixEmptyAndTrim(name);
checkName(fixedName);
JSONObject formData = req.getSubmittedForm();
formData.put("name", fixedName);
// TODO type is probably NodeDescriptor.id but confirm
Node result = NodeDescriptor.all().find(type).newInstance(req, formData);
app.addNode(result);
// take the user back to the slave list top page
rsp.sendRedirect2(".");
}
/**
* Makes sure that the given name is good as a slave name.
* @return trimmed name if valid; throws ParseException if not
*/
public String checkName(String name) throws Failure {
if(name==null)
throw new Failure("Query parameter 'name' is required");
name = name.trim();
Jenkins.checkGoodName(name);
if(Jenkins.getInstance().getNode(name)!=null)
throw new Failure(Messages.ComputerSet_SlaveAlreadyExists(name));
// looks good
return name;
}
/**
* Makes sure that the given name is good as a slave name.
*/
public FormValidation doCheckName(@QueryParameter String value) throws IOException, ServletException {
Jenkins.getInstance().checkPermission(Computer.CREATE);
if(Util.fixEmpty(value)==null)
return FormValidation.ok();
try {
checkName(value);
return FormValidation.ok();
} catch (Failure e) {
return FormValidation.error(e.getMessage());
}
}
/**
* Accepts submission from the configuration page.
*/
@RequirePOST
public synchronized HttpResponse doConfigSubmit( StaplerRequest req) throws IOException, ServletException, FormException {
BulkChange bc = new BulkChange(MONITORS_OWNER);
try {
Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
monitors.rebuild(req,req.getSubmittedForm(),getNodeMonitorDescriptors());
// add in the rest of instances are ignored instances
for (Descriptor<NodeMonitor> d : NodeMonitor.all())
if(monitors.get(d)==null) {
NodeMonitor i = createDefaultInstance(d, true);
if(i!=null)
monitors.add(i);
}
// recompute the data
for (NodeMonitor nm : monitors) {
nm.triggerUpdate();
}
return FormApply.success(".");
} finally {
bc.commit();
}
}
/**
* {@link NodeMonitor}s are persisted in this file.
*/
private static XmlFile getConfigFile() {
return new XmlFile(new File(Jenkins.getInstance().getRootDir(),"nodeMonitors.xml"));
}
public Api getApi() {
return new Api(this);
}
public Descriptor<ComputerSet> getDescriptor() {
return Jenkins.getInstance().getDescriptorOrDie(ComputerSet.class);
}
@Extension
public static class DescriptorImpl extends Descriptor<ComputerSet> {
@Override
public String getDisplayName() {
return "";
}
/**
* Auto-completion for the "copy from" field in the new job page.
*/
public AutoCompletionCandidates doAutoCompleteCopyNewItemFrom(@QueryParameter final String value) {
final AutoCompletionCandidates r = new AutoCompletionCandidates();
for (Node n : Jenkins.getInstance().getNodes()) {
if (n.getNodeName().startsWith(value))
r.add(n.getNodeName());
}
return r;
}
}
/**
* Just to force the execution of the static initializer.
*/
public static void initialize() {}
@Initializer(after= JOB_LOADED)
public static void init() {
// start monitoring nodes, although there's no hurry.
Timer.get().schedule(new SafeTimerTask() {
public void doRun() {
ComputerSet.initialize();
}
}, 10, TimeUnit.SECONDS);
}
private static final Logger LOGGER = Logger.getLogger(ComputerSet.class.getName());
static {
try {
DescribableList<NodeMonitor,Descriptor<NodeMonitor>> r
= new DescribableList<NodeMonitor, Descriptor<NodeMonitor>>(Saveable.NOOP);
// load persisted monitors
XmlFile xf = getConfigFile();
if(xf.exists()) {
DescribableList<NodeMonitor,Descriptor<NodeMonitor>> persisted =
(DescribableList<NodeMonitor,Descriptor<NodeMonitor>>) xf.read();
List<NodeMonitor> sanitized = new ArrayList<NodeMonitor>();
for (NodeMonitor nm : persisted) {
try {
nm.getDescriptor();
sanitized.add(nm);
} catch (Throwable e) {
// the descriptor didn't load? see JENKINS-15869
}
}
r.replaceBy(sanitized);
}
// if we have any new monitors, let's add them
for (Descriptor<NodeMonitor> d : NodeMonitor.all())
if(r.get(d)==null) {
NodeMonitor i = createDefaultInstance(d,false);
if(i!=null)
r.add(i);
}
monitors.replaceBy(r.toList());
} catch (Throwable x) {
LOGGER.log(Level.WARNING, "Failed to instantiate NodeMonitors", x);
}
}
private static NodeMonitor createDefaultInstance(Descriptor<NodeMonitor> d, boolean ignored) {
try {
NodeMonitor nm = d.clazz.newInstance();
nm.setIgnored(ignored);
return nm;
} catch (InstantiationException e) {
LOGGER.log(Level.SEVERE, "Failed to instanciate "+d.clazz,e);
} catch (IllegalAccessException e) {
LOGGER.log(Level.SEVERE, "Failed to instanciate "+d.clazz,e);
}
return null;
}
}
| core/src/main/java/hudson/model/ComputerSet.java | /*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Stephen Connolly, Thomas J. Black
*
* 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.
*/
package hudson.model;
import hudson.BulkChange;
import hudson.DescriptorExtensionList;
import hudson.Extension;
import hudson.Util;
import hudson.XmlFile;
import hudson.init.Initializer;
import hudson.model.Descriptor.FormException;
import hudson.model.listeners.SaveableListener;
import hudson.node_monitors.NodeMonitor;
import hudson.slaves.NodeDescriptor;
import hudson.triggers.SafeTimerTask;
import hudson.util.DescribableList;
import hudson.util.FormApply;
import hudson.util.FormValidation;
import jenkins.model.Jenkins;
import jenkins.model.ModelObjectWithChildren;
import jenkins.model.ModelObjectWithContextMenu.ContextMenu;
import jenkins.util.Timer;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.stapler.interceptor.RequirePOST;
import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sf.json.JSONObject;
import static hudson.init.InitMilestone.JOB_LOADED;
/**
* Serves as the top of {@link Computer}s in the URL hierarchy.
* <p>
* Getter methods are prefixed with '_' to avoid collision with computer names.
*
* @author Kohsuke Kawaguchi
*/
@ExportedBean
public final class ComputerSet extends AbstractModelObject implements Describable<ComputerSet>, ModelObjectWithChildren {
/**
* This is the owner that persists {@link #monitors}.
*/
private static final Saveable MONITORS_OWNER = new Saveable() {
public void save() throws IOException {
getConfigFile().write(monitors);
SaveableListener.fireOnChange(this, getConfigFile());
}
};
private static final DescribableList<NodeMonitor,Descriptor<NodeMonitor>> monitors
= new DescribableList<NodeMonitor, Descriptor<NodeMonitor>>(MONITORS_OWNER);
@Exported
public String getDisplayName() {
return Messages.ComputerSet_DisplayName();
}
/**
* @deprecated as of 1.301
* Use {@link #getMonitors()}.
*/
public static List<NodeMonitor> get_monitors() {
return monitors.toList();
}
@Exported(name="computer",inline=true)
public Computer[] get_all() {
return Jenkins.getInstance().getComputers();
}
public ContextMenu doChildrenContextMenu(StaplerRequest request, StaplerResponse response) throws Exception {
ContextMenu m = new ContextMenu();
for (Computer c : get_all()) {
m.add(c);
}
return m;
}
/**
* Exposing {@link NodeMonitor#all()} for Jelly binding.
*/
public DescriptorExtensionList<NodeMonitor,Descriptor<NodeMonitor>> getNodeMonitorDescriptors() {
return NodeMonitor.all();
}
public static DescribableList<NodeMonitor,Descriptor<NodeMonitor>> getMonitors() {
return monitors;
}
/**
* Returns a subset pf {@link #getMonitors()} that are {@linkplain NodeMonitor#isIgnored() not ignored}.
*/
public static Map<Descriptor<NodeMonitor>,NodeMonitor> getNonIgnoredMonitors() {
Map<Descriptor<NodeMonitor>,NodeMonitor> r = new HashMap<Descriptor<NodeMonitor>, NodeMonitor>();
for (NodeMonitor m : monitors) {
if(!m.isIgnored())
r.put(m.getDescriptor(),m);
}
return r;
}
/**
* Gets all the slave names.
*/
public List<String> get_slaveNames() {
return new AbstractList<String>() {
final List<Node> nodes = Jenkins.getInstance().getNodes();
public String get(int index) {
return nodes.get(index).getNodeName();
}
public int size() {
return nodes.size();
}
};
}
/**
* Number of total {@link Executor}s that belong to this label that are functioning.
* <p>
* This excludes executors that belong to offline nodes.
*/
@Exported
public int getTotalExecutors() {
int r=0;
for (Computer c : get_all()) {
if(c.isOnline())
r += c.countExecutors();
}
return r;
}
/**
* Number of busy {@link Executor}s that are carrying out some work right now.
*/
@Exported
public int getBusyExecutors() {
int r=0;
for (Computer c : get_all()) {
if(c.isOnline())
r += c.countBusy();
}
return r;
}
/**
* {@code getTotalExecutors()-getBusyExecutors()}, plus executors that are being brought online.
*/
public int getIdleExecutors() {
int r=0;
for (Computer c : get_all())
if((c.isOnline() || c.isConnecting()) && c.isAcceptingTasks())
r += c.countIdle();
return r;
}
public String getSearchUrl() {
return "/computers/";
}
public Computer getDynamic(String token, StaplerRequest req, StaplerResponse rsp) {
return Jenkins.getInstance().getComputer(token);
}
public void do_launchAll(StaplerRequest req, StaplerResponse rsp) throws IOException {
Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
for(Computer c : get_all()) {
if(c.isLaunchSupported())
c.connect(true);
}
rsp.sendRedirect(".");
}
/**
* Triggers the schedule update now.
*
* TODO: ajax on the client side to wait until the update completion might be nice.
*/
public void doUpdateNow( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
for (NodeMonitor nodeMonitor : NodeMonitor.getAll()) {
Thread t = nodeMonitor.triggerUpdate();
String columnCaption = nodeMonitor.getColumnCaption();
if (columnCaption != null) {
t.setName(columnCaption);
}
}
rsp.forwardToPreviousPage(req);
}
/**
* First check point in creating a new slave.
*/
public synchronized void doCreateItem( StaplerRequest req, StaplerResponse rsp,
@QueryParameter String name, @QueryParameter String mode,
@QueryParameter String from ) throws IOException, ServletException {
final Jenkins app = Jenkins.getInstance();
app.checkPermission(Computer.CREATE);
if(mode!=null && mode.equals("copy")) {
name = checkName(name);
Node src = app.getNode(from);
if(src==null) {
if (Util.fixEmpty(from) == null) {
throw new Failure(Messages.ComputerSet_SpecifySlaveToCopy());
} else {
throw new Failure(Messages.ComputerSet_NoSuchSlave(from));
}
}
// copy through XStream
String xml = Jenkins.XSTREAM.toXML(src);
Node result = (Node) Jenkins.XSTREAM.fromXML(xml);
result.setNodeName(name);
if(result instanceof Slave){ //change userId too
User user = User.current();
((Slave)result).setUserId(user==null ? "anonymous" : user.getId());
}
result.holdOffLaunchUntilSave = true;
app.addNode(result);
// send the browser to the config page
rsp.sendRedirect2(result.getNodeName()+"/configure");
} else {
// proceed to step 2
if (mode == null) {
throw new Failure("No mode given");
}
NodeDescriptor d = NodeDescriptor.all().findByName(mode);
if (d == null) {
throw new Failure("No node type ‘" + mode + "’ is known");
}
d.handleNewNodePage(this,name,req,rsp);
}
}
/**
* Really creates a new slave.
*/
public synchronized void doDoCreateItem( StaplerRequest req, StaplerResponse rsp,
@QueryParameter String name,
@QueryParameter String type ) throws IOException, ServletException, FormException {
final Jenkins app = Jenkins.getInstance();
app.checkPermission(Computer.CREATE);
String fixedName = Util.fixEmptyAndTrim(name);
checkName(fixedName);
JSONObject formData = req.getSubmittedForm();
formData.put("name", fixedName);
// TODO type is probably NodeDescriptor.id but confirm
Node result = NodeDescriptor.all().find(type).newInstance(req, formData);
app.addNode(result);
// take the user back to the slave list top page
rsp.sendRedirect2(".");
}
/**
* Makes sure that the given name is good as a slave name.
* @return trimmed name if valid; throws ParseException if not
*/
public String checkName(String name) throws Failure {
if(name==null)
throw new Failure("Query parameter 'name' is required");
name = name.trim();
Jenkins.checkGoodName(name);
if(Jenkins.getInstance().getNode(name)!=null)
throw new Failure(Messages.ComputerSet_SlaveAlreadyExists(name));
// looks good
return name;
}
/**
* Makes sure that the given name is good as a slave name.
*/
public FormValidation doCheckName(@QueryParameter String value) throws IOException, ServletException {
Jenkins.getInstance().checkPermission(Computer.CREATE);
if(Util.fixEmpty(value)==null)
return FormValidation.ok();
try {
checkName(value);
return FormValidation.ok();
} catch (Failure e) {
return FormValidation.error(e.getMessage());
}
}
/**
* Accepts submission from the configuration page.
*/
@RequirePOST
public synchronized HttpResponse doConfigSubmit( StaplerRequest req) throws IOException, ServletException, FormException {
BulkChange bc = new BulkChange(MONITORS_OWNER);
try {
Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
monitors.rebuild(req,req.getSubmittedForm(),getNodeMonitorDescriptors());
// add in the rest of instances are ignored instances
for (Descriptor<NodeMonitor> d : NodeMonitor.all())
if(monitors.get(d)==null) {
NodeMonitor i = createDefaultInstance(d, true);
if(i!=null)
monitors.add(i);
}
// recompute the data
for (NodeMonitor nm : monitors) {
nm.triggerUpdate();
}
return FormApply.success(".");
} finally {
bc.commit();
}
}
/**
* {@link NodeMonitor}s are persisted in this file.
*/
private static XmlFile getConfigFile() {
return new XmlFile(new File(Jenkins.getInstance().getRootDir(),"nodeMonitors.xml"));
}
public Api getApi() {
return new Api(this);
}
public Descriptor<ComputerSet> getDescriptor() {
return Jenkins.getInstance().getDescriptorOrDie(ComputerSet.class);
}
@Extension
public static class DescriptorImpl extends Descriptor<ComputerSet> {
@Override
public String getDisplayName() {
return "";
}
/**
* Auto-completion for the "copy from" field in the new job page.
*/
public AutoCompletionCandidates doAutoCompleteCopyNewItemFrom(@QueryParameter final String value) {
final AutoCompletionCandidates r = new AutoCompletionCandidates();
for (Node n : Jenkins.getInstance().getNodes()) {
if (n.getNodeName().startsWith(value))
r.add(n.getNodeName());
}
return r;
}
}
/**
* Just to force the execution of the static initializer.
*/
public static void initialize() {}
@Initializer(after= JOB_LOADED)
public static void init() {
// start monitoring nodes, although there's no hurry.
Timer.get().schedule(new SafeTimerTask() {
public void doRun() {
ComputerSet.initialize();
}
}, 10, TimeUnit.SECONDS);
}
private static final Logger LOGGER = Logger.getLogger(ComputerSet.class.getName());
static {
try {
DescribableList<NodeMonitor,Descriptor<NodeMonitor>> r
= new DescribableList<NodeMonitor, Descriptor<NodeMonitor>>(Saveable.NOOP);
// load persisted monitors
XmlFile xf = getConfigFile();
if(xf.exists()) {
DescribableList<NodeMonitor,Descriptor<NodeMonitor>> persisted =
(DescribableList<NodeMonitor,Descriptor<NodeMonitor>>) xf.read();
List<NodeMonitor> sanitized = new ArrayList<NodeMonitor>();
for (NodeMonitor nm : persisted) {
try {
nm.getDescriptor();
sanitized.add(nm);
} catch (Throwable e) {
// the descriptor didn't load? see JENKINS-15869
}
}
r.replaceBy(sanitized);
}
// if we have any new monitors, let's add them
for (Descriptor<NodeMonitor> d : NodeMonitor.all())
if(r.get(d)==null) {
NodeMonitor i = createDefaultInstance(d,false);
if(i!=null)
r.add(i);
}
monitors.replaceBy(r.toList());
} catch (Throwable x) {
LOGGER.log(Level.WARNING, "Failed to instantiate NodeMonitors", x);
}
}
private static NodeMonitor createDefaultInstance(Descriptor<NodeMonitor> d, boolean ignored) {
try {
NodeMonitor nm = d.clazz.newInstance();
nm.setIgnored(ignored);
return nm;
} catch (InstantiationException e) {
LOGGER.log(Level.SEVERE, "Failed to instanciate "+d.clazz,e);
} catch (IllegalAccessException e) {
LOGGER.log(Level.SEVERE, "Failed to instanciate "+d.clazz,e);
}
return null;
}
}
| Reverting whitespace change.
| core/src/main/java/hudson/model/ComputerSet.java | Reverting whitespace change. | <ide><path>ore/src/main/java/hudson/model/ComputerSet.java
<ide>
<ide> JSONObject formData = req.getSubmittedForm();
<ide> formData.put("name", fixedName);
<del>
<add>
<ide> // TODO type is probably NodeDescriptor.id but confirm
<ide> Node result = NodeDescriptor.all().find(type).newInstance(req, formData);
<ide> app.addNode(result); |
|
Java | apache-2.0 | 834b839bf5deab60499ecfb85facd55f06f8e258 | 0 | PeterKnego/appengine-maven-plugin-oath2-config,RajMondaz/appengine-maven-plugin,renfeng/appengine-maven-plugin,rdwallis/appengine-maven-plugin,ludoch/appengine-maven-plugin,GoogleCloudPlatform/appengine-maven-plugin,kuldeep0709/appengine-maven-plugin,ArcBees/appengine-maven-plugin,tinesoft/appengine-maven-plugin,josephburnett/appengine-maven-plugin | package com.google.appengine;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.Plugin;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.BuildPluginManager;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.descriptor.MojoDescriptor;
import org.apache.maven.plugin.descriptor.PluginDescriptor;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.configuration.PlexusConfiguration;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.codehaus.plexus.util.xml.Xpp3DomUtils;
/**
* Runs the datanucleus enhancer.
*
* @author Matt Stephenson <[email protected]>
* @goal enhance
* @phase compile
*/
public class AppengineEnhancerMojo extends AbstractMojo {
/**
* @parameter expression="${project}"
* @required
* @readonly
*/
private MavenProject mavenProject;
/**
* The Maven Session Object
*
* @parameter expression="${session}"
* @required
* @readonly
*/
protected MavenSession session;
/**
* The Maven PluginManager Object
*
* @component
* @required
*/
protected BuildPluginManager pluginManager;
/**
* The api to use ( JDO or JPA ) for enhancement
*
* @parameter expression="${appengine.enhancerApi}" default-value="JDO"
*/
private String enhancerApi;
private static final String DATANUCLEUS_VERSION = "3.2.0-release";
private static final Dependency JDO_DEPENDENCY = new Dependency() {
{
setGroupId("org.datanucleus");
setArtifactId("datanucleus-api-jdo");
setVersion(DATANUCLEUS_VERSION);
}
};
private static final Dependency JPA_DEPENDENCY = new Dependency() {
{
setGroupId("org.datanucleus");
setArtifactId("datanucleus-api-jpa");
setVersion(DATANUCLEUS_VERSION);
}
};
@Override
public void execute() throws MojoExecutionException {
if(!enhancerApi.equals("JDO") && !enhancerApi.equals("JPA")) {
throw new MojoExecutionException("enhancerApi must be either JPA or JDO");
}
Plugin plugin = new Plugin();
plugin.setGroupId("org.datanucleus");
plugin.setArtifactId("datanucleus-maven-plugin");
plugin.setVersion(DATANUCLEUS_VERSION);
plugin.addDependency(enhancerApi.equals("JDO") ? JDO_DEPENDENCY : JPA_DEPENDENCY);
for (Dependency transitiveDep: mavenProject.getDependencies()){
plugin.addDependency(transitiveDep);
}
PluginDescriptor pluginDescriptor = null;
try {
pluginDescriptor = pluginManager.loadPlugin(
plugin,
mavenProject.getRemotePluginRepositories(),
session.getRepositorySession());
} catch (Exception e) {
throw new MojoExecutionException("Could not load the datanucleus plugin.", e);
}
MojoDescriptor mojoDescriptor = pluginDescriptor.getMojo("enhance");
Xpp3Dom configuration = new Xpp3Dom("configuration");
Xpp3Dom apiElement = new Xpp3Dom("api");
apiElement.setValue(enhancerApi);
Xpp3Dom verboseElement = new Xpp3Dom("verbose");
verboseElement.setValue("true");
configuration.addChild(apiElement);
configuration.addChild(verboseElement);
configuration = Xpp3DomUtils.mergeXpp3Dom(configuration, convertPlexusConfiguration(mojoDescriptor.getMojoConfiguration()));
MojoExecution exec = new MojoExecution(mojoDescriptor, configuration);
try {
pluginManager.executeMojo(session, exec);
} catch (Exception e) {
throw new MojoExecutionException("Could not execute datanucleus enhancer.", e);
}
}
private Xpp3Dom convertPlexusConfiguration(PlexusConfiguration config) {
Xpp3Dom xpp3DomElement = new Xpp3Dom(config.getName());
xpp3DomElement.setValue(config.getValue());
for (String name : config.getAttributeNames()) {
xpp3DomElement.setAttribute(name, config.getAttribute(name));
}
for (PlexusConfiguration child : config.getChildren()) {
xpp3DomElement.addChild(convertPlexusConfiguration(child));
}
return xpp3DomElement;
}
}
| src/main/java/com/google/appengine/AppengineEnhancerMojo.java | package com.google.appengine;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.Plugin;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.BuildPluginManager;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.descriptor.MojoDescriptor;
import org.apache.maven.plugin.descriptor.PluginDescriptor;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.configuration.PlexusConfiguration;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.codehaus.plexus.util.xml.Xpp3DomUtils;
/**
* Runs the datanucleus enhancer.
*
* @author Matt Stephenson <[email protected]>
* @goal enhance
* @phase compile
*/
public class AppengineEnhancerMojo extends AbstractMojo {
/**
* @parameter expression="${project}"
* @required
* @readonly
*/
private MavenProject mavenProject;
/**
* The Maven Session Object
*
* @parameter expression="${session}"
* @required
* @readonly
*/
protected MavenSession session;
/**
* The Maven PluginManager Object
*
* @component
* @required
*/
protected BuildPluginManager pluginManager;
/**
* The api to use ( JDO or JPA ) for enhancement
*
* @parameter expression="${appengine.enhancerApi}" default-value="JDO"
*/
private String enhancerApi;
private static final String DATANUCLEUS_VERSION = "3.2.0-m1";
private static final Dependency JDO_DEPENDENCY = new Dependency() {
{
setGroupId("org.datanucleus");
setArtifactId("datanucleus-api-jdo");
setVersion(DATANUCLEUS_VERSION);
}
};
private static final Dependency JPA_DEPENDENCY = new Dependency() {
{
setGroupId("org.datanucleus");
setArtifactId("datanucleus-api-jpa");
setVersion(DATANUCLEUS_VERSION);
}
};
@Override
public void execute() throws MojoExecutionException {
if(!enhancerApi.equals("JDO") && !enhancerApi.equals("JPA")) {
throw new MojoExecutionException("enhancerApi must be either JPA or JDO");
}
Plugin plugin = new Plugin();
plugin.setGroupId("org.datanucleus");
plugin.setArtifactId("maven-datanucleus-plugin");
plugin.setVersion(DATANUCLEUS_VERSION);
plugin.addDependency(enhancerApi.equals("JDO") ? JDO_DEPENDENCY : JPA_DEPENDENCY);
PluginDescriptor pluginDescriptor = null;
try {
pluginDescriptor = pluginManager.loadPlugin(
plugin,
mavenProject.getRemotePluginRepositories(),
session.getRepositorySession());
} catch (Exception e) {
throw new MojoExecutionException("Could not load the datanucleus plugin.", e);
}
MojoDescriptor mojoDescriptor = pluginDescriptor.getMojo("enhance");
Xpp3Dom configuration = new Xpp3Dom("configuration");
Xpp3Dom apiElement = new Xpp3Dom("api");
apiElement.setValue(enhancerApi);
Xpp3Dom verboseElement = new Xpp3Dom("verbose");
verboseElement.setValue("true");
configuration.addChild(apiElement);
configuration.addChild(verboseElement);
configuration = Xpp3DomUtils.mergeXpp3Dom(configuration, convertPlexusConfiguration(mojoDescriptor.getMojoConfiguration()));
MojoExecution exec = new MojoExecution(mojoDescriptor, configuration);
try {
pluginManager.executeMojo(session, exec);
} catch (Exception e) {
throw new MojoExecutionException("Could not execute datanucleus enhancer.", e);
}
}
private Xpp3Dom convertPlexusConfiguration(PlexusConfiguration config) {
Xpp3Dom xpp3DomElement = new Xpp3Dom(config.getName());
xpp3DomElement.setValue(config.getValue());
for (String name : config.getAttributeNames()) {
xpp3DomElement.setAttribute(name, config.getAttribute(name));
}
for (PlexusConfiguration child : config.getChildren()) {
xpp3DomElement.addChild(convertPlexusConfiguration(child));
}
return xpp3DomElement;
}
}
| Fix enhance jar dependencies and use the official enhancer 3.2.0 release
| src/main/java/com/google/appengine/AppengineEnhancerMojo.java | Fix enhance jar dependencies and use the official enhancer 3.2.0 release | <ide><path>rc/main/java/com/google/appengine/AppengineEnhancerMojo.java
<ide> */
<ide> private String enhancerApi;
<ide>
<del> private static final String DATANUCLEUS_VERSION = "3.2.0-m1";
<add> private static final String DATANUCLEUS_VERSION = "3.2.0-release";
<ide>
<ide> private static final Dependency JDO_DEPENDENCY = new Dependency() {
<ide> {
<ide>
<ide> Plugin plugin = new Plugin();
<ide> plugin.setGroupId("org.datanucleus");
<del> plugin.setArtifactId("maven-datanucleus-plugin");
<add> plugin.setArtifactId("datanucleus-maven-plugin");
<ide> plugin.setVersion(DATANUCLEUS_VERSION);
<ide> plugin.addDependency(enhancerApi.equals("JDO") ? JDO_DEPENDENCY : JPA_DEPENDENCY);
<del>
<add> for (Dependency transitiveDep: mavenProject.getDependencies()){
<add> plugin.addDependency(transitiveDep);
<add> }
<add>
<ide> PluginDescriptor pluginDescriptor = null;
<ide>
<ide> try { |
|
Java | agpl-3.0 | 851a1b44c364e2a506e308eead62262414c60c45 | 0 | JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,JanMarvin/rstudio | /*
* AceEditor.java
*
* Copyright (C) 2009-18 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
package org.rstudio.studio.client.workbench.views.source.editors.text;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.google.gwt.animation.client.AnimationScheduler;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.JsArrayString;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.RepeatingCommand;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.dom.client.PreElement;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.event.logical.shared.AttachEvent;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import org.rstudio.core.client.CommandWithArg;
import org.rstudio.core.client.ElementIds;
import org.rstudio.core.client.ExternalJavaScriptLoader;
import org.rstudio.core.client.ExternalJavaScriptLoader.Callback;
import org.rstudio.core.client.Rectangle;
import org.rstudio.core.client.StringUtil;
import org.rstudio.core.client.command.KeyboardShortcut.KeySequence;
import org.rstudio.core.client.dom.DomUtils;
import org.rstudio.core.client.dom.WindowEx;
import org.rstudio.core.client.js.JsMap;
import org.rstudio.core.client.js.JsObject;
import org.rstudio.core.client.js.JsUtil;
import org.rstudio.core.client.regex.Match;
import org.rstudio.core.client.regex.Pattern;
import org.rstudio.core.client.resources.StaticDataResource;
import org.rstudio.core.client.widget.DynamicIFrame;
import org.rstudio.studio.client.RStudioGinjector;
import org.rstudio.studio.client.application.Desktop;
import org.rstudio.studio.client.application.events.EventBus;
import org.rstudio.studio.client.common.SuperDevMode;
import org.rstudio.studio.client.common.codetools.CodeToolsServerOperations;
import org.rstudio.studio.client.common.debugging.model.Breakpoint;
import org.rstudio.studio.client.common.filetypes.DocumentMode;
import org.rstudio.studio.client.common.filetypes.TextFileType;
import org.rstudio.studio.client.common.filetypes.DocumentMode.Mode;
import org.rstudio.studio.client.server.Void;
import org.rstudio.studio.client.workbench.MainWindowObject;
import org.rstudio.studio.client.workbench.commands.Commands;
import org.rstudio.studio.client.workbench.model.ChangeTracker;
import org.rstudio.studio.client.workbench.model.EventBasedChangeTracker;
import org.rstudio.studio.client.workbench.prefs.model.UIPrefs;
import org.rstudio.studio.client.workbench.prefs.model.UIPrefsAccessor;
import org.rstudio.studio.client.workbench.snippets.SnippetHelper;
import org.rstudio.studio.client.workbench.views.console.shell.assist.CompletionManager;
import org.rstudio.studio.client.workbench.views.console.shell.assist.CompletionManager.InitCompletionFilter;
import org.rstudio.studio.client.workbench.views.console.shell.assist.CompletionPopupPanel;
import org.rstudio.studio.client.workbench.views.console.shell.assist.DelegatingCompletionManager;
import org.rstudio.studio.client.workbench.views.console.shell.assist.NullCompletionManager;
import org.rstudio.studio.client.workbench.views.console.shell.assist.PythonCompletionManager;
import org.rstudio.studio.client.workbench.views.console.shell.assist.RCompletionManager;
import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorDisplay;
import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorPosition;
import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorSelection;
import org.rstudio.studio.client.workbench.views.output.lint.DiagnosticsBackgroundPopup;
import org.rstudio.studio.client.workbench.views.output.lint.model.AceAnnotation;
import org.rstudio.studio.client.workbench.views.output.lint.model.LintItem;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.*;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.AceClickEvent.Handler;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Mode.InsertChunkInfo;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Renderer.ScreenCoordinates;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.spelling.CharClassifier;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.spelling.TokenPredicate;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.spelling.WordIterable;
import org.rstudio.studio.client.workbench.views.source.editors.text.cpp.CppCompletionContext;
import org.rstudio.studio.client.workbench.views.source.editors.text.cpp.CppCompletionManager;
import org.rstudio.studio.client.workbench.views.source.editors.text.events.*;
import org.rstudio.studio.client.workbench.views.source.editors.text.rmd.ChunkDefinition;
import org.rstudio.studio.client.workbench.views.source.editors.text.rmd.TextEditingTargetNotebook;
import org.rstudio.studio.client.workbench.views.source.events.CollabEditStartParams;
import org.rstudio.studio.client.workbench.views.source.events.RecordNavigationPositionEvent;
import org.rstudio.studio.client.workbench.views.source.events.RecordNavigationPositionHandler;
import org.rstudio.studio.client.workbench.views.source.events.SaveFileEvent;
import org.rstudio.studio.client.workbench.views.source.events.SaveFileHandler;
import org.rstudio.studio.client.workbench.views.source.model.DirtyState;
import org.rstudio.studio.client.workbench.views.source.model.RnwCompletionContext;
import org.rstudio.studio.client.workbench.views.source.model.SourcePosition;
public class AceEditor implements DocDisplay,
InputEditorDisplay,
NavigableSourceEditor
{
public enum NewLineMode
{
Windows("windows"),
Unix("unix"),
Auto("auto");
NewLineMode(String type)
{
this.type = type;
}
public String getType()
{
return type;
}
private String type;
}
private class Filter implements InitCompletionFilter
{
public boolean shouldComplete(NativeEvent event)
{
// Never complete if there's an active selection
Range range = getSession().getSelection().getRange();
if (!range.isEmpty())
return false;
// Don't consider Tab to be a completion if we're at the start of a
// line (e.g. only zero or more whitespace characters between the
// beginning of the line and the cursor)
if (event != null && event.getKeyCode() != KeyCodes.KEY_TAB)
return true;
// Short-circuit if the user has explicitly opted in
if (uiPrefs_.allowTabMultilineCompletion().getValue())
return true;
int col = range.getStart().getColumn();
if (col == 0)
return false;
String line = getSession().getLine(range.getStart().getRow());
return line.substring(0, col).trim().length() != 0;
}
}
private class AnchoredSelectionImpl implements AnchoredSelection
{
private AnchoredSelectionImpl(Anchor start, Anchor end)
{
start_ = start;
end_ = end;
}
public String getValue()
{
return getSession().getTextRange(getRange());
}
public void apply()
{
getSession().getSelection().setSelectionRange(
getRange());
}
public Range getRange()
{
return Range.fromPoints(start_.getPosition(), end_.getPosition());
}
public void detach()
{
start_.detach();
end_.detach();
}
private final Anchor start_;
private final Anchor end_;
}
private class AceEditorChangeTracker extends EventBasedChangeTracker<Void>
{
private AceEditorChangeTracker()
{
super(AceEditor.this);
AceEditor.this.addFoldChangeHandler(new org.rstudio.studio.client.workbench.views.source.editors.text.events.FoldChangeEvent.Handler()
{
@Override
public void onFoldChange(FoldChangeEvent event)
{
changed_ = true;
}
});
AceEditor.this.addLineWidgetsChangedHandler(new org.rstudio.studio.client.workbench.views.source.editors.text.events.LineWidgetsChangedEvent.Handler() {
@Override
public void onLineWidgetsChanged(LineWidgetsChangedEvent event)
{
changed_ = true;
}
});
}
@Override
public ChangeTracker fork()
{
AceEditorChangeTracker forked = new AceEditorChangeTracker();
forked.changed_ = changed_;
return forked;
}
}
public static void preload()
{
load(null);
}
public static void load(final Command command)
{
aceLoader_.addCallback(new Callback()
{
public void onLoaded()
{
aceSupportLoader_.addCallback(new Callback()
{
public void onLoaded()
{
extLanguageToolsLoader_.addCallback(new Callback()
{
public void onLoaded()
{
vimLoader_.addCallback(new Callback()
{
public void onLoaded()
{
emacsLoader_.addCallback(new Callback()
{
public void onLoaded()
{
if (command != null)
command.execute();
}
});
}
});
}
});
}
});
}
});
}
public static final native AceEditor getEditor(Element el)
/*-{
for (; el != null; el = el.parentElement)
if (el.$RStudioAceEditor != null)
return el.$RStudioAceEditor;
}-*/;
private static final native void attachToWidget(Element el, AceEditor editor)
/*-{
el.$RStudioAceEditor = editor;
}-*/;
private static final native void detachFromWidget(Element el)
/*-{
el.$RStudioAceEditor = null;
}-*/;
@Inject
public AceEditor()
{
widget_ = new AceEditorWidget();
snippets_ = new SnippetHelper(this);
editorEventListeners_ = new ArrayList<HandlerRegistration>();
mixins_ = new AceEditorMixins(this);
ElementIds.assignElementId(widget_.getElement(), ElementIds.SOURCE_TEXT_EDITOR);
completionManager_ = new NullCompletionManager();
diagnosticsBgPopup_ = new DiagnosticsBackgroundPopup(this);
RStudioGinjector.INSTANCE.injectMembers(this);
backgroundTokenizer_ = new BackgroundTokenizer(this);
vim_ = new Vim(this);
bgLinkHighlighter_ = new AceEditorBackgroundLinkHighlighter(this);
bgChunkHighlighter_ = new AceBackgroundHighlighter(this);
widget_.addValueChangeHandler(new ValueChangeHandler<Void>()
{
public void onValueChange(ValueChangeEvent<Void> evt)
{
if (!valueChangeSuppressed_)
{
ValueChangeEvent.fire(AceEditor.this, null);
}
}
});
widget_.addFoldChangeHandler(new FoldChangeEvent.Handler()
{
@Override
public void onFoldChange(FoldChangeEvent event)
{
AceEditor.this.fireEvent(new FoldChangeEvent());
}
});
addPasteHandler(new PasteEvent.Handler()
{
@Override
public void onPaste(PasteEvent event)
{
if (completionManager_ != null)
completionManager_.onPaste(event);
final Position start = getSelectionStart();
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
@Override
public void execute()
{
Range range = Range.fromPoints(start, getSelectionEnd());
indentPastedRange(range);
}
});
}
});
// handle click events
addAceClickHandler(new AceClickEvent.Handler()
{
@Override
public void onAceClick(AceClickEvent event)
{
fixVerticalOffsetBug();
if (DomUtils.isCommandClick(event.getNativeEvent()))
{
// eat the event so ace doesn't do anything with it
event.preventDefault();
event.stopPropagation();
// go to function definition
fireEvent(new CommandClickEvent(event));
}
else
{
// if the focus in the Help pane or another iframe
// we need to make sure to get it back
WindowEx.get().focus();
}
}
});
lastCursorChangedTime_ = 0;
addCursorChangedHandler(new CursorChangedHandler()
{
@Override
public void onCursorChanged(CursorChangedEvent event)
{
fixVerticalOffsetBug();
clearLineHighlight();
lastCursorChangedTime_ = System.currentTimeMillis();
}
});
lastModifiedTime_ = 0;
addValueChangeHandler(new ValueChangeHandler<Void>()
{
@Override
public void onValueChange(ValueChangeEvent<Void> event)
{
lastModifiedTime_ = System.currentTimeMillis();
clearDebugLineHighlight();
}
});
widget_.addAttachHandler(new AttachEvent.Handler()
{
@Override
public void onAttachOrDetach(AttachEvent event)
{
if (event.isAttached())
attachToWidget(widget_.getElement(), AceEditor.this);
else
detachFromWidget(widget_.getElement());
if (!event.isAttached())
{
for (HandlerRegistration handler : editorEventListeners_)
handler.removeHandler();
editorEventListeners_.clear();
if (completionManager_ != null)
{
completionManager_.detach();
completionManager_ = null;
}
}
}
});
widget_.addFocusHandler(new FocusHandler()
{
@Override
public void onFocus(FocusEvent event)
{
String id = AceEditor.this.getWidget().getElement().getId();
MainWindowObject.lastFocusedEditor().set(id);
}
});
events_.addHandler(
AceEditorCommandEvent.TYPE,
new AceEditorCommandEvent.Handler()
{
@Override
public void onEditorCommand(AceEditorCommandEvent event)
{
// skip this if this is only for the actively focused Ace instance
if (event.getExecutionPolicy() == AceEditorCommandEvent.EXECUTION_POLICY_FOCUSED &&
!AceEditor.this.isFocused())
{
return;
}
switch (event.getCommand())
{
case AceEditorCommandEvent.YANK_REGION: yankRegion(); break;
case AceEditorCommandEvent.YANK_BEFORE_CURSOR: yankBeforeCursor(); break;
case AceEditorCommandEvent.YANK_AFTER_CURSOR: yankAfterCursor(); break;
case AceEditorCommandEvent.PASTE_LAST_YANK: pasteLastYank(); break;
case AceEditorCommandEvent.INSERT_ASSIGNMENT_OPERATOR: insertAssignmentOperator(); break;
case AceEditorCommandEvent.INSERT_PIPE_OPERATOR: insertPipeOperator(); break;
case AceEditorCommandEvent.JUMP_TO_MATCHING: jumpToMatching(); break;
case AceEditorCommandEvent.SELECT_TO_MATCHING: selectToMatching(); break;
case AceEditorCommandEvent.EXPAND_TO_MATCHING: expandToMatching(); break;
case AceEditorCommandEvent.ADD_CURSOR_ABOVE: addCursorAbove(); break;
case AceEditorCommandEvent.ADD_CURSOR_BELOW: addCursorBelow(); break;
case AceEditorCommandEvent.INSERT_SNIPPET: insertSnippet(); break;
}
}
});
}
public void yankRegion()
{
if (isVimModeOn() && !isVimInInsertMode())
return;
// no-op if there is no selection
String selectionValue = getSelectionValue();
if (StringUtil.isNullOrEmpty(selectionValue))
return;
if (Desktop.isDesktop() && isEmacsModeOn())
{
Desktop.getFrame().clipboardCut();
clearEmacsMark();
}
else
{
yankedText_ = getSelectionValue();
replaceSelection("");
}
}
public void yankBeforeCursor()
{
if (isVimModeOn() && !isVimInInsertMode())
return;
Position cursorPos = getCursorPosition();
Range yankRange = Range.fromPoints(
Position.create(cursorPos.getRow(), 0),
cursorPos);
if (Desktop.isDesktop() && isEmacsModeOn())
{
String text = getTextForRange(yankRange);
Desktop.getFrame().setClipboardText(StringUtil.notNull(text));
replaceRange(yankRange, "");
clearEmacsMark();
}
else
{
setSelectionRange(yankRange);
yankedText_ = getSelectionValue();
replaceSelection("");
}
}
public void yankAfterCursor()
{
if (isVimModeOn() && !isVimInInsertMode())
return;
Position cursorPos = getCursorPosition();
Range yankRange = null;
String line = getLine(cursorPos.getRow());
int lineLength = line.length();
// if the cursor is already at the end of the line
// (allowing for trailing whitespace), then eat the
// newline as well; otherwise, just eat to end of line
String rest = line.substring(cursorPos.getColumn());
if (rest.trim().isEmpty())
{
yankRange = Range.fromPoints(
cursorPos,
Position.create(cursorPos.getRow() + 1, 0));
}
else
{
yankRange = Range.fromPoints(
cursorPos,
Position.create(cursorPos.getRow(), lineLength));
}
if (Desktop.isDesktop() && isEmacsModeOn())
{
String text = getTextForRange(yankRange);
Desktop.getFrame().setClipboardText(StringUtil.notNull(text));
replaceRange(yankRange, "");
clearEmacsMark();
}
else
{
setSelectionRange(yankRange);
yankedText_ = getSelectionValue();
replaceSelection("");
}
}
public void pasteLastYank()
{
if (isVimModeOn() && !isVimInInsertMode())
return;
if (Desktop.isDesktop() && isEmacsModeOn())
{
Desktop.getFrame().clipboardPaste();
}
else
{
if (yankedText_ == null)
return;
replaceSelection(yankedText_);
setCursorPosition(getSelectionEnd());
}
}
public void insertAssignmentOperator()
{
if (DocumentMode.isCursorInRMode(this))
insertAssignmentOperatorImpl("<-");
else
insertAssignmentOperatorImpl("=");
}
@SuppressWarnings("deprecation")
private void insertAssignmentOperatorImpl(String op)
{
boolean hasWhitespaceBefore =
Character.isSpace(getCharacterBeforeCursor()) ||
(!hasSelection() && getCursorPosition().getColumn() == 0);
String insertion = hasWhitespaceBefore
? op + " "
: " " + op + " ";
insertCode(insertion, false);
}
@SuppressWarnings("deprecation")
public void insertPipeOperator()
{
boolean hasWhitespaceBefore =
Character.isSpace(getCharacterBeforeCursor()) ||
(!hasSelection() && getCursorPosition().getColumn() == 0);
if (hasWhitespaceBefore)
insertCode("%>% ", false);
else
insertCode(" %>% ", false);
}
private void indentPastedRange(Range range)
{
if (fileType_ == null ||
!fileType_.canAutoIndent() ||
!RStudioGinjector.INSTANCE.getUIPrefs().reindentOnPaste().getValue())
{
return;
}
String firstLinePrefix = getSession().getTextRange(
Range.fromPoints(Position.create(range.getStart().getRow(), 0),
range.getStart()));
if (firstLinePrefix.trim().length() != 0)
{
Position newStart = Position.create(range.getStart().getRow() + 1, 0);
if (newStart.compareTo(range.getEnd()) >= 0)
return;
range = Range.fromPoints(newStart, range.getEnd());
}
getSession().reindent(range);
}
public AceCommandManager getCommandManager()
{
return getWidget().getEditor().getCommandManager();
}
public void setEditorCommandBinding(String id, List<KeySequence> keys)
{
getWidget().getEditor().getCommandManager().rebindCommand(id, keys);
}
public void resetCommands()
{
AceCommandManager manager = AceCommandManager.create();
JsObject commands = manager.getCommands();
for (String key : JsUtil.asIterable(commands.keys()))
{
AceCommand command = commands.getObject(key);
getWidget().getEditor().getCommandManager().addCommand(command);
}
}
@Inject
void initialize(CodeToolsServerOperations server,
UIPrefs uiPrefs,
CollabEditor collab,
Commands commands,
EventBus events)
{
server_ = server;
uiPrefs_ = uiPrefs;
collab_ = collab;
commands_ = commands;
events_ = events;
}
public TextFileType getFileType()
{
return fileType_;
}
public void setFileType(TextFileType fileType)
{
setFileType(fileType, false);
}
public void setFileType(TextFileType fileType, boolean suppressCompletion)
{
fileType_ = fileType;
updateLanguage(suppressCompletion);
}
public void setFileType(TextFileType fileType,
CompletionManager completionManager)
{
fileType_ = fileType;
updateLanguage(completionManager);
}
@Override
public void setRnwCompletionContext(RnwCompletionContext rnwContext)
{
rnwContext_ = rnwContext;
}
@Override
public void setCppCompletionContext(CppCompletionContext cppContext)
{
cppContext_ = cppContext;
}
@Override
public void setRCompletionContext(RCompletionContext rContext)
{
rContext_ = rContext;
}
private void updateLanguage(boolean suppressCompletion)
{
if (fileType_ == null)
return;
CompletionManager completionManager;
if (!suppressCompletion && fileType_.getEditorLanguage().useRCompletion())
{
// GWT throws an exception if we bind Ace using 'AceEditor.this' below
// so work around that by just creating a final reference and use that
final AceEditor editor = this;
completionManager = new DelegatingCompletionManager(this)
{
@Override
protected void initialize(Map<Mode, CompletionManager> managers)
{
// R completion manager
managers.put(DocumentMode.Mode.R, new RCompletionManager(
editor,
editor,
new CompletionPopupPanel(),
server_,
new Filter(),
rContext_,
fileType_.canExecuteChunks() ? rnwContext_ : null,
editor,
false));
// Python completion manager
managers.put(DocumentMode.Mode.PYTHON, new PythonCompletionManager(
editor,
editor,
new CompletionPopupPanel(),
server_,
new Filter(),
rContext_,
fileType_.canExecuteChunks() ? rnwContext_ : null,
editor,
false));
// C++ completion manager
managers.put(DocumentMode.Mode.C_CPP, new CppCompletionManager(
editor,
new Filter(),
cppContext_));
}
};
}
else
{
completionManager = new NullCompletionManager();
}
updateLanguage(completionManager);
}
private void updateLanguage(CompletionManager completionManager)
{
clearLint();
if (fileType_ == null)
return;
if (completionManager_ != null)
{
completionManager_.detach();
completionManager_ = null;
}
completionManager_ = completionManager;
updateKeyboardHandlers();
syncCompletionPrefs();
syncDiagnosticsPrefs();
snippets_.ensureSnippetsLoaded();
getSession().setEditorMode(
fileType_.getEditorLanguage().getParserName(),
false);
handlers_.fireEvent(new EditorModeChangedEvent(getModeId()));
getSession().setUseWrapMode(fileType_.getWordWrap());
syncWrapLimit();
}
@Override
public void syncCompletionPrefs()
{
if (fileType_ == null)
return;
boolean enabled = fileType_.getEditorLanguage().useAceLanguageTools();
boolean live = uiPrefs_.codeCompleteOther().getValue() ==
UIPrefsAccessor.COMPLETION_ALWAYS;
int characterThreshold = uiPrefs_.alwaysCompleteCharacters().getValue();
int delay = uiPrefs_.alwaysCompleteDelayMs().getValue();
widget_.getEditor().setCompletionOptions(
enabled,
uiPrefs_.enableSnippets().getValue(),
live,
characterThreshold,
delay);
}
@Override
public void syncDiagnosticsPrefs()
{
if (fileType_ == null)
return;
boolean useWorker = uiPrefs_.showDiagnosticsOther().getValue() &&
fileType_.getEditorLanguage().useAceLanguageTools();
getSession().setUseWorker(useWorker);
getSession().setWorkerTimeout(
uiPrefs_.backgroundDiagnosticsDelayMs().getValue());
}
private void syncWrapLimit()
{
// bail if there is no filetype yet
if (fileType_ == null)
return;
// We originally observed that large word-wrapped documents
// would cause Chrome on Liunx to freeze (bug #3207), eventually
// running of of memory. Running the profiler indicated that the
// time was being spent inside wrap width calculations in Ace.
// Looking at the Ace bug database there were other wrapping problems
// that were solvable by changing the wrap mode from "free" to a
// specific range. So, for Chrome on Linux we started syncing the
// wrap limit to the user-specified margin width.
//
// Unfortunately, this caused another problem whereby the ace
// horizontal scrollbar would show up over the top of the editor
// and the console (bug #3428). We tried reverting the fix to
// #3207 and sure enough this solved the horizontal scrollbar
// problem _and_ no longer froze Chrome (so perhaps there was a
// bug in Chrome).
//
// In the meantime we added user pref to soft wrap to the margin
// column, essentially allowing users to opt-in to the behavior
// we used to fix the bug. So the net is:
//
// (1) To fix the horizontal scrollbar problem we revereted
// the wrap mode behavior we added from Chrome (under the
// assumption that the issue has been fixed in Chrome)
//
// (2) We added another check for desktop mode (since we saw
// the problem in both Chrome and Safari) to prevent the
// application of the problematic wrap mode setting.
//
// Perhaps there is an ace issue here as well, so the next time
// we sync to Ace tip we should see if we can bring back the
// wrapping option for Chrome (note the repro for this
// is having a soft-wrapping source document in the editor that
// exceed the horizontal threshold)
// NOTE: we no longer do this at all since we observed the
// scollbar problem on desktop as well
}
private void updateKeyboardHandlers()
{
// clear out existing editor handlers (they will be refreshed if necessary)
for (HandlerRegistration handler : editorEventListeners_)
if (handler != null)
handler.removeHandler();
editorEventListeners_.clear();
// save and restore Vim marks as they can be lost when refreshing
// the keyboard handlers. this is necessary as keyboard handlers are
// regenerated on each document save, and clearing the Vim handler will
// clear any local Vim state.
JsMap<Position> marks = JsMap.create().cast();
if (useVimMode_)
marks = widget_.getEditor().getMarks();
// create a keyboard previewer for our special hooks
AceKeyboardPreviewer previewer = new AceKeyboardPreviewer(completionManager_);
// set default key handler
if (useVimMode_)
widget_.getEditor().setKeyboardHandler(KeyboardHandler.vim());
else if (useEmacsKeybindings_)
widget_.getEditor().setKeyboardHandler(KeyboardHandler.emacs());
else
widget_.getEditor().setKeyboardHandler(null);
// add the previewer
widget_.getEditor().addKeyboardHandler(previewer.getKeyboardHandler());
// Listen for command execution
editorEventListeners_.add(AceEditorNative.addEventListener(
widget_.getEditor().getCommandManager(),
"afterExec",
new CommandWithArg<JavaScriptObject>()
{
@Override
public void execute(JavaScriptObject event)
{
events_.fireEvent(new AceAfterCommandExecutedEvent(event));
}
}));
// Listen for keyboard activity
editorEventListeners_.add(AceEditorNative.addEventListener(
widget_.getEditor(),
"keyboardActivity",
new CommandWithArg<JavaScriptObject>()
{
@Override
public void execute(JavaScriptObject event)
{
events_.fireEvent(new AceKeyboardActivityEvent(event));
}
}));
if (useVimMode_)
widget_.getEditor().setMarks(marks);
}
public String getCode()
{
return getSession().getValue();
}
public void setCode(String code, boolean preserveCursorPosition)
{
// Calling setCode("", false) while the editor contains multiple lines of
// content causes bug 2928: Flickering console when typing. Empirically,
// first setting code to a single line of content and then clearing it,
// seems to correct this problem.
if (StringUtil.isNullOrEmpty(code))
doSetCode(" ", preserveCursorPosition);
doSetCode(code, preserveCursorPosition);
}
private void doSetCode(String code, boolean preserveCursorPosition)
{
// Filter out Escape characters that might have snuck in from an old
// bug in 0.95. We can choose to remove this when 0.95 ships, hopefully
// any documents that would be affected by this will be gone by then.
code = code.replaceAll("\u001B", "");
// Normalize newlines -- convert all of '\r', '\r\n', '\n\r' to '\n'.
code = StringUtil.normalizeNewLines(code);
final AceEditorNative ed = widget_.getEditor();
if (preserveCursorPosition)
{
final Position cursorPos;
final int scrollTop, scrollLeft;
cursorPos = ed.getSession().getSelection().getCursor();
scrollTop = ed.getRenderer().getScrollTop();
scrollLeft = ed.getRenderer().getScrollLeft();
// Setting the value directly on the document prevents undo/redo
// stack from being blown away
widget_.getEditor().getSession().getDocument().setValue(code);
ed.getSession().getSelection().moveCursorTo(cursorPos.getRow(),
cursorPos.getColumn(),
false);
ed.getRenderer().scrollToY(scrollTop);
ed.getRenderer().scrollToX(scrollLeft);
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
@Override
public void execute()
{
ed.getRenderer().scrollToY(scrollTop);
ed.getRenderer().scrollToX(scrollLeft);
}
});
}
else
{
ed.getSession().setValue(code);
ed.getSession().getSelection().moveCursorTo(0, 0, false);
}
}
public int getScrollLeft()
{
return widget_.getEditor().getRenderer().getScrollLeft();
}
public void scrollToX(int x)
{
widget_.getEditor().getRenderer().scrollToX(x);
}
public int getScrollTop()
{
return widget_.getEditor().getRenderer().getScrollTop();
}
public void scrollToY(int y, int animateMs)
{
// cancel any existing scroll animation
if (scrollAnimator_ != null)
scrollAnimator_.complete();
if (animateMs == 0)
widget_.getEditor().getRenderer().scrollToY(y);
else
scrollAnimator_ = new ScrollAnimator(y, animateMs);
}
public void insertCode(String code)
{
insertCode(code, false);
}
public void insertCode(String code, boolean blockMode)
{
widget_.getEditor().insert(StringUtil.normalizeNewLines(code));
}
public String getCode(Position start, Position end)
{
return getSession().getTextRange(Range.fromPoints(start, end));
}
@Override
public InputEditorSelection search(String needle,
boolean backwards,
boolean wrap,
boolean caseSensitive,
boolean wholeWord,
Position start,
Range range,
boolean regexpMode)
{
Search search = Search.create(needle,
backwards,
wrap,
caseSensitive,
wholeWord,
start,
range,
regexpMode);
Range resultRange = search.find(getSession());
if (resultRange != null)
{
return createSelection(resultRange.getStart(), resultRange.getEnd());
}
else
{
return null;
}
}
@Override
public void quickAddNext()
{
if (getNativeSelection().isEmpty())
{
getNativeSelection().selectWord();
return;
}
String needle = getSelectionValue();
Search search = Search.create(
needle,
false,
true,
true,
true,
getCursorPosition(),
null,
false);
Range range = search.find(getSession());
if (range == null)
return;
getNativeSelection().addRange(range, false);
centerSelection();
}
@Override
public void insertCode(InputEditorPosition position, String content)
{
insertCode(selectionToPosition(position), content);
}
public void insertCode(Position position, String content)
{
getSession().insert(position, content);
}
@Override
public String getCode(InputEditorSelection selection)
{
return getCode(((AceInputEditorPosition)selection.getStart()).getValue(),
((AceInputEditorPosition)selection.getEnd()).getValue());
}
@Override
public JsArrayString getLines()
{
return getLines(0, getSession().getLength());
}
@Override
public JsArrayString getLines(int startRow, int endRow)
{
return getSession().getLines(startRow, endRow);
}
public void focus()
{
widget_.getEditor().focus();
}
public boolean isFocused()
{
return widget_.getEditor().isFocused();
}
public void codeCompletion()
{
completionManager_.codeCompletion();
}
public void goToHelp()
{
completionManager_.goToHelp();
}
public void goToDefinition()
{
completionManager_.goToDefinition();
}
class PrintIFrame extends DynamicIFrame
{
public PrintIFrame(String code, double fontSize)
{
code_ = code;
fontSize_ = fontSize;
getElement().getStyle().setPosition(com.google.gwt.dom.client.Style.Position.ABSOLUTE);
getElement().getStyle().setLeft(-5000, Unit.PX);
}
@Override
protected void onFrameLoaded()
{
Document doc = getDocument();
PreElement pre = doc.createPreElement();
pre.setInnerText(code_);
pre.getStyle().setProperty("whiteSpace", "pre-wrap");
pre.getStyle().setFontSize(fontSize_, Unit.PT);
doc.getBody().appendChild(pre);
getWindow().print();
// Bug 1224: ace: print from source causes inability to reconnect
// This was caused by the iframe being removed from the document too
// quickly after the print job was sent. As a result, attempting to
// navigate away from the page at any point afterwards would result
// in the error "Document cannot change while printing or in Print
// Preview". The only thing you could do is close the browser tab.
// By inserting a 5-minute delay hopefully Firefox would be done with
// whatever print related operations are important.
Scheduler.get().scheduleFixedDelay(new RepeatingCommand()
{
public boolean execute()
{
PrintIFrame.this.removeFromParent();
return false;
}
}, 1000 * 60 * 5);
}
private final String code_;
private final double fontSize_;
}
public void print()
{
if (Desktop.isDesktop())
{
// the desktop frame prints the code directly
Desktop.getFrame().printText(StringUtil.notNull(getCode()));
}
else
{
// in server mode, we render the code to an IFrame and then print
// the frame using the browser
PrintIFrame printIFrame = new PrintIFrame(
getCode(),
RStudioGinjector.INSTANCE.getUIPrefs().fontSize().getValue());
RootPanel.get().add(printIFrame);
}
}
public String getText()
{
return getSession().getLine(
getSession().getSelection().getCursor().getRow());
}
public void setText(String string)
{
setCode(string, false);
getSession().getSelection().moveCursorFileEnd();
}
public boolean hasSelection()
{
return !getSession().getSelection().getRange().isEmpty();
}
public final Selection getNativeSelection() {
return widget_.getEditor().getSession().getSelection();
}
public InputEditorSelection getSelection()
{
Range selection = getSession().getSelection().getRange();
return new InputEditorSelection(
new AceInputEditorPosition(getSession(), selection.getStart()),
new AceInputEditorPosition(getSession(), selection.getEnd()));
}
public String getSelectionValue()
{
return getSession().getTextRange(
getSession().getSelection().getRange());
}
public Position getSelectionStart()
{
return getSession().getSelection().getRange().getStart();
}
public Position getSelectionEnd()
{
return getSession().getSelection().getRange().getEnd();
}
@Override
public Range getSelectionRange()
{
return Range.fromPoints(getSelectionStart(), getSelectionEnd());
}
@Override
public void setSelectionRange(Range range)
{
getSession().getSelection().setSelectionRange(range);
}
public void setSelectionRanges(JsArray<Range> ranges)
{
int n = ranges.length();
if (n == 0)
return;
if (vim_.isActive())
vim_.exitVisualMode();
setSelectionRange(ranges.get(0));
for (int i = 1; i < n; i++)
getNativeSelection().addRange(ranges.get(i), false);
}
public int getLength(int row)
{
return getSession().getDocument().getLine(row).length();
}
public int getRowCount()
{
return getSession().getDocument().getLength();
}
@Override
public int getPixelWidth()
{
Element[] content = DomUtils.getElementsByClassName(
widget_.getElement(), "ace_content");
if (content.length < 1)
return widget_.getElement().getOffsetWidth();
else
return content[0].getOffsetWidth();
}
public String getLine(int row)
{
return getSession().getLine(row);
}
@Override
public Position getDocumentEnd()
{
int lastRow = getRowCount() - 1;
return Position.create(lastRow, getLength(lastRow));
}
@Override
public void setInsertMatching(boolean value)
{
widget_.getEditor().setInsertMatching(value);
}
@Override
public void setSurroundSelectionPref(String value)
{
widget_.getEditor().setSurroundSelectionPref(value);
}
@Override
public InputEditorSelection createSelection(Position pos1, Position pos2)
{
return new InputEditorSelection(
new AceInputEditorPosition(getSession(), pos1),
new AceInputEditorPosition(getSession(), pos2));
}
@Override
public Position selectionToPosition(InputEditorPosition pos)
{
// HACK: This cast is gross, InputEditorPosition should just become
// AceInputEditorPosition
return Position.create((Integer) pos.getLine(), pos.getPosition());
}
@Override
public InputEditorPosition createInputEditorPosition(Position pos)
{
return new AceInputEditorPosition(getSession(), pos);
}
@Override
public Iterable<Range> getWords(TokenPredicate tokenPredicate,
CharClassifier charClassifier,
Position start,
Position end)
{
return new WordIterable(getSession(),
tokenPredicate,
charClassifier,
start,
end);
}
@Override
public String getTextForRange(Range range)
{
return getSession().getTextRange(range);
}
@Override
public Anchor createAnchor(Position pos)
{
return Anchor.createAnchor(getSession().getDocument(),
pos.getRow(),
pos.getColumn());
}
private void fixVerticalOffsetBug()
{
widget_.getEditor().getRenderer().fixVerticalOffsetBug();
}
@Override
public String debug_getDocumentDump()
{
return widget_.getEditor().getSession().getDocument().getDocumentDump();
}
@Override
public void debug_setSessionValueDirectly(String s)
{
widget_.getEditor().getSession().setValue(s);
}
public void setSelection(InputEditorSelection selection)
{
AceInputEditorPosition start = (AceInputEditorPosition)selection.getStart();
AceInputEditorPosition end = (AceInputEditorPosition)selection.getEnd();
getSession().getSelection().setSelectionRange(Range.fromPoints(
start.getValue(), end.getValue()));
}
public Rectangle getCursorBounds()
{
Range range = getSession().getSelection().getRange();
return toScreenCoordinates(range);
}
public Rectangle toScreenCoordinates(Range range)
{
Renderer renderer = widget_.getEditor().getRenderer();
ScreenCoordinates start = renderer.textToScreenCoordinates(
range.getStart().getRow(),
range.getStart().getColumn());
ScreenCoordinates end = renderer.textToScreenCoordinates(
range.getEnd().getRow(),
range.getEnd().getColumn());
return new Rectangle(start.getPageX(),
start.getPageY(),
end.getPageX() - start.getPageX(),
renderer.getLineHeight());
}
public Position toDocumentPosition(ScreenCoordinates coordinates)
{
return widget_.getEditor().getRenderer().screenToTextCoordinates(
coordinates.getPageX(),
coordinates.getPageY());
}
public Range toDocumentRange(Rectangle rectangle)
{
Renderer renderer = widget_.getEditor().getRenderer();
return Range.fromPoints(
renderer.screenToTextCoordinates(rectangle.getLeft(), rectangle.getTop()),
renderer.screenToTextCoordinates(rectangle.getRight(), rectangle.getBottom()));
}
@Override
public Rectangle getPositionBounds(Position position)
{
Renderer renderer = widget_.getEditor().getRenderer();
ScreenCoordinates start = renderer.textToScreenCoordinates(
position.getRow(),
position.getColumn());
return new Rectangle(start.getPageX(), start.getPageY(),
(int) Math.round(renderer.getCharacterWidth()),
(int) (renderer.getLineHeight() * 0.8));
}
@Override
public Rectangle getRangeBounds(Range range)
{
range = Range.toOrientedRange(range);
Renderer renderer = widget_.getEditor().getRenderer();
if (!range.isMultiLine())
{
ScreenCoordinates start = documentPositionToScreenCoordinates(range.getStart());
ScreenCoordinates end = documentPositionToScreenCoordinates(range.getEnd());
int width = (end.getPageX() - start.getPageX()) + (int) renderer.getCharacterWidth();
int height = (end.getPageY() - start.getPageY()) + (int) renderer.getLineHeight();
return new Rectangle(start.getPageX(), start.getPageY(), width, height);
}
Position startPos = range.getStart();
Position endPos = range.getEnd();
int startRow = startPos.getRow();
int endRow = endPos.getRow();
// figure out top left coordinates
ScreenCoordinates topLeft = documentPositionToScreenCoordinates(Position.create(startRow, 0));
// figure out bottom right coordinates (need to walk rows to figure out longest line)
ScreenCoordinates bottomRight = documentPositionToScreenCoordinates(Position.create(endPos));
for (int row = startRow; row <= endRow; row++)
{
Position rowEndPos = Position.create(row, getLength(row));
ScreenCoordinates coords = documentPositionToScreenCoordinates(rowEndPos);
if (coords.getPageX() > bottomRight.getPageX())
bottomRight = ScreenCoordinates.create(coords.getPageX(), bottomRight.getPageY());
}
// construct resulting range
int width = (bottomRight.getPageX() - topLeft.getPageX()) + (int) renderer.getCharacterWidth();
int height = (bottomRight.getPageY() - topLeft.getPageY()) + (int) renderer.getLineHeight();
return new Rectangle(topLeft.getPageX(), topLeft.getPageY(), width, height);
}
@Override
public Rectangle getPositionBounds(InputEditorPosition position)
{
Position pos = ((AceInputEditorPosition) position).getValue();
return getPositionBounds(pos);
}
public Rectangle getBounds()
{
return new Rectangle(
widget_.getAbsoluteLeft(),
widget_.getAbsoluteTop(),
widget_.getOffsetWidth(),
widget_.getOffsetHeight());
}
public void setFocus(boolean focused)
{
if (focused)
widget_.getEditor().focus();
else
widget_.getEditor().blur();
}
public void replaceRange(Range range, String text) {
getSession().replace(range, text);
}
public String replaceSelection(String value, boolean collapseSelection)
{
Selection selection = getSession().getSelection();
String oldValue = getSession().getTextRange(selection.getRange());
replaceSelection(value);
if (collapseSelection)
{
collapseSelection(false);
}
return oldValue;
}
public boolean isSelectionCollapsed()
{
return getSession().getSelection().isEmpty();
}
public boolean isCursorAtEnd()
{
int lastRow = getRowCount() - 1;
Position cursorPos = getCursorPosition();
return cursorPos.compareTo(Position.create(lastRow,
getLength(lastRow))) == 0;
}
public void clear()
{
setCode("", false);
}
public boolean inMultiSelectMode()
{
return widget_.getEditor().inMultiSelectMode();
}
public void exitMultiSelectMode()
{
widget_.getEditor().exitMultiSelectMode();
}
public void clearSelection()
{
widget_.getEditor().clearSelection();
}
public void collapseSelection(boolean collapseToStart)
{
Selection selection = getSession().getSelection();
Range rng = selection.getRange();
Position pos = collapseToStart ? rng.getStart() : rng.getEnd();
selection.setSelectionRange(Range.fromPoints(pos, pos));
}
public InputEditorSelection getStart()
{
return new InputEditorSelection(
new AceInputEditorPosition(getSession(), Position.create(0, 0)));
}
public InputEditorSelection getEnd()
{
EditSession session = getSession();
int rows = session.getLength();
Position end = Position.create(rows, session.getLine(rows).length());
return new InputEditorSelection(new AceInputEditorPosition(session, end));
}
public String getCurrentLine()
{
int row = getSession().getSelection().getRange().getStart().getRow();
return getSession().getLine(row);
}
public char getCharacterAtCursor()
{
Position cursorPos = getCursorPosition();
int column = cursorPos.getColumn();
String line = getLine(cursorPos.getRow());
if (column == line.length())
return '\0';
return line.charAt(column);
}
public char getCharacterBeforeCursor()
{
Position cursorPos = getCursorPosition();
int column = cursorPos.getColumn();
if (column == 0)
return '\0';
String line = getLine(cursorPos.getRow());
return line.charAt(column - 1);
}
public String getCurrentLineUpToCursor()
{
return getCurrentLine().substring(0, getCursorPosition().getColumn());
}
public int getCurrentLineNum()
{
Position pos = getCursorPosition();
return getSession().documentToScreenRow(pos);
}
public int getCurrentLineCount()
{
return getSession().getScreenLength();
}
@Override
public String getLanguageMode(Position position)
{
return getSession().getMode().getLanguageMode(position);
}
@Override
public String getModeId()
{
return getSession().getMode().getId();
}
public void replaceCode(String code)
{
int endRow, endCol;
endRow = getSession().getLength() - 1;
if (endRow < 0)
{
endRow = 0;
endCol = 0;
}
else
{
endCol = getSession().getLine(endRow).length();
}
Range range = Range.fromPoints(Position.create(0, 0),
Position.create(endRow, endCol));
getSession().replace(range, code);
}
public void replaceSelection(String code)
{
code = StringUtil.normalizeNewLines(code);
Range selRange = getSession().getSelection().getRange();
Position position = getSession().replace(selRange, code);
Range range = Range.fromPoints(selRange.getStart(), position);
getSession().getSelection().setSelectionRange(range);
if (isEmacsModeOn()) clearEmacsMark();
}
public boolean moveSelectionToNextLine(boolean skipBlankLines)
{
int curRow = getSession().getSelection().getCursor().getRow();
while (++curRow < getSession().getLength())
{
String line = getSession().getLine(curRow);
Pattern pattern = Pattern.create("[^\\s]");
Match match = pattern.match(line, 0);
if (skipBlankLines && match == null)
continue;
int col = (match != null) ? match.getIndex() : 0;
getSession().getSelection().moveCursorTo(curRow, col, false);
getSession().unfold(curRow, true);
scrollCursorIntoViewIfNecessary();
return true;
}
return false;
}
@Override
public boolean moveSelectionToBlankLine()
{
int curRow = getSession().getSelection().getCursor().getRow();
// if the current row is the last row then insert a new row
if (curRow == (getSession().getLength() - 1))
{
int rowLen = getSession().getLine(curRow).length();
getSession().getSelection().moveCursorTo(curRow, rowLen, false);
insertCode("\n");
}
while (curRow < getSession().getLength())
{
String line = getSession().getLine(curRow).trim();
if (line.length() == 0)
{
getSession().getSelection().moveCursorTo(curRow, 0, false);
getSession().unfold(curRow, true);
return true;
}
curRow++;
}
return false;
}
@Override
public void expandSelection()
{
widget_.getEditor().expandSelection();
}
@Override
public void shrinkSelection()
{
widget_.getEditor().shrinkSelection();
}
@Override
public void expandRaggedSelection()
{
if (!inMultiSelectMode())
return;
// TODO: It looks like we need to use an alternative API when
// using Vim mode.
if (isVimModeOn())
return;
boolean hasSelection = hasSelection();
Range[] ranges =
widget_.getEditor().getSession().getSelection().getAllRanges();
// Get the maximum columns for the current selection.
int colMin = Integer.MAX_VALUE;
int colMax = 0;
for (Range range : ranges)
{
colMin = Math.min(range.getStart().getColumn(), colMin);
colMax = Math.max(range.getEnd().getColumn(), colMax);
}
// For each range:
//
// 1. Set the left side of the selection to the minimum,
// 2. Set the right side of the selection to the maximum,
// moving the cursor and inserting whitespace as necessary.
for (Range range : ranges)
{
range.getStart().setColumn(colMin);
range.getEnd().setColumn(colMax);
String line = getLine(range.getStart().getRow());
if (line.length() < colMax)
{
insertCode(
Position.create(range.getStart().getRow(), line.length()),
StringUtil.repeat(" ", colMax - line.length()));
}
}
clearSelection();
Selection selection = getNativeSelection();
for (Range range : ranges)
{
if (hasSelection)
selection.addRange(range, true);
else
{
Range newRange = Range.create(
range.getEnd().getRow(),
range.getEnd().getColumn(),
range.getEnd().getRow(),
range.getEnd().getColumn());
selection.addRange(newRange, true);
}
}
}
@Override
public void clearSelectionHistory()
{
widget_.getEditor().clearSelectionHistory();
}
@Override
public void reindent()
{
boolean emptySelection = getSelection().isEmpty();
getSession().reindent(getSession().getSelection().getRange());
if (emptySelection)
moveSelectionToNextLine(false);
}
@Override
public void reindent(Range range)
{
getSession().reindent(range);
}
@Override
public void toggleCommentLines()
{
widget_.getEditor().toggleCommentLines();
}
public ChangeTracker getChangeTracker()
{
return new AceEditorChangeTracker();
}
// Because anchored selections create Ace event listeners, they
// must be explicitly detached (otherwise they will listen for
// edit events into perpetuity). The easiest way to facilitate this
// is to have anchored selection tied to the lifetime of a particular
// 'host' widget; this way, on detach, we can ensure that the associated
// anchors are detached as well.
public AnchoredSelection createAnchoredSelection(Widget hostWidget,
Position startPos,
Position endPos)
{
Anchor start = Anchor.createAnchor(getSession().getDocument(),
startPos.getRow(),
startPos.getColumn());
Anchor end = Anchor.createAnchor(getSession().getDocument(),
endPos.getRow(),
endPos.getColumn());
final AnchoredSelection selection = new AnchoredSelectionImpl(start, end);
if (hostWidget != null)
{
hostWidget.addAttachHandler(new AttachEvent.Handler()
{
@Override
public void onAttachOrDetach(AttachEvent event)
{
if (!event.isAttached() && selection != null)
selection.detach();
}
});
}
return selection;
}
public AnchoredSelection createAnchoredSelection(Position start, Position end)
{
return createAnchoredSelection(null, start, end);
}
public void fitSelectionToLines(boolean expand)
{
Range range = getSession().getSelection().getRange();
Position start = range.getStart();
Position newStart = start;
if (start.getColumn() > 0)
{
if (expand)
{
newStart = Position.create(start.getRow(), 0);
}
else
{
String firstLine = getSession().getLine(start.getRow());
if (firstLine.substring(0, start.getColumn()).trim().length() == 0)
newStart = Position.create(start.getRow(), 0);
}
}
Position end = range.getEnd();
Position newEnd = end;
if (expand)
{
int endRow = end.getRow();
if (endRow == newStart.getRow() || end.getColumn() > 0)
{
// If selection ends at the start of a line, keep the selection
// there--unless that means less than one line will be selected
// in total.
newEnd = Position.create(
endRow, getSession().getLine(endRow).length());
}
}
else
{
while (newEnd.getRow() != newStart.getRow())
{
String line = getSession().getLine(newEnd.getRow());
if (line.substring(0, newEnd.getColumn()).trim().length() != 0)
break;
int prevRow = newEnd.getRow() - 1;
int len = getSession().getLine(prevRow).length();
newEnd = Position.create(prevRow, len);
}
}
getSession().getSelection().setSelectionRange(
Range.fromPoints(newStart, newEnd));
}
public int getSelectionOffset(boolean start)
{
Range range = getSession().getSelection().getRange();
if (start)
return range.getStart().getColumn();
else
return range.getEnd().getColumn();
}
public void onActivate()
{
Scheduler.get().scheduleFinally(new RepeatingCommand()
{
public boolean execute()
{
widget_.onResize();
widget_.onActivate();
return false;
}
});
}
public void onVisibilityChanged(boolean visible)
{
if (visible)
widget_.getEditor().getRenderer().updateFontSize();
}
public void onResize()
{
widget_.onResize();
}
public void setHighlightSelectedLine(boolean on)
{
widget_.getEditor().setHighlightActiveLine(on);
}
public void setHighlightSelectedWord(boolean on)
{
widget_.getEditor().setHighlightSelectedWord(on);
}
public void setShowLineNumbers(boolean on)
{
widget_.getEditor().getRenderer().setShowGutter(on);
}
public boolean getUseSoftTabs()
{
return getSession().getUseSoftTabs();
}
public void setUseSoftTabs(boolean on)
{
getSession().setUseSoftTabs(on);
}
public void setScrollPastEndOfDocument(boolean enable)
{
widget_.getEditor().getRenderer().setScrollPastEnd(enable);
}
public void setHighlightRFunctionCalls(boolean highlight)
{
_setHighlightRFunctionCallsImpl(highlight);
widget_.getEditor().retokenizeDocument();
}
public void setScrollLeft(int x)
{
getSession().setScrollLeft(x);
}
public void setScrollTop(int y)
{
getSession().setScrollTop(y);
}
public void scrollTo(int x, int y)
{
getSession().setScrollLeft(x);
getSession().setScrollTop(y);
}
private native final void _setHighlightRFunctionCallsImpl(boolean highlight)
/*-{
var Mode = $wnd.require("mode/r_highlight_rules");
Mode.setHighlightRFunctionCalls(highlight);
}-*/;
public void enableSearchHighlight()
{
widget_.getEditor().enableSearchHighlight();
}
public void disableSearchHighlight()
{
widget_.getEditor().disableSearchHighlight();
}
/**
* Warning: This will be overridden whenever the file type is set
*/
public void setUseWrapMode(boolean useWrapMode)
{
getSession().setUseWrapMode(useWrapMode);
}
public void setTabSize(int tabSize)
{
getSession().setTabSize(tabSize);
}
public void autoDetectIndentation(boolean on)
{
if (!on)
return;
JsArrayString lines = getLines();
if (lines.length() < 5)
return;
int indentSize = StringUtil.detectIndent(lines);
if (indentSize > 0)
setTabSize(indentSize);
}
public void setShowInvisibles(boolean show)
{
widget_.getEditor().getRenderer().setShowInvisibles(show);
}
public void setShowIndentGuides(boolean show)
{
widget_.getEditor().getRenderer().setShowIndentGuides(show);
}
public void setBlinkingCursor(boolean blinking)
{
String style = blinking ? "ace" : "wide";
widget_.getEditor().setCursorStyle(style);
}
public void setShowPrintMargin(boolean on)
{
widget_.getEditor().getRenderer().setShowPrintMargin(on);
}
@Override
public void setUseEmacsKeybindings(boolean use)
{
if (widget_.getEditor().getReadOnly())
return;
useEmacsKeybindings_ = use;
updateKeyboardHandlers();
}
@Override
public boolean isEmacsModeOn()
{
return useEmacsKeybindings_;
}
@Override
public void clearEmacsMark()
{
widget_.getEditor().clearEmacsMark();
}
@Override
public void setUseVimMode(boolean use)
{
// no-op if the editor is read-only (since vim mode doesn't
// work for read-only ace instances)
if (widget_.getEditor().getReadOnly())
return;
useVimMode_ = use;
updateKeyboardHandlers();
}
@Override
public boolean isVimModeOn()
{
return useVimMode_;
}
@Override
public boolean isVimInInsertMode()
{
return useVimMode_ && widget_.getEditor().isVimInInsertMode();
}
public void setPadding(int padding)
{
widget_.getEditor().getRenderer().setPadding(padding);
}
public void setPrintMarginColumn(int column)
{
widget_.getEditor().getRenderer().setPrintMarginColumn(column);
syncWrapLimit();
}
@Override
public JsArray<AceFold> getFolds()
{
return getSession().getAllFolds();
}
@Override
public String getFoldState(int row)
{
AceFold fold = getSession().getFoldAt(row, 0);
if (fold == null)
return null;
Position foldPos = fold.getStart();
return getSession().getState(foldPos.getRow());
}
@Override
public void addFold(Range range)
{
getSession().addFold("...", range);
}
@Override
public void addFoldFromRow(int row)
{
FoldingRules foldingRules = getSession().getMode().getFoldingRules();
if (foldingRules == null)
return;
Range range = foldingRules.getFoldWidgetRange(getSession(),
"markbegin",
row);
if (range != null)
addFold(range);
}
@Override
public void unfold(AceFold fold)
{
getSession().unfold(Range.fromPoints(fold.getStart(), fold.getEnd()),
false);
}
@Override
public void unfold(int row)
{
getSession().unfold(row, false);
}
@Override
public void unfold(Range range)
{
getSession().unfold(range, false);
}
public void setReadOnly(boolean readOnly)
{
widget_.getEditor().setReadOnly(readOnly);
}
public HandlerRegistration addCursorChangedHandler(final CursorChangedHandler handler)
{
return widget_.addCursorChangedHandler(handler);
}
public HandlerRegistration addSaveCompletedHandler(SaveFileHandler handler)
{
return handlers_.addHandler(SaveFileEvent.TYPE, handler);
}
public HandlerRegistration addAttachHandler(AttachEvent.Handler handler)
{
return widget_.addAttachHandler(handler);
}
public HandlerRegistration addEditorFocusHandler(FocusHandler handler)
{
return widget_.addFocusHandler(handler);
}
public Scope getCurrentScope()
{
return getSession().getMode().getCodeModel().getCurrentScope(
getCursorPosition());
}
public Scope getScopeAtPosition(Position position)
{
return getSession().getMode().getCodeModel().getCurrentScope(position);
}
@Override
public String getNextLineIndent()
{
EditSession session = getSession();
Position cursorPosition = getCursorPosition();
int row = cursorPosition.getRow();
String state = getSession().getState(row);
String line = getCurrentLine().substring(
0, cursorPosition.getColumn());
String tab = session.getTabString();
int tabSize = session.getTabSize();
return session.getMode().getNextLineIndent(
state,
line,
tab,
tabSize,
row);
}
public Scope getCurrentChunk()
{
return getCurrentChunk(getCursorPosition());
}
@Override
public Scope getCurrentChunk(Position position)
{
return getSession().getMode().getCodeModel().getCurrentChunk(position);
}
@Override
public ScopeFunction getCurrentFunction(boolean allowAnonymous)
{
return getFunctionAtPosition(getCursorPosition(), allowAnonymous);
}
@Override
public ScopeFunction getFunctionAtPosition(Position position,
boolean allowAnonymous)
{
return getSession().getMode().getCodeModel().getCurrentFunction(
position, allowAnonymous);
}
@Override
public Scope getCurrentSection()
{
return getSectionAtPosition(getCursorPosition());
}
@Override
public Scope getSectionAtPosition(Position position)
{
return getSession().getMode().getCodeModel().getCurrentSection(position);
}
public Position getCursorPosition()
{
return getSession().getSelection().getCursor();
}
public Position getCursorPositionScreen()
{
return widget_.getEditor().getCursorPositionScreen();
}
public void setCursorPosition(Position position)
{
getSession().getSelection().setSelectionRange(
Range.fromPoints(position, position));
}
public void goToLineStart()
{
widget_.getEditor().getCommandManager().exec("gotolinestart", widget_.getEditor());
}
public void goToLineEnd()
{
widget_.getEditor().getCommandManager().exec("gotolineend", widget_.getEditor());
}
@Override
public void moveCursorNearTop(int rowOffset)
{
int screenRow = getSession().documentToScreenRow(getCursorPosition());
widget_.getEditor().scrollToRow(Math.max(0, screenRow - rowOffset));
}
@Override
public void moveCursorForward()
{
moveCursorForward(1);
}
@Override
public void moveCursorForward(int characters)
{
widget_.getEditor().moveCursorRight(characters);
}
@Override
public void moveCursorBackward()
{
moveCursorBackward(1);
}
@Override
public void moveCursorBackward(int characters)
{
widget_.getEditor().moveCursorLeft(characters);
}
@Override
public void moveCursorNearTop()
{
moveCursorNearTop(7);
}
@Override
public void ensureCursorVisible()
{
if (!widget_.getEditor().isRowFullyVisible(getCursorPosition().getRow()))
moveCursorNearTop();
}
@Override
public void ensureRowVisible(int row)
{
if (!widget_.getEditor().isRowFullyVisible(row))
setCursorPosition(Position.create(row, 0));
}
@Override
public void scrollCursorIntoViewIfNecessary(int rowsAround)
{
Position cursorPos = getCursorPosition();
int cursorRow = cursorPos.getRow();
if (cursorRow >= widget_.getEditor().getLastVisibleRow() - rowsAround)
{
Position alignPos = Position.create(cursorRow + rowsAround, 0);
widget_.getEditor().getRenderer().alignCursor(alignPos, 1);
}
else if (cursorRow <= widget_.getEditor().getFirstVisibleRow() + rowsAround)
{
Position alignPos = Position.create(cursorRow - rowsAround, 0);
widget_.getEditor().getRenderer().alignCursor(alignPos, 0);
}
}
@Override
public void scrollCursorIntoViewIfNecessary()
{
scrollCursorIntoViewIfNecessary(0);
}
@Override
public boolean isCursorInSingleLineString()
{
return StringUtil.isEndOfLineInRStringState(getCurrentLineUpToCursor());
}
public void gotoPageUp()
{
widget_.getEditor().gotoPageUp();
}
public void gotoPageDown()
{
widget_.getEditor().gotoPageDown();
}
public void scrollToBottom()
{
SourcePosition pos = SourcePosition.create(getCurrentLineCount() - 1, 0);
navigate(pos, false);
}
public void revealRange(Range range, boolean animate)
{
widget_.getEditor().revealRange(range, animate);
}
public CodeModel getCodeModel()
{
return getSession().getMode().getCodeModel();
}
public boolean hasCodeModel()
{
return getSession().getMode().hasCodeModel();
}
public boolean hasScopeTree()
{
return hasCodeModel() && getCodeModel().hasScopes();
}
public void buildScopeTree()
{
// Builds the scope tree as a side effect
if (hasScopeTree())
getScopeTree();
}
public int buildScopeTreeUpToRow(int row)
{
if (!hasScopeTree())
return 0;
return getSession().getMode().getRCodeModel().buildScopeTreeUpToRow(row);
}
public JsArray<Scope> getScopeTree()
{
return getSession().getMode().getCodeModel().getScopeTree();
}
@Override
public InsertChunkInfo getInsertChunkInfo()
{
return getSession().getMode().getInsertChunkInfo();
}
@Override
public void foldAll()
{
getSession().foldAll();
}
@Override
public void unfoldAll()
{
getSession().unfoldAll();
}
@Override
public void toggleFold()
{
getSession().toggleFold();
}
@Override
public void setFoldStyle(String style)
{
getSession().setFoldStyle(style);
}
@Override
public JsMap<Position> getMarks()
{
return widget_.getEditor().getMarks();
}
@Override
public void setMarks(JsMap<Position> marks)
{
widget_.getEditor().setMarks(marks);
}
@Override
public void jumpToMatching()
{
widget_.getEditor().jumpToMatching(false, false);
}
@Override
public void selectToMatching()
{
widget_.getEditor().jumpToMatching(true, false);
}
@Override
public void expandToMatching()
{
widget_.getEditor().jumpToMatching(true, true);
}
@Override
public void addCursorAbove()
{
widget_.getEditor().execCommand("addCursorAbove");
}
@Override
public void addCursorBelow()
{
widget_.getEditor().execCommand("addCursorBelow");
}
@Override
public void splitIntoLines()
{
widget_.getEditor().splitIntoLines();
}
@Override
public int getFirstFullyVisibleRow()
{
return widget_.getEditor().getRenderer().getFirstFullyVisibleRow();
}
@Override
public SourcePosition findFunctionPositionFromCursor(String functionName)
{
Scope func =
getSession().getMode().getCodeModel().findFunctionDefinitionFromUsage(
getCursorPosition(),
functionName);
if (func != null)
{
Position position = func.getPreamble();
return SourcePosition.create(position.getRow(), position.getColumn());
}
else
{
return null;
}
}
public JsArray<ScopeFunction> getAllFunctionScopes()
{
CodeModel codeModel = widget_.getEditor().getSession().getMode().getRCodeModel();
if (codeModel == null)
return null;
return codeModel.getAllFunctionScopes();
}
@Override
public void recordCurrentNavigationPosition()
{
fireRecordNavigationPosition(getCursorPosition());
}
@Override
public void navigateToPosition(SourcePosition position,
boolean recordCurrent)
{
navigateToPosition(position, recordCurrent, false);
}
@Override
public void navigateToPosition(SourcePosition position,
boolean recordCurrent,
boolean highlightLine)
{
if (recordCurrent)
recordCurrentNavigationPosition();
navigate(position, true, highlightLine);
}
@Override
public void restorePosition(SourcePosition position)
{
navigate(position, false);
}
@Override
public boolean isAtSourceRow(SourcePosition position)
{
Position currPos = getCursorPosition();
return currPos.getRow() == position.getRow();
}
@Override
public void highlightDebugLocation(SourcePosition startPosition,
SourcePosition endPosition,
boolean executing)
{
int firstRow = widget_.getEditor().getFirstVisibleRow();
int lastRow = widget_.getEditor().getLastVisibleRow();
// if the expression is large, let's just try to land in the middle
int debugRow = (int) Math.floor(startPosition.getRow() + (
endPosition.getRow() - startPosition.getRow())/2);
// if the row at which the debugging occurs is inside a fold, unfold it
getSession().unfold(debugRow, true);
// if the line to be debugged is past or near the edges of the screen,
// scroll it into view. allow some lines of context.
if (debugRow <= (firstRow + DEBUG_CONTEXT_LINES) ||
debugRow >= (lastRow - DEBUG_CONTEXT_LINES))
{
widget_.getEditor().scrollToLine(debugRow, true);
}
applyDebugLineHighlight(
startPosition.asPosition(),
endPosition.asPosition(),
executing);
}
@Override
public void endDebugHighlighting()
{
clearDebugLineHighlight();
}
@Override
public HandlerRegistration addBreakpointSetHandler(
BreakpointSetEvent.Handler handler)
{
return widget_.addBreakpointSetHandler(handler);
}
@Override
public HandlerRegistration addBreakpointMoveHandler(
BreakpointMoveEvent.Handler handler)
{
return widget_.addBreakpointMoveHandler(handler);
}
@Override
public void addOrUpdateBreakpoint(Breakpoint breakpoint)
{
widget_.addOrUpdateBreakpoint(breakpoint);
}
@Override
public void removeBreakpoint(Breakpoint breakpoint)
{
widget_.removeBreakpoint(breakpoint);
}
@Override
public void toggleBreakpointAtCursor()
{
widget_.toggleBreakpointAtCursor();
}
@Override
public void removeAllBreakpoints()
{
widget_.removeAllBreakpoints();
}
@Override
public boolean hasBreakpoints()
{
return widget_.hasBreakpoints();
}
public void setChunkLineExecState(int start, int end, int state)
{
widget_.setChunkLineExecState(start, end, state);
}
private void navigate(SourcePosition srcPosition, boolean addToHistory)
{
navigate(srcPosition, addToHistory, false);
}
private void navigate(SourcePosition srcPosition,
boolean addToHistory,
boolean highlightLine)
{
// get existing cursor position
Position previousCursorPos = getCursorPosition();
// set cursor to function line
Position position = Position.create(srcPosition.getRow(),
srcPosition.getColumn());
setCursorPosition(position);
// skip whitespace if necessary
if (srcPosition.getColumn() == 0)
{
int curRow = getSession().getSelection().getCursor().getRow();
String line = getSession().getLine(curRow);
int funStart = line.indexOf(line.trim());
position = Position.create(curRow, funStart);
setCursorPosition(position);
}
// scroll as necessary
if (srcPosition.getScrollPosition() != -1)
scrollToY(srcPosition.getScrollPosition(), 0);
else if (position.getRow() != previousCursorPos.getRow())
moveCursorNearTop();
else
ensureCursorVisible();
// set focus
focus();
if (highlightLine)
applyLineHighlight(position.getRow());
// add to navigation history if requested and our current mode
// supports history navigation
if (addToHistory)
fireRecordNavigationPosition(position);
}
private void fireRecordNavigationPosition(Position pos)
{
SourcePosition srcPos = SourcePosition.create(pos.getRow(),
pos.getColumn());
fireEvent(new RecordNavigationPositionEvent(srcPos));
}
@Override
public HandlerRegistration addRecordNavigationPositionHandler(
RecordNavigationPositionHandler handler)
{
return handlers_.addHandler(RecordNavigationPositionEvent.TYPE, handler);
}
@Override
public HandlerRegistration addCommandClickHandler(
CommandClickEvent.Handler handler)
{
return handlers_.addHandler(CommandClickEvent.TYPE, handler);
}
@Override
public HandlerRegistration addFindRequestedHandler(
FindRequestedEvent.Handler handler)
{
return handlers_.addHandler(FindRequestedEvent.TYPE, handler);
}
public void setFontSize(double size)
{
// No change needed--the AceEditorWidget uses the "normalSize" style
// However, we do need to resize the gutter
widget_.getEditor().getRenderer().updateFontSize();
widget_.forceResize();
widget_.getLineWidgetManager().syncLineWidgetHeights();
}
public HandlerRegistration addValueChangeHandler(
ValueChangeHandler<Void> handler)
{
return handlers_.addHandler(ValueChangeEvent.getType(), handler);
}
public HandlerRegistration addFoldChangeHandler(
FoldChangeEvent.Handler handler)
{
return handlers_.addHandler(FoldChangeEvent.TYPE, handler);
}
public HandlerRegistration addLineWidgetsChangedHandler(
LineWidgetsChangedEvent.Handler handler)
{
return handlers_.addHandler(LineWidgetsChangedEvent.TYPE, handler);
}
public boolean isScopeTreeReady(int row)
{
return backgroundTokenizer_.isReady(row);
}
public HandlerRegistration addScopeTreeReadyHandler(ScopeTreeReadyEvent.Handler handler)
{
return handlers_.addHandler(ScopeTreeReadyEvent.TYPE, handler);
}
public HandlerRegistration addRenderFinishedHandler(RenderFinishedEvent.Handler handler)
{
return widget_.addHandler(handler, RenderFinishedEvent.TYPE);
}
public HandlerRegistration addDocumentChangedHandler(DocumentChangedEvent.Handler handler)
{
return widget_.addHandler(handler, DocumentChangedEvent.TYPE);
}
public HandlerRegistration addCapturingKeyDownHandler(KeyDownHandler handler)
{
return widget_.addCapturingKeyDownHandler(handler);
}
public HandlerRegistration addCapturingKeyPressHandler(KeyPressHandler handler)
{
return widget_.addCapturingKeyPressHandler(handler);
}
public HandlerRegistration addCapturingKeyUpHandler(KeyUpHandler handler)
{
return widget_.addCapturingKeyUpHandler(handler);
}
public HandlerRegistration addUndoRedoHandler(UndoRedoHandler handler)
{
return widget_.addUndoRedoHandler(handler);
}
public HandlerRegistration addPasteHandler(PasteEvent.Handler handler)
{
return widget_.addPasteHandler(handler);
}
public HandlerRegistration addAceClickHandler(Handler handler)
{
return widget_.addAceClickHandler(handler);
}
public HandlerRegistration addEditorModeChangedHandler(
EditorModeChangedEvent.Handler handler)
{
return handlers_.addHandler(EditorModeChangedEvent.TYPE, handler);
}
public JavaScriptObject getCleanStateToken()
{
return getSession().getUndoManager().peek();
}
public boolean checkCleanStateToken(JavaScriptObject token)
{
JavaScriptObject other = getSession().getUndoManager().peek();
if (token == null ^ other == null)
return false;
return token == null || other.equals(token);
}
public void fireEvent(GwtEvent<?> event)
{
handlers_.fireEvent(event);
}
public Widget asWidget()
{
return widget_;
}
public EditSession getSession()
{
return widget_.getEditor().getSession();
}
public HandlerRegistration addBlurHandler(BlurHandler handler)
{
return widget_.addBlurHandler(handler);
}
public HandlerRegistration addMouseDownHandler(MouseDownHandler handler)
{
return widget_.addMouseDownHandler(handler);
}
public HandlerRegistration addMouseMoveHandler(MouseMoveHandler handler)
{
return widget_.addMouseMoveHandler(handler);
}
public HandlerRegistration addMouseUpHandler(MouseUpHandler handler)
{
return widget_.addMouseUpHandler(handler);
}
public HandlerRegistration addClickHandler(ClickHandler handler)
{
return widget_.addClickHandler(handler);
}
public HandlerRegistration addFocusHandler(FocusHandler handler)
{
return widget_.addFocusHandler(handler);
}
public AceEditorWidget getWidget()
{
return widget_;
}
public HandlerRegistration addKeyDownHandler(KeyDownHandler handler)
{
return widget_.addKeyDownHandler(handler);
}
public HandlerRegistration addKeyPressHandler(KeyPressHandler handler)
{
return widget_.addKeyPressHandler(handler);
}
public HandlerRegistration addKeyUpHandler(KeyUpHandler handler)
{
return widget_.addKeyUpHandler(handler);
}
public HandlerRegistration addSelectionChangedHandler(AceSelectionChangedEvent.Handler handler)
{
return widget_.addSelectionChangedHandler(handler);
}
public void autoHeight()
{
widget_.autoHeight();
}
public void forceCursorChange()
{
widget_.forceCursorChange();
}
public void scrollToCursor(ScrollPanel scrollPanel,
int paddingVert,
int paddingHoriz)
{
DomUtils.ensureVisibleVert(
scrollPanel.getElement(),
widget_.getEditor().getRenderer().getCursorElement(),
paddingVert);
DomUtils.ensureVisibleHoriz(
scrollPanel.getElement(),
widget_.getEditor().getRenderer().getCursorElement(),
paddingHoriz, paddingHoriz,
false);
}
public void scrollToLine(int row, boolean center)
{
widget_.getEditor().scrollToLine(row, center);
}
public void centerSelection()
{
widget_.getEditor().centerSelection();
}
public void alignCursor(Position position, double ratio)
{
widget_.getEditor().getRenderer().alignCursor(position, ratio);
}
public void forceImmediateRender()
{
widget_.getEditor().getRenderer().forceImmediateRender();
}
public void setNewLineMode(NewLineMode mode)
{
getSession().setNewLineMode(mode.getType());
}
public boolean isPasswordMode()
{
return passwordMode_;
}
public void setPasswordMode(boolean passwordMode)
{
passwordMode_ = passwordMode;
widget_.getEditor().getRenderer().setPasswordMode(passwordMode);
}
public void setDisableOverwrite(boolean disableOverwrite)
{
getSession().setDisableOverwrite(disableOverwrite);
}
private Integer createLineHighlightMarker(int line, String style)
{
return createRangeHighlightMarker(Position.create(line, 0),
Position.create(line+1, 0),
style);
}
private Integer createRangeHighlightMarker(
Position start,
Position end,
String style)
{
Range range = Range.fromPoints(start, end);
return getSession().addMarker(range, style, "text", false);
}
private void applyLineHighlight(int line)
{
clearLineHighlight();
if (!widget_.getEditor().getHighlightActiveLine())
{
lineHighlightMarkerId_ = createLineHighlightMarker(line,
"ace_find_line");
}
}
private void clearLineHighlight()
{
if (lineHighlightMarkerId_ != null)
{
getSession().removeMarker(lineHighlightMarkerId_);
lineHighlightMarkerId_ = null;
}
}
private void applyDebugLineHighlight(
Position startPos,
Position endPos,
boolean executing)
{
clearDebugLineHighlight();
lineDebugMarkerId_ = createRangeHighlightMarker(
startPos, endPos,
"ace_active_debug_line");
if (executing)
{
executionLine_ = startPos.getRow();
widget_.getEditor().getRenderer().addGutterDecoration(
executionLine_,
"ace_executing-line");
}
}
private void clearDebugLineHighlight()
{
if (lineDebugMarkerId_ != null)
{
getSession().removeMarker(lineDebugMarkerId_);
lineDebugMarkerId_ = null;
}
if (executionLine_ != null)
{
widget_.getEditor().getRenderer().removeGutterDecoration(
executionLine_,
"ace_executing-line");
executionLine_ = null;
}
}
public void setPopupVisible(boolean visible)
{
popupVisible_ = visible;
}
public boolean isPopupVisible()
{
return popupVisible_;
}
public void selectAll(String needle)
{
widget_.getEditor().findAll(needle);
}
public void selectAll(String needle, Range range, boolean wholeWord, boolean caseSensitive)
{
widget_.getEditor().findAll(needle, range, wholeWord, caseSensitive);
}
public void moveCursorLeft()
{
moveCursorLeft(1);
}
public void moveCursorLeft(int times)
{
widget_.getEditor().moveCursorLeft(times);
}
public void moveCursorRight()
{
moveCursorRight(1);
}
public void moveCursorRight(int times)
{
widget_.getEditor().moveCursorRight(times);
}
public void expandSelectionLeft(int times)
{
widget_.getEditor().expandSelectionLeft(times);
}
public void expandSelectionRight(int times)
{
widget_.getEditor().expandSelectionRight(times);
}
public int getTabSize()
{
return widget_.getEditor().getSession().getTabSize();
}
// TODO: Enable similar logic for C++ mode?
public int getStartOfCurrentStatement()
{
if (!DocumentMode.isSelectionInRMode(this))
return -1;
TokenCursor cursor =
getSession().getMode().getCodeModel().getTokenCursor();
if (!cursor.moveToPosition(getCursorPosition()))
return -1;
if (!cursor.moveToStartOfCurrentStatement())
return -1;
return cursor.getRow();
}
// TODO: Enable similar logic for C++ mode?
public int getEndOfCurrentStatement()
{
if (!DocumentMode.isSelectionInRMode(this))
return -1;
TokenCursor cursor =
getSession().getMode().getCodeModel().getTokenCursor();
if (!cursor.moveToPosition(getCursorPosition()))
return -1;
if (!cursor.moveToEndOfCurrentStatement())
return -1;
return cursor.getRow();
}
private boolean rowEndsInBinaryOp(int row)
{
// move to the last interesting token on this line
JsArray<Token> tokens = getSession().getTokens(row);
for (int i = tokens.length() - 1; i >= 0; i--)
{
Token t = tokens.get(i);
if (t.hasType("text", "comment", "virtual-comment"))
continue;
if (t.getType() == "keyword.operator" ||
t.getType() == "keyword.operator.infix" ||
t.getValue() == ",")
return true;
break;
}
return false;
}
private boolean rowIsEmptyOrComment(int row)
{
JsArray<Token> tokens = getSession().getTokens(row);
for (int i = 0, n = tokens.length(); i < n; i++)
if (!tokens.get(i).hasType("text", "comment", "virtual-comment"))
return false;
return true;
}
private boolean rowStartsWithClosingBracket(int row)
{
JsArray<Token> tokens = getSession().getTokens(row);
int n = tokens.length();
if (n == 0)
return false;
for (int i = 0; i < n; i++)
{
Token token = tokens.get(i);
if (token.hasType("text"))
continue;
String tokenValue = token.getValue();
return tokenValue == "}" ||
tokenValue == ")" ||
tokenValue == "]";
}
return false;
}
private boolean rowEndsWithOpenBracket(int row)
{
JsArray<Token> tokens = getSession().getTokens(row);
int n = tokens.length();
if (n == 0)
return false;
for (int i = 0; i < n; i++)
{
Token token = tokens.get(n - i - 1);
if (token.hasType("text", "comment", "virtual-comment"))
continue;
String tokenValue = token.getValue();
return tokenValue == "{" ||
tokenValue == "(" ||
tokenValue == "[";
}
return false;
}
/**
* Finds the last non-empty line starting at the given line.
*
* @param initial Row to start on
* @param limit Row at which to stop searching
* @return Index of last non-empty line, or limit line if no empty lines
* were found.
*/
private int findParagraphBoundary(int initial, int limit)
{
// no work to do if already at limit
if (initial == limit)
return initial;
// walk towards limit
int delta = limit > initial ? 1 : -1;
for (int row = initial + delta; row != limit; row += delta)
{
if (getLine(row).trim().isEmpty())
return row - delta;
}
// didn't find boundary
return limit;
}
@Override
public Range getParagraph(Position pos, int startRowLimit, int endRowLimit)
{
// find upper and lower paragraph boundaries
return Range.create(
findParagraphBoundary(pos.getRow(), startRowLimit), 0,
findParagraphBoundary(pos.getRow(), endRowLimit)+ 1, 0);
}
@Override
public Range getMultiLineExpr(Position pos, int startRowLimit, int endRowLimit)
{
if (DocumentMode.isSelectionInRMode(this))
{
return rMultiLineExpr(pos, startRowLimit, endRowLimit);
}
else
{
return getParagraph(pos, startRowLimit, endRowLimit);
}
}
private Range rMultiLineExpr(Position pos, int startRowLimit, int endRowLimit)
{
// create token cursor (will be used to walk tokens as needed)
TokenCursor c = getSession().getMode().getCodeModel().getTokenCursor();
// assume start, end at current position
int startRow = pos.getRow();
int endRow = pos.getRow();
// expand to enclosing '(' or '['
do
{
c.setRow(pos.getRow());
// move forward over commented / empty lines
int n = getSession().getLength();
while (rowIsEmptyOrComment(c.getRow()))
{
if (c.getRow() == n - 1)
break;
c.setRow(c.getRow() + 1);
}
// move to last non-right-bracket token on line
c.moveToEndOfRow(c.getRow());
while (c.valueEquals(")") || c.valueEquals("]"))
if (!c.moveToPreviousToken())
break;
// find the top-most enclosing bracket
// check for function scope
String[] candidates = new String[] {"(", "["};
int savedRow = -1;
int savedOffset = -1;
while (c.findOpeningBracket(candidates, true))
{
// check for function scope
if (c.valueEquals("(") &&
c.peekBwd(1).valueEquals("function") &&
c.peekBwd(2).isLeftAssign())
{
ScopeFunction scope = getFunctionAtPosition(c.currentPosition(), false);
if (scope != null)
return Range.fromPoints(scope.getPreamble(), scope.getEnd());
}
// move off of opening bracket and continue lookup
savedRow = c.getRow();
savedOffset = c.getOffset();
if (!c.moveToPreviousToken())
break;
}
// if we found a row, use it
if (savedRow != -1 && savedOffset != -1)
{
c.setRow(savedRow);
c.setOffset(savedOffset);
if (c.fwdToMatchingToken())
{
startRow = savedRow;
endRow = c.getRow();
}
}
} while (false);
// discover start of current statement
while (startRow >= startRowLimit)
{
// if we've hit the start of the document, bail
if (startRow <= 0)
break;
// if the row starts with an open bracket, expand to its match
if (rowStartsWithClosingBracket(startRow))
{
c.moveToStartOfRow(startRow);
if (c.bwdToMatchingToken())
{
startRow = c.getRow();
continue;
}
}
// keep going if the line is empty or previous ends w/binary op
if (rowEndsInBinaryOp(startRow - 1) || rowIsEmptyOrComment(startRow - 1))
{
startRow--;
continue;
}
// keep going if we're in a multiline string
String state = getSession().getState(startRow - 1);
if (state == "qstring" || state == "qqstring")
{
startRow--;
continue;
}
// bail out of the loop -- we've found the start of the statement
break;
}
// discover end of current statement -- we search from the inferred statement
// start, so that we can perform counting of matching pairs of brackets
endRow = startRow;
// NOTE: '[[' is not tokenized as a single token in our Ace tokenizer,
// so it is not included here (this shouldn't cause issues in practice
// since balanced pairs of '[' and '[[' would still imply a correct count
// of matched pairs of '[' anyhow)
int parenCount = 0; // '(', ')'
int braceCount = 0; // '{', '}'
int bracketCount = 0; // '[', ']'
while (endRow <= endRowLimit)
{
// update bracket token counts
JsArray<Token> tokens = getTokens(endRow);
for (Token token : JsUtil.asIterable(tokens))
{
String value = token.getValue();
parenCount += value == "(" ? 1 : 0;
parenCount -= value == ")" ? 1 : 0;
braceCount += value == "{" ? 1 : 0;
braceCount -= value == "}" ? 1 : 0;
bracketCount += value == "[" ? 1 : 0;
bracketCount -= value == "]" ? 1 : 0;
}
// continue search if line ends with binary operator
if (rowEndsInBinaryOp(endRow) || rowIsEmptyOrComment(endRow))
{
endRow++;
continue;
}
// continue search if we have unbalanced brackets
if (parenCount > 0 || braceCount > 0 || bracketCount > 0)
{
endRow++;
continue;
}
// continue search if we're in a multi-line string
String state = getSession().getState(endRow);
if (state == "qstring" || state == "qqstring")
{
endRow++;
continue;
}
// we had balanced brackets and no trailing binary operator; bail
break;
}
// if we're unbalanced at this point, that means we tried to
// expand in an unclosed expression -- just execute the current
// line rather than potentially executing unintended code
if (parenCount + braceCount + bracketCount > 0)
return Range.create(pos.getRow(), 0, pos.getRow() + 1, 0);
// shrink selection for empty lines at borders
while (startRow < endRow && rowIsEmptyOrComment(startRow))
startRow++;
while (endRow > startRow && rowIsEmptyOrComment(endRow))
endRow--;
// fixup for single-line execution
if (startRow > endRow)
startRow = endRow;
// if we've captured the body of a function definition, expand
// to include whole definition
c.setRow(startRow);
c.setOffset(0);
if (c.valueEquals("{") &&
c.moveToPreviousToken() &&
c.valueEquals(")") &&
c.bwdToMatchingToken() &&
c.moveToPreviousToken() &&
c.valueEquals("function") &&
c.moveToPreviousToken() &&
c.isLeftAssign())
{
ScopeFunction fn = getFunctionAtPosition(c.currentPosition(), false);
if (fn != null)
return Range.fromPoints(fn.getPreamble(), fn.getEnd());
}
// construct range
int endColumn = getSession().getLine(endRow).length();
Range range = Range.create(startRow, 0, endRow, endColumn);
// return empty range if nothing to execute
if (getTextForRange(range).trim().isEmpty())
range = Range.fromPoints(pos, pos);
return range;
}
// ---- Annotation related operations
public JsArray<AceAnnotation> getAnnotations()
{
return widget_.getAnnotations();
}
public void setAnnotations(JsArray<AceAnnotation> annotations)
{
widget_.setAnnotations(annotations);
}
@Override
public void removeMarkersAtCursorPosition()
{
widget_.removeMarkersAtCursorPosition();
}
@Override
public void removeMarkersOnCursorLine()
{
widget_.removeMarkersOnCursorLine();
}
@Override
public void showLint(JsArray<LintItem> lint)
{
widget_.showLint(lint);
}
@Override
public void clearLint()
{
widget_.clearLint();
}
@Override
public void showInfoBar(String message)
{
if (infoBar_ == null)
{
infoBar_ = new AceInfoBar(widget_);
widget_.addKeyDownHandler(new KeyDownHandler()
{
@Override
public void onKeyDown(KeyDownEvent event)
{
if (event.getNativeKeyCode() == KeyCodes.KEY_ESCAPE)
infoBar_.hide();
}
});
}
infoBar_.setText(message);
infoBar_.show();
}
public AnchoredRange createAnchoredRange(Position start, Position end)
{
return widget_.getEditor().getSession().createAnchoredRange(start, end);
}
public void insertRoxygenSkeleton()
{
getSession().getMode().getCodeModel().insertRoxygenSkeleton();
}
public long getLastModifiedTime()
{
return lastModifiedTime_;
}
public long getLastCursorChangedTime()
{
return lastCursorChangedTime_;
}
public int getFirstVisibleRow()
{
return widget_.getEditor().getFirstVisibleRow();
}
public int getLastVisibleRow()
{
return widget_.getEditor().getLastVisibleRow();
}
public void blockOutdent()
{
widget_.getEditor().blockOutdent();
}
public ScreenCoordinates documentPositionToScreenCoordinates(Position position)
{
return widget_.getEditor().getRenderer().textToScreenCoordinates(position);
}
public Position screenCoordinatesToDocumentPosition(int pageX, int pageY)
{
return widget_.getEditor().getRenderer().screenToTextCoordinates(pageX, pageY);
}
public boolean isPositionVisible(Position position)
{
return widget_.getEditor().isRowFullyVisible(position.getRow());
}
@Override
public void tokenizeDocument()
{
widget_.getEditor().tokenizeDocument();
}
@Override
public void retokenizeDocument()
{
widget_.getEditor().retokenizeDocument();
}
@Override
public Token getTokenAt(int row, int column)
{
return getSession().getTokenAt(row, column);
}
@Override
public Token getTokenAt(Position position)
{
return getSession().getTokenAt(position);
}
@Override
public JsArray<Token> getTokens(int row)
{
return getSession().getTokens(row);
}
@Override
public TokenIterator createTokenIterator()
{
return createTokenIterator(null);
}
@Override
public TokenIterator createTokenIterator(Position position)
{
TokenIterator it = TokenIterator.create(getSession());
if (position != null)
it.moveToPosition(position);
return it;
}
@Override
public void beginCollabSession(CollabEditStartParams params,
DirtyState dirtyState)
{
// suppress external value change events while the editor's contents are
// being swapped out for the contents of the collab session--otherwise
// there's going to be a lot of flickering as dirty state (etc) try to
// keep up
valueChangeSuppressed_ = true;
collab_.beginCollabSession(this, params, dirtyState, new Command()
{
@Override
public void execute()
{
valueChangeSuppressed_ = false;
}
});
}
@Override
public boolean hasActiveCollabSession()
{
return collab_.hasActiveCollabSession(this);
}
@Override
public boolean hasFollowingCollabSession()
{
return collab_.hasFollowingCollabSession(this);
}
public void endCollabSession()
{
collab_.endCollabSession(this);
}
@Override
public void setDragEnabled(boolean enabled)
{
widget_.setDragEnabled(enabled);
}
@Override
public boolean isSnippetsTabStopManagerActive()
{
return isSnippetsTabStopManagerActiveImpl(widget_.getEditor());
}
private static final native
boolean isSnippetsTabStopManagerActiveImpl(AceEditorNative editor)
/*-{
return editor.tabstopManager != null;
}-*/;
private void insertSnippet()
{
if (!snippets_.onInsertSnippet())
blockOutdent();
}
@Override
public boolean onInsertSnippet()
{
return snippets_.onInsertSnippet();
}
public void toggleTokenInfo()
{
toggleTokenInfo(widget_.getEditor());
}
private static final native void toggleTokenInfo(AceEditorNative editor) /*-{
if (editor.tokenTooltip && editor.tokenTooltip.destroy) {
editor.tokenTooltip.destroy();
} else {
var TokenTooltip = $wnd.require("ace/token_tooltip").TokenTooltip;
editor.tokenTooltip = new TokenTooltip(editor);
}
}-*/;
@Override
public void addLineWidget(final LineWidget widget)
{
// position the element far offscreen if it's above the currently
// visible row; Ace does not position line widgets above the viewport
// until the document is scrolled there
if (widget.getRow() < getFirstVisibleRow())
{
widget.getElement().getStyle().setTop(-10000, Unit.PX);
// set left/right values so that the widget consumes space; necessary
// to get layout offsets inside the widget while rendering but before
// it comes onscreen
widget.getElement().getStyle().setLeft(48, Unit.PX);
widget.getElement().getStyle().setRight(15, Unit.PX);
}
widget_.getLineWidgetManager().addLineWidget(widget);
adjustScrollForLineWidget(widget);
fireLineWidgetsChanged();
}
@Override
public void removeLineWidget(LineWidget widget)
{
widget_.getLineWidgetManager().removeLineWidget(widget);
fireLineWidgetsChanged();
}
@Override
public void removeAllLineWidgets()
{
widget_.getLineWidgetManager().removeAllLineWidgets();
fireLineWidgetsChanged();
}
@Override
public void onLineWidgetChanged(LineWidget widget)
{
// if the widget is above the viewport, this size change might push it
// into visibility, so push it offscreen first
if (widget.getRow() + 1 < getFirstVisibleRow())
widget.getElement().getStyle().setTop(-10000, Unit.PX);
widget_.getLineWidgetManager().onWidgetChanged(widget);
adjustScrollForLineWidget(widget);
fireLineWidgetsChanged();
}
@Override
public JsArray<LineWidget> getLineWidgets()
{
return widget_.getLineWidgetManager().getLineWidgets();
}
@Override
public LineWidget getLineWidgetForRow(int row)
{
return widget_.getLineWidgetManager().getLineWidgetForRow(row);
}
@Override
public boolean hasLineWidgets()
{
return widget_.getLineWidgetManager().hasLineWidgets();
}
private void adjustScrollForLineWidget(LineWidget w)
{
// the cursor is above the line widget, so the line widget is going
// to change the cursor position; adjust the scroll position to hold
// the cursor in place
if (getCursorPosition().getRow() > w.getRow())
{
int delta = w.getElement().getOffsetHeight() - w.getRenderedHeight();
// skip if no change to report
if (delta == 0)
return;
// we adjust the scrolltop on the session since it knows the
// currently queued scroll position; the renderer only knows the
// actual scroll position, which may not reflect unrendered changes
getSession().setScrollTop(getSession().getScrollTop() + delta);
}
// mark the current height as rendered
w.setRenderedHeight(w.getElement().getOffsetHeight());
}
@Override
public JsArray<ChunkDefinition> getChunkDefs()
{
// chunk definitions are populated at render time, so don't return any
// if we haven't rendered yet
if (!isRendered())
return null;
JsArray<ChunkDefinition> chunks = JsArray.createArray().cast();
JsArray<LineWidget> lineWidgets = getLineWidgets();
ScopeList scopes = new ScopeList(this);
for (int i = 0; i<lineWidgets.length(); i++)
{
LineWidget lineWidget = lineWidgets.get(i);
if (lineWidget.getType() == ChunkDefinition.LINE_WIDGET_TYPE)
{
ChunkDefinition chunk = lineWidget.getData();
chunks.push(chunk.with(lineWidget.getRow(),
TextEditingTargetNotebook.getKnitrChunkLabel(
lineWidget.getRow(), this, scopes)));
}
}
return chunks;
}
@Override
public boolean isRendered()
{
return widget_.isRendered();
}
@Override
public boolean showChunkOutputInline()
{
return showChunkOutputInline_;
}
@Override
public void setShowChunkOutputInline(boolean show)
{
showChunkOutputInline_ = show;
}
private void fireLineWidgetsChanged()
{
AceEditor.this.fireEvent(new LineWidgetsChangedEvent());
}
private static class BackgroundTokenizer
{
public BackgroundTokenizer(final AceEditor editor)
{
editor_ = editor;
timer_ = new Timer()
{
@Override
public void run()
{
// Stop our timer if we've tokenized up to the end of the document.
if (row_ >= editor_.getRowCount())
{
editor_.fireEvent(new ScopeTreeReadyEvent(
editor_.getScopeTree(),
editor_.getCurrentScope()));
return;
}
row_ += ROWS_TOKENIZED_PER_ITERATION;
row_ = Math.max(row_, editor.buildScopeTreeUpToRow(row_));
timer_.schedule(DELAY_MS);
}
};
editor_.addDocumentChangedHandler(new DocumentChangedEvent.Handler()
{
@Override
public void onDocumentChanged(DocumentChangedEvent event)
{
row_ = event.getEvent().getRange().getStart().getRow();
timer_.schedule(DELAY_MS);
}
});
}
public boolean isReady(int row)
{
return row < row_;
}
private final AceEditor editor_;
private final Timer timer_;
private int row_ = 0;
private static final int DELAY_MS = 5;
private static final int ROWS_TOKENIZED_PER_ITERATION = 200;
}
private class ScrollAnimator
implements AnimationScheduler.AnimationCallback
{
public ScrollAnimator(int targetY, int ms)
{
targetY_ = targetY;
startY_ = widget_.getEditor().getRenderer().getScrollTop();
delta_ = targetY_ - startY_;
ms_ = ms;
handle_ = AnimationScheduler.get().requestAnimationFrame(this);
}
public void complete()
{
handle_.cancel();
scrollAnimator_ = null;
}
@Override
public void execute(double timestamp)
{
if (startTime_ < 0)
startTime_ = timestamp;
double elapsed = timestamp - startTime_;
if (elapsed >= ms_)
{
widget_.getEditor().getRenderer().scrollToY(targetY_);
complete();
return;
}
// ease-out exponential
widget_.getEditor().getRenderer().scrollToY(
(int)(delta_ * (-Math.pow(2, -10 * elapsed / ms_) + 1)) + startY_);
// request next frame
handle_ = AnimationScheduler.get().requestAnimationFrame(this);
}
private final int ms_;
private final int targetY_;
private final int startY_;
private final int delta_;
private double startTime_ = -1;
private AnimationScheduler.AnimationHandle handle_;
}
private static final int DEBUG_CONTEXT_LINES = 2;
private final HandlerManager handlers_ = new HandlerManager(this);
private final AceEditorWidget widget_;
private final SnippetHelper snippets_;
private ScrollAnimator scrollAnimator_;
private CompletionManager completionManager_;
private CodeToolsServerOperations server_;
private UIPrefs uiPrefs_;
private CollabEditor collab_;
private Commands commands_;
private EventBus events_;
private TextFileType fileType_;
private boolean passwordMode_;
private boolean useEmacsKeybindings_ = false;
private boolean useVimMode_ = false;
private RnwCompletionContext rnwContext_;
private CppCompletionContext cppContext_;
private RCompletionContext rContext_ = null;
private Integer lineHighlightMarkerId_ = null;
private Integer lineDebugMarkerId_ = null;
private Integer executionLine_ = null;
private boolean valueChangeSuppressed_ = false;
private AceInfoBar infoBar_;
private boolean showChunkOutputInline_ = false;
private BackgroundTokenizer backgroundTokenizer_;
private final Vim vim_;
private final AceBackgroundHighlighter bgChunkHighlighter_;
private final AceEditorBackgroundLinkHighlighter bgLinkHighlighter_;
private int scrollTarget_ = 0;
private HandlerRegistration scrollCompleteReg_;
private final AceEditorMixins mixins_;
private static final ExternalJavaScriptLoader getLoader(StaticDataResource release)
{
return getLoader(release, null);
}
private static final ExternalJavaScriptLoader getLoader(StaticDataResource release,
StaticDataResource debug)
{
if (debug == null || !SuperDevMode.isActive())
return new ExternalJavaScriptLoader(release.getSafeUri().asString());
else
return new ExternalJavaScriptLoader(debug.getSafeUri().asString());
}
private static final ExternalJavaScriptLoader aceLoader_ =
getLoader(AceResources.INSTANCE.acejs(), AceResources.INSTANCE.acejsUncompressed());
private static final ExternalJavaScriptLoader aceSupportLoader_ =
getLoader(AceResources.INSTANCE.acesupportjs());
private static final ExternalJavaScriptLoader vimLoader_ =
getLoader(AceResources.INSTANCE.keybindingVimJs(),
AceResources.INSTANCE.keybindingVimUncompressedJs());
private static final ExternalJavaScriptLoader emacsLoader_ =
getLoader(AceResources.INSTANCE.keybindingEmacsJs(),
AceResources.INSTANCE.keybindingEmacsUncompressedJs());
private static final ExternalJavaScriptLoader extLanguageToolsLoader_ =
getLoader(AceResources.INSTANCE.extLanguageTools(),
AceResources.INSTANCE.extLanguageToolsUncompressed());
private boolean popupVisible_;
private final DiagnosticsBackgroundPopup diagnosticsBgPopup_;
private long lastCursorChangedTime_;
private long lastModifiedTime_;
private String yankedText_ = null;
private final List<HandlerRegistration> editorEventListeners_;
}
| src/gwt/src/org/rstudio/studio/client/workbench/views/source/editors/text/AceEditor.java | /*
* AceEditor.java
*
* Copyright (C) 2009-18 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
package org.rstudio.studio.client.workbench.views.source.editors.text;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.google.gwt.animation.client.AnimationScheduler;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.JsArrayString;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.RepeatingCommand;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.dom.client.PreElement;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.event.logical.shared.AttachEvent;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import org.rstudio.core.client.CommandWithArg;
import org.rstudio.core.client.ElementIds;
import org.rstudio.core.client.ExternalJavaScriptLoader;
import org.rstudio.core.client.ExternalJavaScriptLoader.Callback;
import org.rstudio.core.client.Rectangle;
import org.rstudio.core.client.StringUtil;
import org.rstudio.core.client.command.KeyboardShortcut.KeySequence;
import org.rstudio.core.client.dom.DomUtils;
import org.rstudio.core.client.dom.WindowEx;
import org.rstudio.core.client.js.JsMap;
import org.rstudio.core.client.js.JsObject;
import org.rstudio.core.client.js.JsUtil;
import org.rstudio.core.client.regex.Match;
import org.rstudio.core.client.regex.Pattern;
import org.rstudio.core.client.resources.StaticDataResource;
import org.rstudio.core.client.widget.DynamicIFrame;
import org.rstudio.studio.client.RStudioGinjector;
import org.rstudio.studio.client.application.Desktop;
import org.rstudio.studio.client.application.events.EventBus;
import org.rstudio.studio.client.common.SuperDevMode;
import org.rstudio.studio.client.common.codetools.CodeToolsServerOperations;
import org.rstudio.studio.client.common.debugging.model.Breakpoint;
import org.rstudio.studio.client.common.filetypes.DocumentMode;
import org.rstudio.studio.client.common.filetypes.TextFileType;
import org.rstudio.studio.client.common.filetypes.DocumentMode.Mode;
import org.rstudio.studio.client.server.Void;
import org.rstudio.studio.client.workbench.MainWindowObject;
import org.rstudio.studio.client.workbench.commands.Commands;
import org.rstudio.studio.client.workbench.model.ChangeTracker;
import org.rstudio.studio.client.workbench.model.EventBasedChangeTracker;
import org.rstudio.studio.client.workbench.prefs.model.UIPrefs;
import org.rstudio.studio.client.workbench.prefs.model.UIPrefsAccessor;
import org.rstudio.studio.client.workbench.snippets.SnippetHelper;
import org.rstudio.studio.client.workbench.views.console.shell.assist.CompletionManager;
import org.rstudio.studio.client.workbench.views.console.shell.assist.CompletionManager.InitCompletionFilter;
import org.rstudio.studio.client.workbench.views.console.shell.assist.CompletionPopupPanel;
import org.rstudio.studio.client.workbench.views.console.shell.assist.DelegatingCompletionManager;
import org.rstudio.studio.client.workbench.views.console.shell.assist.NullCompletionManager;
import org.rstudio.studio.client.workbench.views.console.shell.assist.PythonCompletionManager;
import org.rstudio.studio.client.workbench.views.console.shell.assist.RCompletionManager;
import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorDisplay;
import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorPosition;
import org.rstudio.studio.client.workbench.views.console.shell.editor.InputEditorSelection;
import org.rstudio.studio.client.workbench.views.output.lint.DiagnosticsBackgroundPopup;
import org.rstudio.studio.client.workbench.views.output.lint.model.AceAnnotation;
import org.rstudio.studio.client.workbench.views.output.lint.model.LintItem;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.*;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.AceClickEvent.Handler;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Mode.InsertChunkInfo;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Renderer.ScreenCoordinates;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.spelling.CharClassifier;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.spelling.TokenPredicate;
import org.rstudio.studio.client.workbench.views.source.editors.text.ace.spelling.WordIterable;
import org.rstudio.studio.client.workbench.views.source.editors.text.cpp.CppCompletionContext;
import org.rstudio.studio.client.workbench.views.source.editors.text.cpp.CppCompletionManager;
import org.rstudio.studio.client.workbench.views.source.editors.text.events.*;
import org.rstudio.studio.client.workbench.views.source.editors.text.rmd.ChunkDefinition;
import org.rstudio.studio.client.workbench.views.source.editors.text.rmd.TextEditingTargetNotebook;
import org.rstudio.studio.client.workbench.views.source.events.CollabEditStartParams;
import org.rstudio.studio.client.workbench.views.source.events.RecordNavigationPositionEvent;
import org.rstudio.studio.client.workbench.views.source.events.RecordNavigationPositionHandler;
import org.rstudio.studio.client.workbench.views.source.events.SaveFileEvent;
import org.rstudio.studio.client.workbench.views.source.events.SaveFileHandler;
import org.rstudio.studio.client.workbench.views.source.model.DirtyState;
import org.rstudio.studio.client.workbench.views.source.model.RnwCompletionContext;
import org.rstudio.studio.client.workbench.views.source.model.SourcePosition;
public class AceEditor implements DocDisplay,
InputEditorDisplay,
NavigableSourceEditor
{
public enum NewLineMode
{
Windows("windows"),
Unix("unix"),
Auto("auto");
NewLineMode(String type)
{
this.type = type;
}
public String getType()
{
return type;
}
private String type;
}
private class Filter implements InitCompletionFilter
{
public boolean shouldComplete(NativeEvent event)
{
// Never complete if there's an active selection
Range range = getSession().getSelection().getRange();
if (!range.isEmpty())
return false;
// Don't consider Tab to be a completion if we're at the start of a
// line (e.g. only zero or more whitespace characters between the
// beginning of the line and the cursor)
if (event != null && event.getKeyCode() != KeyCodes.KEY_TAB)
return true;
// Short-circuit if the user has explicitly opted in
if (uiPrefs_.allowTabMultilineCompletion().getValue())
return true;
int col = range.getStart().getColumn();
if (col == 0)
return false;
String line = getSession().getLine(range.getStart().getRow());
return line.substring(0, col).trim().length() != 0;
}
}
private class AnchoredSelectionImpl implements AnchoredSelection
{
private AnchoredSelectionImpl(Anchor start, Anchor end)
{
start_ = start;
end_ = end;
}
public String getValue()
{
return getSession().getTextRange(getRange());
}
public void apply()
{
getSession().getSelection().setSelectionRange(
getRange());
}
public Range getRange()
{
return Range.fromPoints(start_.getPosition(), end_.getPosition());
}
public void detach()
{
start_.detach();
end_.detach();
}
private final Anchor start_;
private final Anchor end_;
}
private class AceEditorChangeTracker extends EventBasedChangeTracker<Void>
{
private AceEditorChangeTracker()
{
super(AceEditor.this);
AceEditor.this.addFoldChangeHandler(new org.rstudio.studio.client.workbench.views.source.editors.text.events.FoldChangeEvent.Handler()
{
@Override
public void onFoldChange(FoldChangeEvent event)
{
changed_ = true;
}
});
AceEditor.this.addLineWidgetsChangedHandler(new org.rstudio.studio.client.workbench.views.source.editors.text.events.LineWidgetsChangedEvent.Handler() {
@Override
public void onLineWidgetsChanged(LineWidgetsChangedEvent event)
{
changed_ = true;
}
});
}
@Override
public ChangeTracker fork()
{
AceEditorChangeTracker forked = new AceEditorChangeTracker();
forked.changed_ = changed_;
return forked;
}
}
public static void preload()
{
load(null);
}
public static void load(final Command command)
{
aceLoader_.addCallback(new Callback()
{
public void onLoaded()
{
aceSupportLoader_.addCallback(new Callback()
{
public void onLoaded()
{
extLanguageToolsLoader_.addCallback(new Callback()
{
public void onLoaded()
{
vimLoader_.addCallback(new Callback()
{
public void onLoaded()
{
emacsLoader_.addCallback(new Callback()
{
public void onLoaded()
{
if (command != null)
command.execute();
}
});
}
});
}
});
}
});
}
});
}
public static final native AceEditor getEditor(Element el)
/*-{
for (; el != null; el = el.parentElement)
if (el.$RStudioAceEditor != null)
return el.$RStudioAceEditor;
}-*/;
private static final native void attachToWidget(Element el, AceEditor editor)
/*-{
el.$RStudioAceEditor = editor;
}-*/;
private static final native void detachFromWidget(Element el)
/*-{
el.$RStudioAceEditor = null;
}-*/;
@Inject
public AceEditor()
{
widget_ = new AceEditorWidget();
snippets_ = new SnippetHelper(this);
editorEventListeners_ = new ArrayList<HandlerRegistration>();
mixins_ = new AceEditorMixins(this);
ElementIds.assignElementId(widget_.getElement(), ElementIds.SOURCE_TEXT_EDITOR);
completionManager_ = new NullCompletionManager();
diagnosticsBgPopup_ = new DiagnosticsBackgroundPopup(this);
RStudioGinjector.INSTANCE.injectMembers(this);
backgroundTokenizer_ = new BackgroundTokenizer(this);
vim_ = new Vim(this);
bgLinkHighlighter_ = new AceEditorBackgroundLinkHighlighter(this);
bgChunkHighlighter_ = new AceBackgroundHighlighter(this);
widget_.addValueChangeHandler(new ValueChangeHandler<Void>()
{
public void onValueChange(ValueChangeEvent<Void> evt)
{
if (!valueChangeSuppressed_)
{
ValueChangeEvent.fire(AceEditor.this, null);
}
}
});
widget_.addFoldChangeHandler(new FoldChangeEvent.Handler()
{
@Override
public void onFoldChange(FoldChangeEvent event)
{
AceEditor.this.fireEvent(new FoldChangeEvent());
}
});
addPasteHandler(new PasteEvent.Handler()
{
@Override
public void onPaste(PasteEvent event)
{
if (completionManager_ != null)
completionManager_.onPaste(event);
final Position start = getSelectionStart();
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
@Override
public void execute()
{
Range range = Range.fromPoints(start, getSelectionEnd());
indentPastedRange(range);
}
});
}
});
// handle click events
addAceClickHandler(new AceClickEvent.Handler()
{
@Override
public void onAceClick(AceClickEvent event)
{
fixVerticalOffsetBug();
if (DomUtils.isCommandClick(event.getNativeEvent()))
{
// eat the event so ace doesn't do anything with it
event.preventDefault();
event.stopPropagation();
// go to function definition
fireEvent(new CommandClickEvent(event));
}
else
{
// if the focus in the Help pane or another iframe
// we need to make sure to get it back
WindowEx.get().focus();
}
}
});
lastCursorChangedTime_ = 0;
addCursorChangedHandler(new CursorChangedHandler()
{
@Override
public void onCursorChanged(CursorChangedEvent event)
{
fixVerticalOffsetBug();
clearLineHighlight();
lastCursorChangedTime_ = System.currentTimeMillis();
}
});
lastModifiedTime_ = 0;
addValueChangeHandler(new ValueChangeHandler<Void>()
{
@Override
public void onValueChange(ValueChangeEvent<Void> event)
{
lastModifiedTime_ = System.currentTimeMillis();
clearDebugLineHighlight();
}
});
widget_.addAttachHandler(new AttachEvent.Handler()
{
@Override
public void onAttachOrDetach(AttachEvent event)
{
if (event.isAttached())
attachToWidget(widget_.getElement(), AceEditor.this);
else
detachFromWidget(widget_.getElement());
if (!event.isAttached())
{
for (HandlerRegistration handler : editorEventListeners_)
handler.removeHandler();
editorEventListeners_.clear();
if (completionManager_ != null)
{
completionManager_.detach();
completionManager_ = null;
}
}
}
});
widget_.addFocusHandler(new FocusHandler()
{
@Override
public void onFocus(FocusEvent event)
{
String id = AceEditor.this.getWidget().getElement().getId();
MainWindowObject.lastFocusedEditor().set(id);
}
});
events_.addHandler(
AceEditorCommandEvent.TYPE,
new AceEditorCommandEvent.Handler()
{
@Override
public void onEditorCommand(AceEditorCommandEvent event)
{
// skip this if this is only for the actively focused Ace instance
if (event.getExecutionPolicy() == AceEditorCommandEvent.EXECUTION_POLICY_FOCUSED &&
!AceEditor.this.isFocused())
{
return;
}
switch (event.getCommand())
{
case AceEditorCommandEvent.YANK_REGION: yankRegion(); break;
case AceEditorCommandEvent.YANK_BEFORE_CURSOR: yankBeforeCursor(); break;
case AceEditorCommandEvent.YANK_AFTER_CURSOR: yankAfterCursor(); break;
case AceEditorCommandEvent.PASTE_LAST_YANK: pasteLastYank(); break;
case AceEditorCommandEvent.INSERT_ASSIGNMENT_OPERATOR: insertAssignmentOperator(); break;
case AceEditorCommandEvent.INSERT_PIPE_OPERATOR: insertPipeOperator(); break;
case AceEditorCommandEvent.JUMP_TO_MATCHING: jumpToMatching(); break;
case AceEditorCommandEvent.SELECT_TO_MATCHING: selectToMatching(); break;
case AceEditorCommandEvent.EXPAND_TO_MATCHING: expandToMatching(); break;
case AceEditorCommandEvent.ADD_CURSOR_ABOVE: addCursorAbove(); break;
case AceEditorCommandEvent.ADD_CURSOR_BELOW: addCursorBelow(); break;
case AceEditorCommandEvent.INSERT_SNIPPET: insertSnippet(); break;
}
}
});
}
public void yankRegion()
{
if (isVimModeOn() && !isVimInInsertMode())
return;
// no-op if there is no selection
String selectionValue = getSelectionValue();
if (StringUtil.isNullOrEmpty(selectionValue))
return;
if (Desktop.isDesktop() && isEmacsModeOn())
{
Desktop.getFrame().clipboardCut();
clearEmacsMark();
}
else
{
yankedText_ = getSelectionValue();
replaceSelection("");
}
}
public void yankBeforeCursor()
{
if (isVimModeOn() && !isVimInInsertMode())
return;
Position cursorPos = getCursorPosition();
Range yankRange = Range.fromPoints(
Position.create(cursorPos.getRow(), 0),
cursorPos);
if (Desktop.isDesktop() && isEmacsModeOn())
{
String text = getTextForRange(yankRange);
Desktop.getFrame().setClipboardText(StringUtil.notNull(text));
replaceRange(yankRange, "");
clearEmacsMark();
}
else
{
setSelectionRange(yankRange);
yankedText_ = getSelectionValue();
replaceSelection("");
}
}
public void yankAfterCursor()
{
if (isVimModeOn() && !isVimInInsertMode())
return;
Position cursorPos = getCursorPosition();
Range yankRange = null;
String line = getLine(cursorPos.getRow());
int lineLength = line.length();
// if the cursor is already at the end of the line
// (allowing for trailing whitespace), then eat the
// newline as well; otherwise, just eat to end of line
String rest = line.substring(cursorPos.getColumn());
if (rest.trim().isEmpty())
{
yankRange = Range.fromPoints(
cursorPos,
Position.create(cursorPos.getRow() + 1, 0));
}
else
{
yankRange = Range.fromPoints(
cursorPos,
Position.create(cursorPos.getRow(), lineLength));
}
if (Desktop.isDesktop() && isEmacsModeOn())
{
String text = getTextForRange(yankRange);
Desktop.getFrame().setClipboardText(StringUtil.notNull(text));
replaceRange(yankRange, "");
clearEmacsMark();
}
else
{
setSelectionRange(yankRange);
yankedText_ = getSelectionValue();
replaceSelection("");
}
}
public void pasteLastYank()
{
if (isVimModeOn() && !isVimInInsertMode())
return;
if (Desktop.isDesktop() && isEmacsModeOn())
{
Desktop.getFrame().clipboardPaste();
}
else
{
if (yankedText_ == null)
return;
replaceSelection(yankedText_);
setCursorPosition(getSelectionEnd());
}
}
public void insertAssignmentOperator()
{
if (DocumentMode.isCursorInRMode(this))
insertAssignmentOperatorImpl("<-");
else
insertAssignmentOperatorImpl("=");
}
@SuppressWarnings("deprecation")
private void insertAssignmentOperatorImpl(String op)
{
boolean hasWhitespaceBefore =
Character.isSpace(getCharacterBeforeCursor()) ||
(!hasSelection() && getCursorPosition().getColumn() == 0);
String insertion = hasWhitespaceBefore
? op + " "
: " " + op + " ";
insertCode(insertion, false);
}
@SuppressWarnings("deprecation")
public void insertPipeOperator()
{
boolean hasWhitespaceBefore =
Character.isSpace(getCharacterBeforeCursor()) ||
(!hasSelection() && getCursorPosition().getColumn() == 0);
if (hasWhitespaceBefore)
insertCode("%>% ", false);
else
insertCode(" %>% ", false);
}
private void indentPastedRange(Range range)
{
if (fileType_ == null ||
!fileType_.canAutoIndent() ||
!RStudioGinjector.INSTANCE.getUIPrefs().reindentOnPaste().getValue())
{
return;
}
String firstLinePrefix = getSession().getTextRange(
Range.fromPoints(Position.create(range.getStart().getRow(), 0),
range.getStart()));
if (firstLinePrefix.trim().length() != 0)
{
Position newStart = Position.create(range.getStart().getRow() + 1, 0);
if (newStart.compareTo(range.getEnd()) >= 0)
return;
range = Range.fromPoints(newStart, range.getEnd());
}
getSession().reindent(range);
}
public AceCommandManager getCommandManager()
{
return getWidget().getEditor().getCommandManager();
}
public void setEditorCommandBinding(String id, List<KeySequence> keys)
{
getWidget().getEditor().getCommandManager().rebindCommand(id, keys);
}
public void resetCommands()
{
AceCommandManager manager = AceCommandManager.create();
JsObject commands = manager.getCommands();
for (String key : JsUtil.asIterable(commands.keys()))
{
AceCommand command = commands.getObject(key);
getWidget().getEditor().getCommandManager().addCommand(command);
}
}
@Inject
void initialize(CodeToolsServerOperations server,
UIPrefs uiPrefs,
CollabEditor collab,
Commands commands,
EventBus events)
{
server_ = server;
uiPrefs_ = uiPrefs;
collab_ = collab;
commands_ = commands;
events_ = events;
}
public TextFileType getFileType()
{
return fileType_;
}
public void setFileType(TextFileType fileType)
{
setFileType(fileType, false);
}
public void setFileType(TextFileType fileType, boolean suppressCompletion)
{
fileType_ = fileType;
updateLanguage(suppressCompletion);
}
public void setFileType(TextFileType fileType,
CompletionManager completionManager)
{
fileType_ = fileType;
updateLanguage(completionManager);
}
@Override
public void setRnwCompletionContext(RnwCompletionContext rnwContext)
{
rnwContext_ = rnwContext;
}
@Override
public void setCppCompletionContext(CppCompletionContext cppContext)
{
cppContext_ = cppContext;
}
@Override
public void setRCompletionContext(RCompletionContext rContext)
{
rContext_ = rContext;
}
private void updateLanguage(boolean suppressCompletion)
{
if (fileType_ == null)
return;
CompletionManager completionManager;
if (!suppressCompletion && fileType_.getEditorLanguage().useRCompletion())
{
completionManager = new DelegatingCompletionManager(this)
{
@Override
protected void initialize(Map<Mode, CompletionManager> managers)
{
// R completion manager
managers.put(DocumentMode.Mode.R, new RCompletionManager(
AceEditor.this,
AceEditor.this,
new CompletionPopupPanel(),
server_,
new Filter(),
rContext_,
fileType_.canExecuteChunks() ? rnwContext_ : null,
AceEditor.this,
false));
// Python completion manager
managers.put(DocumentMode.Mode.PYTHON, new PythonCompletionManager(
AceEditor.this,
AceEditor.this,
new CompletionPopupPanel(),
server_,
new Filter(),
rContext_,
fileType_.canExecuteChunks() ? rnwContext_ : null,
AceEditor.this,
false));
// C++ completion manager
managers.put(DocumentMode.Mode.C_CPP, new CppCompletionManager(
AceEditor.this,
new Filter(),
cppContext_));
}
};
}
else
{
completionManager = new NullCompletionManager();
}
updateLanguage(completionManager);
}
private void updateLanguage(CompletionManager completionManager)
{
clearLint();
if (fileType_ == null)
return;
if (completionManager_ != null)
{
completionManager_.detach();
completionManager_ = null;
}
completionManager_ = completionManager;
updateKeyboardHandlers();
syncCompletionPrefs();
syncDiagnosticsPrefs();
snippets_.ensureSnippetsLoaded();
getSession().setEditorMode(
fileType_.getEditorLanguage().getParserName(),
false);
handlers_.fireEvent(new EditorModeChangedEvent(getModeId()));
getSession().setUseWrapMode(fileType_.getWordWrap());
syncWrapLimit();
}
@Override
public void syncCompletionPrefs()
{
if (fileType_ == null)
return;
boolean enabled = fileType_.getEditorLanguage().useAceLanguageTools();
boolean live = uiPrefs_.codeCompleteOther().getValue() ==
UIPrefsAccessor.COMPLETION_ALWAYS;
int characterThreshold = uiPrefs_.alwaysCompleteCharacters().getValue();
int delay = uiPrefs_.alwaysCompleteDelayMs().getValue();
widget_.getEditor().setCompletionOptions(
enabled,
uiPrefs_.enableSnippets().getValue(),
live,
characterThreshold,
delay);
}
@Override
public void syncDiagnosticsPrefs()
{
if (fileType_ == null)
return;
boolean useWorker = uiPrefs_.showDiagnosticsOther().getValue() &&
fileType_.getEditorLanguage().useAceLanguageTools();
getSession().setUseWorker(useWorker);
getSession().setWorkerTimeout(
uiPrefs_.backgroundDiagnosticsDelayMs().getValue());
}
private void syncWrapLimit()
{
// bail if there is no filetype yet
if (fileType_ == null)
return;
// We originally observed that large word-wrapped documents
// would cause Chrome on Liunx to freeze (bug #3207), eventually
// running of of memory. Running the profiler indicated that the
// time was being spent inside wrap width calculations in Ace.
// Looking at the Ace bug database there were other wrapping problems
// that were solvable by changing the wrap mode from "free" to a
// specific range. So, for Chrome on Linux we started syncing the
// wrap limit to the user-specified margin width.
//
// Unfortunately, this caused another problem whereby the ace
// horizontal scrollbar would show up over the top of the editor
// and the console (bug #3428). We tried reverting the fix to
// #3207 and sure enough this solved the horizontal scrollbar
// problem _and_ no longer froze Chrome (so perhaps there was a
// bug in Chrome).
//
// In the meantime we added user pref to soft wrap to the margin
// column, essentially allowing users to opt-in to the behavior
// we used to fix the bug. So the net is:
//
// (1) To fix the horizontal scrollbar problem we revereted
// the wrap mode behavior we added from Chrome (under the
// assumption that the issue has been fixed in Chrome)
//
// (2) We added another check for desktop mode (since we saw
// the problem in both Chrome and Safari) to prevent the
// application of the problematic wrap mode setting.
//
// Perhaps there is an ace issue here as well, so the next time
// we sync to Ace tip we should see if we can bring back the
// wrapping option for Chrome (note the repro for this
// is having a soft-wrapping source document in the editor that
// exceed the horizontal threshold)
// NOTE: we no longer do this at all since we observed the
// scollbar problem on desktop as well
}
private void updateKeyboardHandlers()
{
// clear out existing editor handlers (they will be refreshed if necessary)
for (HandlerRegistration handler : editorEventListeners_)
if (handler != null)
handler.removeHandler();
editorEventListeners_.clear();
// save and restore Vim marks as they can be lost when refreshing
// the keyboard handlers. this is necessary as keyboard handlers are
// regenerated on each document save, and clearing the Vim handler will
// clear any local Vim state.
JsMap<Position> marks = JsMap.create().cast();
if (useVimMode_)
marks = widget_.getEditor().getMarks();
// create a keyboard previewer for our special hooks
AceKeyboardPreviewer previewer = new AceKeyboardPreviewer(completionManager_);
// set default key handler
if (useVimMode_)
widget_.getEditor().setKeyboardHandler(KeyboardHandler.vim());
else if (useEmacsKeybindings_)
widget_.getEditor().setKeyboardHandler(KeyboardHandler.emacs());
else
widget_.getEditor().setKeyboardHandler(null);
// add the previewer
widget_.getEditor().addKeyboardHandler(previewer.getKeyboardHandler());
// Listen for command execution
editorEventListeners_.add(AceEditorNative.addEventListener(
widget_.getEditor().getCommandManager(),
"afterExec",
new CommandWithArg<JavaScriptObject>()
{
@Override
public void execute(JavaScriptObject event)
{
events_.fireEvent(new AceAfterCommandExecutedEvent(event));
}
}));
// Listen for keyboard activity
editorEventListeners_.add(AceEditorNative.addEventListener(
widget_.getEditor(),
"keyboardActivity",
new CommandWithArg<JavaScriptObject>()
{
@Override
public void execute(JavaScriptObject event)
{
events_.fireEvent(new AceKeyboardActivityEvent(event));
}
}));
if (useVimMode_)
widget_.getEditor().setMarks(marks);
}
public String getCode()
{
return getSession().getValue();
}
public void setCode(String code, boolean preserveCursorPosition)
{
// Calling setCode("", false) while the editor contains multiple lines of
// content causes bug 2928: Flickering console when typing. Empirically,
// first setting code to a single line of content and then clearing it,
// seems to correct this problem.
if (StringUtil.isNullOrEmpty(code))
doSetCode(" ", preserveCursorPosition);
doSetCode(code, preserveCursorPosition);
}
private void doSetCode(String code, boolean preserveCursorPosition)
{
// Filter out Escape characters that might have snuck in from an old
// bug in 0.95. We can choose to remove this when 0.95 ships, hopefully
// any documents that would be affected by this will be gone by then.
code = code.replaceAll("\u001B", "");
// Normalize newlines -- convert all of '\r', '\r\n', '\n\r' to '\n'.
code = StringUtil.normalizeNewLines(code);
final AceEditorNative ed = widget_.getEditor();
if (preserveCursorPosition)
{
final Position cursorPos;
final int scrollTop, scrollLeft;
cursorPos = ed.getSession().getSelection().getCursor();
scrollTop = ed.getRenderer().getScrollTop();
scrollLeft = ed.getRenderer().getScrollLeft();
// Setting the value directly on the document prevents undo/redo
// stack from being blown away
widget_.getEditor().getSession().getDocument().setValue(code);
ed.getSession().getSelection().moveCursorTo(cursorPos.getRow(),
cursorPos.getColumn(),
false);
ed.getRenderer().scrollToY(scrollTop);
ed.getRenderer().scrollToX(scrollLeft);
Scheduler.get().scheduleDeferred(new ScheduledCommand()
{
@Override
public void execute()
{
ed.getRenderer().scrollToY(scrollTop);
ed.getRenderer().scrollToX(scrollLeft);
}
});
}
else
{
ed.getSession().setValue(code);
ed.getSession().getSelection().moveCursorTo(0, 0, false);
}
}
public int getScrollLeft()
{
return widget_.getEditor().getRenderer().getScrollLeft();
}
public void scrollToX(int x)
{
widget_.getEditor().getRenderer().scrollToX(x);
}
public int getScrollTop()
{
return widget_.getEditor().getRenderer().getScrollTop();
}
public void scrollToY(int y, int animateMs)
{
// cancel any existing scroll animation
if (scrollAnimator_ != null)
scrollAnimator_.complete();
if (animateMs == 0)
widget_.getEditor().getRenderer().scrollToY(y);
else
scrollAnimator_ = new ScrollAnimator(y, animateMs);
}
public void insertCode(String code)
{
insertCode(code, false);
}
public void insertCode(String code, boolean blockMode)
{
widget_.getEditor().insert(StringUtil.normalizeNewLines(code));
}
public String getCode(Position start, Position end)
{
return getSession().getTextRange(Range.fromPoints(start, end));
}
@Override
public InputEditorSelection search(String needle,
boolean backwards,
boolean wrap,
boolean caseSensitive,
boolean wholeWord,
Position start,
Range range,
boolean regexpMode)
{
Search search = Search.create(needle,
backwards,
wrap,
caseSensitive,
wholeWord,
start,
range,
regexpMode);
Range resultRange = search.find(getSession());
if (resultRange != null)
{
return createSelection(resultRange.getStart(), resultRange.getEnd());
}
else
{
return null;
}
}
@Override
public void quickAddNext()
{
if (getNativeSelection().isEmpty())
{
getNativeSelection().selectWord();
return;
}
String needle = getSelectionValue();
Search search = Search.create(
needle,
false,
true,
true,
true,
getCursorPosition(),
null,
false);
Range range = search.find(getSession());
if (range == null)
return;
getNativeSelection().addRange(range, false);
centerSelection();
}
@Override
public void insertCode(InputEditorPosition position, String content)
{
insertCode(selectionToPosition(position), content);
}
public void insertCode(Position position, String content)
{
getSession().insert(position, content);
}
@Override
public String getCode(InputEditorSelection selection)
{
return getCode(((AceInputEditorPosition)selection.getStart()).getValue(),
((AceInputEditorPosition)selection.getEnd()).getValue());
}
@Override
public JsArrayString getLines()
{
return getLines(0, getSession().getLength());
}
@Override
public JsArrayString getLines(int startRow, int endRow)
{
return getSession().getLines(startRow, endRow);
}
public void focus()
{
widget_.getEditor().focus();
}
public boolean isFocused()
{
return widget_.getEditor().isFocused();
}
public void codeCompletion()
{
completionManager_.codeCompletion();
}
public void goToHelp()
{
completionManager_.goToHelp();
}
public void goToDefinition()
{
completionManager_.goToDefinition();
}
class PrintIFrame extends DynamicIFrame
{
public PrintIFrame(String code, double fontSize)
{
code_ = code;
fontSize_ = fontSize;
getElement().getStyle().setPosition(com.google.gwt.dom.client.Style.Position.ABSOLUTE);
getElement().getStyle().setLeft(-5000, Unit.PX);
}
@Override
protected void onFrameLoaded()
{
Document doc = getDocument();
PreElement pre = doc.createPreElement();
pre.setInnerText(code_);
pre.getStyle().setProperty("whiteSpace", "pre-wrap");
pre.getStyle().setFontSize(fontSize_, Unit.PT);
doc.getBody().appendChild(pre);
getWindow().print();
// Bug 1224: ace: print from source causes inability to reconnect
// This was caused by the iframe being removed from the document too
// quickly after the print job was sent. As a result, attempting to
// navigate away from the page at any point afterwards would result
// in the error "Document cannot change while printing or in Print
// Preview". The only thing you could do is close the browser tab.
// By inserting a 5-minute delay hopefully Firefox would be done with
// whatever print related operations are important.
Scheduler.get().scheduleFixedDelay(new RepeatingCommand()
{
public boolean execute()
{
PrintIFrame.this.removeFromParent();
return false;
}
}, 1000 * 60 * 5);
}
private final String code_;
private final double fontSize_;
}
public void print()
{
if (Desktop.isDesktop())
{
// the desktop frame prints the code directly
Desktop.getFrame().printText(StringUtil.notNull(getCode()));
}
else
{
// in server mode, we render the code to an IFrame and then print
// the frame using the browser
PrintIFrame printIFrame = new PrintIFrame(
getCode(),
RStudioGinjector.INSTANCE.getUIPrefs().fontSize().getValue());
RootPanel.get().add(printIFrame);
}
}
public String getText()
{
return getSession().getLine(
getSession().getSelection().getCursor().getRow());
}
public void setText(String string)
{
setCode(string, false);
getSession().getSelection().moveCursorFileEnd();
}
public boolean hasSelection()
{
return !getSession().getSelection().getRange().isEmpty();
}
public final Selection getNativeSelection() {
return widget_.getEditor().getSession().getSelection();
}
public InputEditorSelection getSelection()
{
Range selection = getSession().getSelection().getRange();
return new InputEditorSelection(
new AceInputEditorPosition(getSession(), selection.getStart()),
new AceInputEditorPosition(getSession(), selection.getEnd()));
}
public String getSelectionValue()
{
return getSession().getTextRange(
getSession().getSelection().getRange());
}
public Position getSelectionStart()
{
return getSession().getSelection().getRange().getStart();
}
public Position getSelectionEnd()
{
return getSession().getSelection().getRange().getEnd();
}
@Override
public Range getSelectionRange()
{
return Range.fromPoints(getSelectionStart(), getSelectionEnd());
}
@Override
public void setSelectionRange(Range range)
{
getSession().getSelection().setSelectionRange(range);
}
public void setSelectionRanges(JsArray<Range> ranges)
{
int n = ranges.length();
if (n == 0)
return;
if (vim_.isActive())
vim_.exitVisualMode();
setSelectionRange(ranges.get(0));
for (int i = 1; i < n; i++)
getNativeSelection().addRange(ranges.get(i), false);
}
public int getLength(int row)
{
return getSession().getDocument().getLine(row).length();
}
public int getRowCount()
{
return getSession().getDocument().getLength();
}
@Override
public int getPixelWidth()
{
Element[] content = DomUtils.getElementsByClassName(
widget_.getElement(), "ace_content");
if (content.length < 1)
return widget_.getElement().getOffsetWidth();
else
return content[0].getOffsetWidth();
}
public String getLine(int row)
{
return getSession().getLine(row);
}
@Override
public Position getDocumentEnd()
{
int lastRow = getRowCount() - 1;
return Position.create(lastRow, getLength(lastRow));
}
@Override
public void setInsertMatching(boolean value)
{
widget_.getEditor().setInsertMatching(value);
}
@Override
public void setSurroundSelectionPref(String value)
{
widget_.getEditor().setSurroundSelectionPref(value);
}
@Override
public InputEditorSelection createSelection(Position pos1, Position pos2)
{
return new InputEditorSelection(
new AceInputEditorPosition(getSession(), pos1),
new AceInputEditorPosition(getSession(), pos2));
}
@Override
public Position selectionToPosition(InputEditorPosition pos)
{
// HACK: This cast is gross, InputEditorPosition should just become
// AceInputEditorPosition
return Position.create((Integer) pos.getLine(), pos.getPosition());
}
@Override
public InputEditorPosition createInputEditorPosition(Position pos)
{
return new AceInputEditorPosition(getSession(), pos);
}
@Override
public Iterable<Range> getWords(TokenPredicate tokenPredicate,
CharClassifier charClassifier,
Position start,
Position end)
{
return new WordIterable(getSession(),
tokenPredicate,
charClassifier,
start,
end);
}
@Override
public String getTextForRange(Range range)
{
return getSession().getTextRange(range);
}
@Override
public Anchor createAnchor(Position pos)
{
return Anchor.createAnchor(getSession().getDocument(),
pos.getRow(),
pos.getColumn());
}
private void fixVerticalOffsetBug()
{
widget_.getEditor().getRenderer().fixVerticalOffsetBug();
}
@Override
public String debug_getDocumentDump()
{
return widget_.getEditor().getSession().getDocument().getDocumentDump();
}
@Override
public void debug_setSessionValueDirectly(String s)
{
widget_.getEditor().getSession().setValue(s);
}
public void setSelection(InputEditorSelection selection)
{
AceInputEditorPosition start = (AceInputEditorPosition)selection.getStart();
AceInputEditorPosition end = (AceInputEditorPosition)selection.getEnd();
getSession().getSelection().setSelectionRange(Range.fromPoints(
start.getValue(), end.getValue()));
}
public Rectangle getCursorBounds()
{
Range range = getSession().getSelection().getRange();
return toScreenCoordinates(range);
}
public Rectangle toScreenCoordinates(Range range)
{
Renderer renderer = widget_.getEditor().getRenderer();
ScreenCoordinates start = renderer.textToScreenCoordinates(
range.getStart().getRow(),
range.getStart().getColumn());
ScreenCoordinates end = renderer.textToScreenCoordinates(
range.getEnd().getRow(),
range.getEnd().getColumn());
return new Rectangle(start.getPageX(),
start.getPageY(),
end.getPageX() - start.getPageX(),
renderer.getLineHeight());
}
public Position toDocumentPosition(ScreenCoordinates coordinates)
{
return widget_.getEditor().getRenderer().screenToTextCoordinates(
coordinates.getPageX(),
coordinates.getPageY());
}
public Range toDocumentRange(Rectangle rectangle)
{
Renderer renderer = widget_.getEditor().getRenderer();
return Range.fromPoints(
renderer.screenToTextCoordinates(rectangle.getLeft(), rectangle.getTop()),
renderer.screenToTextCoordinates(rectangle.getRight(), rectangle.getBottom()));
}
@Override
public Rectangle getPositionBounds(Position position)
{
Renderer renderer = widget_.getEditor().getRenderer();
ScreenCoordinates start = renderer.textToScreenCoordinates(
position.getRow(),
position.getColumn());
return new Rectangle(start.getPageX(), start.getPageY(),
(int) Math.round(renderer.getCharacterWidth()),
(int) (renderer.getLineHeight() * 0.8));
}
@Override
public Rectangle getRangeBounds(Range range)
{
range = Range.toOrientedRange(range);
Renderer renderer = widget_.getEditor().getRenderer();
if (!range.isMultiLine())
{
ScreenCoordinates start = documentPositionToScreenCoordinates(range.getStart());
ScreenCoordinates end = documentPositionToScreenCoordinates(range.getEnd());
int width = (end.getPageX() - start.getPageX()) + (int) renderer.getCharacterWidth();
int height = (end.getPageY() - start.getPageY()) + (int) renderer.getLineHeight();
return new Rectangle(start.getPageX(), start.getPageY(), width, height);
}
Position startPos = range.getStart();
Position endPos = range.getEnd();
int startRow = startPos.getRow();
int endRow = endPos.getRow();
// figure out top left coordinates
ScreenCoordinates topLeft = documentPositionToScreenCoordinates(Position.create(startRow, 0));
// figure out bottom right coordinates (need to walk rows to figure out longest line)
ScreenCoordinates bottomRight = documentPositionToScreenCoordinates(Position.create(endPos));
for (int row = startRow; row <= endRow; row++)
{
Position rowEndPos = Position.create(row, getLength(row));
ScreenCoordinates coords = documentPositionToScreenCoordinates(rowEndPos);
if (coords.getPageX() > bottomRight.getPageX())
bottomRight = ScreenCoordinates.create(coords.getPageX(), bottomRight.getPageY());
}
// construct resulting range
int width = (bottomRight.getPageX() - topLeft.getPageX()) + (int) renderer.getCharacterWidth();
int height = (bottomRight.getPageY() - topLeft.getPageY()) + (int) renderer.getLineHeight();
return new Rectangle(topLeft.getPageX(), topLeft.getPageY(), width, height);
}
@Override
public Rectangle getPositionBounds(InputEditorPosition position)
{
Position pos = ((AceInputEditorPosition) position).getValue();
return getPositionBounds(pos);
}
public Rectangle getBounds()
{
return new Rectangle(
widget_.getAbsoluteLeft(),
widget_.getAbsoluteTop(),
widget_.getOffsetWidth(),
widget_.getOffsetHeight());
}
public void setFocus(boolean focused)
{
if (focused)
widget_.getEditor().focus();
else
widget_.getEditor().blur();
}
public void replaceRange(Range range, String text) {
getSession().replace(range, text);
}
public String replaceSelection(String value, boolean collapseSelection)
{
Selection selection = getSession().getSelection();
String oldValue = getSession().getTextRange(selection.getRange());
replaceSelection(value);
if (collapseSelection)
{
collapseSelection(false);
}
return oldValue;
}
public boolean isSelectionCollapsed()
{
return getSession().getSelection().isEmpty();
}
public boolean isCursorAtEnd()
{
int lastRow = getRowCount() - 1;
Position cursorPos = getCursorPosition();
return cursorPos.compareTo(Position.create(lastRow,
getLength(lastRow))) == 0;
}
public void clear()
{
setCode("", false);
}
public boolean inMultiSelectMode()
{
return widget_.getEditor().inMultiSelectMode();
}
public void exitMultiSelectMode()
{
widget_.getEditor().exitMultiSelectMode();
}
public void clearSelection()
{
widget_.getEditor().clearSelection();
}
public void collapseSelection(boolean collapseToStart)
{
Selection selection = getSession().getSelection();
Range rng = selection.getRange();
Position pos = collapseToStart ? rng.getStart() : rng.getEnd();
selection.setSelectionRange(Range.fromPoints(pos, pos));
}
public InputEditorSelection getStart()
{
return new InputEditorSelection(
new AceInputEditorPosition(getSession(), Position.create(0, 0)));
}
public InputEditorSelection getEnd()
{
EditSession session = getSession();
int rows = session.getLength();
Position end = Position.create(rows, session.getLine(rows).length());
return new InputEditorSelection(new AceInputEditorPosition(session, end));
}
public String getCurrentLine()
{
int row = getSession().getSelection().getRange().getStart().getRow();
return getSession().getLine(row);
}
public char getCharacterAtCursor()
{
Position cursorPos = getCursorPosition();
int column = cursorPos.getColumn();
String line = getLine(cursorPos.getRow());
if (column == line.length())
return '\0';
return line.charAt(column);
}
public char getCharacterBeforeCursor()
{
Position cursorPos = getCursorPosition();
int column = cursorPos.getColumn();
if (column == 0)
return '\0';
String line = getLine(cursorPos.getRow());
return line.charAt(column - 1);
}
public String getCurrentLineUpToCursor()
{
return getCurrentLine().substring(0, getCursorPosition().getColumn());
}
public int getCurrentLineNum()
{
Position pos = getCursorPosition();
return getSession().documentToScreenRow(pos);
}
public int getCurrentLineCount()
{
return getSession().getScreenLength();
}
@Override
public String getLanguageMode(Position position)
{
return getSession().getMode().getLanguageMode(position);
}
@Override
public String getModeId()
{
return getSession().getMode().getId();
}
public void replaceCode(String code)
{
int endRow, endCol;
endRow = getSession().getLength() - 1;
if (endRow < 0)
{
endRow = 0;
endCol = 0;
}
else
{
endCol = getSession().getLine(endRow).length();
}
Range range = Range.fromPoints(Position.create(0, 0),
Position.create(endRow, endCol));
getSession().replace(range, code);
}
public void replaceSelection(String code)
{
code = StringUtil.normalizeNewLines(code);
Range selRange = getSession().getSelection().getRange();
Position position = getSession().replace(selRange, code);
Range range = Range.fromPoints(selRange.getStart(), position);
getSession().getSelection().setSelectionRange(range);
if (isEmacsModeOn()) clearEmacsMark();
}
public boolean moveSelectionToNextLine(boolean skipBlankLines)
{
int curRow = getSession().getSelection().getCursor().getRow();
while (++curRow < getSession().getLength())
{
String line = getSession().getLine(curRow);
Pattern pattern = Pattern.create("[^\\s]");
Match match = pattern.match(line, 0);
if (skipBlankLines && match == null)
continue;
int col = (match != null) ? match.getIndex() : 0;
getSession().getSelection().moveCursorTo(curRow, col, false);
getSession().unfold(curRow, true);
scrollCursorIntoViewIfNecessary();
return true;
}
return false;
}
@Override
public boolean moveSelectionToBlankLine()
{
int curRow = getSession().getSelection().getCursor().getRow();
// if the current row is the last row then insert a new row
if (curRow == (getSession().getLength() - 1))
{
int rowLen = getSession().getLine(curRow).length();
getSession().getSelection().moveCursorTo(curRow, rowLen, false);
insertCode("\n");
}
while (curRow < getSession().getLength())
{
String line = getSession().getLine(curRow).trim();
if (line.length() == 0)
{
getSession().getSelection().moveCursorTo(curRow, 0, false);
getSession().unfold(curRow, true);
return true;
}
curRow++;
}
return false;
}
@Override
public void expandSelection()
{
widget_.getEditor().expandSelection();
}
@Override
public void shrinkSelection()
{
widget_.getEditor().shrinkSelection();
}
@Override
public void expandRaggedSelection()
{
if (!inMultiSelectMode())
return;
// TODO: It looks like we need to use an alternative API when
// using Vim mode.
if (isVimModeOn())
return;
boolean hasSelection = hasSelection();
Range[] ranges =
widget_.getEditor().getSession().getSelection().getAllRanges();
// Get the maximum columns for the current selection.
int colMin = Integer.MAX_VALUE;
int colMax = 0;
for (Range range : ranges)
{
colMin = Math.min(range.getStart().getColumn(), colMin);
colMax = Math.max(range.getEnd().getColumn(), colMax);
}
// For each range:
//
// 1. Set the left side of the selection to the minimum,
// 2. Set the right side of the selection to the maximum,
// moving the cursor and inserting whitespace as necessary.
for (Range range : ranges)
{
range.getStart().setColumn(colMin);
range.getEnd().setColumn(colMax);
String line = getLine(range.getStart().getRow());
if (line.length() < colMax)
{
insertCode(
Position.create(range.getStart().getRow(), line.length()),
StringUtil.repeat(" ", colMax - line.length()));
}
}
clearSelection();
Selection selection = getNativeSelection();
for (Range range : ranges)
{
if (hasSelection)
selection.addRange(range, true);
else
{
Range newRange = Range.create(
range.getEnd().getRow(),
range.getEnd().getColumn(),
range.getEnd().getRow(),
range.getEnd().getColumn());
selection.addRange(newRange, true);
}
}
}
@Override
public void clearSelectionHistory()
{
widget_.getEditor().clearSelectionHistory();
}
@Override
public void reindent()
{
boolean emptySelection = getSelection().isEmpty();
getSession().reindent(getSession().getSelection().getRange());
if (emptySelection)
moveSelectionToNextLine(false);
}
@Override
public void reindent(Range range)
{
getSession().reindent(range);
}
@Override
public void toggleCommentLines()
{
widget_.getEditor().toggleCommentLines();
}
public ChangeTracker getChangeTracker()
{
return new AceEditorChangeTracker();
}
// Because anchored selections create Ace event listeners, they
// must be explicitly detached (otherwise they will listen for
// edit events into perpetuity). The easiest way to facilitate this
// is to have anchored selection tied to the lifetime of a particular
// 'host' widget; this way, on detach, we can ensure that the associated
// anchors are detached as well.
public AnchoredSelection createAnchoredSelection(Widget hostWidget,
Position startPos,
Position endPos)
{
Anchor start = Anchor.createAnchor(getSession().getDocument(),
startPos.getRow(),
startPos.getColumn());
Anchor end = Anchor.createAnchor(getSession().getDocument(),
endPos.getRow(),
endPos.getColumn());
final AnchoredSelection selection = new AnchoredSelectionImpl(start, end);
if (hostWidget != null)
{
hostWidget.addAttachHandler(new AttachEvent.Handler()
{
@Override
public void onAttachOrDetach(AttachEvent event)
{
if (!event.isAttached() && selection != null)
selection.detach();
}
});
}
return selection;
}
public AnchoredSelection createAnchoredSelection(Position start, Position end)
{
return createAnchoredSelection(null, start, end);
}
public void fitSelectionToLines(boolean expand)
{
Range range = getSession().getSelection().getRange();
Position start = range.getStart();
Position newStart = start;
if (start.getColumn() > 0)
{
if (expand)
{
newStart = Position.create(start.getRow(), 0);
}
else
{
String firstLine = getSession().getLine(start.getRow());
if (firstLine.substring(0, start.getColumn()).trim().length() == 0)
newStart = Position.create(start.getRow(), 0);
}
}
Position end = range.getEnd();
Position newEnd = end;
if (expand)
{
int endRow = end.getRow();
if (endRow == newStart.getRow() || end.getColumn() > 0)
{
// If selection ends at the start of a line, keep the selection
// there--unless that means less than one line will be selected
// in total.
newEnd = Position.create(
endRow, getSession().getLine(endRow).length());
}
}
else
{
while (newEnd.getRow() != newStart.getRow())
{
String line = getSession().getLine(newEnd.getRow());
if (line.substring(0, newEnd.getColumn()).trim().length() != 0)
break;
int prevRow = newEnd.getRow() - 1;
int len = getSession().getLine(prevRow).length();
newEnd = Position.create(prevRow, len);
}
}
getSession().getSelection().setSelectionRange(
Range.fromPoints(newStart, newEnd));
}
public int getSelectionOffset(boolean start)
{
Range range = getSession().getSelection().getRange();
if (start)
return range.getStart().getColumn();
else
return range.getEnd().getColumn();
}
public void onActivate()
{
Scheduler.get().scheduleFinally(new RepeatingCommand()
{
public boolean execute()
{
widget_.onResize();
widget_.onActivate();
return false;
}
});
}
public void onVisibilityChanged(boolean visible)
{
if (visible)
widget_.getEditor().getRenderer().updateFontSize();
}
public void onResize()
{
widget_.onResize();
}
public void setHighlightSelectedLine(boolean on)
{
widget_.getEditor().setHighlightActiveLine(on);
}
public void setHighlightSelectedWord(boolean on)
{
widget_.getEditor().setHighlightSelectedWord(on);
}
public void setShowLineNumbers(boolean on)
{
widget_.getEditor().getRenderer().setShowGutter(on);
}
public boolean getUseSoftTabs()
{
return getSession().getUseSoftTabs();
}
public void setUseSoftTabs(boolean on)
{
getSession().setUseSoftTabs(on);
}
public void setScrollPastEndOfDocument(boolean enable)
{
widget_.getEditor().getRenderer().setScrollPastEnd(enable);
}
public void setHighlightRFunctionCalls(boolean highlight)
{
_setHighlightRFunctionCallsImpl(highlight);
widget_.getEditor().retokenizeDocument();
}
public void setScrollLeft(int x)
{
getSession().setScrollLeft(x);
}
public void setScrollTop(int y)
{
getSession().setScrollTop(y);
}
public void scrollTo(int x, int y)
{
getSession().setScrollLeft(x);
getSession().setScrollTop(y);
}
private native final void _setHighlightRFunctionCallsImpl(boolean highlight)
/*-{
var Mode = $wnd.require("mode/r_highlight_rules");
Mode.setHighlightRFunctionCalls(highlight);
}-*/;
public void enableSearchHighlight()
{
widget_.getEditor().enableSearchHighlight();
}
public void disableSearchHighlight()
{
widget_.getEditor().disableSearchHighlight();
}
/**
* Warning: This will be overridden whenever the file type is set
*/
public void setUseWrapMode(boolean useWrapMode)
{
getSession().setUseWrapMode(useWrapMode);
}
public void setTabSize(int tabSize)
{
getSession().setTabSize(tabSize);
}
public void autoDetectIndentation(boolean on)
{
if (!on)
return;
JsArrayString lines = getLines();
if (lines.length() < 5)
return;
int indentSize = StringUtil.detectIndent(lines);
if (indentSize > 0)
setTabSize(indentSize);
}
public void setShowInvisibles(boolean show)
{
widget_.getEditor().getRenderer().setShowInvisibles(show);
}
public void setShowIndentGuides(boolean show)
{
widget_.getEditor().getRenderer().setShowIndentGuides(show);
}
public void setBlinkingCursor(boolean blinking)
{
String style = blinking ? "ace" : "wide";
widget_.getEditor().setCursorStyle(style);
}
public void setShowPrintMargin(boolean on)
{
widget_.getEditor().getRenderer().setShowPrintMargin(on);
}
@Override
public void setUseEmacsKeybindings(boolean use)
{
if (widget_.getEditor().getReadOnly())
return;
useEmacsKeybindings_ = use;
updateKeyboardHandlers();
}
@Override
public boolean isEmacsModeOn()
{
return useEmacsKeybindings_;
}
@Override
public void clearEmacsMark()
{
widget_.getEditor().clearEmacsMark();
}
@Override
public void setUseVimMode(boolean use)
{
// no-op if the editor is read-only (since vim mode doesn't
// work for read-only ace instances)
if (widget_.getEditor().getReadOnly())
return;
useVimMode_ = use;
updateKeyboardHandlers();
}
@Override
public boolean isVimModeOn()
{
return useVimMode_;
}
@Override
public boolean isVimInInsertMode()
{
return useVimMode_ && widget_.getEditor().isVimInInsertMode();
}
public void setPadding(int padding)
{
widget_.getEditor().getRenderer().setPadding(padding);
}
public void setPrintMarginColumn(int column)
{
widget_.getEditor().getRenderer().setPrintMarginColumn(column);
syncWrapLimit();
}
@Override
public JsArray<AceFold> getFolds()
{
return getSession().getAllFolds();
}
@Override
public String getFoldState(int row)
{
AceFold fold = getSession().getFoldAt(row, 0);
if (fold == null)
return null;
Position foldPos = fold.getStart();
return getSession().getState(foldPos.getRow());
}
@Override
public void addFold(Range range)
{
getSession().addFold("...", range);
}
@Override
public void addFoldFromRow(int row)
{
FoldingRules foldingRules = getSession().getMode().getFoldingRules();
if (foldingRules == null)
return;
Range range = foldingRules.getFoldWidgetRange(getSession(),
"markbegin",
row);
if (range != null)
addFold(range);
}
@Override
public void unfold(AceFold fold)
{
getSession().unfold(Range.fromPoints(fold.getStart(), fold.getEnd()),
false);
}
@Override
public void unfold(int row)
{
getSession().unfold(row, false);
}
@Override
public void unfold(Range range)
{
getSession().unfold(range, false);
}
public void setReadOnly(boolean readOnly)
{
widget_.getEditor().setReadOnly(readOnly);
}
public HandlerRegistration addCursorChangedHandler(final CursorChangedHandler handler)
{
return widget_.addCursorChangedHandler(handler);
}
public HandlerRegistration addSaveCompletedHandler(SaveFileHandler handler)
{
return handlers_.addHandler(SaveFileEvent.TYPE, handler);
}
public HandlerRegistration addAttachHandler(AttachEvent.Handler handler)
{
return widget_.addAttachHandler(handler);
}
public HandlerRegistration addEditorFocusHandler(FocusHandler handler)
{
return widget_.addFocusHandler(handler);
}
public Scope getCurrentScope()
{
return getSession().getMode().getCodeModel().getCurrentScope(
getCursorPosition());
}
public Scope getScopeAtPosition(Position position)
{
return getSession().getMode().getCodeModel().getCurrentScope(position);
}
@Override
public String getNextLineIndent()
{
EditSession session = getSession();
Position cursorPosition = getCursorPosition();
int row = cursorPosition.getRow();
String state = getSession().getState(row);
String line = getCurrentLine().substring(
0, cursorPosition.getColumn());
String tab = session.getTabString();
int tabSize = session.getTabSize();
return session.getMode().getNextLineIndent(
state,
line,
tab,
tabSize,
row);
}
public Scope getCurrentChunk()
{
return getCurrentChunk(getCursorPosition());
}
@Override
public Scope getCurrentChunk(Position position)
{
return getSession().getMode().getCodeModel().getCurrentChunk(position);
}
@Override
public ScopeFunction getCurrentFunction(boolean allowAnonymous)
{
return getFunctionAtPosition(getCursorPosition(), allowAnonymous);
}
@Override
public ScopeFunction getFunctionAtPosition(Position position,
boolean allowAnonymous)
{
return getSession().getMode().getCodeModel().getCurrentFunction(
position, allowAnonymous);
}
@Override
public Scope getCurrentSection()
{
return getSectionAtPosition(getCursorPosition());
}
@Override
public Scope getSectionAtPosition(Position position)
{
return getSession().getMode().getCodeModel().getCurrentSection(position);
}
public Position getCursorPosition()
{
return getSession().getSelection().getCursor();
}
public Position getCursorPositionScreen()
{
return widget_.getEditor().getCursorPositionScreen();
}
public void setCursorPosition(Position position)
{
getSession().getSelection().setSelectionRange(
Range.fromPoints(position, position));
}
public void goToLineStart()
{
widget_.getEditor().getCommandManager().exec("gotolinestart", widget_.getEditor());
}
public void goToLineEnd()
{
widget_.getEditor().getCommandManager().exec("gotolineend", widget_.getEditor());
}
@Override
public void moveCursorNearTop(int rowOffset)
{
int screenRow = getSession().documentToScreenRow(getCursorPosition());
widget_.getEditor().scrollToRow(Math.max(0, screenRow - rowOffset));
}
@Override
public void moveCursorForward()
{
moveCursorForward(1);
}
@Override
public void moveCursorForward(int characters)
{
widget_.getEditor().moveCursorRight(characters);
}
@Override
public void moveCursorBackward()
{
moveCursorBackward(1);
}
@Override
public void moveCursorBackward(int characters)
{
widget_.getEditor().moveCursorLeft(characters);
}
@Override
public void moveCursorNearTop()
{
moveCursorNearTop(7);
}
@Override
public void ensureCursorVisible()
{
if (!widget_.getEditor().isRowFullyVisible(getCursorPosition().getRow()))
moveCursorNearTop();
}
@Override
public void ensureRowVisible(int row)
{
if (!widget_.getEditor().isRowFullyVisible(row))
setCursorPosition(Position.create(row, 0));
}
@Override
public void scrollCursorIntoViewIfNecessary(int rowsAround)
{
Position cursorPos = getCursorPosition();
int cursorRow = cursorPos.getRow();
if (cursorRow >= widget_.getEditor().getLastVisibleRow() - rowsAround)
{
Position alignPos = Position.create(cursorRow + rowsAround, 0);
widget_.getEditor().getRenderer().alignCursor(alignPos, 1);
}
else if (cursorRow <= widget_.getEditor().getFirstVisibleRow() + rowsAround)
{
Position alignPos = Position.create(cursorRow - rowsAround, 0);
widget_.getEditor().getRenderer().alignCursor(alignPos, 0);
}
}
@Override
public void scrollCursorIntoViewIfNecessary()
{
scrollCursorIntoViewIfNecessary(0);
}
@Override
public boolean isCursorInSingleLineString()
{
return StringUtil.isEndOfLineInRStringState(getCurrentLineUpToCursor());
}
public void gotoPageUp()
{
widget_.getEditor().gotoPageUp();
}
public void gotoPageDown()
{
widget_.getEditor().gotoPageDown();
}
public void scrollToBottom()
{
SourcePosition pos = SourcePosition.create(getCurrentLineCount() - 1, 0);
navigate(pos, false);
}
public void revealRange(Range range, boolean animate)
{
widget_.getEditor().revealRange(range, animate);
}
public CodeModel getCodeModel()
{
return getSession().getMode().getCodeModel();
}
public boolean hasCodeModel()
{
return getSession().getMode().hasCodeModel();
}
public boolean hasScopeTree()
{
return hasCodeModel() && getCodeModel().hasScopes();
}
public void buildScopeTree()
{
// Builds the scope tree as a side effect
if (hasScopeTree())
getScopeTree();
}
public int buildScopeTreeUpToRow(int row)
{
if (!hasScopeTree())
return 0;
return getSession().getMode().getRCodeModel().buildScopeTreeUpToRow(row);
}
public JsArray<Scope> getScopeTree()
{
return getSession().getMode().getCodeModel().getScopeTree();
}
@Override
public InsertChunkInfo getInsertChunkInfo()
{
return getSession().getMode().getInsertChunkInfo();
}
@Override
public void foldAll()
{
getSession().foldAll();
}
@Override
public void unfoldAll()
{
getSession().unfoldAll();
}
@Override
public void toggleFold()
{
getSession().toggleFold();
}
@Override
public void setFoldStyle(String style)
{
getSession().setFoldStyle(style);
}
@Override
public JsMap<Position> getMarks()
{
return widget_.getEditor().getMarks();
}
@Override
public void setMarks(JsMap<Position> marks)
{
widget_.getEditor().setMarks(marks);
}
@Override
public void jumpToMatching()
{
widget_.getEditor().jumpToMatching(false, false);
}
@Override
public void selectToMatching()
{
widget_.getEditor().jumpToMatching(true, false);
}
@Override
public void expandToMatching()
{
widget_.getEditor().jumpToMatching(true, true);
}
@Override
public void addCursorAbove()
{
widget_.getEditor().execCommand("addCursorAbove");
}
@Override
public void addCursorBelow()
{
widget_.getEditor().execCommand("addCursorBelow");
}
@Override
public void splitIntoLines()
{
widget_.getEditor().splitIntoLines();
}
@Override
public int getFirstFullyVisibleRow()
{
return widget_.getEditor().getRenderer().getFirstFullyVisibleRow();
}
@Override
public SourcePosition findFunctionPositionFromCursor(String functionName)
{
Scope func =
getSession().getMode().getCodeModel().findFunctionDefinitionFromUsage(
getCursorPosition(),
functionName);
if (func != null)
{
Position position = func.getPreamble();
return SourcePosition.create(position.getRow(), position.getColumn());
}
else
{
return null;
}
}
public JsArray<ScopeFunction> getAllFunctionScopes()
{
CodeModel codeModel = widget_.getEditor().getSession().getMode().getRCodeModel();
if (codeModel == null)
return null;
return codeModel.getAllFunctionScopes();
}
@Override
public void recordCurrentNavigationPosition()
{
fireRecordNavigationPosition(getCursorPosition());
}
@Override
public void navigateToPosition(SourcePosition position,
boolean recordCurrent)
{
navigateToPosition(position, recordCurrent, false);
}
@Override
public void navigateToPosition(SourcePosition position,
boolean recordCurrent,
boolean highlightLine)
{
if (recordCurrent)
recordCurrentNavigationPosition();
navigate(position, true, highlightLine);
}
@Override
public void restorePosition(SourcePosition position)
{
navigate(position, false);
}
@Override
public boolean isAtSourceRow(SourcePosition position)
{
Position currPos = getCursorPosition();
return currPos.getRow() == position.getRow();
}
@Override
public void highlightDebugLocation(SourcePosition startPosition,
SourcePosition endPosition,
boolean executing)
{
int firstRow = widget_.getEditor().getFirstVisibleRow();
int lastRow = widget_.getEditor().getLastVisibleRow();
// if the expression is large, let's just try to land in the middle
int debugRow = (int) Math.floor(startPosition.getRow() + (
endPosition.getRow() - startPosition.getRow())/2);
// if the row at which the debugging occurs is inside a fold, unfold it
getSession().unfold(debugRow, true);
// if the line to be debugged is past or near the edges of the screen,
// scroll it into view. allow some lines of context.
if (debugRow <= (firstRow + DEBUG_CONTEXT_LINES) ||
debugRow >= (lastRow - DEBUG_CONTEXT_LINES))
{
widget_.getEditor().scrollToLine(debugRow, true);
}
applyDebugLineHighlight(
startPosition.asPosition(),
endPosition.asPosition(),
executing);
}
@Override
public void endDebugHighlighting()
{
clearDebugLineHighlight();
}
@Override
public HandlerRegistration addBreakpointSetHandler(
BreakpointSetEvent.Handler handler)
{
return widget_.addBreakpointSetHandler(handler);
}
@Override
public HandlerRegistration addBreakpointMoveHandler(
BreakpointMoveEvent.Handler handler)
{
return widget_.addBreakpointMoveHandler(handler);
}
@Override
public void addOrUpdateBreakpoint(Breakpoint breakpoint)
{
widget_.addOrUpdateBreakpoint(breakpoint);
}
@Override
public void removeBreakpoint(Breakpoint breakpoint)
{
widget_.removeBreakpoint(breakpoint);
}
@Override
public void toggleBreakpointAtCursor()
{
widget_.toggleBreakpointAtCursor();
}
@Override
public void removeAllBreakpoints()
{
widget_.removeAllBreakpoints();
}
@Override
public boolean hasBreakpoints()
{
return widget_.hasBreakpoints();
}
public void setChunkLineExecState(int start, int end, int state)
{
widget_.setChunkLineExecState(start, end, state);
}
private void navigate(SourcePosition srcPosition, boolean addToHistory)
{
navigate(srcPosition, addToHistory, false);
}
private void navigate(SourcePosition srcPosition,
boolean addToHistory,
boolean highlightLine)
{
// get existing cursor position
Position previousCursorPos = getCursorPosition();
// set cursor to function line
Position position = Position.create(srcPosition.getRow(),
srcPosition.getColumn());
setCursorPosition(position);
// skip whitespace if necessary
if (srcPosition.getColumn() == 0)
{
int curRow = getSession().getSelection().getCursor().getRow();
String line = getSession().getLine(curRow);
int funStart = line.indexOf(line.trim());
position = Position.create(curRow, funStart);
setCursorPosition(position);
}
// scroll as necessary
if (srcPosition.getScrollPosition() != -1)
scrollToY(srcPosition.getScrollPosition(), 0);
else if (position.getRow() != previousCursorPos.getRow())
moveCursorNearTop();
else
ensureCursorVisible();
// set focus
focus();
if (highlightLine)
applyLineHighlight(position.getRow());
// add to navigation history if requested and our current mode
// supports history navigation
if (addToHistory)
fireRecordNavigationPosition(position);
}
private void fireRecordNavigationPosition(Position pos)
{
SourcePosition srcPos = SourcePosition.create(pos.getRow(),
pos.getColumn());
fireEvent(new RecordNavigationPositionEvent(srcPos));
}
@Override
public HandlerRegistration addRecordNavigationPositionHandler(
RecordNavigationPositionHandler handler)
{
return handlers_.addHandler(RecordNavigationPositionEvent.TYPE, handler);
}
@Override
public HandlerRegistration addCommandClickHandler(
CommandClickEvent.Handler handler)
{
return handlers_.addHandler(CommandClickEvent.TYPE, handler);
}
@Override
public HandlerRegistration addFindRequestedHandler(
FindRequestedEvent.Handler handler)
{
return handlers_.addHandler(FindRequestedEvent.TYPE, handler);
}
public void setFontSize(double size)
{
// No change needed--the AceEditorWidget uses the "normalSize" style
// However, we do need to resize the gutter
widget_.getEditor().getRenderer().updateFontSize();
widget_.forceResize();
widget_.getLineWidgetManager().syncLineWidgetHeights();
}
public HandlerRegistration addValueChangeHandler(
ValueChangeHandler<Void> handler)
{
return handlers_.addHandler(ValueChangeEvent.getType(), handler);
}
public HandlerRegistration addFoldChangeHandler(
FoldChangeEvent.Handler handler)
{
return handlers_.addHandler(FoldChangeEvent.TYPE, handler);
}
public HandlerRegistration addLineWidgetsChangedHandler(
LineWidgetsChangedEvent.Handler handler)
{
return handlers_.addHandler(LineWidgetsChangedEvent.TYPE, handler);
}
public boolean isScopeTreeReady(int row)
{
return backgroundTokenizer_.isReady(row);
}
public HandlerRegistration addScopeTreeReadyHandler(ScopeTreeReadyEvent.Handler handler)
{
return handlers_.addHandler(ScopeTreeReadyEvent.TYPE, handler);
}
public HandlerRegistration addRenderFinishedHandler(RenderFinishedEvent.Handler handler)
{
return widget_.addHandler(handler, RenderFinishedEvent.TYPE);
}
public HandlerRegistration addDocumentChangedHandler(DocumentChangedEvent.Handler handler)
{
return widget_.addHandler(handler, DocumentChangedEvent.TYPE);
}
public HandlerRegistration addCapturingKeyDownHandler(KeyDownHandler handler)
{
return widget_.addCapturingKeyDownHandler(handler);
}
public HandlerRegistration addCapturingKeyPressHandler(KeyPressHandler handler)
{
return widget_.addCapturingKeyPressHandler(handler);
}
public HandlerRegistration addCapturingKeyUpHandler(KeyUpHandler handler)
{
return widget_.addCapturingKeyUpHandler(handler);
}
public HandlerRegistration addUndoRedoHandler(UndoRedoHandler handler)
{
return widget_.addUndoRedoHandler(handler);
}
public HandlerRegistration addPasteHandler(PasteEvent.Handler handler)
{
return widget_.addPasteHandler(handler);
}
public HandlerRegistration addAceClickHandler(Handler handler)
{
return widget_.addAceClickHandler(handler);
}
public HandlerRegistration addEditorModeChangedHandler(
EditorModeChangedEvent.Handler handler)
{
return handlers_.addHandler(EditorModeChangedEvent.TYPE, handler);
}
public JavaScriptObject getCleanStateToken()
{
return getSession().getUndoManager().peek();
}
public boolean checkCleanStateToken(JavaScriptObject token)
{
JavaScriptObject other = getSession().getUndoManager().peek();
if (token == null ^ other == null)
return false;
return token == null || other.equals(token);
}
public void fireEvent(GwtEvent<?> event)
{
handlers_.fireEvent(event);
}
public Widget asWidget()
{
return widget_;
}
public EditSession getSession()
{
return widget_.getEditor().getSession();
}
public HandlerRegistration addBlurHandler(BlurHandler handler)
{
return widget_.addBlurHandler(handler);
}
public HandlerRegistration addMouseDownHandler(MouseDownHandler handler)
{
return widget_.addMouseDownHandler(handler);
}
public HandlerRegistration addMouseMoveHandler(MouseMoveHandler handler)
{
return widget_.addMouseMoveHandler(handler);
}
public HandlerRegistration addMouseUpHandler(MouseUpHandler handler)
{
return widget_.addMouseUpHandler(handler);
}
public HandlerRegistration addClickHandler(ClickHandler handler)
{
return widget_.addClickHandler(handler);
}
public HandlerRegistration addFocusHandler(FocusHandler handler)
{
return widget_.addFocusHandler(handler);
}
public AceEditorWidget getWidget()
{
return widget_;
}
public HandlerRegistration addKeyDownHandler(KeyDownHandler handler)
{
return widget_.addKeyDownHandler(handler);
}
public HandlerRegistration addKeyPressHandler(KeyPressHandler handler)
{
return widget_.addKeyPressHandler(handler);
}
public HandlerRegistration addKeyUpHandler(KeyUpHandler handler)
{
return widget_.addKeyUpHandler(handler);
}
public HandlerRegistration addSelectionChangedHandler(AceSelectionChangedEvent.Handler handler)
{
return widget_.addSelectionChangedHandler(handler);
}
public void autoHeight()
{
widget_.autoHeight();
}
public void forceCursorChange()
{
widget_.forceCursorChange();
}
public void scrollToCursor(ScrollPanel scrollPanel,
int paddingVert,
int paddingHoriz)
{
DomUtils.ensureVisibleVert(
scrollPanel.getElement(),
widget_.getEditor().getRenderer().getCursorElement(),
paddingVert);
DomUtils.ensureVisibleHoriz(
scrollPanel.getElement(),
widget_.getEditor().getRenderer().getCursorElement(),
paddingHoriz, paddingHoriz,
false);
}
public void scrollToLine(int row, boolean center)
{
widget_.getEditor().scrollToLine(row, center);
}
public void centerSelection()
{
widget_.getEditor().centerSelection();
}
public void alignCursor(Position position, double ratio)
{
widget_.getEditor().getRenderer().alignCursor(position, ratio);
}
public void forceImmediateRender()
{
widget_.getEditor().getRenderer().forceImmediateRender();
}
public void setNewLineMode(NewLineMode mode)
{
getSession().setNewLineMode(mode.getType());
}
public boolean isPasswordMode()
{
return passwordMode_;
}
public void setPasswordMode(boolean passwordMode)
{
passwordMode_ = passwordMode;
widget_.getEditor().getRenderer().setPasswordMode(passwordMode);
}
public void setDisableOverwrite(boolean disableOverwrite)
{
getSession().setDisableOverwrite(disableOverwrite);
}
private Integer createLineHighlightMarker(int line, String style)
{
return createRangeHighlightMarker(Position.create(line, 0),
Position.create(line+1, 0),
style);
}
private Integer createRangeHighlightMarker(
Position start,
Position end,
String style)
{
Range range = Range.fromPoints(start, end);
return getSession().addMarker(range, style, "text", false);
}
private void applyLineHighlight(int line)
{
clearLineHighlight();
if (!widget_.getEditor().getHighlightActiveLine())
{
lineHighlightMarkerId_ = createLineHighlightMarker(line,
"ace_find_line");
}
}
private void clearLineHighlight()
{
if (lineHighlightMarkerId_ != null)
{
getSession().removeMarker(lineHighlightMarkerId_);
lineHighlightMarkerId_ = null;
}
}
private void applyDebugLineHighlight(
Position startPos,
Position endPos,
boolean executing)
{
clearDebugLineHighlight();
lineDebugMarkerId_ = createRangeHighlightMarker(
startPos, endPos,
"ace_active_debug_line");
if (executing)
{
executionLine_ = startPos.getRow();
widget_.getEditor().getRenderer().addGutterDecoration(
executionLine_,
"ace_executing-line");
}
}
private void clearDebugLineHighlight()
{
if (lineDebugMarkerId_ != null)
{
getSession().removeMarker(lineDebugMarkerId_);
lineDebugMarkerId_ = null;
}
if (executionLine_ != null)
{
widget_.getEditor().getRenderer().removeGutterDecoration(
executionLine_,
"ace_executing-line");
executionLine_ = null;
}
}
public void setPopupVisible(boolean visible)
{
popupVisible_ = visible;
}
public boolean isPopupVisible()
{
return popupVisible_;
}
public void selectAll(String needle)
{
widget_.getEditor().findAll(needle);
}
public void selectAll(String needle, Range range, boolean wholeWord, boolean caseSensitive)
{
widget_.getEditor().findAll(needle, range, wholeWord, caseSensitive);
}
public void moveCursorLeft()
{
moveCursorLeft(1);
}
public void moveCursorLeft(int times)
{
widget_.getEditor().moveCursorLeft(times);
}
public void moveCursorRight()
{
moveCursorRight(1);
}
public void moveCursorRight(int times)
{
widget_.getEditor().moveCursorRight(times);
}
public void expandSelectionLeft(int times)
{
widget_.getEditor().expandSelectionLeft(times);
}
public void expandSelectionRight(int times)
{
widget_.getEditor().expandSelectionRight(times);
}
public int getTabSize()
{
return widget_.getEditor().getSession().getTabSize();
}
// TODO: Enable similar logic for C++ mode?
public int getStartOfCurrentStatement()
{
if (!DocumentMode.isSelectionInRMode(this))
return -1;
TokenCursor cursor =
getSession().getMode().getCodeModel().getTokenCursor();
if (!cursor.moveToPosition(getCursorPosition()))
return -1;
if (!cursor.moveToStartOfCurrentStatement())
return -1;
return cursor.getRow();
}
// TODO: Enable similar logic for C++ mode?
public int getEndOfCurrentStatement()
{
if (!DocumentMode.isSelectionInRMode(this))
return -1;
TokenCursor cursor =
getSession().getMode().getCodeModel().getTokenCursor();
if (!cursor.moveToPosition(getCursorPosition()))
return -1;
if (!cursor.moveToEndOfCurrentStatement())
return -1;
return cursor.getRow();
}
private boolean rowEndsInBinaryOp(int row)
{
// move to the last interesting token on this line
JsArray<Token> tokens = getSession().getTokens(row);
for (int i = tokens.length() - 1; i >= 0; i--)
{
Token t = tokens.get(i);
if (t.hasType("text", "comment", "virtual-comment"))
continue;
if (t.getType() == "keyword.operator" ||
t.getType() == "keyword.operator.infix" ||
t.getValue() == ",")
return true;
break;
}
return false;
}
private boolean rowIsEmptyOrComment(int row)
{
JsArray<Token> tokens = getSession().getTokens(row);
for (int i = 0, n = tokens.length(); i < n; i++)
if (!tokens.get(i).hasType("text", "comment", "virtual-comment"))
return false;
return true;
}
private boolean rowStartsWithClosingBracket(int row)
{
JsArray<Token> tokens = getSession().getTokens(row);
int n = tokens.length();
if (n == 0)
return false;
for (int i = 0; i < n; i++)
{
Token token = tokens.get(i);
if (token.hasType("text"))
continue;
String tokenValue = token.getValue();
return tokenValue == "}" ||
tokenValue == ")" ||
tokenValue == "]";
}
return false;
}
private boolean rowEndsWithOpenBracket(int row)
{
JsArray<Token> tokens = getSession().getTokens(row);
int n = tokens.length();
if (n == 0)
return false;
for (int i = 0; i < n; i++)
{
Token token = tokens.get(n - i - 1);
if (token.hasType("text", "comment", "virtual-comment"))
continue;
String tokenValue = token.getValue();
return tokenValue == "{" ||
tokenValue == "(" ||
tokenValue == "[";
}
return false;
}
/**
* Finds the last non-empty line starting at the given line.
*
* @param initial Row to start on
* @param limit Row at which to stop searching
* @return Index of last non-empty line, or limit line if no empty lines
* were found.
*/
private int findParagraphBoundary(int initial, int limit)
{
// no work to do if already at limit
if (initial == limit)
return initial;
// walk towards limit
int delta = limit > initial ? 1 : -1;
for (int row = initial + delta; row != limit; row += delta)
{
if (getLine(row).trim().isEmpty())
return row - delta;
}
// didn't find boundary
return limit;
}
@Override
public Range getParagraph(Position pos, int startRowLimit, int endRowLimit)
{
// find upper and lower paragraph boundaries
return Range.create(
findParagraphBoundary(pos.getRow(), startRowLimit), 0,
findParagraphBoundary(pos.getRow(), endRowLimit)+ 1, 0);
}
@Override
public Range getMultiLineExpr(Position pos, int startRowLimit, int endRowLimit)
{
if (DocumentMode.isSelectionInRMode(this))
{
return rMultiLineExpr(pos, startRowLimit, endRowLimit);
}
else
{
return getParagraph(pos, startRowLimit, endRowLimit);
}
}
private Range rMultiLineExpr(Position pos, int startRowLimit, int endRowLimit)
{
// create token cursor (will be used to walk tokens as needed)
TokenCursor c = getSession().getMode().getCodeModel().getTokenCursor();
// assume start, end at current position
int startRow = pos.getRow();
int endRow = pos.getRow();
// expand to enclosing '(' or '['
do
{
c.setRow(pos.getRow());
// move forward over commented / empty lines
int n = getSession().getLength();
while (rowIsEmptyOrComment(c.getRow()))
{
if (c.getRow() == n - 1)
break;
c.setRow(c.getRow() + 1);
}
// move to last non-right-bracket token on line
c.moveToEndOfRow(c.getRow());
while (c.valueEquals(")") || c.valueEquals("]"))
if (!c.moveToPreviousToken())
break;
// find the top-most enclosing bracket
// check for function scope
String[] candidates = new String[] {"(", "["};
int savedRow = -1;
int savedOffset = -1;
while (c.findOpeningBracket(candidates, true))
{
// check for function scope
if (c.valueEquals("(") &&
c.peekBwd(1).valueEquals("function") &&
c.peekBwd(2).isLeftAssign())
{
ScopeFunction scope = getFunctionAtPosition(c.currentPosition(), false);
if (scope != null)
return Range.fromPoints(scope.getPreamble(), scope.getEnd());
}
// move off of opening bracket and continue lookup
savedRow = c.getRow();
savedOffset = c.getOffset();
if (!c.moveToPreviousToken())
break;
}
// if we found a row, use it
if (savedRow != -1 && savedOffset != -1)
{
c.setRow(savedRow);
c.setOffset(savedOffset);
if (c.fwdToMatchingToken())
{
startRow = savedRow;
endRow = c.getRow();
}
}
} while (false);
// discover start of current statement
while (startRow >= startRowLimit)
{
// if we've hit the start of the document, bail
if (startRow <= 0)
break;
// if the row starts with an open bracket, expand to its match
if (rowStartsWithClosingBracket(startRow))
{
c.moveToStartOfRow(startRow);
if (c.bwdToMatchingToken())
{
startRow = c.getRow();
continue;
}
}
// keep going if the line is empty or previous ends w/binary op
if (rowEndsInBinaryOp(startRow - 1) || rowIsEmptyOrComment(startRow - 1))
{
startRow--;
continue;
}
// keep going if we're in a multiline string
String state = getSession().getState(startRow - 1);
if (state == "qstring" || state == "qqstring")
{
startRow--;
continue;
}
// bail out of the loop -- we've found the start of the statement
break;
}
// discover end of current statement -- we search from the inferred statement
// start, so that we can perform counting of matching pairs of brackets
endRow = startRow;
// NOTE: '[[' is not tokenized as a single token in our Ace tokenizer,
// so it is not included here (this shouldn't cause issues in practice
// since balanced pairs of '[' and '[[' would still imply a correct count
// of matched pairs of '[' anyhow)
int parenCount = 0; // '(', ')'
int braceCount = 0; // '{', '}'
int bracketCount = 0; // '[', ']'
while (endRow <= endRowLimit)
{
// update bracket token counts
JsArray<Token> tokens = getTokens(endRow);
for (Token token : JsUtil.asIterable(tokens))
{
String value = token.getValue();
parenCount += value == "(" ? 1 : 0;
parenCount -= value == ")" ? 1 : 0;
braceCount += value == "{" ? 1 : 0;
braceCount -= value == "}" ? 1 : 0;
bracketCount += value == "[" ? 1 : 0;
bracketCount -= value == "]" ? 1 : 0;
}
// continue search if line ends with binary operator
if (rowEndsInBinaryOp(endRow) || rowIsEmptyOrComment(endRow))
{
endRow++;
continue;
}
// continue search if we have unbalanced brackets
if (parenCount > 0 || braceCount > 0 || bracketCount > 0)
{
endRow++;
continue;
}
// continue search if we're in a multi-line string
String state = getSession().getState(endRow);
if (state == "qstring" || state == "qqstring")
{
endRow++;
continue;
}
// we had balanced brackets and no trailing binary operator; bail
break;
}
// if we're unbalanced at this point, that means we tried to
// expand in an unclosed expression -- just execute the current
// line rather than potentially executing unintended code
if (parenCount + braceCount + bracketCount > 0)
return Range.create(pos.getRow(), 0, pos.getRow() + 1, 0);
// shrink selection for empty lines at borders
while (startRow < endRow && rowIsEmptyOrComment(startRow))
startRow++;
while (endRow > startRow && rowIsEmptyOrComment(endRow))
endRow--;
// fixup for single-line execution
if (startRow > endRow)
startRow = endRow;
// if we've captured the body of a function definition, expand
// to include whole definition
c.setRow(startRow);
c.setOffset(0);
if (c.valueEquals("{") &&
c.moveToPreviousToken() &&
c.valueEquals(")") &&
c.bwdToMatchingToken() &&
c.moveToPreviousToken() &&
c.valueEquals("function") &&
c.moveToPreviousToken() &&
c.isLeftAssign())
{
ScopeFunction fn = getFunctionAtPosition(c.currentPosition(), false);
if (fn != null)
return Range.fromPoints(fn.getPreamble(), fn.getEnd());
}
// construct range
int endColumn = getSession().getLine(endRow).length();
Range range = Range.create(startRow, 0, endRow, endColumn);
// return empty range if nothing to execute
if (getTextForRange(range).trim().isEmpty())
range = Range.fromPoints(pos, pos);
return range;
}
// ---- Annotation related operations
public JsArray<AceAnnotation> getAnnotations()
{
return widget_.getAnnotations();
}
public void setAnnotations(JsArray<AceAnnotation> annotations)
{
widget_.setAnnotations(annotations);
}
@Override
public void removeMarkersAtCursorPosition()
{
widget_.removeMarkersAtCursorPosition();
}
@Override
public void removeMarkersOnCursorLine()
{
widget_.removeMarkersOnCursorLine();
}
@Override
public void showLint(JsArray<LintItem> lint)
{
widget_.showLint(lint);
}
@Override
public void clearLint()
{
widget_.clearLint();
}
@Override
public void showInfoBar(String message)
{
if (infoBar_ == null)
{
infoBar_ = new AceInfoBar(widget_);
widget_.addKeyDownHandler(new KeyDownHandler()
{
@Override
public void onKeyDown(KeyDownEvent event)
{
if (event.getNativeKeyCode() == KeyCodes.KEY_ESCAPE)
infoBar_.hide();
}
});
}
infoBar_.setText(message);
infoBar_.show();
}
public AnchoredRange createAnchoredRange(Position start, Position end)
{
return widget_.getEditor().getSession().createAnchoredRange(start, end);
}
public void insertRoxygenSkeleton()
{
getSession().getMode().getCodeModel().insertRoxygenSkeleton();
}
public long getLastModifiedTime()
{
return lastModifiedTime_;
}
public long getLastCursorChangedTime()
{
return lastCursorChangedTime_;
}
public int getFirstVisibleRow()
{
return widget_.getEditor().getFirstVisibleRow();
}
public int getLastVisibleRow()
{
return widget_.getEditor().getLastVisibleRow();
}
public void blockOutdent()
{
widget_.getEditor().blockOutdent();
}
public ScreenCoordinates documentPositionToScreenCoordinates(Position position)
{
return widget_.getEditor().getRenderer().textToScreenCoordinates(position);
}
public Position screenCoordinatesToDocumentPosition(int pageX, int pageY)
{
return widget_.getEditor().getRenderer().screenToTextCoordinates(pageX, pageY);
}
public boolean isPositionVisible(Position position)
{
return widget_.getEditor().isRowFullyVisible(position.getRow());
}
@Override
public void tokenizeDocument()
{
widget_.getEditor().tokenizeDocument();
}
@Override
public void retokenizeDocument()
{
widget_.getEditor().retokenizeDocument();
}
@Override
public Token getTokenAt(int row, int column)
{
return getSession().getTokenAt(row, column);
}
@Override
public Token getTokenAt(Position position)
{
return getSession().getTokenAt(position);
}
@Override
public JsArray<Token> getTokens(int row)
{
return getSession().getTokens(row);
}
@Override
public TokenIterator createTokenIterator()
{
return createTokenIterator(null);
}
@Override
public TokenIterator createTokenIterator(Position position)
{
TokenIterator it = TokenIterator.create(getSession());
if (position != null)
it.moveToPosition(position);
return it;
}
@Override
public void beginCollabSession(CollabEditStartParams params,
DirtyState dirtyState)
{
// suppress external value change events while the editor's contents are
// being swapped out for the contents of the collab session--otherwise
// there's going to be a lot of flickering as dirty state (etc) try to
// keep up
valueChangeSuppressed_ = true;
collab_.beginCollabSession(this, params, dirtyState, new Command()
{
@Override
public void execute()
{
valueChangeSuppressed_ = false;
}
});
}
@Override
public boolean hasActiveCollabSession()
{
return collab_.hasActiveCollabSession(this);
}
@Override
public boolean hasFollowingCollabSession()
{
return collab_.hasFollowingCollabSession(this);
}
public void endCollabSession()
{
collab_.endCollabSession(this);
}
@Override
public void setDragEnabled(boolean enabled)
{
widget_.setDragEnabled(enabled);
}
@Override
public boolean isSnippetsTabStopManagerActive()
{
return isSnippetsTabStopManagerActiveImpl(widget_.getEditor());
}
private static final native
boolean isSnippetsTabStopManagerActiveImpl(AceEditorNative editor)
/*-{
return editor.tabstopManager != null;
}-*/;
private void insertSnippet()
{
if (!snippets_.onInsertSnippet())
blockOutdent();
}
@Override
public boolean onInsertSnippet()
{
return snippets_.onInsertSnippet();
}
public void toggleTokenInfo()
{
toggleTokenInfo(widget_.getEditor());
}
private static final native void toggleTokenInfo(AceEditorNative editor) /*-{
if (editor.tokenTooltip && editor.tokenTooltip.destroy) {
editor.tokenTooltip.destroy();
} else {
var TokenTooltip = $wnd.require("ace/token_tooltip").TokenTooltip;
editor.tokenTooltip = new TokenTooltip(editor);
}
}-*/;
@Override
public void addLineWidget(final LineWidget widget)
{
// position the element far offscreen if it's above the currently
// visible row; Ace does not position line widgets above the viewport
// until the document is scrolled there
if (widget.getRow() < getFirstVisibleRow())
{
widget.getElement().getStyle().setTop(-10000, Unit.PX);
// set left/right values so that the widget consumes space; necessary
// to get layout offsets inside the widget while rendering but before
// it comes onscreen
widget.getElement().getStyle().setLeft(48, Unit.PX);
widget.getElement().getStyle().setRight(15, Unit.PX);
}
widget_.getLineWidgetManager().addLineWidget(widget);
adjustScrollForLineWidget(widget);
fireLineWidgetsChanged();
}
@Override
public void removeLineWidget(LineWidget widget)
{
widget_.getLineWidgetManager().removeLineWidget(widget);
fireLineWidgetsChanged();
}
@Override
public void removeAllLineWidgets()
{
widget_.getLineWidgetManager().removeAllLineWidgets();
fireLineWidgetsChanged();
}
@Override
public void onLineWidgetChanged(LineWidget widget)
{
// if the widget is above the viewport, this size change might push it
// into visibility, so push it offscreen first
if (widget.getRow() + 1 < getFirstVisibleRow())
widget.getElement().getStyle().setTop(-10000, Unit.PX);
widget_.getLineWidgetManager().onWidgetChanged(widget);
adjustScrollForLineWidget(widget);
fireLineWidgetsChanged();
}
@Override
public JsArray<LineWidget> getLineWidgets()
{
return widget_.getLineWidgetManager().getLineWidgets();
}
@Override
public LineWidget getLineWidgetForRow(int row)
{
return widget_.getLineWidgetManager().getLineWidgetForRow(row);
}
@Override
public boolean hasLineWidgets()
{
return widget_.getLineWidgetManager().hasLineWidgets();
}
private void adjustScrollForLineWidget(LineWidget w)
{
// the cursor is above the line widget, so the line widget is going
// to change the cursor position; adjust the scroll position to hold
// the cursor in place
if (getCursorPosition().getRow() > w.getRow())
{
int delta = w.getElement().getOffsetHeight() - w.getRenderedHeight();
// skip if no change to report
if (delta == 0)
return;
// we adjust the scrolltop on the session since it knows the
// currently queued scroll position; the renderer only knows the
// actual scroll position, which may not reflect unrendered changes
getSession().setScrollTop(getSession().getScrollTop() + delta);
}
// mark the current height as rendered
w.setRenderedHeight(w.getElement().getOffsetHeight());
}
@Override
public JsArray<ChunkDefinition> getChunkDefs()
{
// chunk definitions are populated at render time, so don't return any
// if we haven't rendered yet
if (!isRendered())
return null;
JsArray<ChunkDefinition> chunks = JsArray.createArray().cast();
JsArray<LineWidget> lineWidgets = getLineWidgets();
ScopeList scopes = new ScopeList(this);
for (int i = 0; i<lineWidgets.length(); i++)
{
LineWidget lineWidget = lineWidgets.get(i);
if (lineWidget.getType() == ChunkDefinition.LINE_WIDGET_TYPE)
{
ChunkDefinition chunk = lineWidget.getData();
chunks.push(chunk.with(lineWidget.getRow(),
TextEditingTargetNotebook.getKnitrChunkLabel(
lineWidget.getRow(), this, scopes)));
}
}
return chunks;
}
@Override
public boolean isRendered()
{
return widget_.isRendered();
}
@Override
public boolean showChunkOutputInline()
{
return showChunkOutputInline_;
}
@Override
public void setShowChunkOutputInline(boolean show)
{
showChunkOutputInline_ = show;
}
private void fireLineWidgetsChanged()
{
AceEditor.this.fireEvent(new LineWidgetsChangedEvent());
}
private static class BackgroundTokenizer
{
public BackgroundTokenizer(final AceEditor editor)
{
editor_ = editor;
timer_ = new Timer()
{
@Override
public void run()
{
// Stop our timer if we've tokenized up to the end of the document.
if (row_ >= editor_.getRowCount())
{
editor_.fireEvent(new ScopeTreeReadyEvent(
editor_.getScopeTree(),
editor_.getCurrentScope()));
return;
}
row_ += ROWS_TOKENIZED_PER_ITERATION;
row_ = Math.max(row_, editor.buildScopeTreeUpToRow(row_));
timer_.schedule(DELAY_MS);
}
};
editor_.addDocumentChangedHandler(new DocumentChangedEvent.Handler()
{
@Override
public void onDocumentChanged(DocumentChangedEvent event)
{
row_ = event.getEvent().getRange().getStart().getRow();
timer_.schedule(DELAY_MS);
}
});
}
public boolean isReady(int row)
{
return row < row_;
}
private final AceEditor editor_;
private final Timer timer_;
private int row_ = 0;
private static final int DELAY_MS = 5;
private static final int ROWS_TOKENIZED_PER_ITERATION = 200;
}
private class ScrollAnimator
implements AnimationScheduler.AnimationCallback
{
public ScrollAnimator(int targetY, int ms)
{
targetY_ = targetY;
startY_ = widget_.getEditor().getRenderer().getScrollTop();
delta_ = targetY_ - startY_;
ms_ = ms;
handle_ = AnimationScheduler.get().requestAnimationFrame(this);
}
public void complete()
{
handle_.cancel();
scrollAnimator_ = null;
}
@Override
public void execute(double timestamp)
{
if (startTime_ < 0)
startTime_ = timestamp;
double elapsed = timestamp - startTime_;
if (elapsed >= ms_)
{
widget_.getEditor().getRenderer().scrollToY(targetY_);
complete();
return;
}
// ease-out exponential
widget_.getEditor().getRenderer().scrollToY(
(int)(delta_ * (-Math.pow(2, -10 * elapsed / ms_) + 1)) + startY_);
// request next frame
handle_ = AnimationScheduler.get().requestAnimationFrame(this);
}
private final int ms_;
private final int targetY_;
private final int startY_;
private final int delta_;
private double startTime_ = -1;
private AnimationScheduler.AnimationHandle handle_;
}
private static final int DEBUG_CONTEXT_LINES = 2;
private final HandlerManager handlers_ = new HandlerManager(this);
private final AceEditorWidget widget_;
private final SnippetHelper snippets_;
private ScrollAnimator scrollAnimator_;
private CompletionManager completionManager_;
private CodeToolsServerOperations server_;
private UIPrefs uiPrefs_;
private CollabEditor collab_;
private Commands commands_;
private EventBus events_;
private TextFileType fileType_;
private boolean passwordMode_;
private boolean useEmacsKeybindings_ = false;
private boolean useVimMode_ = false;
private RnwCompletionContext rnwContext_;
private CppCompletionContext cppContext_;
private RCompletionContext rContext_ = null;
private Integer lineHighlightMarkerId_ = null;
private Integer lineDebugMarkerId_ = null;
private Integer executionLine_ = null;
private boolean valueChangeSuppressed_ = false;
private AceInfoBar infoBar_;
private boolean showChunkOutputInline_ = false;
private BackgroundTokenizer backgroundTokenizer_;
private final Vim vim_;
private final AceBackgroundHighlighter bgChunkHighlighter_;
private final AceEditorBackgroundLinkHighlighter bgLinkHighlighter_;
private int scrollTarget_ = 0;
private HandlerRegistration scrollCompleteReg_;
private final AceEditorMixins mixins_;
private static final ExternalJavaScriptLoader getLoader(StaticDataResource release)
{
return getLoader(release, null);
}
private static final ExternalJavaScriptLoader getLoader(StaticDataResource release,
StaticDataResource debug)
{
if (debug == null || !SuperDevMode.isActive())
return new ExternalJavaScriptLoader(release.getSafeUri().asString());
else
return new ExternalJavaScriptLoader(debug.getSafeUri().asString());
}
private static final ExternalJavaScriptLoader aceLoader_ =
getLoader(AceResources.INSTANCE.acejs(), AceResources.INSTANCE.acejsUncompressed());
private static final ExternalJavaScriptLoader aceSupportLoader_ =
getLoader(AceResources.INSTANCE.acesupportjs());
private static final ExternalJavaScriptLoader vimLoader_ =
getLoader(AceResources.INSTANCE.keybindingVimJs(),
AceResources.INSTANCE.keybindingVimUncompressedJs());
private static final ExternalJavaScriptLoader emacsLoader_ =
getLoader(AceResources.INSTANCE.keybindingEmacsJs(),
AceResources.INSTANCE.keybindingEmacsUncompressedJs());
private static final ExternalJavaScriptLoader extLanguageToolsLoader_ =
getLoader(AceResources.INSTANCE.extLanguageTools(),
AceResources.INSTANCE.extLanguageToolsUncompressed());
private boolean popupVisible_;
private final DiagnosticsBackgroundPopup diagnosticsBgPopup_;
private long lastCursorChangedTime_;
private long lastModifiedTime_;
private String yankedText_ = null;
private final List<HandlerRegistration> editorEventListeners_;
}
| work around GWT exception
| src/gwt/src/org/rstudio/studio/client/workbench/views/source/editors/text/AceEditor.java | work around GWT exception | <ide><path>rc/gwt/src/org/rstudio/studio/client/workbench/views/source/editors/text/AceEditor.java
<ide>
<ide> if (!suppressCompletion && fileType_.getEditorLanguage().useRCompletion())
<ide> {
<add> // GWT throws an exception if we bind Ace using 'AceEditor.this' below
<add> // so work around that by just creating a final reference and use that
<add> final AceEditor editor = this;
<add>
<ide> completionManager = new DelegatingCompletionManager(this)
<ide> {
<ide> @Override
<ide> {
<ide> // R completion manager
<ide> managers.put(DocumentMode.Mode.R, new RCompletionManager(
<del> AceEditor.this,
<del> AceEditor.this,
<add> editor,
<add> editor,
<ide> new CompletionPopupPanel(),
<ide> server_,
<ide> new Filter(),
<ide> rContext_,
<ide> fileType_.canExecuteChunks() ? rnwContext_ : null,
<del> AceEditor.this,
<add> editor,
<ide> false));
<ide>
<ide> // Python completion manager
<ide> managers.put(DocumentMode.Mode.PYTHON, new PythonCompletionManager(
<del> AceEditor.this,
<del> AceEditor.this,
<add> editor,
<add> editor,
<ide> new CompletionPopupPanel(),
<ide> server_,
<ide> new Filter(),
<ide> rContext_,
<ide> fileType_.canExecuteChunks() ? rnwContext_ : null,
<del> AceEditor.this,
<add> editor,
<ide> false));
<ide>
<ide> // C++ completion manager
<ide> managers.put(DocumentMode.Mode.C_CPP, new CppCompletionManager(
<del> AceEditor.this,
<add> editor,
<ide> new Filter(),
<ide> cppContext_));
<ide> } |
|
JavaScript | agpl-3.0 | 6313fac642701f57323249bc446b2715b3360723 | 0 | ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs | /*
* (c) Copyright Ascensio System SIA 2010-2017
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia,
* EU, LV-1021.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
"use strict";
// Import
var g_oTableId = AscCommon.g_oTableId;
var g_oTextMeasurer = AscCommon.g_oTextMeasurer;
var History = AscCommon.History;
var c_oAscShdNil = Asc.c_oAscShdNil;
var reviewtype_Common = 0x00;
var reviewtype_Remove = 0x01;
var reviewtype_Add = 0x02;
/**
*
* @param Paragraph
* @param bMathRun
* @constructor
* @extends {CParagraphContentWithContentBase}
*/
function ParaRun(Paragraph, bMathRun)
{
CParagraphContentWithContentBase.call(this);
this.Id = AscCommon.g_oIdCounter.Get_NewId(); // Id данного элемента
this.Type = para_Run; // тип данного элемента
this.Paragraph = Paragraph; // Ссылка на параграф
this.Pr = new CTextPr(); // Текстовые настройки данного run
this.Content = []; // Содержимое данного run
this.State = new CParaRunState(); // Положение курсора и селекта в данного run
this.Selection = this.State.Selection;
this.CompiledPr = new CTextPr(); // Скомпилированные настройки
this.RecalcInfo = new CParaRunRecalcInfo(); // Флаги для пересчета (там же флаг пересчета стиля)
this.TextAscent = 0; // текстовый ascent + linegap
this.TextAscent = 0; // текстовый ascent + linegap
this.TextDescent = 0; // текстовый descent
this.TextHeight = 0; // высота текста
this.TextAscent2 = 0; // текстовый ascent
this.Ascent = 0; // общий ascent
this.Descent = 0; // общий descent
this.YOffset = 0; // смещение по Y
this.CollPrChangeMine = false;
this.CollPrChangeOther = false;
this.CollaborativeMarks = new CRunCollaborativeMarks();
this.m_oContentChanges = new AscCommon.CContentChanges(); // список изменений(добавление/удаление элементов)
this.NearPosArray = [];
this.SearchMarks = [];
this.SpellingMarks = [];
this.ReviewType = reviewtype_Common;
this.ReviewInfo = new CReviewInfo();
if (editor && !editor.isPresentationEditor && editor.WordControl && editor.WordControl.m_oLogicDocument && true === editor.WordControl.m_oLogicDocument.Is_TrackRevisions())
{
this.ReviewType = reviewtype_Add;
this.ReviewInfo.Update();
}
if(bMathRun)
{
this.Type = para_Math_Run;
// запомним позицию для Recalculate_CurPos, когда Run пустой
this.pos = new CMathPosition();
this.ParaMath = null;
this.Parent = null;
this.ArgSize = 0;
this.size = new CMathSize();
this.MathPrp = new CMPrp();
this.bEqArray = false;
}
this.StartState = null;
this.CompositeInput = null;
// Добавляем данный класс в таблицу Id (обязательно в конце конструктора)
g_oTableId.Add( this, this.Id );
if(this.Paragraph && !this.Paragraph.bFromDocument)
{
this.Save_StartState();
}
}
ParaRun.prototype = Object.create(CParagraphContentWithContentBase.prototype);
ParaRun.prototype.constructor = ParaRun;
ParaRun.prototype.Get_Type = function()
{
return this.Type;
};
//-----------------------------------------------------------------------------------
// Функции для работы с Id
//-----------------------------------------------------------------------------------
ParaRun.prototype.Get_Id = function()
{
return this.Id;
};
ParaRun.prototype.GetParagraph = function()
{
return this.Paragraph;
};
ParaRun.prototype.SetParagraph = function(Paragraph)
{
this.Paragraph = Paragraph;
};
ParaRun.prototype.Set_ParaMath = function(ParaMath, Parent)
{
this.ParaMath = ParaMath;
this.Parent = Parent;
for(var i = 0; i < this.Content.length; i++)
{
this.Content[i].relate(this);
}
};
ParaRun.prototype.Save_StartState = function()
{
this.StartState = new CParaRunStartState(this);
};
//-----------------------------------------------------------------------------------
// Функции для работы с содержимым данного рана
//-----------------------------------------------------------------------------------
ParaRun.prototype.Copy = function(Selected)
{
var bMath = this.Type == para_Math_Run ? true : false;
var NewRun = new ParaRun(this.Paragraph, bMath);
NewRun.Set_Pr( this.Pr.Copy() );
if (this.Paragraph && this.Paragraph.bFromDocument && this.Paragraph.LogicDocument && true === this.Paragraph.LogicDocument.Is_TrackRevisions())
NewRun.Set_ReviewType(reviewtype_Add);
if(true === bMath)
NewRun.Set_MathPr(this.MathPrp.Copy());
var StartPos = 0;
var EndPos = this.Content.length;
if (true === Selected && true === this.State.Selection.Use)
{
StartPos = this.State.Selection.StartPos;
EndPos = this.State.Selection.EndPos;
if (StartPos > EndPos)
{
StartPos = this.State.Selection.EndPos;
EndPos = this.State.Selection.StartPos;
}
}
else if (true === Selected && true !== this.State.Selection.Use)
EndPos = -1;
for ( var CurPos = StartPos; CurPos < EndPos; CurPos++ )
{
var Item = this.Content[CurPos];
// TODO: Как только перенесем para_End в сам параграф (как и нумерацию) убрать здесь
if ( para_End !== Item.Type )
NewRun.Add_ToContent( CurPos - StartPos, Item.Copy(), false );
}
return NewRun;
};
ParaRun.prototype.Copy2 = function()
{
var NewRun = new ParaRun(this.Paragraph);
NewRun.Set_Pr( this.Pr.Copy() );
var StartPos = 0;
var EndPos = this.Content.length;
for ( var CurPos = StartPos; CurPos < EndPos; CurPos++ )
{
var Item = this.Content[CurPos];
NewRun.Add_ToContent( CurPos - StartPos, Item.Copy(), false );
}
return NewRun;
};
ParaRun.prototype.CopyContent = function(Selected)
{
return [this.Copy(Selected)];
};
ParaRun.prototype.GetAllDrawingObjects = function(DrawingObjs)
{
var Count = this.Content.length;
for ( var Index = 0; Index < Count; Index++ )
{
var Item = this.Content[Index];
if ( para_Drawing === Item.Type )
{
DrawingObjs.push(Item);
Item.GetAllDrawingObjects(DrawingObjs);
}
}
};
ParaRun.prototype.Clear_ContentChanges = function()
{
this.m_oContentChanges.Clear();
};
ParaRun.prototype.Add_ContentChanges = function(Changes)
{
this.m_oContentChanges.Add( Changes );
};
ParaRun.prototype.Refresh_ContentChanges = function()
{
this.m_oContentChanges.Refresh();
};
ParaRun.prototype.Get_Text = function(Text)
{
if ( null === Text.Text )
return;
var ContentLen = this.Content.length;
for ( var CurPos = 0; CurPos < ContentLen; CurPos++ )
{
var Item = this.Content[CurPos];
var ItemType = Item.Type;
var bBreak = false;
switch ( ItemType )
{
case para_Drawing:
case para_PageNum:
case para_PageCount:
{
if (true === Text.BreakOnNonText)
{
Text.Text = null;
bBreak = true;
}
break;
}
case para_End:
{
if (true === Text.BreakOnNonText)
{
Text.Text = null;
bBreak = true;
}
if (true === Text.ParaEndToSpace)
Text.Text += " ";
break;
}
case para_Text : Text.Text += String.fromCharCode(Item.Value); break;
case para_Space:
case para_Tab : Text.Text += " "; break;
}
if ( true === bBreak )
break;
}
};
// Проверяем пустой ли ран
ParaRun.prototype.Is_Empty = function(Props)
{
var SkipAnchor = (undefined !== Props ? Props.SkipAnchor : false);
var SkipEnd = (undefined !== Props ? Props.SkipEnd : false);
var SkipPlcHldr= (undefined !== Props ? Props.SkipPlcHldr: false);
var SkipNewLine= (undefined !== Props ? Props.SkipNewLine: false);
var Count = this.Content.length;
if (true !== SkipAnchor && true !== SkipEnd && true !== SkipPlcHldr && true !== SkipNewLine)
{
if ( Count > 0 )
return false;
else
return true;
}
else
{
for ( var CurPos = 0; CurPos < this.Content.length; CurPos++ )
{
var Item = this.Content[CurPos];
var ItemType = Item.Type;
if ((true !== SkipAnchor || para_Drawing !== ItemType || false !== Item.Is_Inline()) && (true !== SkipEnd || para_End !== ItemType) && (true !== SkipPlcHldr || true !== Item.IsPlaceholder()) && (true !== SkipNewLine || para_NewLine !== ItemType))
return false;
}
return true;
}
};
ParaRun.prototype.Is_CheckingNearestPos = function()
{
if (this.NearPosArray.length > 0)
return true;
return false;
};
// Начинается ли данный ран с новой строки
ParaRun.prototype.Is_StartFromNewLine = function()
{
if (this.protected_GetLinesCount() < 2 || 0 !== this.protected_GetRangeStartPos(1, 0))
return false;
return true;
};
// Добавляем элемент в текущую позицию
ParaRun.prototype.Add = function(Item, bMath)
{
if (undefined !== Item.Parent)
Item.Parent = this;
if (this.Paragraph && this.Paragraph.LogicDocument && this.Paragraph.bFromDocument)
{
// Специальный код, связанный с обработкой изменения языка ввода при наборе.
if (true === this.Paragraph.LogicDocument.CheckLanguageOnTextAdd && editor)
{
var nRequiredLanguage = editor.asc_getKeyboardLanguage();
var nCurrentLanguage = this.Get_CompiledPr(false).Lang.Val;
if (-1 !== nRequiredLanguage && nRequiredLanguage !== nCurrentLanguage)
{
var NewLang = new CLang();
NewLang.Val = nRequiredLanguage;
if (this.Is_Empty())
{
this.Set_Lang(NewLang);
}
else
{
var NewRun = this.private_SplitRunInCurPos();
if (NewRun)
{
NewRun.Set_Lang(NewLang);
NewRun.MoveCursorToStartPos();
NewRun.Add(Item, bMath);
NewRun.Make_ThisElementCurrent();
return;
}
}
}
}
// Специальный код, связанный с работой сносок:
// 1. При добавлении сноски мы ее оборачиваем в отдельный ран со специальным стилем.
// 2. Если мы находимся в ране со специальным стилем сносок и следующий или предыдущий элемент и есть сноска, тогда
// мы добавляем элемент (если это не ссылка на сноску) в новый ран без стиля для сносок.
var oStyles = this.Paragraph.LogicDocument.Get_Styles();
if (para_FootnoteRef === Item.Type || para_FootnoteReference === Item.Type)
{
if (this.Is_Empty())
{
this.Set_RStyle(oStyles.GetDefaultFootnoteReference());
}
else
{
var NewRun = this.private_SplitRunInCurPos();
if (NewRun)
{
NewRun.Set_VertAlign(undefined);
NewRun.Set_RStyle(oStyles.GetDefaultFootnoteReference());
NewRun.MoveCursorToStartPos();
NewRun.Add(Item, bMath);
NewRun.Make_ThisElementCurrent();
return;
}
}
}
else if (true === this.private_IsCurPosNearFootnoteReference())
{
var NewRun = this.private_SplitRunInCurPos();
if (NewRun)
{
NewRun.Set_VertAlign(AscCommon.vertalign_Baseline);
NewRun.MoveCursorToStartPos();
NewRun.Add(Item, bMath);
NewRun.Make_ThisElementCurrent();
return;
}
}
}
var TrackRevisions = false;
if (this.Paragraph && this.Paragraph.LogicDocument)
TrackRevisions = this.Paragraph.LogicDocument.Is_TrackRevisions();
var ReviewType = this.Get_ReviewType();
if ((true === TrackRevisions && (reviewtype_Add !== ReviewType || true !== this.ReviewInfo.Is_CurrentUser())) || (false === TrackRevisions && reviewtype_Common !== ReviewType))
{
var DstReviewType = true === TrackRevisions ? reviewtype_Add : reviewtype_Common;
// Если мы стоим в конце рана, тогда проверяем следующий элемент родительского класса, аналогично если мы стоим
// в начале рана, проверяем предыдущий элемент родительского класса.
var Parent = this.Get_Parent();
if (null === Parent)
return;
// Ищем данный элемент в родительском классе
var RunPos = this.private_GetPosInParent(Parent);
if (-1 === RunPos)
return;
var CurPos = this.State.ContentPos;
if (0 === CurPos && RunPos > 0)
{
var PrevElement = Parent.Content[RunPos - 1];
if (para_Run === PrevElement.Type && DstReviewType === PrevElement.Get_ReviewType() && true === this.Pr.Is_Equal(PrevElement.Pr) && PrevElement.ReviewInfo && true === PrevElement.ReviewInfo.Is_CurrentUser())
{
PrevElement.State.ContentPos = PrevElement.Content.length;
PrevElement.private_AddItemToRun(PrevElement.Content.length, Item);
PrevElement.Make_ThisElementCurrent();
return;
}
}
if (this.Content.length === CurPos && (RunPos < Parent.Content.length - 2 || (RunPos < Parent.Content.length - 1 && !(Parent instanceof Paragraph))))
{
var NextElement = Parent.Content[RunPos + 1];
if (para_Run === NextElement.Type && DstReviewType === NextElement.Get_ReviewType() && true === this.Pr.Is_Equal(NextElement.Pr) && NextElement.ReviewInfo && true === NextElement.ReviewInfo.Is_CurrentUser())
{
NextElement.State.ContentPos = 0;
NextElement.private_AddItemToRun(0, Item);
NextElement.Make_ThisElementCurrent();
return;
}
}
// Если мы дошли до сюда, значит нам надо создать новый ран
var NewRun = new ParaRun(this.Paragraph, bMath);
NewRun.Set_Pr(this.Pr.Copy());
NewRun.Set_ReviewType(DstReviewType);
NewRun.private_AddItemToRun(0, Item);
if (0 === CurPos)
Parent.Add_ToContent(RunPos, NewRun);
else if (this.Content.length === CurPos)
Parent.Add_ToContent(RunPos + 1, NewRun);
else
{
var OldReviewInfo = (this.ReviewInfo ? this.ReviewInfo.Copy() : undefined);
var OldReviewType = this.ReviewType;
// Нужно разделить данный ран в текущей позиции
var RightRun = this.Split2(CurPos);
Parent.Add_ToContent(RunPos + 1, NewRun);
Parent.Add_ToContent(RunPos + 2, RightRun);
this.Set_ReviewTypeWithInfo(OldReviewType, OldReviewInfo);
RightRun.Set_ReviewTypeWithInfo(OldReviewType, OldReviewInfo);
}
NewRun.Make_ThisElementCurrent();
}
else if(this.Type == para_Math_Run && this.State.ContentPos == 0 && true === this.Is_StartForcedBreakOperator()) // если в начале текущего Run идет принудительный перенос => создаем новый Run
{
var NewRun = new ParaRun(this.Paragraph, bMath);
NewRun.Set_Pr(this.Pr.Copy());
NewRun.private_AddItemToRun(0, Item);
// Ищем данный элемент в родительском классе
var RunPos = this.private_GetPosInParent(this.Parent);
this.Parent.Internal_Content_Add(RunPos, NewRun, true);
}
else
{
this.private_AddItemToRun(this.State.ContentPos, Item);
}
};
ParaRun.prototype.private_SplitRunInCurPos = function()
{
var NewRun = null;
var Parent = this.Get_Parent();
var RunPos = this.private_GetPosInParent();
if (null !== Parent && -1 !== RunPos)
{
// Если мы стоим в начале рана, тогда добавим новый ран в начало, если мы стоим в конце рана, тогда
// добавим новый ран после текущего, а если мы в середине рана, тогда надо разбивать текущий ран.
NewRun = new ParaRun(this.Paragraph, para_Math_Run === this.Type);
NewRun.Set_Pr(this.Pr.Copy());
var CurPos = this.State.ContentPos;
if (0 === CurPos)
{
Parent.Add_ToContent(RunPos, NewRun);
}
else if (this.Content.length === CurPos)
{
Parent.Add_ToContent(RunPos + 1, NewRun);
}
else
{
// Нужно разделить данный ран в текущей позиции
var RightRun = this.Split2(CurPos);
Parent.Add_ToContent(RunPos + 1, NewRun);
Parent.Add_ToContent(RunPos + 2, RightRun);
}
}
return NewRun;
};
ParaRun.prototype.private_IsCurPosNearFootnoteReference = function()
{
if (this.Paragraph && this.Paragraph.LogicDocument && this.Paragraph.bFromDocument)
{
var oStyles = this.Paragraph.LogicDocument.Get_Styles();
var nCurPos = this.State.ContentPos;
if (this.Get_RStyle() === oStyles.GetDefaultFootnoteReference()
&& ((nCurPos > 0 && this.Content[nCurPos - 1] && (para_FootnoteRef === this.Content[nCurPos - 1].Type || para_FootnoteReference === this.Content[nCurPos - 1].Type))
|| (nCurPos < this.Content.length && this.Content[nCurPos] && (para_FootnoteRef === this.Content[nCurPos].Type || para_FootnoteReference === this.Content[nCurPos].Type))))
return true;
}
return false;
};
ParaRun.prototype.private_AddItemToRun = function(nPos, Item)
{
if (para_FootnoteReference === Item.Type && true === Item.IsCustomMarkFollows() && undefined !== Item.GetCustomText())
{
this.Add_ToContent(nPos, Item, true);
var sCustomText = Item.GetCustomText();
for (var nIndex = 0, nLen = sCustomText.length; nIndex < nLen; ++nIndex)
{
var nChar = sCustomText.charAt(nIndex);
if (" " === nChar)
this.Add_ToContent(nPos + 1 + nIndex, new ParaSpace(), true);
else
this.Add_ToContent(nPos + 1 + nIndex, new ParaText(nChar), true);
}
}
else
{
this.Add_ToContent(nPos, Item, true);
}
};
ParaRun.prototype.Remove = function(Direction, bOnAddText)
{
var TrackRevisions = null;
if (this.Paragraph && this.Paragraph.LogicDocument)
TrackRevisions = this.Paragraph.LogicDocument.Is_TrackRevisions();
var Selection = this.State.Selection;
var ReviewType = this.Get_ReviewType();
if (true === TrackRevisions && reviewtype_Add !== ReviewType)
{
if (reviewtype_Remove === ReviewType)
{
// Тут мы ничего не делаем, просто перешагиваем через удаленный текст
if (true !== Selection.Use)
{
var CurPos = this.State.ContentPos;
// Просто перешагиваем через элемент
if (Direction < 0)
{
// Пропускаем все Flow-объекты
while (CurPos > 0 && para_Drawing === this.Content[CurPos - 1].Type && false === this.Content[CurPos - 1].Is_Inline())
CurPos--;
if (CurPos <= 0)
return false;
this.State.ContentPos--;
}
else
{
if (CurPos >= this.Content.length || para_End === this.Content[CurPos].Type)
return false;
this.State.ContentPos++;
}
this.Make_ThisElementCurrent();
}
else
{
// Ничего не делаем
}
}
else
{
if (true === Selection.Use)
{
// Мы должны данный ран разбить в начальной и конечной точках выделения и центральный ран пометить как
// удаленный.
var StartPos = Selection.StartPos;
var EndPos = Selection.EndPos;
if (StartPos > EndPos)
{
StartPos = Selection.EndPos;
EndPos = Selection.StartPos;
}
var Parent = this.Get_Parent();
var RunPos = this.private_GetPosInParent(Parent);
if (-1 !== RunPos)
{
var DeletedRun = null;
if (StartPos <= 0 && EndPos >= this.Content.length)
DeletedRun = this;
else if (StartPos <= 0)
{
this.Split2(EndPos, Parent, RunPos);
DeletedRun = this;
}
else if (EndPos >= this.Content.length)
{
DeletedRun = this.Split2(StartPos, Parent, RunPos);
}
else
{
this.Split2(EndPos, Parent, RunPos);
DeletedRun = this.Split2(StartPos, Parent, RunPos);
}
DeletedRun.Set_ReviewType(reviewtype_Remove);
}
}
else
{
var Parent = this.Get_Parent();
var RunPos = this.private_GetPosInParent(Parent);
var CurPos = this.State.ContentPos;
if (Direction < 0)
{
// Пропускаем все Flow-объекты
while (CurPos > 0 && para_Drawing === this.Content[CurPos - 1].Type && false === this.Content[CurPos - 1].Is_Inline())
CurPos--;
if (CurPos <= 0)
return false;
// Проверяем, возможно предыдущий элемент - инлайн картинка, тогда мы его не удаляем, а выделяем как картинку
if (para_Drawing == this.Content[CurPos - 1].Type && true === this.Content[CurPos - 1].Is_Inline())
{
return this.Paragraph.Parent.Select_DrawingObject(this.Content[CurPos - 1].Get_Id());
}
if (1 === CurPos && 1 === this.Content.length)
{
this.Set_ReviewType(reviewtype_Remove);
this.State.ContentPos = CurPos - 1;
this.Make_ThisElementCurrent();
return true;
}
else if (1 === CurPos && Parent && RunPos > 0)
{
var PrevElement = Parent.Content[RunPos - 1];
if (para_Run === PrevElement.Type && reviewtype_Remove === PrevElement.Get_ReviewType() && true === this.Pr.Is_Equal(PrevElement.Pr))
{
var Item = this.Content[CurPos - 1];
this.Remove_FromContent(CurPos - 1, 1, true);
PrevElement.Add_ToContent(PrevElement.Content.length, Item);
PrevElement.State.ContentPos = PrevElement.Content.length - 1;
PrevElement.Make_ThisElementCurrent();
return true;
}
}
else if (CurPos === this.Content.length && Parent && RunPos < Parent.Content.length - 1)
{
var NextElement = Parent.Content[RunPos + 1];
if (para_Run === NextElement.Type && reviewtype_Remove === NextElement.Get_ReviewType() && true === this.Pr.Is_Equal(NextElement.Pr))
{
var Item = this.Content[CurPos - 1];
this.Remove_FromContent(CurPos - 1, 1, true);
NextElement.Add_ToContent(0, Item);
this.State.ContentPos = CurPos - 1;
this.Make_ThisElementCurrent();
return true;
}
}
// Если мы дошли до сюда, значит данный элемент нужно выделять в отдельный ран
var RRun = this.Split2(CurPos, Parent, RunPos);
var CRun = this.Split2(CurPos - 1, Parent, RunPos);
CRun.Set_ReviewType(reviewtype_Remove);
this.State.ContentPos = CurPos - 1;
this.Make_ThisElementCurrent();
}
else
{
if (CurPos >= this.Content.length || para_End === this.Content[CurPos].Type)
return false;
// Проверяем, возможно следующий элемент - инлайн картинка, тогда мы его не удаляем, а выделяем как картинку
if (para_Drawing == this.Content[CurPos].Type && true === this.Content[CurPos].Is_Inline())
{
return this.Paragraph.Parent.Select_DrawingObject(this.Content[CurPos].Get_Id());
}
if (CurPos === this.Content.length - 1 && 0 === CurPos)
{
this.Set_ReviewType(reviewtype_Remove);
this.State.ContentPos = 1;
this.Make_ThisElementCurrent();
return true;
}
else if (0 === CurPos && Parent && RunPos > 0)
{
var PrevElement = Parent.Content[RunPos - 1];
if (para_Run === PrevElement.Type && reviewtype_Remove === PrevElement.Get_ReviewType() && true === this.Pr.Is_Equal(PrevElement.Pr))
{
var Item = this.Content[CurPos];
this.Remove_FromContent(CurPos, 1, true);
PrevElement.Add_ToContent(PrevElement.Content.length, Item);
this.State.ContentPos = CurPos;
this.Make_ThisElementCurrent();
return true;
}
}
else if (CurPos === this.Content.length - 1 && Parent && RunPos < Parent.Content.length - 1)
{
var NextElement = Parent.Content[RunPos + 1];
if (para_Run === NextElement.Type && reviewtype_Remove === NextElement.Get_ReviewType() && true === this.Pr.Is_Equal(NextElement.Pr))
{
var Item = this.Content[CurPos];
this.Remove_FromContent(CurPos, 1, true);
NextElement.Add_ToContent(0, Item);
NextElement.State.ContentPos = 1;
NextElement.Make_ThisElementCurrent();
return true;
}
}
// Если мы дошли до сюда, значит данный элемент нужно выделять в отдельный ран
var RRun = this.Split2(CurPos + 1, Parent, RunPos);
var CRun = this.Split2(CurPos, Parent, RunPos);
CRun.Set_ReviewType(reviewtype_Remove);
RRun.State.ContentPos = 0;
RRun.Make_ThisElementCurrent();
}
}
}
}
else
{
if (true === Selection.Use)
{
var StartPos = Selection.StartPos;
var EndPos = Selection.EndPos;
if (StartPos > EndPos)
{
var Temp = StartPos;
StartPos = EndPos;
EndPos = Temp;
}
// Если в выделение попадает ParaEnd, тогда удаляем все кроме этого элемента
if (true === this.Selection_CheckParaEnd())
{
for (var CurPos = EndPos - 1; CurPos >= StartPos; CurPos--)
{
if (para_End !== this.Content[CurPos].Type)
this.Remove_FromContent(CurPos, 1, true);
}
}
else
{
this.Remove_FromContent(StartPos, EndPos - StartPos, true);
}
this.RemoveSelection();
this.State.ContentPos = StartPos;
}
else
{
var CurPos = this.State.ContentPos;
if (Direction < 0)
{
// Пропускаем все Flow-объекты
while (CurPos > 0 && para_Drawing === this.Content[CurPos - 1].Type && false === this.Content[CurPos - 1].Is_Inline())
CurPos--;
if (CurPos <= 0)
return false;
// Проверяем, возможно предыдущий элемент - инлайн картинка, тогда мы его не удаляем, а выделяем как картинку
if (para_Drawing == this.Content[CurPos - 1].Type && true === this.Content[CurPos - 1].Is_Inline())
{
return this.Paragraph.Parent.Select_DrawingObject(this.Content[CurPos - 1].Get_Id());
}
this.Remove_FromContent(CurPos - 1, 1, true);
this.State.ContentPos = CurPos - 1;
}
else
{
while (CurPos < this.Content.length && para_Drawing === this.Content[CurPos].Type && false === this.Content[CurPos].Is_Inline())
CurPos++;
if (CurPos >= this.Content.length || para_End === this.Content[CurPos].Type)
return false;
// Проверяем, возможно следующий элемент - инлайн картинка, тогда мы его не удаляем, а выделяем как картинку
if (para_Drawing == this.Content[CurPos].Type && true === this.Content[CurPos].Is_Inline())
{
return this.Paragraph.Parent.Select_DrawingObject(this.Content[CurPos].Get_Id());
}
this.Remove_FromContent(CurPos, 1, true);
this.State.ContentPos = CurPos;
}
}
}
return true;
};
ParaRun.prototype.Remove_ParaEnd = function()
{
var Pos = -1;
var ContentLen = this.Content.length;
for ( var CurPos = 0; CurPos < ContentLen; CurPos++ )
{
if ( para_End === this.Content[CurPos].Type )
{
Pos = CurPos;
break;
}
}
if ( -1 === Pos )
return false;
this.Remove_FromContent( Pos, ContentLen - Pos, true );
return true;
};
/**
* Обновляем позиции селекта, курсора и переносов строк при добавлении элемента в контент данного рана.
* @param Pos
*/
ParaRun.prototype.private_UpdatePositionsOnAdd = function(Pos)
{
// Обновляем текущую позицию
if (this.State.ContentPos >= Pos)
this.State.ContentPos++;
// Обновляем начало и конец селекта
if (true === this.State.Selection.Use)
{
if (this.State.Selection.StartPos >= Pos)
this.State.Selection.StartPos++;
if (this.State.Selection.EndPos >= Pos)
this.State.Selection.EndPos++;
}
// Также передвинем всем метки переносов страниц и строк
var LinesCount = this.protected_GetLinesCount();
for (var CurLine = 0; CurLine < LinesCount; CurLine++)
{
var RangesCount = this.protected_GetRangesCount(CurLine);
for (var CurRange = 0; CurRange < RangesCount; CurRange++)
{
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
if (StartPos > Pos)
StartPos++;
if (EndPos > Pos)
EndPos++;
this.protected_FillRange(CurLine, CurRange, StartPos, EndPos);
}
// Особый случай, когда мы добавляем элемент в самый последний ран
if (Pos === this.Content.length - 1 && LinesCount - 1 === CurLine)
{
this.protected_FillRangeEndPos(CurLine, RangesCount - 1, this.protected_GetRangeEndPos(CurLine, RangesCount - 1) + 1);
}
}
};
/**
* Обновляем позиции селекта, курсора и переносов строк при удалении элементов из контента данного рана.
* @param Pos
* @param Count
*/
ParaRun.prototype.private_UpdatePositionsOnRemove = function(Pos, Count)
{
// Обновим текущую позицию
if (this.State.ContentPos > Pos + Count)
this.State.ContentPos -= Count;
else if (this.State.ContentPos > Pos)
this.State.ContentPos = Pos;
// Обновим начало и конец селекта
if (true === this.State.Selection.Use)
{
if (this.State.Selection.StartPos <= this.State.Selection.EndPos)
{
if (this.State.Selection.StartPos > Pos + Count)
this.State.Selection.StartPos -= Count;
else if (this.State.Selection.StartPos > Pos)
this.State.Selection.StartPos = Pos;
if (this.State.Selection.EndPos >= Pos + Count)
this.State.Selection.EndPos -= Count;
else if (this.State.Selection.EndPos > Pos)
this.State.Selection.EndPos = Math.max(0, Pos - 1);
}
else
{
if (this.State.Selection.StartPos >= Pos + Count)
this.State.Selection.StartPos -= Count;
else if (this.State.Selection.StartPos > Pos)
this.State.Selection.StartPos = Math.max(0, Pos - 1);
if (this.State.Selection.EndPos > Pos + Count)
this.State.Selection.EndPos -= Count;
else if (this.State.Selection.EndPos > Pos)
this.State.Selection.EndPos = Pos;
}
}
// Также передвинем всем метки переносов страниц и строк
var LinesCount = this.protected_GetLinesCount();
for (var CurLine = 0; CurLine < LinesCount; CurLine++)
{
var RangesCount = this.protected_GetRangesCount(CurLine);
for (var CurRange = 0; CurRange < RangesCount; CurRange++)
{
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
if (StartPos > Pos + Count)
StartPos -= Count;
else if (StartPos > Pos)
StartPos = Math.max(0, Pos);
if (EndPos >= Pos + Count)
EndPos -= Count;
else if (EndPos >= Pos)
EndPos = Math.max(0, Pos);
this.protected_FillRange(CurLine, CurRange, StartPos, EndPos);
}
}
};
ParaRun.prototype.private_UpdateCompositeInputPositionsOnAdd = function(Pos)
{
if (null !== this.CompositeInput)
{
if (Pos <= this.CompositeInput.Pos)
this.CompositeInput.Pos++;
else if (Pos < this.CompositeInput.Pos + this.CompositeInput.Length)
this.CompositeInput.Length++;
}
};
ParaRun.prototype.private_UpdateCompositeInputPositionsOnRemove = function(Pos, Count)
{
if (null !== this.CompositeInput)
{
if (Pos + Count <= this.CompositeInput.Pos)
{
this.CompositeInput.Pos -= Count;
}
else if (Pos < this.CompositeInput.Pos)
{
this.CompositeInput.Pos = Pos;
this.CompositeInput.Length = Math.max(0, this.CompositeInput.Length - (Count - (this.CompositeInput.Pos - Pos)));
}
else if (Pos + Count < this.CompositeInput.Pos + this.CompositeInput.Length)
{
this.CompositeInput.Length = Math.max(0, this.CompositeInput.Length - Count);
}
else if (Pos < this.CompositeInput.Pos + this.CompositeInput.Length)
{
this.CompositeInput.Length = Math.max(0, Pos - this.CompositeInput.Pos);
}
}
};
// Добавляем элемент в позицию с сохранием в историю
ParaRun.prototype.Add_ToContent = function(Pos, Item, UpdatePosition)
{
History.Add(new CChangesRunAddItem(this, Pos, [Item], true));
this.Content.splice( Pos, 0, Item );
if (true === UpdatePosition)
this.private_UpdatePositionsOnAdd(Pos);
// Обновляем позиции в NearestPos
var NearPosLen = this.NearPosArray.length;
for ( var Index = 0; Index < NearPosLen; Index++ )
{
var RunNearPos = this.NearPosArray[Index];
var ContentPos = RunNearPos.NearPos.ContentPos;
var Depth = RunNearPos.Depth;
if ( ContentPos.Data[Depth] >= Pos )
ContentPos.Data[Depth]++;
}
// Обновляем позиции в поиске
var SearchMarksCount = this.SearchMarks.length;
for ( var Index = 0; Index < SearchMarksCount; Index++ )
{
var Mark = this.SearchMarks[Index];
var ContentPos = ( true === Mark.Start ? Mark.SearchResult.StartPos : Mark.SearchResult.EndPos );
var Depth = Mark.Depth;
if ( ContentPos.Data[Depth] >= Pos )
ContentPos.Data[Depth]++;
}
// Обновляем позиции для орфографии
var SpellingMarksCount = this.SpellingMarks.length;
for ( var Index = 0; Index < SpellingMarksCount; Index++ )
{
var Mark = this.SpellingMarks[Index];
var ContentPos = ( true === Mark.Start ? Mark.Element.StartPos : Mark.Element.EndPos );
var Depth = Mark.Depth;
if ( ContentPos.Data[Depth] >= Pos )
ContentPos.Data[Depth]++;
}
this.protected_UpdateSpellChecking();
this.private_UpdateTrackRevisionOnChangeContent(true);
// Обновляем позиции меток совместного редактирования
this.CollaborativeMarks.Update_OnAdd( Pos );
// Отмечаем, что надо перемерить элементы в данном ране
this.RecalcInfo.Measure = true;
};
ParaRun.prototype.Remove_FromContent = function(Pos, Count, UpdatePosition)
{
// Получим массив удаляемых элементов
var DeletedItems = this.Content.slice( Pos, Pos + Count );
History.Add(new CChangesRunRemoveItem(this, Pos, DeletedItems));
this.Content.splice( Pos, Count );
if (true === UpdatePosition)
this.private_UpdatePositionsOnRemove(Pos, Count);
// Обновляем позиции в NearestPos
var NearPosLen = this.NearPosArray.length;
for ( var Index = 0; Index < NearPosLen; Index++ )
{
var RunNearPos = this.NearPosArray[Index];
var ContentPos = RunNearPos.NearPos.ContentPos;
var Depth = RunNearPos.Depth;
if ( ContentPos.Data[Depth] > Pos + Count )
ContentPos.Data[Depth] -= Count;
else if ( ContentPos.Data[Depth] > Pos )
ContentPos.Data[Depth] = Math.max( 0 , Pos );
}
// Обновляем позиции в поиске
var SearchMarksCount = this.SearchMarks.length;
for ( var Index = 0; Index < SearchMarksCount; Index++ )
{
var Mark = this.SearchMarks[Index];
var ContentPos = ( true === Mark.Start ? Mark.SearchResult.StartPos : Mark.SearchResult.EndPos );
var Depth = Mark.Depth;
if ( ContentPos.Data[Depth] > Pos + Count )
ContentPos.Data[Depth] -= Count;
else if ( ContentPos.Data[Depth] > Pos )
ContentPos.Data[Depth] = Math.max( 0 , Pos );
}
// Обновляем позиции для орфографии
var SpellingMarksCount = this.SpellingMarks.length;
for ( var Index = 0; Index < SpellingMarksCount; Index++ )
{
var Mark = this.SpellingMarks[Index];
var ContentPos = ( true === Mark.Start ? Mark.Element.StartPos : Mark.Element.EndPos );
var Depth = Mark.Depth;
if ( ContentPos.Data[Depth] > Pos + Count )
ContentPos.Data[Depth] -= Count;
else if ( ContentPos.Data[Depth] > Pos )
ContentPos.Data[Depth] = Math.max( 0 , Pos );
}
this.protected_UpdateSpellChecking();
this.private_UpdateTrackRevisionOnChangeContent(true);
// Обновляем позиции меток совместного редактирования
this.CollaborativeMarks.Update_OnRemove( Pos, Count );
// Отмечаем, что надо перемерить элементы в данном ране
this.RecalcInfo.Measure = true;
};
ParaRun.prototype.Concat_ToContent = function(NewItems)
{
var StartPos = this.Content.length;
this.Content = this.Content.concat( NewItems );
History.Add(new CChangesRunAddItem(this, StartPos, NewItems, false));
this.private_UpdateTrackRevisionOnChangeContent(true);
// Отмечаем, что надо перемерить элементы в данном ране
this.RecalcInfo.Measure = true;
};
// Определим строку и отрезок текущей позиции
ParaRun.prototype.Get_CurrentParaPos = function()
{
var Pos = this.State.ContentPos;
if (-1 === this.StartLine)
return new CParaPos(-1, -1, -1, -1);
var CurLine = 0;
var CurRange = 0;
var LinesCount = this.protected_GetLinesCount();
for (; CurLine < LinesCount; CurLine++)
{
var RangesCount = this.protected_GetRangesCount(CurLine);
for (CurRange = 0; CurRange < RangesCount; CurRange++)
{
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
if ( Pos < EndPos && Pos >= StartPos )
return new CParaPos((CurLine === 0 ? CurRange + this.StartRange : CurRange), CurLine + this.StartLine, 0, 0);
}
}
// Значит курсор стоит в самом конце, поэтому посылаем последний отрезок
if(this.Type == para_Math_Run && LinesCount > 1)
{
var Line = LinesCount - 1,
Range = this.protected_GetRangesCount(LinesCount - 1) - 1;
StartPos = this.protected_GetRangeStartPos(Line, Range);
EndPos = this.protected_GetRangeEndPos(Line, Range);
// учтем, что в одной строке в формуле может быть только один Range
while(StartPos == EndPos && Line > 0 && this.Content.length !== 0) // == this.Content.length, т.к. последний Range
{
Line--;
StartPos = this.protected_GetRangeStartPos(Line, Range);
EndPos = this.protected_GetRangeEndPos(Line, Range);
}
return new CParaPos((this.protected_GetRangesCount(Line) - 1), Line + this.StartLine, 0, 0 );
}
return new CParaPos((LinesCount <= 1 ? this.protected_GetRangesCount(0) - 1 + this.StartRange : this.protected_GetRangesCount(LinesCount - 1) - 1), LinesCount - 1 + this.StartLine, 0, 0 );
};
ParaRun.prototype.Get_ParaPosByContentPos = function(ContentPos, Depth)
{
if (this.StartRange < 0 || this.StartLine < 0)
return new CParaPos(0, 0, 0, 0);
var Pos = ContentPos.Get(Depth);
var CurLine = 0;
var CurRange = 0;
var LinesCount = this.protected_GetLinesCount();
if (LinesCount <= 0)
return new CParaPos(0, 0, 0, 0);
for (; CurLine < LinesCount; CurLine++)
{
var RangesCount = this.protected_GetRangesCount(CurLine);
for (CurRange = 0; CurRange < RangesCount; CurRange++)
{
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
var bUpdateMathRun = Pos == EndPos && StartPos == EndPos && EndPos == this.Content.length && this.Type == para_Math_Run; // для para_Run позиция может быть после последнего элемента (пример: Run, за ним идет мат объект)
if (Pos < EndPos && Pos >= StartPos || bUpdateMathRun)
return new CParaPos((CurLine === 0 ? CurRange + this.StartRange : CurRange), CurLine + this.StartLine, 0, 0);
}
}
return new CParaPos((LinesCount === 1 ? this.protected_GetRangesCount(0) - 1 + this.StartRange : this.protected_GetRangesCount(0) - 1), LinesCount - 1 + this.StartLine, 0, 0);
};
ParaRun.prototype.Recalculate_CurPos = function(X, Y, CurrentRun, _CurRange, _CurLine, CurPage, UpdateCurPos, UpdateTarget, ReturnTarget)
{
var Para = this.Paragraph;
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
var Pos = StartPos;
var _EndPos = ( true === CurrentRun ? Math.min( EndPos, this.State.ContentPos ) : EndPos );
if(this.Type == para_Math_Run)
{
var Lng = this.Content.length;
Pos = _EndPos;
var LocParaMath = this.ParaMath.GetLinePosition(_CurLine, _CurRange);
X = LocParaMath.x;
Y = LocParaMath.y;
var MATH_Y = Y;
var loc;
if(Lng == 0)
{
X += this.pos.x;
Y += this.pos.y;
}
else if(Pos < EndPos)
{
loc = this.Content[Pos].GetLocationOfLetter();
X += loc.x;
Y += loc.y;
}
else if(!(StartPos == EndPos)) // исключаем этот случай StartPos == EndPos && EndPos == Pos, это возможно когда конец Run находится в начале строки, при этом ни одна из букв этого Run не входит в эту строку
{
var Letter = this.Content[Pos - 1];
loc = Letter.GetLocationOfLetter();
X += loc.x + Letter.Get_WidthVisible();
Y += loc.y;
}
}
else
{
for ( ; Pos < _EndPos; Pos++ )
{
var Item = this.Content[Pos];
var ItemType = Item.Type;
if (para_Drawing === ItemType && drawing_Inline !== Item.DrawingType)
continue;
X += Item.Get_WidthVisible();
}
}
var bNearFootnoteReference = this.private_IsCurPosNearFootnoteReference();
if ( true === CurrentRun && Pos === this.State.ContentPos )
{
if ( true === UpdateCurPos )
{
// Обновляем позицию курсора в параграфе
Para.CurPos.X = X;
Para.CurPos.Y = Y;
Para.CurPos.PagesPos = CurPage;
if ( true === UpdateTarget )
{
var CurTextPr = this.Get_CompiledPr(false);
var dFontKoef = bNearFootnoteReference ? 1 : CurTextPr.Get_FontKoef();
g_oTextMeasurer.SetTextPr(CurTextPr, this.Paragraph.Get_Theme());
g_oTextMeasurer.SetFontSlot(fontslot_ASCII, dFontKoef);
var Height = g_oTextMeasurer.GetHeight();
var Descender = Math.abs(g_oTextMeasurer.GetDescender());
var Ascender = Height - Descender;
Para.DrawingDocument.SetTargetSize( Height );
var RGBA;
Para.DrawingDocument.UpdateTargetTransform(Para.Get_ParentTextTransform());
if(CurTextPr.TextFill)
{
CurTextPr.TextFill.check(Para.Get_Theme(), Para.Get_ColorMap());
var oColor = CurTextPr.TextFill.getRGBAColor();
Para.DrawingDocument.SetTargetColor( oColor.R, oColor.G, oColor.B );
}
else if(CurTextPr.Unifill)
{
CurTextPr.Unifill.check(Para.Get_Theme(), Para.Get_ColorMap());
RGBA = CurTextPr.Unifill.getRGBAColor();
Para.DrawingDocument.SetTargetColor( RGBA.R, RGBA.G, RGBA.B );
}
else
{
if ( true === CurTextPr.Color.Auto )
{
// Выясним какая заливка у нашего текста
var Pr = Para.Get_CompiledPr();
var BgColor = undefined;
if ( undefined !== Pr.ParaPr.Shd && c_oAscShdNil !== Pr.ParaPr.Shd.Value )
{
if(Pr.ParaPr.Shd.Unifill)
{
Pr.ParaPr.Shd.Unifill.check(this.Paragraph.Get_Theme(), this.Paragraph.Get_ColorMap());
var RGBA = Pr.ParaPr.Shd.Unifill.getRGBAColor();
BgColor = new CDocumentColor(RGBA.R, RGBA.G, RGBA.B, false);
}
else
{
BgColor = Pr.ParaPr.Shd.Color;
}
}
else
{
// Нам надо выяснить заливку у родительского класса (возможно мы находимся в ячейке таблицы с забивкой)
BgColor = Para.Parent.Get_TextBackGroundColor();
if ( undefined !== CurTextPr.Shd && c_oAscShdNil !== CurTextPr.Shd.Value )
BgColor = CurTextPr.Shd.Get_Color( this.Paragraph );
}
// Определим автоцвет относительно заливки
var AutoColor = ( undefined != BgColor && false === BgColor.Check_BlackAutoColor() ? new CDocumentColor( 255, 255, 255, false ) : new CDocumentColor( 0, 0, 0, false ) );
Para.DrawingDocument.SetTargetColor( AutoColor.r, AutoColor.g, AutoColor.b );
}
else
Para.DrawingDocument.SetTargetColor( CurTextPr.Color.r, CurTextPr.Color.g, CurTextPr.Color.b );
}
var TargetY = Y - Ascender - CurTextPr.Position;
if (!bNearFootnoteReference)
{
switch (CurTextPr.VertAlign)
{
case AscCommon.vertalign_SubScript:
{
TargetY -= CurTextPr.FontSize * g_dKoef_pt_to_mm * vertalign_Koef_Sub;
break;
}
case AscCommon.vertalign_SuperScript:
{
TargetY -= CurTextPr.FontSize * g_dKoef_pt_to_mm * vertalign_Koef_Super;
break;
}
}
}
var PageAbs = Para.Get_AbsolutePage(CurPage);
// TODO: Тут делаем, чтобы курсор не выходил за границы буквицы. На самом деле, надо делать, чтобы
// курсор не выходил за границы строки, но для этого надо делать обрезку по строкам, а без нее
// такой вариант будет смотреться плохо.
if (para_Math_Run === this.Type && null !== this.Parent && true !== this.Parent.bRoot && this.Parent.bMath_OneLine)
{
var oBounds = this.Parent.Get_Bounds();
var __Y0 = TargetY, __Y1 = TargetY + Height;
// пока так
// TO DO : переделать
var YY = this.Parent.pos.y - this.Parent.size.ascent,
XX = this.Parent.pos.x;
var ___Y0 = MATH_Y + YY - 0.2 * oBounds.H;
var ___Y1 = MATH_Y + YY + 1.4 * oBounds.H;
__Y0 = Math.max( __Y0, ___Y0 );
__Y1 = Math.min( __Y1, ___Y1 );
Para.DrawingDocument.SetTargetSize( __Y1 - __Y0 );
Para.DrawingDocument.UpdateTarget( X, __Y0, PageAbs );
}
else if ( undefined != Para.Get_FramePr() )
{
var __Y0 = TargetY, __Y1 = TargetY + Height;
var ___Y0 = Para.Pages[CurPage].Y + Para.Lines[CurLine].Top;
var ___Y1 = Para.Pages[CurPage].Y + Para.Lines[CurLine].Bottom;
__Y0 = Math.max( __Y0, ___Y0 );
__Y1 = Math.min( __Y1, ___Y1 );
Para.DrawingDocument.SetTargetSize( __Y1 - __Y0 );
Para.DrawingDocument.UpdateTarget( X, __Y0, PageAbs );
}
else
{
Para.DrawingDocument.UpdateTarget(X, TargetY, PageAbs);
}
}
}
if ( true === ReturnTarget )
{
var CurTextPr = this.Get_CompiledPr(false);
var dFontKoef = bNearFootnoteReference ? 1 : CurTextPr.Get_FontKoef();
g_oTextMeasurer.SetTextPr(CurTextPr, this.Paragraph.Get_Theme());
g_oTextMeasurer.SetFontSlot(fontslot_ASCII, dFontKoef);
var Height = g_oTextMeasurer.GetHeight();
var Descender = Math.abs(g_oTextMeasurer.GetDescender());
var Ascender = Height - Descender;
var TargetY = Y - Ascender - CurTextPr.Position;
if (!bNearFootnoteReference)
{
switch (CurTextPr.VertAlign)
{
case AscCommon.vertalign_SubScript:
{
TargetY -= CurTextPr.FontSize * g_dKoef_pt_to_mm * vertalign_Koef_Sub;
break;
}
case AscCommon.vertalign_SuperScript:
{
TargetY -= CurTextPr.FontSize * g_dKoef_pt_to_mm * vertalign_Koef_Super;
break;
}
}
}
return { X : X, Y : TargetY, Height : Height, PageNum : Para.Get_AbsolutePage(CurPage), Internal : { Line : CurLine, Page : CurPage, Range : CurRange } };
}
else
return { X : X, Y : Y, PageNum : Para.Get_AbsolutePage(CurPage), Internal : { Line : CurLine, Page : CurPage, Range : CurRange } };
}
return { X : X, Y: Y, PageNum : Para.Get_AbsolutePage(CurPage), Internal : { Line : CurLine, Page : CurPage, Range : CurRange } };
};
// Проверяем, произошло ли простейшее изменение (набор или удаление текста)
ParaRun.prototype.Is_SimpleChanges = function(Changes)
{
var ParaPos = null;
var Count = Changes.length;
for (var Index = 0; Index < Count; Index++)
{
var Data = Changes[Index].Data;
if (undefined === Data.Items || 1 !== Data.Items.length)
return false;
var Type = Data.Type;
var Item = Data.Items[0];
if (undefined === Item)
return false;
if (AscDFH.historyitem_ParaRun_AddItem !== Type && AscDFH.historyitem_ParaRun_RemoveItem !== Type)
return false;
// Добавление/удаление картинок может изменить размер строки. Добавление/удаление переноса строки/страницы/колонки
// нельзя обсчитывать функцией Recalculate_Fast.
// TODO: Но на самом деле стоило бы сделать нормальную проверку на высоту строки в функции Recalculate_Fast
var ItemType = Item.Type;
if (para_Drawing === ItemType || para_NewLine === ItemType || para_FootnoteRef === ItemType || para_FootnoteReference === ItemType)
return false;
// Проверяем, что все изменения произошли в одном и том же отрезке
var CurParaPos = this.Get_SimpleChanges_ParaPos([Changes[Index]]);
if (null === CurParaPos)
return false;
if (null === ParaPos)
ParaPos = CurParaPos;
else if (ParaPos.Line !== CurParaPos.Line || ParaPos.Range !== CurParaPos.Range)
return false;
}
return true;
};
/**
* Проверяем произошло ли простое изменение параграфа, сейчас главное, чтобы это было не добавлениe/удаление картинки
* или ссылки на сноску. На вход приходит либо массив изменений, либо одно изменение (можно не в массиве).
*/
ParaRun.prototype.Is_ParagraphSimpleChanges = function(_Changes)
{
var Changes = _Changes;
if (!_Changes.length)
Changes = [_Changes];
var ChangesCount = Changes.length;
for (var ChangesIndex = 0; ChangesIndex < ChangesCount; ChangesIndex++)
{
var Data = Changes[ChangesIndex].Data;
var ChangeType = Data.Type;
if (AscDFH.historyitem_ParaRun_AddItem === ChangeType || AscDFH.historyitem_ParaRun_RemoveItem === ChangeType)
{
for (var ItemIndex = 0, ItemsCount = Data.Items.length; ItemIndex < ItemsCount; ItemIndex++)
{
var Item = Data.Items[ItemIndex];
if (para_Drawing === Item.Type || para_FootnoteReference === Item.Type)
return false;
}
}
}
return true;
};
// Возвращаем строку и отрезок, в котором произошли простейшие изменения
ParaRun.prototype.Get_SimpleChanges_ParaPos = function(Changes)
{
var Change = Changes[0].Data;
var Type = Changes[0].Data.Type;
var Pos = Change.Pos;
var CurLine = 0;
var CurRange = 0;
var LinesCount = this.protected_GetLinesCount();
for (; CurLine < LinesCount; CurLine++)
{
var RangesCount = this.protected_GetRangesCount(CurLine);
for (CurRange = 0; CurRange < RangesCount; CurRange++)
{
var RangeStartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var RangeEndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
if ( ( AscDFH.historyitem_ParaRun_AddItem === Type && Pos < RangeEndPos && Pos >= RangeStartPos ) || ( AscDFH.historyitem_ParaRun_RemoveItem === Type && Pos < RangeEndPos && Pos >= RangeStartPos ) || ( AscDFH.historyitem_ParaRun_RemoveItem === Type && Pos >= RangeEndPos && CurLine === LinesCount - 1 && CurRange === RangesCount - 1 ) )
{
// Если отрезок остается пустым, тогда надо все заново пересчитывать
if ( RangeStartPos === RangeEndPos )
return null;
return new CParaPos( ( CurLine === 0 ? CurRange + this.StartRange : CurRange ), CurLine + this.StartLine, 0, 0 );
}
}
}
// Если отрезок остается пустым, тогда надо все заново пересчитывать
if (this.protected_GetRangeStartPos(0, 0) === this.protected_GetRangeEndPos(0, 0))
return null;
return new CParaPos( this.StartRange, this.StartLine, 0, 0 );
};
ParaRun.prototype.Split = function (ContentPos, Depth)
{
var CurPos = ContentPos.Get(Depth);
return this.Split2( CurPos );
};
ParaRun.prototype.Split2 = function(CurPos, Parent, ParentPos)
{
History.Add(new CChangesRunOnStartSplit(this, CurPos));
AscCommon.CollaborativeEditing.OnStart_SplitRun(this, CurPos);
// Если задается Parent и ParentPos, тогда ран автоматически добавляется в родительский класс
var UpdateParent = (undefined !== Parent && undefined !== ParentPos && this === Parent.Content[ParentPos] ? true : false);
var UpdateSelection = (true === UpdateParent && true === Parent.IsSelectionUse() && true === this.IsSelectionUse() ? true : false);
// Создаем новый ран
var bMathRun = this.Type == para_Math_Run;
var NewRun = new ParaRun(this.Paragraph, bMathRun);
// Копируем настройки
NewRun.Set_Pr(this.Pr.Copy(true));
NewRun.Set_ReviewType(this.ReviewType);
NewRun.CollPrChangeMine = this.CollPrChangeMine;
NewRun.CollPrChangeOther = this.CollPrChangeOther;
if(bMathRun)
NewRun.Set_MathPr(this.MathPrp.Copy());
// TODO: Как только избавимся от para_End переделать тут
// Проверим, если наш ран содержит para_End, тогда мы должны para_End переметить в правый ран
var CheckEndPos = -1;
var CheckEndPos2 = Math.min( CurPos, this.Content.length );
for ( var Pos = 0; Pos < CheckEndPos2; Pos++ )
{
if ( para_End === this.Content[Pos].Type )
{
CheckEndPos = Pos;
break;
}
}
if ( -1 !== CheckEndPos )
CurPos = CheckEndPos;
var ParentOldSelectionStartPos, ParentOldSelectionEndPos, OldSelectionStartPos, OldSelectionEndPos;
if (true === UpdateSelection)
{
ParentOldSelectionStartPos = Parent.Selection.StartPos;
ParentOldSelectionEndPos = Parent.Selection.EndPos;
OldSelectionStartPos = this.Selection.StartPos;
OldSelectionEndPos = this.Selection.EndPos;
}
if (true === UpdateParent)
{
Parent.Add_ToContent(ParentPos + 1, NewRun);
// Обновим массив NearPosArray
for (var Index = 0, Count = this.NearPosArray.length; Index < Count; Index++)
{
var RunNearPos = this.NearPosArray[Index];
var ContentPos = RunNearPos.NearPos.ContentPos;
var Depth = RunNearPos.Depth;
var Pos = ContentPos.Get(Depth);
if (Pos >= CurPos)
{
ContentPos.Update2(Pos - CurPos, Depth);
ContentPos.Update2(ParentPos + 1, Depth - 1);
this.NearPosArray.splice(Index, 1);
Count--;
Index--;
NewRun.NearPosArray.push(RunNearPos);
if (this.Paragraph)
{
for (var ParaIndex = 0, ParaCount = this.Paragraph.NearPosArray.length; ParaIndex < ParaCount; ParaIndex++)
{
var ParaNearPos = this.Paragraph.NearPosArray[ParaIndex];
if (ParaNearPos.Classes[ParaNearPos.Classes.length - 1] === this)
ParaNearPos.Classes[ParaNearPos.Classes.length - 1] = NewRun;
}
}
}
}
}
// Разделяем содержимое по ранам
NewRun.Concat_ToContent( this.Content.slice(CurPos) );
this.Remove_FromContent( CurPos, this.Content.length - CurPos, true );
// Если были точки орфографии, тогда переместим их в новый ран
var SpellingMarksCount = this.SpellingMarks.length;
for ( var Index = 0; Index < SpellingMarksCount; Index++ )
{
var Mark = this.SpellingMarks[Index];
var MarkPos = ( true === Mark.Start ? Mark.Element.StartPos.Get(Mark.Depth) : Mark.Element.EndPos.Get(Mark.Depth) );
if ( MarkPos >= CurPos )
{
var MarkElement = Mark.Element;
if ( true === Mark.Start )
{
MarkElement.StartPos.Data[Mark.Depth] -= CurPos;
}
else
{
MarkElement.EndPos.Data[Mark.Depth] -= CurPos;
}
NewRun.SpellingMarks.push( Mark );
this.SpellingMarks.splice( Index, 1 );
SpellingMarksCount--;
Index--;
}
}
if (true === UpdateSelection)
{
if (ParentOldSelectionStartPos <= ParentPos && ParentPos <= ParentOldSelectionEndPos)
Parent.Selection.EndPos = ParentOldSelectionEndPos + 1;
else if (ParentOldSelectionEndPos <= ParentPos && ParentPos <= ParentOldSelectionStartPos)
Parent.Selection.StartPos = ParentOldSelectionStartPos + 1;
if (OldSelectionStartPos <= CurPos && CurPos <= OldSelectionEndPos)
{
this.Selection.EndPos = this.Content.length;
NewRun.Selection.Use = true;
NewRun.Selection.StartPos = 0;
NewRun.Selection.EndPos = OldSelectionEndPos - CurPos;
}
else if (OldSelectionEndPos <= CurPos && CurPos <= OldSelectionStartPos)
{
this.Selection.StartPos = this.Content.length;
NewRun.Selection.Use = true;
NewRun.Selection.EndPos = 0;
NewRun.Selection.StartPos = OldSelectionStartPos - CurPos;
}
}
History.Add(new CChangesRunOnEndSplit(this, NewRun));
AscCommon.CollaborativeEditing.OnEnd_SplitRun(NewRun);
return NewRun;
};
ParaRun.prototype.Check_NearestPos = function(ParaNearPos, Depth)
{
var RunNearPos = new CParagraphElementNearPos();
RunNearPos.NearPos = ParaNearPos.NearPos;
RunNearPos.Depth = Depth;
this.NearPosArray.push( RunNearPos );
ParaNearPos.Classes.push( this );
};
ParaRun.prototype.Get_DrawingObjectRun = function(Id)
{
var ContentLen = this.Content.length;
for ( var CurPos = 0; CurPos < ContentLen; CurPos++ )
{
var Element = this.Content[CurPos];
if ( para_Drawing === Element.Type && Id === Element.Get_Id() )
return this;
}
return null;
};
ParaRun.prototype.Get_DrawingObjectContentPos = function(Id, ContentPos, Depth)
{
var ContentLen = this.Content.length;
for ( var CurPos = 0; CurPos < ContentLen; CurPos++ )
{
var Element = this.Content[CurPos];
if ( para_Drawing === Element.Type && Id === Element.Get_Id() )
{
ContentPos.Update( CurPos, Depth );
return true;
}
}
return false;
};
ParaRun.prototype.Get_DrawingObjectSimplePos = function(Id)
{
var ContentLen = this.Content.length;
for (var CurPos = 0; CurPos < ContentLen; CurPos++)
{
var Element = this.Content[CurPos];
if (para_Drawing === Element.Type && Id === Element.Get_Id())
return CurPos;
}
return -1;
};
ParaRun.prototype.Remove_DrawingObject = function(Id)
{
var ContentLen = this.Content.length;
for ( var CurPos = 0; CurPos < ContentLen; CurPos++ )
{
var Element = this.Content[CurPos];
if ( para_Drawing === Element.Type && Id === Element.Get_Id() )
{
var TrackRevisions = null;
if (this.Paragraph && this.Paragraph.LogicDocument && this.Paragraph.bFromDocument)
TrackRevisions = this.Paragraph.LogicDocument.Is_TrackRevisions();
if (true === TrackRevisions)
{
var ReviewType = this.Get_ReviewType();
if (reviewtype_Common === ReviewType)
{
// Разбиваем ран на две части
var StartPos = CurPos;
var EndPos = CurPos + 1;
var Parent = this.Get_Parent();
var RunPos = this.private_GetPosInParent(Parent);
if (-1 !== RunPos && Parent)
{
var DeletedRun = null;
if (StartPos <= 0 && EndPos >= this.Content.length)
DeletedRun = this;
else if (StartPos <= 0)
{
this.Split2(EndPos, Parent, RunPos);
DeletedRun = this;
}
else if (EndPos >= this.Content.length)
{
DeletedRun = this.Split2(StartPos, Parent, RunPos);
}
else
{
this.Split2(EndPos, Parent, RunPos);
DeletedRun = this.Split2(StartPos, Parent, RunPos);
}
DeletedRun.Set_ReviewType(reviewtype_Remove);
}
}
else if (reviewtype_Add === ReviewType)
{
this.Remove_FromContent(CurPos, 1, true);
}
else if (reviewtype_Remove === ReviewType)
{
// Ничего не делаем
}
}
else
{
this.Remove_FromContent(CurPos, 1, true);
}
return;
}
}
};
ParaRun.prototype.Get_Layout = function(DrawingLayout, UseContentPos, ContentPos, Depth)
{
var CurLine = DrawingLayout.Line - this.StartLine;
var CurRange = ( 0 === CurLine ? DrawingLayout.Range - this.StartRange : DrawingLayout.Range );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
var CurContentPos = ( true === UseContentPos ? ContentPos.Get(Depth) : -1 );
var CurPos = StartPos;
for ( ; CurPos < EndPos; CurPos++ )
{
if ( CurContentPos === CurPos )
break;
var Item = this.Content[CurPos];
var ItemType = Item.Type;
var WidthVisible = Item.Get_WidthVisible();
switch ( ItemType )
{
case para_Text:
case para_Space:
case para_PageNum:
case para_PageCount:
{
DrawingLayout.LastW = WidthVisible;
break;
}
case para_Drawing:
{
if ( true === Item.Is_Inline() || true === DrawingLayout.Paragraph.Parent.Is_DrawingShape() )
{
DrawingLayout.LastW = WidthVisible;
}
break;
}
}
DrawingLayout.X += WidthVisible;
}
if (CurContentPos === CurPos)
DrawingLayout.Layout = true;
};
ParaRun.prototype.Get_NextRunElements = function(RunElements, UseContentPos, Depth)
{
var StartPos = ( true === UseContentPos ? RunElements.ContentPos.Get(Depth) : 0 );
var ContentLen = this.Content.length;
for ( var CurPos = StartPos; CurPos < ContentLen; CurPos++ )
{
var Item = this.Content[CurPos];
if (RunElements.CheckType(Item.Type))
{
RunElements.Elements.push( Item );
RunElements.Count--;
if ( RunElements.Count <= 0 )
return;
}
}
};
ParaRun.prototype.Get_PrevRunElements = function(RunElements, UseContentPos, Depth)
{
var StartPos = ( true === UseContentPos ? RunElements.ContentPos.Get(Depth) - 1 : this.Content.length - 1 );
var ContentLen = this.Content.length;
for ( var CurPos = StartPos; CurPos >= 0; CurPos-- )
{
var Item = this.Content[CurPos];
var ItemType = Item.Type;
if (RunElements.CheckType(Item.Type))
{
RunElements.Elements.push( Item );
RunElements.Count--;
if ( RunElements.Count <= 0 )
return;
}
}
};
ParaRun.prototype.CollectDocumentStatistics = function(ParaStats)
{
var Count = this.Content.length;
for (var Index = 0; Index < Count; Index++)
{
var Item = this.Content[Index];
var ItemType = Item.Type;
var bSymbol = false;
var bSpace = false;
var bNewWord = false;
if ((para_Text === ItemType && false === Item.Is_NBSP()) || (para_PageNum === ItemType || para_PageCount === ItemType))
{
if (false === ParaStats.Word)
bNewWord = true;
bSymbol = true;
bSpace = false;
ParaStats.Word = true;
ParaStats.EmptyParagraph = false;
}
else if ((para_Text === ItemType && true === Item.Is_NBSP()) || para_Space === ItemType || para_Tab === ItemType)
{
bSymbol = true;
bSpace = true;
ParaStats.Word = false;
}
if (true === bSymbol)
ParaStats.Stats.Add_Symbol(bSpace);
if (true === bNewWord)
ParaStats.Stats.Add_Word();
}
};
ParaRun.prototype.Create_FontMap = function(Map)
{
// для Math_Para_Pun argSize учитывается, когда мержатся текстовые настройки в Internal_Compile_Pr()
if ( undefined !== this.Paragraph && null !== this.Paragraph )
{
var TextPr;
var FontSize, FontSizeCS;
if(this.Type === para_Math_Run)
{
TextPr = this.Get_CompiledPr(false);
FontSize = TextPr.FontSize;
FontSizeCS = TextPr.FontSizeCS;
if(null !== this.Parent && undefined !== this.Parent && null !== this.Parent.ParaMath && undefined !== this.Parent.ParaMath)
{
TextPr.FontSize = this.Math_GetRealFontSize(TextPr.FontSize);
TextPr.FontSizeCS = this.Math_GetRealFontSize(TextPr.FontSizeCS);
}
}
else
TextPr = this.Get_CompiledPr(false);
TextPr.Document_CreateFontMap(Map, this.Paragraph.Get_Theme().themeElements.fontScheme);
var Count = this.Content.length;
for (var Index = 0; Index < Count; Index++)
{
var Item = this.Content[Index];
if (para_Drawing === Item.Type)
Item.documentCreateFontMap(Map);
else if (para_FootnoteReference === Item.Type)
Item.CreateDocumentFontMap(Map);
}
if(this.Type === para_Math_Run)
{
TextPr.FontSize = FontSize;
TextPr.FontSizeCS = FontSizeCS;
}
}
};
ParaRun.prototype.Get_AllFontNames = function(AllFonts)
{
this.Pr.Document_Get_AllFontNames( AllFonts );
var Count = this.Content.length;
for (var Index = 0; Index < Count; Index++)
{
var Item = this.Content[Index];
if ( para_Drawing === Item.Type )
Item.documentGetAllFontNames( AllFonts );
}
};
ParaRun.prototype.GetSelectedText = function(bAll, bClearText, oPr)
{
var StartPos = 0;
var EndPos = 0;
if ( true === bAll )
{
StartPos = 0;
EndPos = this.Content.length;
}
else if ( true === this.Selection.Use )
{
StartPos = this.State.Selection.StartPos;
EndPos = this.State.Selection.EndPos;
if ( StartPos > EndPos )
{
var Temp = EndPos;
EndPos = StartPos;
StartPos = Temp;
}
}
var Str = "";
for ( var Pos = StartPos; Pos < EndPos; Pos++ )
{
var Item = this.Content[Pos];
var ItemType = Item.Type;
switch ( ItemType )
{
case para_Drawing:
case para_Numbering:
case para_PresentationNumbering:
case para_PageNum:
case para_PageCount:
{
if ( true === bClearText )
return null;
break;
}
case para_Text :
{
Str += AscCommon.encodeSurrogateChar(Item.Value);
break;
}
case para_Space:
case para_Tab : Str += " "; break;
case para_End:
{
if (oPr && true === oPr.NewLineParagraph)
{
Str += '\r\n';
}
break;
}
}
}
return Str;
};
ParaRun.prototype.Get_SelectionDirection = function()
{
if (true !== this.Selection.Use)
return 0;
if (this.Selection.StartPos <= this.Selection.EndPos)
return 1;
return -1;
};
ParaRun.prototype.Can_AddDropCap = function()
{
var Count = this.Content.length;
for ( var Pos = 0; Pos < Count; Pos++ )
{
var Item = this.Content[Pos];
var ItemType = Item.Type;
switch ( ItemType )
{
case para_Text:
return true;
case para_Space:
case para_Tab:
case para_PageNum:
case para_PageCount:
return false;
}
}
return null;
};
ParaRun.prototype.Get_TextForDropCap = function(DropCapText, UseContentPos, ContentPos, Depth)
{
var EndPos = ( true === UseContentPos ? ContentPos.Get(Depth) : this.Content.length );
for ( var Pos = 0; Pos < EndPos; Pos++ )
{
var Item = this.Content[Pos];
var ItemType = Item.Type;
if ( true === DropCapText.Check )
{
if (para_Space === ItemType || para_Tab === ItemType || para_PageNum === ItemType || para_PageCount === ItemType || para_Drawing === ItemType || para_End === ItemType)
{
DropCapText.Mixed = true;
return;
}
}
else
{
if ( para_Text === ItemType )
{
DropCapText.Runs.push(this);
DropCapText.Text.push(Item);
this.Remove_FromContent( Pos, 1, true );
Pos--;
EndPos--;
if ( true === DropCapText.Mixed )
return;
}
}
}
};
ParaRun.prototype.Get_StartTabsCount = function(TabsCounter)
{
var ContentLen = this.Content.length;
for ( var Pos = 0; Pos < ContentLen; Pos++ )
{
var Item = this.Content[Pos];
var ItemType = Item.Type;
if ( para_Tab === ItemType )
{
TabsCounter.Count++;
TabsCounter.Pos.push( Pos );
}
else if ( para_Text === ItemType || para_Space === ItemType || (para_Drawing === ItemType && true === Item.Is_Inline() ) || para_PageNum === ItemType || para_PageCount === ItemType || para_Math === ItemType )
return false;
}
return true;
};
ParaRun.prototype.Remove_StartTabs = function(TabsCounter)
{
var ContentLen = this.Content.length;
for ( var Pos = 0; Pos < ContentLen; Pos++ )
{
var Item = this.Content[Pos];
var ItemType = Item.Type;
if ( para_Tab === ItemType )
{
this.Remove_FromContent( Pos, 1, true );
TabsCounter.Count--;
Pos--;
ContentLen--;
}
else if ( para_Text === ItemType || para_Space === ItemType || (para_Drawing === ItemType && true === Item.Is_Inline() ) || para_PageNum === ItemType || para_PageCount === ItemType || para_Math === ItemType )
return false;
}
return true;
};
//-----------------------------------------------------------------------------------
// Функции пересчета
//-----------------------------------------------------------------------------------
// Пересчитываем размеры всех элементов
ParaRun.prototype.Recalculate_MeasureContent = function()
{
if ( false === this.RecalcInfo.Measure )
return;
var Pr = this.Get_CompiledPr(false);
var Theme = this.Paragraph.Get_Theme();
g_oTextMeasurer.SetTextPr(Pr, Theme);
g_oTextMeasurer.SetFontSlot(fontslot_ASCII);
// Запрашиваем текущие метрики шрифта, под TextAscent мы будем понимать ascent + linegap(которые записаны в шрифте)
this.TextHeight = g_oTextMeasurer.GetHeight();
this.TextDescent = Math.abs( g_oTextMeasurer.GetDescender() );
this.TextAscent = this.TextHeight - this.TextDescent;
this.TextAscent2 = g_oTextMeasurer.GetAscender();
this.YOffset = Pr.Position;
var ContentLength = this.Content.length;
var InfoMathText;
if(para_Math_Run == this.Type)
{
var InfoTextPr =
{
TextPr: Pr,
ArgSize: this.Parent.Compiled_ArgSz.value,
bNormalText: this.IsNormalText(),
bEqArray: this.Parent.IsEqArray()
};
InfoMathText = new CMathInfoTextPr(InfoTextPr);
}
for ( var Pos = 0; Pos < ContentLength; Pos++ )
{
var Item = this.Content[Pos];
var ItemType = Item.Type;
if (para_Drawing === ItemType)
{
Item.Parent = this.Paragraph;
Item.DocumentContent = this.Paragraph.Parent;
Item.DrawingDocument = this.Paragraph.Parent.DrawingDocument;
}
// TODO: Как только избавимся от para_End переделать здесь
if ( para_End === ItemType )
{
var EndTextPr = this.Paragraph.Get_CompiledPr2(false).TextPr.Copy();
EndTextPr.Merge(this.Paragraph.TextPr.Value);
g_oTextMeasurer.SetTextPr( EndTextPr, this.Paragraph.Get_Theme());
Item.Measure( g_oTextMeasurer, EndTextPr );
continue;
}
Item.Measure( g_oTextMeasurer, Pr, InfoMathText, this);
if (para_Drawing === Item.Type)
{
// После автофигур надо заново выставлять настройки
g_oTextMeasurer.SetTextPr(Pr, Theme);
g_oTextMeasurer.SetFontSlot(fontslot_ASCII);
}
}
this.RecalcInfo.Recalc = true;
this.RecalcInfo.Measure = false;
};
ParaRun.prototype.Recalculate_Measure2 = function(Metrics)
{
var TAscent = Metrics.Ascent;
var TDescent = Metrics.Descent;
var Count = this.Content.length;
for ( var Index = 0; Index < Count; Index++ )
{
var Item = this.Content[Index];
var ItemType = Item.Type;
if ( para_Text === ItemType )
{
var Temp = g_oTextMeasurer.Measure2(String.fromCharCode(Item.Value));
if ( null === TAscent || TAscent < Temp.Ascent )
TAscent = Temp.Ascent;
if ( null === TDescent || TDescent > Temp.Ascent - Temp.Height )
TDescent = Temp.Ascent - Temp.Height;
}
}
Metrics.Ascent = TAscent;
Metrics.Descent = TDescent;
};
ParaRun.prototype.Recalculate_Range = function(PRS, ParaPr, Depth)
{
if ( this.Paragraph !== PRS.Paragraph )
{
this.Paragraph = PRS.Paragraph;
this.RecalcInfo.TextPr = true;
this.RecalcInfo.Measure = true;
this.protected_UpdateSpellChecking();
}
// Сначала измеряем элементы (можно вызывать каждый раз, внутри разруливается, чтобы измерялось 1 раз)
this.Recalculate_MeasureContent();
var CurLine = PRS.Line - this.StartLine;
var CurRange = ( 0 === CurLine ? PRS.Range - this.StartRange : PRS.Range );
// Если мы рассчитываем первый отрезок в первой строке, тогда нам нужно обновить информацию о нумерации
if ( 0 === CurRange && 0 === CurLine )
{
var PrevRecalcInfo = PRS.RunRecalcInfoLast;
// Либо до этого ничего не было (изначально первая строка и первый отрезок), либо мы заново пересчитываем
// первую строку и первый отрезок (из-за обтекания, например).
if ( null === PrevRecalcInfo )
this.RecalcInfo.NumberingAdd = true;
else
this.RecalcInfo.NumberingAdd = PrevRecalcInfo.NumberingAdd;
this.RecalcInfo.NumberingUse = false;
this.RecalcInfo.NumberingItem = null;
}
// Сохраняем ссылку на информацию пересчета данного рана
PRS.RunRecalcInfoLast = this.RecalcInfo;
// Добавляем информацию о новом отрезке
var RangeStartPos = this.protected_AddRange(CurLine, CurRange);
var RangeEndPos = 0;
var Para = PRS.Paragraph;
var MoveToLBP = PRS.MoveToLBP;
var NewRange = PRS.NewRange;
var ForceNewPage = PRS.ForceNewPage;
var NewPage = PRS.NewPage;
var End = PRS.End;
var Word = PRS.Word;
var StartWord = PRS.StartWord;
var FirstItemOnLine = PRS.FirstItemOnLine;
var EmptyLine = PRS.EmptyLine;
var RangesCount = PRS.RangesCount;
var SpaceLen = PRS.SpaceLen;
var WordLen = PRS.WordLen;
var X = PRS.X;
var XEnd = PRS.XEnd;
var ParaLine = PRS.Line;
var ParaRange = PRS.Range;
var bMathWordLarge = PRS.bMathWordLarge;
var OperGapRight = PRS.OperGapRight;
var OperGapLeft = PRS.OperGapLeft;
var bInsideOper = PRS.bInsideOper;
var bContainCompareOper = PRS.bContainCompareOper;
var bEndRunToContent = PRS.bEndRunToContent;
var bNoOneBreakOperator = PRS.bNoOneBreakOperator;
var bForcedBreak = PRS.bForcedBreak;
var Pos = RangeStartPos;
var ContentLen = this.Content.length;
var XRange = PRS.XRange;
var oSectionPr = undefined;
if (false === StartWord && true === FirstItemOnLine && XEnd - X < 0.001 && RangesCount > 0)
{
NewRange = true;
RangeEndPos = Pos;
}
else
{
for (; Pos < ContentLen; Pos++)
{
var Item = this.Content[Pos];
var ItemType = Item.Type;
// Проверяем, не нужно ли добавить нумерацию к данному элементу
if (true === this.RecalcInfo.NumberingAdd && true === Item.Can_AddNumbering())
X = this.private_RecalculateNumbering(PRS, Item, ParaPr, X);
switch (ItemType)
{
case para_Sym:
case para_Text:
case para_FootnoteReference:
case para_FootnoteRef:
case para_Separator:
case para_ContinuationSeparator:
{
// Отмечаем, что началось слово
StartWord = true;
if (para_ContinuationSeparator === ItemType || para_Separator === ItemType)
Item.UpdateWidth(PRS);
if (true !== PRS.IsFastRecalculate())
{
if (para_FootnoteReference === ItemType)
{
Item.UpdateNumber(PRS);
PRS.AddFootnoteReference(Item, PRS.GetCurrentContentPos(Pos));
}
else if (para_FootnoteRef === ItemType)
{
Item.UpdateNumber(PRS.TopDocument);
}
}
// При проверке, убирается ли слово, мы должны учитывать ширину предшествующих пробелов.
var LetterLen = Item.Width / TEXTWIDTH_DIVIDER;//var LetterLen = Item.Get_Width();
if (true !== Word)
{
// Слово только началось. Делаем следующее:
// 1) Если до него на строке ничего не было и данная строка не
// имеет разрывов, тогда не надо проверять убирается ли слово в строке.
// 2) В противном случае, проверяем убирается ли слово в промежутке.
// Если слово только началось, и до него на строке ничего не было, и в строке нет разрывов, тогда не надо проверять убирается ли оно на строке.
if (true !== FirstItemOnLine || false === Para.Internal_Check_Ranges(ParaLine, ParaRange))
{
if (X + SpaceLen + LetterLen > XEnd)
{
NewRange = true;
RangeEndPos = Pos;
}
}
if (true !== NewRange)
{
// Отмечаем начало нового слова
PRS.Set_LineBreakPos(Pos);
// Если текущий символ с переносом, например, дефис, тогда на нем заканчивается слово
if (Item.Flags & PARATEXT_FLAGS_SPACEAFTER)//if ( true === Item.Is_SpaceAfter() )
{
// Добавляем длину пробелов до слова и ширину самого слова.
X += SpaceLen + LetterLen;
Word = false;
FirstItemOnLine = false;
EmptyLine = false;
SpaceLen = 0;
WordLen = 0;
}
else
{
Word = true;
WordLen = LetterLen;
}
}
}
else
{
if(X + SpaceLen + WordLen + LetterLen > XEnd)
{
if(true === FirstItemOnLine)
{
// Слово оказалось единственным элементом в промежутке, и, все равно,
// не умещается целиком. Делаем следующее:
//
//
// 1) Если у нас строка без вырезов, тогда ставим перенос строки на
// текущей позиции.
// 2) Если у нас строка с вырезом, и данный вырез не последний, тогда
// ставим перенос внутри строки в начале слова.
// 3) Если у нас строка с вырезом и вырез последний, тогда ставим перенос
// строки в начале слова.
if (false === Para.Internal_Check_Ranges(ParaLine, ParaRange))
{
// Слово не убирается в отрезке. Переносим слово в следующий отрезок
MoveToLBP = true;
NewRange = true;
}
else
{
EmptyLine = false;
X += WordLen;
// Слово не убирается в отрезке, но, поскольку, слово 1 на строке и отрезок тоже 1,
// делим слово в данном месте
NewRange = true;
RangeEndPos = Pos;
}
}
else
{
// Слово не убирается в отрезке. Переносим слово в следующий отрезок
MoveToLBP = true;
NewRange = true;
}
}
if (true !== NewRange)
{
// Мы убираемся в пределах данной строки. Прибавляем ширину буквы к ширине слова
WordLen += LetterLen;
// Если текущий символ с переносом, например, дефис, тогда на нем заканчивается слово
if (Item.Flags & PARATEXT_FLAGS_SPACEAFTER)//if ( true === Item.Is_SpaceAfter() )
{
// Добавляем длину пробелов до слова и ширину самого слова.
X += SpaceLen + WordLen;
Word = false;
FirstItemOnLine = false;
EmptyLine = false;
SpaceLen = 0;
WordLen = 0;
}
}
}
break;
}
case para_Math_Text:
case para_Math_Ampersand:
case para_Math_Placeholder:
{
// Отмечаем, что началось слово
StartWord = true;
// При проверке, убирается ли слово, мы должны учитывать ширину предшествующих пробелов.
var LetterLen = Item.Get_Width2() / TEXTWIDTH_DIVIDER;//var LetterLen = Item.Get_Width();
if (true !== Word)
{
// Если слово только началось, и до него на строке ничего не было, и в строке нет разрывов, тогда не надо проверять убирается ли оно на строке.
if (true !== FirstItemOnLine /*|| false === Para.Internal_Check_Ranges(ParaLine, ParaRange)*/)
{
if (X + SpaceLen + LetterLen > XEnd)
{
NewRange = true;
RangeEndPos = Pos;
}
else if(bForcedBreak == true)
{
MoveToLBP = true;
NewRange = true;
PRS.Set_LineBreakPos(Pos);
}
}
if(true !== NewRange)
{
if(this.Parent.bRoot == true)
PRS.Set_LineBreakPos(Pos);
WordLen += LetterLen;
Word = true;
}
}
else
{
if(X + SpaceLen + WordLen + LetterLen > XEnd)
{
if(true === FirstItemOnLine /*&& true === Para.Internal_Check_Ranges(ParaLine, ParaRange)*/)
{
// Слово оказалось единственным элементом в промежутке, и, все равно, не умещается целиком.
// для Формулы слово не разбиваем, перенос не делаем, пишем в одну строку (слово выйдет за границу как в Ворде)
bMathWordLarge = true;
}
else
{
// Слово не убирается в отрезке. Переносим слово в следующий отрезок
MoveToLBP = true;
NewRange = true;
}
}
if (true !== NewRange)
{
// Мы убираемся в пределах данной строки. Прибавляем ширину буквы к ширине слова
WordLen += LetterLen;
}
}
break;
}
case para_Space:
{
FirstItemOnLine = false;
if (true === Word)
{
// Добавляем длину пробелов до слова + длина самого слова. Не надо проверять
// убирается ли слово, мы это проверяем при добавленнии букв.
X += SpaceLen + WordLen;
Word = false;
EmptyLine = false;
SpaceLen = 0;
WordLen = 0;
}
// На пробеле не делаем перенос. Перенос строки или внутристрочный
// перенос делаем при добавлении любого непробельного символа
SpaceLen += Item.Width / TEXTWIDTH_DIVIDER;//SpaceLen += Item.Get_Width();
break;
}
case para_Math_BreakOperator:
{
var BrkLen = Item.Get_Width2()/TEXTWIDTH_DIVIDER;
var bCompareOper = Item.Is_CompareOperator();
var bOperBefore = this.ParaMath.Is_BrkBinBefore() == true;
var bOperInEndContent = bOperBefore === false && bEndRunToContent === true && Pos == ContentLen - 1 && Word == true, // необходимо для того, чтобы у контентов мат объектов (к-ые могут разбиваться на строки) не было отметки Set_LineBreakPos, иначе скобка (или GapLeft), перед которой стоит break_Operator, перенесется на следующую строку (без текста !)
bLowPriority = bCompareOper == false && bContainCompareOper == false;
if(Pos == 0 && true === this.IsForcedBreak()) // принудительный перенос срабатывает всегда
{
if(FirstItemOnLine === true && Word == false && bNoOneBreakOperator == true) // первый оператор в строке
{
WordLen += BrkLen;
}
else if(bOperBefore)
{
X += SpaceLen + WordLen;
WordLen = 0;
SpaceLen = 0;
NewRange = true;
RangeEndPos = Pos;
}
else
{
if(FirstItemOnLine == false && X + SpaceLen + WordLen + BrkLen > XEnd)
{
MoveToLBP = true;
NewRange = true;
}
else
{
X += SpaceLen + WordLen;
Word = false;
MoveToLBP = true;
NewRange = true;
PRS.Set_LineBreakPos(1);
}
}
}
else if(bOperInEndContent || bLowPriority) // у этого break Operator приоритет низкий(в контенте на данном уровне есть другие операторы с более высоким приоритетом) => по нему не разбиваем, обрабатываем как обычную букву
{
if(X + SpaceLen + WordLen + BrkLen > XEnd)
{
if(FirstItemOnLine == true)
{
bMathWordLarge = true;
}
else
{
// Слово не убирается в отрезке. Переносим слово в следующий отрезок
MoveToLBP = true;
NewRange = true;
}
}
else
{
WordLen += BrkLen;
}
}
else
{
var WorLenCompareOper = WordLen + X - XRange + (bOperBefore ? SpaceLen : BrkLen);
var bOverXEnd, bOverXEndMWordLarge;
var bNotUpdBreakOper = false;
var bCompareWrapIndent = PRS.bFirstLine == true ? WorLenCompareOper > PRS.WrapIndent : true;
if(PRS.bPriorityOper == true && bCompareOper == true && bContainCompareOper == true && bCompareWrapIndent == true && !(Word == false && FirstItemOnLine === true)) // (Word == true && FirstItemOnLine == true) - не первый элемент в строке
bContainCompareOper = false;
if(bOperBefore) // оператор "до" => оператор находится в начале строки
{
bOverXEnd = X + WordLen + SpaceLen + BrkLen > XEnd; // BrkLen прибавляем дла случая, если идут подряд Brk Operators в конце
bOverXEndMWordLarge = X + WordLen + SpaceLen > XEnd; // ширину самого оператора не учитываем при расчете bMathWordLarge, т.к. он будет находится на следующей строке
if(bOverXEnd && (true !== FirstItemOnLine || true === Word))
{
// если вышли за границы не обновляем параметр bInsideOper, т.к. если уже были breakOperator, то, соответственно, он уже выставлен в true
// а если на этом уровне не было breakOperator, то и обновлять его нне нужо
if(FirstItemOnLine === false)
{
MoveToLBP = true;
NewRange = true;
}
else
{
if(Word == true && bOverXEndMWordLarge == true)
{
bMathWordLarge = true;
}
X += SpaceLen + WordLen;
if(PRS.bBreakPosInLWord == true)
{
PRS.Set_LineBreakPos(Pos);
}
else
{
bNotUpdBreakOper = true;
}
RangeEndPos = Pos;
SpaceLen = 0;
WordLen = 0;
NewRange = true;
EmptyLine = false;
}
}
else
{
if(FirstItemOnLine === false)
bInsideOper = true;
if(Word == false && FirstItemOnLine == true )
{
SpaceLen += BrkLen;
}
else
{
// проверка на FirstItemOnLine == false нужна для случая, если иду подряд несколько breakOperator
// в этом случае Word == false && FirstItemOnLine == false, нужно также поставить отметку для потенциального переноса
X += SpaceLen + WordLen;
PRS.Set_LineBreakPos(Pos);
EmptyLine = false;
WordLen = BrkLen;
SpaceLen = 0;
}
// в первой строке может не быть ни одного break Operator, при этом слово не выходит за границы, т.о. обновляем FirstItemOnLine также и на Word = true
// т.к. оператор идет в начале строки, то соответственно слово в стоке не будет первым, если в строке больше одного оператора
if(bNoOneBreakOperator == false || Word == true)
FirstItemOnLine = false;
}
}
else // оператор "после" => оператор находится в конце строки
{
bOverXEnd = X + WordLen + BrkLen - Item.GapRight > XEnd;
bOverXEndMWordLarge = bOverXEnd;
if(bOverXEnd && FirstItemOnLine === false) // Слово не убирается в отрезке. Переносим слово в следующий отрезок
{
MoveToLBP = true;
NewRange = true;
if(Word == false)
PRS.Set_LineBreakPos(Pos);
}
else
{
bInsideOper = true;
// осуществляем здесь, чтобы не изменить GapRight в случае, когда новое слово не убирается на break_Operator
OperGapRight = Item.GapRight;
if(bOverXEndMWordLarge == true) // FirstItemOnLine == true
{
bMathWordLarge = true;
}
X += BrkLen + WordLen;
EmptyLine = false;
SpaceLen = 0;
WordLen = 0;
var bNotUpdate = bOverXEnd == true && PRS.bBreakPosInLWord == false;
// FirstItemOnLine == true
if(bNotUpdate == false) // LineBreakPos обновляем здесь, т.к. слово может начаться с мат объекта, а не с Run, в мат объекте нет соответствующей проверки
{
PRS.Set_LineBreakPos(Pos+1);
}
else
{
bNotUpdBreakOper = true;
}
FirstItemOnLine = false;
Word = false;
}
}
}
if(bNotUpdBreakOper == false)
bNoOneBreakOperator = false;
break;
}
case para_Drawing:
{
if(oSectionPr === undefined)
{
oSectionPr = Para.Get_SectPr();
}
Item.CheckRecalcAutoFit(oSectionPr);
if (true === Item.Is_Inline() || true === Para.Parent.Is_DrawingShape())
{
// TODO: Нельзя что-то писать в историю во время пересчета, это действие надо делать при открытии
// if (true !== Item.Is_Inline())
// Item.Set_DrawingType(drawing_Inline);
if (true === StartWord)
FirstItemOnLine = false;
Item.YOffset = this.YOffset;
// Если до этого было слово, тогда не надо проверять убирается ли оно, но если стояли пробелы,
// тогда мы их учитываем при проверке убирается ли данный элемент, и добавляем только если
// данный элемент убирается
if (true === Word || WordLen > 0)
{
// Добавляем длину пробелов до слова + длина самого слова. Не надо проверять
// убирается ли слово, мы это проверяем при добавленнии букв.
X += SpaceLen + WordLen;
Word = false;
EmptyLine = false;
SpaceLen = 0;
WordLen = 0;
}
var DrawingWidth = Item.Get_Width();
if (X + SpaceLen + DrawingWidth > XEnd && ( false === FirstItemOnLine || false === Para.Internal_Check_Ranges(ParaLine, ParaRange) ))
{
// Автофигура не убирается, ставим перенос перед ней
NewRange = true;
RangeEndPos = Pos;
}
else
{
// Добавляем длину пробелов до автофигуры
X += SpaceLen + DrawingWidth;
FirstItemOnLine = false;
EmptyLine = false;
}
SpaceLen = 0;
}
else if (!Item.IsSkipOnRecalculate())
{
// Основная обработка происходит в Recalculate_Range_Spaces. Здесь обрабатывается единственный случай,
// когда после второго пересчета с уже добавленной картинкой оказывается, что место в параграфе, где
// идет картинка ушло на следующую страницу. В этом случае мы ставим перенос страницы перед картинкой.
var LogicDocument = Para.Parent;
var LDRecalcInfo = LogicDocument.RecalcInfo;
var DrawingObjects = LogicDocument.DrawingObjects;
var CurPage = PRS.Page;
if (true === LDRecalcInfo.Check_FlowObject(Item) && true === LDRecalcInfo.Is_PageBreakBefore())
{
LDRecalcInfo.Reset();
// Добавляем разрыв страницы. Если это первая страница, тогда ставим разрыв страницы в начале параграфа,
// если нет, тогда в начале текущей строки.
if (null != Para.Get_DocumentPrev() && true != Para.Parent.IsTableCellContent() && 0 === CurPage)
{
Para.Recalculate_Drawing_AddPageBreak(0, 0, true);
PRS.RecalcResult = recalcresult_NextPage | recalcresultflags_Page;
PRS.NewRange = true;
return;
}
else
{
if (ParaLine != Para.Pages[CurPage].FirstLine)
{
Para.Recalculate_Drawing_AddPageBreak(ParaLine, CurPage, false);
PRS.RecalcResult = recalcresult_NextPage | recalcresultflags_Page;
PRS.NewRange = true;
return;
}
else
{
RangeEndPos = Pos;
NewRange = true;
ForceNewPage = true;
}
}
// Если до этого было слово, тогда не надо проверять убирается ли оно
if (true === Word || WordLen > 0)
{
// Добавляем длину пробелов до слова + длина самого слова. Не надо проверять
// убирается ли слово, мы это проверяем при добавленнии букв.
X += SpaceLen + WordLen;
Word = false;
SpaceLen = 0;
WordLen = 0;
}
}
}
break;
}
case para_PageCount:
case para_PageNum:
{
if (para_PageCount === ItemType)
{
var oHdrFtr = Para.Parent.Is_HdrFtr(true);
if (oHdrFtr)
oHdrFtr.Add_PageCountElement(Item);
}
else if (para_PageNum === ItemType)
{
var LogicDocument = Para.LogicDocument;
var SectionPage = LogicDocument.Get_SectionPageNumInfo2(Para.Get_AbsolutePage(PRS.Page)).CurPage;
Item.Set_Page(SectionPage);
}
// Если до этого было слово, тогда не надо проверять убирается ли оно, но если стояли пробелы,
// тогда мы их учитываем при проверке убирается ли данный элемент, и добавляем только если
// данный элемент убирается
if (true === Word || WordLen > 0)
{
// Добавляем длину пробелов до слова + длина самого слова. Не надо проверять
// убирается ли слово, мы это проверяем при добавленнии букв.
X += SpaceLen + WordLen;
Word = false;
EmptyLine = false;
SpaceLen = 0;
WordLen = 0;
}
// Если на строке начиналось какое-то слово, тогда данная строка уже не пустая
if (true === StartWord)
FirstItemOnLine = false;
var PageNumWidth = Item.Get_Width();
if (X + SpaceLen + PageNumWidth > XEnd && ( false === FirstItemOnLine || false === Para.Internal_Check_Ranges(ParaLine, ParaRange) ))
{
// Данный элемент не убирается, ставим перенос перед ним
NewRange = true;
RangeEndPos = Pos;
}
else
{
// Добавляем длину пробелов до слова и ширину данного элемента
X += SpaceLen + PageNumWidth;
FirstItemOnLine = false;
EmptyLine = false;
}
SpaceLen = 0;
break;
}
case para_Tab:
{
// Сначала проверяем, если у нас уже есть таб, которым мы должны рассчитать, тогда высчитываем
// его ширину.
X = this.Internal_Recalculate_LastTab(PRS.LastTab, X, XEnd, Word, WordLen, SpaceLen);
// Добавляем длину пробелов до слова + длина самого слова. Не надо проверять
// убирается ли слово, мы это проверяем при добавленнии букв.
X += SpaceLen + WordLen;
Word = false;
SpaceLen = 0;
WordLen = 0;
var TabPos = Para.private_RecalculateGetTabPos(X, ParaPr, PRS.Page, false);
var NewX = TabPos.NewX;
var TabValue = TabPos.TabValue;
// Если таб не левый, значит он не может быть сразу рассчитан, а если левый, тогда
// рассчитываем его сразу здесь
if (tab_Left !== TabValue)
{
PRS.LastTab.TabPos = NewX;
PRS.LastTab.Value = TabValue;
PRS.LastTab.X = X;
PRS.LastTab.Item = Item;
Item.Width = 0;
Item.WidthVisible = 0;
}
else
{
if (true !== TabPos.DefaultTab && NewX > XEnd - 0.001 && XEnd < 558.7 && PRS.Range >= PRS.RangesCount - 1)
{
Para.Lines[PRS.Line].Ranges[PRS.Range].XEnd = 558.7;
XEnd = 558.7;
PRS.BadLeftTab = true;
}
// Так работает Word: он не переносит на новую строку табы, начинающиеся в допустимом отрезке, а
// заканчивающиеся вне его. Поэтому мы проверяем именно, где таб начинается, а не заканчивается.
// (bug 32345)
if (X > XEnd && ( false === FirstItemOnLine || false === Para.Internal_Check_Ranges(ParaLine, ParaRange) ))
{
WordLen = NewX - X;
RangeEndPos = Pos;
NewRange = true;
}
else
{
Item.Width = NewX - X;
Item.WidthVisible = NewX - X;
X = NewX;
}
}
// Если перенос идет по строке, а не из-за обтекания, тогда разрываем перед табом, а если
// из-за обтекания, тогда разрываем перед последним словом, идущим перед табом
if (RangesCount === CurRange)
{
if (true === StartWord)
{
FirstItemOnLine = false;
EmptyLine = false;
}
}
// Считаем, что с таба начинается слово
PRS.Set_LineBreakPos(Pos);
StartWord = true;
Word = true;
break;
}
case para_NewLine:
{
// Сначала проверяем, если у нас уже есть таб, которым мы должны рассчитать, тогда высчитываем
// его ширину.
X = this.Internal_Recalculate_LastTab(PRS.LastTab, X, XEnd, Word, WordLen, SpaceLen);
X += WordLen;
if (true === Word)
{
EmptyLine = false;
Word = false;
X += SpaceLen;
SpaceLen = 0;
}
if (break_Page === Item.BreakType || break_Column === Item.BreakType)
{
PRS.BreakPageLine = true;
if (break_Page === Item.BreakType)
PRS.BreakRealPageLine = true;
// PageBreak вне самого верхнего документа не надо учитывать
if (!(Para.Parent instanceof CDocument) || true !== Para.Is_Inline())
{
// TODO: Продумать, как избавиться от данного элемента, т.к. удалять его при пересчете нельзя,
// иначе будут проблемы с совместным редактированием.
Item.Flags.Use = false;
continue;
}
if (break_Page === Item.BreakType && true === Para.Check_BreakPageEnd(Item))
continue;
Item.Flags.NewLine = true;
NewPage = true;
NewRange = true;
}
else
{
NewRange = true;
EmptyLine = false;
// здесь оставляем проверку, т.к. в случае, если после неинлайновой формулы нах-ся инлайновая необходимо в любом случае сделать перенос (проверка в private_RecalculateRange(), где выставляется PRS.ForceNewLine = true не пройдет)
if (true === PRS.MathNotInline)
PRS.ForceNewLine = true;
}
RangeEndPos = Pos + 1;
break;
}
case para_End:
{
if (true === Word)
{
FirstItemOnLine = false;
EmptyLine = false;
}
X += WordLen;
if (true === Word)
{
X += SpaceLen;
SpaceLen = 0;
WordLen = 0;
}
X = this.Internal_Recalculate_LastTab(PRS.LastTab, X, XEnd, Word, WordLen, SpaceLen);
NewRange = true;
End = true;
RangeEndPos = Pos + 1;
break;
}
}
if (true === NewRange)
break;
}
}
PRS.MoveToLBP = MoveToLBP;
PRS.NewRange = NewRange;
PRS.ForceNewPage = ForceNewPage;
PRS.NewPage = NewPage;
PRS.End = End;
PRS.Word = Word;
PRS.StartWord = StartWord;
PRS.FirstItemOnLine = FirstItemOnLine;
PRS.EmptyLine = EmptyLine;
PRS.SpaceLen = SpaceLen;
PRS.WordLen = WordLen;
PRS.bMathWordLarge = bMathWordLarge;
PRS.OperGapRight = OperGapRight;
PRS.OperGapLeft = OperGapLeft;
PRS.X = X;
PRS.XEnd = XEnd;
PRS.bInsideOper = bInsideOper;
PRS.bContainCompareOper = bContainCompareOper;
PRS.bEndRunToContent = bEndRunToContent;
PRS.bNoOneBreakOperator = bNoOneBreakOperator;
PRS.bForcedBreak = bForcedBreak;
if(this.Type == para_Math_Run)
{
if(true === NewRange)
{
var WidthLine = X - XRange;
if(this.ParaMath.Is_BrkBinBefore() == false)
WidthLine += SpaceLen;
this.ParaMath.UpdateWidthLine(PRS, WidthLine);
}
else
{
// для пустого Run, обновляем LineBreakPos на случай, если пустой Run находится между break_operator (мат. объект) и мат объектом
if(this.Content.length == 0)
{
if(PRS.bForcedBreak == true)
{
PRS.MoveToLBP = true;
PRS.NewRange = true;
PRS.Set_LineBreakPos(0);
}
else if(this.ParaMath.Is_BrkBinBefore() == false && Word == false && PRS.bBreakBox == true)
{
PRS.Set_LineBreakPos(Pos);
PRS.X += SpaceLen;
PRS.SpaceLen = 0;
}
}
// запоминаем конец Run
PRS.PosEndRun.Set(PRS.CurPos);
PRS.PosEndRun.Update2(this.Content.length, Depth);
}
}
if ( Pos >= ContentLen )
{
RangeEndPos = Pos;
}
this.protected_FillRange(CurLine, CurRange, RangeStartPos, RangeEndPos);
this.RecalcInfo.Recalc = false;
};
ParaRun.prototype.Recalculate_Set_RangeEndPos = function(PRS, PRP, Depth)
{
var CurLine = PRS.Line - this.StartLine;
var CurRange = ( 0 === CurLine ? PRS.Range - this.StartRange : PRS.Range );
var CurPos = PRP.Get(Depth);
this.protected_FillRangeEndPos(CurLine, CurRange, CurPos);
};
ParaRun.prototype.Recalculate_LineMetrics = function(PRS, ParaPr, _CurLine, _CurRange, ContentMetrics)
{
var Para = PRS.Paragraph;
// Если заданный отрезок пустой, тогда мы не должны учитывать метрики данного рана.
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
var UpdateLineMetricsText = false;
var LineRule = ParaPr.Spacing.LineRule;
for (var CurPos = StartPos; CurPos < EndPos; CurPos++)
{
var Item = this.Content[CurPos];
if (Item === Para.Numbering.Item)
{
PRS.LineAscent = Para.Numbering.LineAscent;
}
switch (Item.Type)
{
case para_Sym:
case para_Text:
case para_PageNum:
case para_PageCount:
case para_FootnoteReference:
case para_FootnoteRef:
case para_Separator:
case para_ContinuationSeparator:
{
UpdateLineMetricsText = true;
break;
}
case para_Math_Text:
case para_Math_Ampersand:
case para_Math_Placeholder:
case para_Math_BreakOperator:
{
ContentMetrics.UpdateMetrics(Item.size);
break;
}
case para_Space:
{
break;
}
case para_Drawing:
{
if (true === Item.Is_Inline() || true === Para.Parent.Is_DrawingShape())
{
// Обновим метрики строки
if (Asc.linerule_Exact === LineRule)
{
if (PRS.LineAscent < Item.Height)
PRS.LineAscent = Item.Height;
}
else
{
if (PRS.LineAscent < Item.Height + this.YOffset)
PRS.LineAscent = Item.Height + this.YOffset;
if (PRS.LineDescent < -this.YOffset)
PRS.LineDescent = -this.YOffset;
}
}
break;
}
case para_End:
{
// TODO: Тут можно сделать проверку на пустую строку.
break;
}
}
}
if ( true === UpdateLineMetricsText)
{
// Пересчитаем метрику строки относительно размера данного текста
if ( PRS.LineTextAscent < this.TextAscent )
PRS.LineTextAscent = this.TextAscent;
if ( PRS.LineTextAscent2 < this.TextAscent2 )
PRS.LineTextAscent2 = this.TextAscent2;
if ( PRS.LineTextDescent < this.TextDescent )
PRS.LineTextDescent = this.TextDescent;
if ( Asc.linerule_Exact === LineRule )
{
// Смещение не учитывается в метриках строки, когда расстояние между строк точное
if ( PRS.LineAscent < this.TextAscent )
PRS.LineAscent = this.TextAscent;
if ( PRS.LineDescent < this.TextDescent )
PRS.LineDescent = this.TextDescent;
}
else
{
if ( PRS.LineAscent < this.TextAscent + this.YOffset )
PRS.LineAscent = this.TextAscent + this.YOffset;
if ( PRS.LineDescent < this.TextDescent - this.YOffset )
PRS.LineDescent = this.TextDescent - this.YOffset;
}
}
};
ParaRun.prototype.Recalculate_Range_Width = function(PRSC, _CurLine, _CurRange)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
for ( var Pos = StartPos; Pos < EndPos; Pos++ )
{
var Item = this.Content[Pos];
var ItemType = Item.Type;
switch( ItemType )
{
case para_Sym:
case para_Text:
case para_FootnoteReference:
case para_FootnoteRef:
case para_Separator:
case para_ContinuationSeparator:
{
PRSC.Letters++;
if ( true !== PRSC.Word )
{
PRSC.Word = true;
PRSC.Words++;
}
PRSC.Range.W += Item.Width / TEXTWIDTH_DIVIDER;//Item.Get_Width();
PRSC.Range.W += PRSC.SpaceLen;
PRSC.SpaceLen = 0;
// Пробелы перед первым словом в строке не считаем
if (PRSC.Words > 1)
PRSC.Spaces += PRSC.SpacesCount;
else
PRSC.SpacesSkip += PRSC.SpacesCount;
PRSC.SpacesCount = 0;
// Если текущий символ, например, дефис, тогда на нем заканчивается слово
if (Item.Flags & PARATEXT_FLAGS_SPACEAFTER)//if ( true === Item.Is_SpaceAfter() )
PRSC.Word = false;
break;
}
case para_Math_Text:
case para_Math_Placeholder:
case para_Math_Ampersand:
case para_Math_BreakOperator:
{
PRSC.Letters++;
PRSC.Range.W += Item.Get_Width() / TEXTWIDTH_DIVIDER; // Get_Width рассчитываем ширину с учетом состояний Gaps
break;
}
case para_Space:
{
if ( true === PRSC.Word )
{
PRSC.Word = false;
PRSC.SpacesCount = 1;
PRSC.SpaceLen = Item.Width / TEXTWIDTH_DIVIDER;//Item.Get_Width();
}
else
{
PRSC.SpacesCount++;
PRSC.SpaceLen += Item.Width / TEXTWIDTH_DIVIDER;//Item.Get_Width();
}
break;
}
case para_Drawing:
{
PRSC.Words++;
PRSC.Range.W += PRSC.SpaceLen;
if (PRSC.Words > 1)
PRSC.Spaces += PRSC.SpacesCount;
else
PRSC.SpacesSkip += PRSC.SpacesCount;
PRSC.Word = false;
PRSC.SpacesCount = 0;
PRSC.SpaceLen = 0;
if ( true === Item.Is_Inline() || true === PRSC.Paragraph.Parent.Is_DrawingShape() )
PRSC.Range.W += Item.Get_Width();
break;
}
case para_PageNum:
case para_PageCount:
{
PRSC.Words++;
PRSC.Range.W += PRSC.SpaceLen;
if (PRSC.Words > 1)
PRSC.Spaces += PRSC.SpacesCount;
else
PRSC.SpacesSkip += PRSC.SpacesCount;
PRSC.Word = false;
PRSC.SpacesCount = 0;
PRSC.SpaceLen = 0;
PRSC.Range.W += Item.Get_Width();
break;
}
case para_Tab:
{
PRSC.Range.W += Item.Get_Width();
PRSC.Range.W += PRSC.SpaceLen;
// Учитываем только слова и пробелы, идущие после последнего таба
PRSC.LettersSkip += PRSC.Letters;
PRSC.SpacesSkip += PRSC.Spaces;
PRSC.Words = 0;
PRSC.Spaces = 0;
PRSC.Letters = 0;
PRSC.SpaceLen = 0;
PRSC.SpacesCount = 0;
PRSC.Word = false;
break;
}
case para_NewLine:
{
if (true === PRSC.Word && PRSC.Words > 1)
PRSC.Spaces += PRSC.SpacesCount;
PRSC.SpacesCount = 0;
PRSC.Word = false;
break;
}
case para_End:
{
if ( true === PRSC.Word )
PRSC.Spaces += PRSC.SpacesCount;
PRSC.Range.WEnd = Item.Get_WidthVisible();
break;
}
}
}
};
ParaRun.prototype.Recalculate_Range_Spaces = function(PRSA, _CurLine, _CurRange, CurPage)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
for ( var Pos = StartPos; Pos < EndPos; Pos++ )
{
var Item = this.Content[Pos];
var ItemType = Item.Type;
switch( ItemType )
{
case para_Sym:
case para_Text:
case para_FootnoteReference:
case para_FootnoteRef:
case para_Separator:
case para_ContinuationSeparator:
{
var WidthVisible = 0;
if ( 0 !== PRSA.LettersSkip )
{
WidthVisible = Item.Width / TEXTWIDTH_DIVIDER;//WidthVisible = Item.Get_Width();
PRSA.LettersSkip--;
}
else
WidthVisible = Item.Width / TEXTWIDTH_DIVIDER + PRSA.JustifyWord;//WidthVisible = Item.Get_Width() + PRSA.JustifyWord;
Item.WidthVisible = (WidthVisible * TEXTWIDTH_DIVIDER) | 0;//Item.Set_WidthVisible(WidthVisible);
if (para_FootnoteReference === ItemType)
{
var oFootnote = Item.Get_Footnote();
oFootnote.UpdatePositionInfo(this.Paragraph, this, _CurLine, _CurRange, PRSA.X, WidthVisible);
}
PRSA.X += WidthVisible;
PRSA.LastW = WidthVisible;
break;
}
case para_Math_Text:
case para_Math_Placeholder:
case para_Math_BreakOperator:
case para_Math_Ampersand:
{
var WidthVisible = Item.Get_Width() / TEXTWIDTH_DIVIDER; // Get_Width рассчитываем ширину с учетом состояний Gaps
Item.WidthVisible = (WidthVisible * TEXTWIDTH_DIVIDER)| 0;//Item.Set_WidthVisible(WidthVisible);
PRSA.X += WidthVisible;
PRSA.LastW = WidthVisible;
break;
}
case para_Space:
{
var WidthVisible = Item.Width / TEXTWIDTH_DIVIDER;//WidthVisible = Item.Get_Width();
if ( 0 !== PRSA.SpacesSkip )
{
PRSA.SpacesSkip--;
}
else if ( 0 !== PRSA.SpacesCounter )
{
WidthVisible += PRSA.JustifySpace;
PRSA.SpacesCounter--;
}
Item.WidthVisible = (WidthVisible * TEXTWIDTH_DIVIDER) | 0;//Item.Set_WidthVisible(WidthVisible);
PRSA.X += WidthVisible;
PRSA.LastW = WidthVisible;
break;
}
case para_Drawing:
{
var Para = PRSA.Paragraph;
var PageAbs = Para.private_GetAbsolutePageIndex(CurPage);
var PageRel = Para.private_GetRelativePageIndex(CurPage);
var ColumnAbs = Para.Get_AbsoluteColumn(CurPage);
var LogicDocument = this.Paragraph.LogicDocument;
var LD_PageLimits = LogicDocument.Get_PageLimits(PageAbs);
var LD_PageFields = LogicDocument.Get_PageFields(PageAbs);
var Page_Width = LD_PageLimits.XLimit;
var Page_Height = LD_PageLimits.YLimit;
var DrawingObjects = Para.Parent.DrawingObjects;
var PageLimits = Para.Parent.Get_PageLimits(PageRel);
var PageFields = Para.Parent.Get_PageFields(PageRel);
var X_Left_Field = PageFields.X;
var Y_Top_Field = PageFields.Y;
var X_Right_Field = PageFields.XLimit;
var Y_Bottom_Field = PageFields.YLimit;
var X_Left_Margin = PageFields.X - PageLimits.X;
var Y_Top_Margin = PageFields.Y - PageLimits.Y;
var X_Right_Margin = PageLimits.XLimit - PageFields.XLimit;
var Y_Bottom_Margin = PageLimits.YLimit - PageFields.YLimit;
if (true === Para.Parent.IsTableCellContent() && (true !== Item.Use_TextWrap() || false === Item.Is_LayoutInCell()))
{
X_Left_Field = LD_PageFields.X;
Y_Top_Field = LD_PageFields.Y;
X_Right_Field = LD_PageFields.XLimit;
Y_Bottom_Field = LD_PageFields.YLimit;
X_Left_Margin = X_Left_Field;
X_Right_Margin = Page_Width - X_Right_Field;
Y_Bottom_Margin = Page_Height - Y_Bottom_Field;
Y_Top_Margin = Y_Top_Field;
}
var _CurPage = 0;
if (0 !== PageAbs && CurPage > ColumnAbs)
_CurPage = CurPage - ColumnAbs;
var ColumnStartX = (0 === CurPage ? Para.X_ColumnStart : Para.Pages[_CurPage].X );
var ColumnEndX = (0 === CurPage ? Para.X_ColumnEnd : Para.Pages[_CurPage].XLimit);
var Top_Margin = Y_Top_Margin;
var Bottom_Margin = Y_Bottom_Margin;
var Page_H = Page_Height;
if ( true === Para.Parent.IsTableCellContent() && true == Item.Use_TextWrap() )
{
Top_Margin = 0;
Bottom_Margin = 0;
Page_H = 0;
}
var PageLimitsOrigin = Para.Parent.Get_PageLimits(PageRel);
if (true === Para.Parent.IsTableCellContent() && false === Item.Is_LayoutInCell())
{
PageLimitsOrigin = LogicDocument.Get_PageLimits(PageAbs);
var PageFieldsOrigin = LogicDocument.Get_PageFields(PageAbs);
ColumnStartX = PageFieldsOrigin.X;
ColumnEndX = PageFieldsOrigin.XLimit;
}
if ( true != Item.Use_TextWrap() )
{
PageFields.X = X_Left_Field;
PageFields.Y = Y_Top_Field;
PageFields.XLimit = X_Right_Field;
PageFields.YLimit = Y_Bottom_Field;
PageLimits.X = 0;
PageLimits.Y = 0;
PageLimits.XLimit = Page_Width;
PageLimits.YLimit = Page_Height;
}
if ( true === Item.Is_Inline() || true === Para.Parent.Is_DrawingShape() )
{
Item.Update_Position(PRSA.Paragraph, new CParagraphLayout( PRSA.X, PRSA.Y , PageAbs, PRSA.LastW, ColumnStartX, ColumnEndX, X_Left_Margin, X_Right_Margin, Page_Width, Top_Margin, Bottom_Margin, Page_H, PageFields.X, PageFields.Y, Para.Pages[CurPage].Y + Para.Lines[CurLine].Y - Para.Lines[CurLine].Metrics.Ascent, Para.Pages[CurPage].Y), PageLimits, PageLimitsOrigin, _CurLine);
Item.Reset_SavedPosition();
PRSA.X += Item.WidthVisible;
PRSA.LastW = Item.WidthVisible;
}
else if (!Item.IsSkipOnRecalculate())
{
Para.Pages[CurPage].Add_Drawing(Item);
if ( true === PRSA.RecalcFast )
{
// Если у нас быстрый пересчет, тогда мы не трогаем плавающие картинки
// TODO: Если здесь привязка к символу, тогда быстрый пересчет надо отменить
break;
}
if (true === PRSA.RecalcFast2)
{
// Тут мы должны сравнить положение картинок
var oRecalcObj = Item.SaveRecalculateObject();
Item.Update_Position(PRSA.Paragraph, new CParagraphLayout( PRSA.X, PRSA.Y , PageAbs, PRSA.LastW, ColumnStartX, ColumnEndX, X_Left_Margin, X_Right_Margin, Page_Width, Top_Margin, Bottom_Margin, Page_H, PageFields.X, PageFields.Y, Para.Pages[CurPage].Y + Para.Lines[CurLine].Y - Para.Lines[CurLine].Metrics.Ascent, Para.Pages[_CurPage].Y), PageLimits, PageLimitsOrigin, _CurLine);
if (Math.abs(Item.X - oRecalcObj.X) > 0.001 || Math.abs(Item.Y - oRecalcObj.Y) > 0.001 || Item.PageNum !== oRecalcObj.PageNum)
{
// Положение картинок не совпало, отправляем пересчет текущей страницы.
PRSA.RecalcResult = recalcresult_CurPage | recalcresultflags_Page;
return;
}
break;
}
// У нас Flow-объект. Если он с обтеканием, тогда мы останавливаем пересчет и
// запоминаем текущий объект. В функции Internal_Recalculate_2 пересчитываем
// его позицию и сообщаем ее внешнему классу.
if ( true === Item.Use_TextWrap() )
{
var LogicDocument = Para.Parent;
var LDRecalcInfo = Para.Parent.RecalcInfo;
if ( true === LDRecalcInfo.Can_RecalcObject() )
{
// Обновляем позицию объекта
Item.Update_Position(PRSA.Paragraph, new CParagraphLayout( PRSA.X, PRSA.Y , PageAbs, PRSA.LastW, ColumnStartX, ColumnEndX, X_Left_Margin, X_Right_Margin, Page_Width, Top_Margin, Bottom_Margin, Page_H, PageFields.X, PageFields.Y, Para.Pages[CurPage].Y + Para.Lines[CurLine].Y - Para.Lines[CurLine].Metrics.Ascent, Para.Pages[_CurPage].Y), PageLimits, PageLimitsOrigin, _CurLine);
LDRecalcInfo.Set_FlowObject( Item, 0, recalcresult_NextElement, -1 );
// TODO: Добавить проверку на не попадание в предыдущие колонки
if (0 === PRSA.CurPage && Item.wrappingPolygon.top > PRSA.PageY + 0.001 && Item.wrappingPolygon.left > PRSA.PageX + 0.001)
PRSA.RecalcResult = recalcresult_CurPagePara;
else
PRSA.RecalcResult = recalcresult_CurPage | recalcresultflags_Page;
return;
}
else if ( true === LDRecalcInfo.Check_FlowObject(Item) )
{
// Если мы находимся с таблице, тогда делаем как Word, не пересчитываем предыдущую страницу,
// даже если это необходимо. Такое поведение нужно для точного определения рассчиталась ли
// данная страница окончательно или нет. Если у нас будет ветка с переходом на предыдущую страницу,
// тогда не рассчитав следующую страницу мы о конечном рассчете текущей страницы не узнаем.
// Если данный объект нашли, значит он уже был рассчитан и нам надо проверить номер страницы.
// Заметим, что даже если картинка привязана к колонке, и после пересчета место привязки картинки
// сдвигается в следующую колонку, мы проверяем все равно только реальную страницу (без
// учета колонок, так делает и Word).
if ( Item.PageNum === PageAbs )
{
// Все нормально, можно продолжить пересчет
LDRecalcInfo.Reset();
Item.Reset_SavedPosition();
}
else if ( true === Para.Parent.IsTableCellContent() )
{
// Картинка не на нужной странице, но так как это таблица
// мы пересчитываем заново текущую страницу, а не предыдущую
// Обновляем позицию объекта
Item.Update_Position(PRSA.Paragraph, new CParagraphLayout( PRSA.X, PRSA.Y, PageAbs, PRSA.LastW, ColumnStartX, ColumnEndX, X_Left_Margin, X_Right_Margin, Page_Width, Top_Margin, Bottom_Margin, Page_H, PageFields.X, PageFields.Y, Para.Pages[CurPage].Y + Para.Lines[CurLine].Y - Para.Lines[CurLine].Metrics.Ascent, Para.Pages[_CurPage].Y), PageLimits, PageLimitsOrigin, _CurLine);
LDRecalcInfo.Set_FlowObject( Item, 0, recalcresult_NextElement, -1 );
LDRecalcInfo.Set_PageBreakBefore( false );
PRSA.RecalcResult = recalcresult_CurPage | recalcresultflags_Page;
return;
}
else
{
LDRecalcInfo.Set_PageBreakBefore( true );
DrawingObjects.removeById( Item.PageNum, Item.Get_Id() );
PRSA.RecalcResult = recalcresult_PrevPage | recalcresultflags_Page;
return;
}
}
else
{
// Либо данный элемент уже обработан, либо будет обработан в будущем
}
continue;
}
else
{
// Картинка ложится на или под текст, в данном случае пересчет можно спокойно продолжать
// Здесь под верхом параграфа понимаем верх первой строки, а не значение, с которого начинается пересчет.
var ParagraphTop = Para.Lines[Para.Pages[_CurPage].StartLine].Top + Para.Pages[_CurPage].Y;
Item.Update_Position(PRSA.Paragraph, new CParagraphLayout( PRSA.X, PRSA.Y , PageAbs, PRSA.LastW, ColumnStartX, ColumnEndX, X_Left_Margin, X_Right_Margin, Page_Width, Top_Margin, Bottom_Margin, Page_H, PageFields.X, PageFields.Y, Para.Pages[CurPage].Y + Para.Lines[CurLine].Y - Para.Lines[CurLine].Metrics.Ascent, ParagraphTop), PageLimits, PageLimitsOrigin, _CurLine);
Item.Reset_SavedPosition();
}
}
break;
}
case para_PageNum:
case para_PageCount:
{
PRSA.X += Item.WidthVisible;
PRSA.LastW = Item.WidthVisible;
break;
}
case para_Tab:
{
PRSA.X += Item.WidthVisible;
break;
}
case para_End:
{
var SectPr = PRSA.Paragraph.Get_SectionPr();
if (!PRSA.Paragraph.LogicDocument || PRSA.Paragraph.LogicDocument !== PRSA.Paragraph.Parent || !PRSA.Paragraph.bFromDocument)
SectPr = undefined;
if ( undefined !== SectPr )
{
// Нас интересует следующая секция
var LogicDocument = PRSA.Paragraph.LogicDocument;
var NextSectPr = LogicDocument.SectionsInfo.Get_SectPr(PRSA.Paragraph.Index + 1).SectPr;
Item.Update_SectionPr(NextSectPr, PRSA.XEnd - PRSA.X);
}
else
Item.Clear_SectionPr();
PRSA.X += Item.Get_Width();
break;
}
case para_NewLine:
{
if (break_Page === Item.BreakType || break_Column === Item.BreakType)
Item.Update_String(PRSA.XEnd - PRSA.X);
PRSA.X += Item.WidthVisible;
break;
}
}
}
};
ParaRun.prototype.Recalculate_PageEndInfo = function(PRSI, _CurLine, _CurRange)
{
};
ParaRun.prototype.private_RecalculateNumbering = function(PRS, Item, ParaPr, _X)
{
var X = PRS.Recalculate_Numbering(Item, this, ParaPr, _X);
// Запоминаем, что на данном элементе была добавлена нумерация
this.RecalcInfo.NumberingAdd = false;
this.RecalcInfo.NumberingUse = true;
this.RecalcInfo.NumberingItem = PRS.Paragraph.Numbering;
return X;
};
ParaRun.prototype.Internal_Recalculate_LastTab = function(LastTab, X, XEnd, Word, WordLen, SpaceLen)
{
if ( -1 !== LastTab.Value )
{
var TempXPos = X;
if ( true === Word || WordLen > 0 )
TempXPos += SpaceLen + WordLen;
var TabItem = LastTab.Item;
var TabStartX = LastTab.X;
var TabRangeW = TempXPos - TabStartX;
var TabValue = LastTab.Value;
var TabPos = LastTab.TabPos;
var TabCalcW = 0;
if ( tab_Right === TabValue )
TabCalcW = Math.max( TabPos - (TabStartX + TabRangeW), 0 );
else if ( tab_Center === TabValue )
TabCalcW = Math.max( TabPos - (TabStartX + TabRangeW / 2), 0 );
if ( X + TabCalcW > XEnd )
TabCalcW = XEnd - X;
TabItem.Width = TabCalcW;
TabItem.WidthVisible = TabCalcW;
LastTab.Reset();
return X + TabCalcW;
}
return X;
};
ParaRun.prototype.Refresh_RecalcData = function(Data)
{
var Para = this.Paragraph;
if(this.Type == para_Math_Run)
{
if(this.Parent !== null && this.Parent !== undefined)
{
this.Parent.Refresh_RecalcData();
}
}
else if ( -1 !== this.StartLine && undefined !== Para )
{
var CurLine = this.StartLine;
var PagesCount = Para.Pages.length;
for (var CurPage = 0 ; CurPage < PagesCount; CurPage++ )
{
var Page = Para.Pages[CurPage];
if ( Page.StartLine <= CurLine && Page.EndLine >= CurLine )
{
Para.Refresh_RecalcData2(CurPage);
return;
}
}
Para.Refresh_RecalcData2(0);
}
};
ParaRun.prototype.Refresh_RecalcData2 = function()
{
this.Refresh_RecalcData();
};
ParaRun.prototype.SaveRecalculateObject = function(Copy)
{
var RecalcObj = new CRunRecalculateObject(this.StartLine, this.StartRange);
RecalcObj.Save_Lines( this, Copy );
RecalcObj.Save_RunContent( this, Copy );
return RecalcObj;
};
ParaRun.prototype.LoadRecalculateObject = function(RecalcObj)
{
RecalcObj.Load_Lines(this);
RecalcObj.Load_RunContent(this);
};
ParaRun.prototype.PrepareRecalculateObject = function()
{
this.protected_ClearLines();
var Count = this.Content.length;
for (var Index = 0; Index < Count; Index++)
{
var Item = this.Content[Index];
var ItemType = Item.Type;
if (para_PageNum === ItemType || para_Drawing === ItemType)
Item.PrepareRecalculateObject();
}
};
ParaRun.prototype.Is_EmptyRange = function(_CurLine, _CurRange)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
if ( EndPos <= StartPos )
return true;
return false;
};
ParaRun.prototype.Check_Range_OnlyMath = function(Checker, _CurRange, _CurLine)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
for (var Pos = StartPos; Pos < EndPos; Pos++)
{
var Item = this.Content[Pos];
var ItemType = Item.Type;
if (para_End === ItemType || para_NewLine === ItemType || (para_Drawing === ItemType && true !== Item.Is_Inline()))
continue;
else
{
Checker.Result = false;
Checker.Math = null;
break;
}
}
};
ParaRun.prototype.Check_MathPara = function(Checker)
{
var Count = this.Content.length;
if ( Count <= 0 )
return;
var Item = ( Checker.Direction > 0 ? this.Content[0] : this.Content[Count - 1] );
var ItemType = Item.Type;
if ( para_End === ItemType || para_NewLine === ItemType )
{
Checker.Result = true;
Checker.Found = true;
}
else
{
Checker.Result = false;
Checker.Found = true;
}
};
ParaRun.prototype.Check_PageBreak = function()
{
var Count = this.Content.length;
for (var Pos = 0; Pos < Count; Pos++)
{
var Item = this.Content[Pos];
if (para_NewLine === Item.Type && (break_Page === Item.BreakType || break_Column === Item.BreakType))
return true;
}
return false;
};
ParaRun.prototype.Check_BreakPageEnd = function(PBChecker)
{
var ContentLen = this.Content.length;
for ( var CurPos = 0; CurPos < ContentLen; CurPos++ )
{
var Item = this.Content[CurPos];
if ( true === PBChecker.FindPB )
{
if ( Item === PBChecker.PageBreak )
{
PBChecker.FindPB = false;
PBChecker.PageBreak.Flags.NewLine = true;
}
}
else
{
var ItemType = Item.Type;
if ( para_End === ItemType )
return true;
else if ( para_Drawing !== ItemType || drawing_Anchor !== Item.Get_DrawingType() )
return false;
}
}
return true;
};
ParaRun.prototype.RecalculateMinMaxContentWidth = function(MinMax)
{
this.Recalculate_MeasureContent();
var bWord = MinMax.bWord;
var nWordLen = MinMax.nWordLen;
var nSpaceLen = MinMax.nSpaceLen;
var nMinWidth = MinMax.nMinWidth;
var nMaxWidth = MinMax.nMaxWidth;
var nCurMaxWidth = MinMax.nCurMaxWidth;
var nMaxHeight = MinMax.nMaxHeight;
var bCheckTextHeight = false;
var Count = this.Content.length;
for ( var Pos = 0; Pos < Count; Pos++ )
{
var Item = this.Content[Pos];
var ItemType = Item.Type;
switch( ItemType )
{
case para_Text:
{
var ItemWidth = Item.Width / TEXTWIDTH_DIVIDER;//var ItemWidth = Item.Get_Width();
if ( false === bWord )
{
bWord = true;
nWordLen = ItemWidth;
}
else
{
nWordLen += ItemWidth;
if (Item.Flags & PARATEXT_FLAGS_SPACEAFTER)
{
if ( nMinWidth < nWordLen )
nMinWidth = nWordLen;
bWord = false;
nWordLen = 0;
}
}
if ( nSpaceLen > 0 )
{
nCurMaxWidth += nSpaceLen;
nSpaceLen = 0;
}
nCurMaxWidth += ItemWidth;
bCheckTextHeight = true;
break;
}
case para_Math_Text:
case para_Math_Ampersand:
case para_Math_Placeholder:
{
var ItemWidth = Item.Get_Width() / TEXTWIDTH_DIVIDER;
if ( false === bWord )
{
bWord = true;
nWordLen = ItemWidth;
}
else
{
nWordLen += ItemWidth;
}
nCurMaxWidth += ItemWidth;
bCheckTextHeight = true;
break;
}
case para_Space:
{
if ( true === bWord )
{
if ( nMinWidth < nWordLen )
nMinWidth = nWordLen;
bWord = false;
nWordLen = 0;
}
// Мы сразу не добавляем ширину пробелов к максимальной ширине, потому что
// пробелы, идущие в конце параграфа или перед переносом строки(явным), не
// должны учитываться.
nSpaceLen += Item.Width / TEXTWIDTH_DIVIDER;//nSpaceLen += Item.Get_Width();
bCheckTextHeight = true;
break;
}
case para_Math_BreakOperator:
{
if ( true === bWord )
{
if ( nMinWidth < nWordLen )
nMinWidth = nWordLen;
bWord = false;
nWordLen = 0;
}
nCurMaxWidth += Item.Get_Width() / TEXTWIDTH_DIVIDER;
bCheckTextHeight = true;
break;
}
case para_Drawing:
{
if ( true === bWord )
{
if ( nMinWidth < nWordLen )
nMinWidth = nWordLen;
bWord = false;
nWordLen = 0;
}
if ((true === Item.Is_Inline() || true === this.Paragraph.Parent.Is_DrawingShape()) && Item.Width > nMinWidth)
{
nMinWidth = Item.Width;
}
else if (true === Item.Use_TextWrap())
{
var DrawingW = Item.getXfrmExtX();
if (DrawingW > nMinWidth)
nMinWidth = DrawingW;
}
if ((true === Item.Is_Inline() || true === this.Paragraph.Parent.Is_DrawingShape()) && Item.Height > nMaxHeight)
{
nMaxHeight = Item.Height;
}
else if (true === Item.Use_TextWrap())
{
var DrawingH = Item.getXfrmExtY();
if (DrawingH > nMaxHeight)
nMaxHeight = DrawingH;
}
if ( nSpaceLen > 0 )
{
nCurMaxWidth += nSpaceLen;
nSpaceLen = 0;
}
if ( true === Item.Is_Inline() || true === this.Paragraph.Parent.Is_DrawingShape() )
nCurMaxWidth += Item.Width;
break;
}
case para_PageNum:
case para_PageCount:
{
if ( true === bWord )
{
if ( nMinWidth < nWordLen )
nMinWidth = nWordLen;
bWord = false;
nWordLen = 0;
}
if ( Item.Width > nMinWidth )
nMinWidth = Item.Get_Width();
if ( nSpaceLen > 0 )
{
nCurMaxWidth += nSpaceLen;
nSpaceLen = 0;
}
nCurMaxWidth += Item.Get_Width();
bCheckTextHeight = true;
break;
}
case para_Tab:
{
nWordLen += Item.Width;
if ( nMinWidth < nWordLen )
nMinWidth = nWordLen;
bWord = false;
nWordLen = 0;
if ( nSpaceLen > 0 )
{
nCurMaxWidth += nSpaceLen;
nSpaceLen = 0;
}
nCurMaxWidth += Item.Width;
bCheckTextHeight = true;
break;
}
case para_NewLine:
{
if ( nMinWidth < nWordLen )
nMinWidth = nWordLen;
bWord = false;
nWordLen = 0;
nSpaceLen = 0;
if ( nCurMaxWidth > nMaxWidth )
nMaxWidth = nCurMaxWidth;
nCurMaxWidth = 0;
bCheckTextHeight = true;
break;
}
case para_End:
{
if ( nMinWidth < nWordLen )
nMinWidth = nWordLen;
if ( nCurMaxWidth > nMaxWidth )
nMaxWidth = nCurMaxWidth;
if (nMaxHeight < 0.001)
bCheckTextHeight = true;
break;
}
}
}
if (true === bCheckTextHeight && nMaxHeight < this.TextAscent + this.TextDescent)
nMaxHeight = this.TextAscent + this.TextDescent;
MinMax.bWord = bWord;
MinMax.nWordLen = nWordLen;
MinMax.nSpaceLen = nSpaceLen;
MinMax.nMinWidth = nMinWidth;
MinMax.nMaxWidth = nMaxWidth;
MinMax.nCurMaxWidth = nCurMaxWidth;
MinMax.nMaxHeight = nMaxHeight;
};
ParaRun.prototype.Get_Range_VisibleWidth = function(RangeW, _CurLine, _CurRange)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
for ( var Pos = StartPos; Pos < EndPos; Pos++ )
{
var Item = this.Content[Pos];
var ItemType = Item.Type;
switch( ItemType )
{
case para_Sym:
case para_Text:
case para_Space:
case para_Math_Text:
case para_Math_Ampersand:
case para_Math_Placeholder:
case para_Math_BreakOperator:
{
RangeW.W += Item.Get_WidthVisible();
break;
}
case para_Drawing:
{
if ( true === Item.Is_Inline() )
RangeW.W += Item.Width;
break;
}
case para_PageNum:
case para_PageCount:
case para_Tab:
{
RangeW.W += Item.Width;
break;
}
case para_NewLine:
{
RangeW.W += Item.WidthVisible;
break;
}
case para_End:
{
RangeW.W += Item.Get_WidthVisible();
RangeW.End = true;
break;
}
}
}
};
ParaRun.prototype.Shift_Range = function(Dx, Dy, _CurLine, _CurRange)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
for ( var CurPos = StartPos; CurPos < EndPos; CurPos++ )
{
var Item = this.Content[CurPos];
if ( para_Drawing === Item.Type )
Item.Shift( Dx, Dy );
}
};
//-----------------------------------------------------------------------------------
// Функции отрисовки
//-----------------------------------------------------------------------------------
ParaRun.prototype.Draw_HighLights = function(PDSH)
{
var pGraphics = PDSH.Graphics;
var CurLine = PDSH.Line - this.StartLine;
var CurRange = ( 0 === CurLine ? PDSH.Range - this.StartRange : PDSH.Range );
var aHigh = PDSH.High;
var aColl = PDSH.Coll;
var aFind = PDSH.Find;
var aComm = PDSH.Comm;
var aShd = PDSH.Shd;
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
var Para = PDSH.Paragraph;
var SearchResults = Para.SearchResults;
var bDrawFind = PDSH.DrawFind;
var bDrawColl = PDSH.DrawColl;
var oCompiledPr = this.Get_CompiledPr(false);
var oShd = oCompiledPr.Shd;
var bDrawShd = ( oShd === undefined || c_oAscShdNil === oShd.Value ? false : true );
var ShdColor = ( true === bDrawShd ? oShd.Get_Color( PDSH.Paragraph ) : null );
if(this.Type == para_Math_Run && this.IsPlaceholder())
bDrawShd = false;
var X = PDSH.X;
var Y0 = PDSH.Y0;
var Y1 = PDSH.Y1;
var CommentsCount = PDSH.Comments.length;
var CommentId = ( CommentsCount > 0 ? PDSH.Comments[CommentsCount - 1] : null );
var CommentsFlag = PDSH.CommentsFlag;
var HighLight = oCompiledPr.HighLight;
var SearchMarksCount = this.SearchMarks.length;
this.CollaborativeMarks.Init_Drawing();
for ( var Pos = StartPos; Pos < EndPos; Pos++ )
{
var Item = this.Content[Pos];
var ItemType = Item.Type;
var ItemWidthVisible = Item.Get_WidthVisible();
// Определим попадание в поиск и совместное редактирование. Попадание в комментарий определять не надо,
// т.к. класс CParaRun попадает или не попадает в комментарий целиком.
for ( var SPos = 0; SPos < SearchMarksCount; SPos++)
{
var Mark = this.SearchMarks[SPos];
var MarkPos = Mark.SearchResult.StartPos.Get(Mark.Depth);
if ( Pos === MarkPos && true === Mark.Start )
PDSH.SearchCounter++;
}
var DrawSearch = ( PDSH.SearchCounter > 0 && true === bDrawFind ? true : false );
var DrawColl = this.CollaborativeMarks.Check( Pos );
if ( true === bDrawShd )
aShd.Add( Y0, Y1, X, X + ItemWidthVisible, 0, ShdColor.r, ShdColor.g, ShdColor.b, undefined, oShd );
switch( ItemType )
{
case para_PageNum:
case para_PageCount:
case para_Drawing:
case para_Tab:
case para_Text:
case para_Math_Text:
case para_Math_Placeholder:
case para_Math_BreakOperator:
case para_Math_Ampersand:
case para_Sym:
case para_FootnoteReference:
case para_FootnoteRef:
case para_Separator:
case para_ContinuationSeparator:
{
if ( para_Drawing === ItemType && !Item.Is_Inline() )
break;
if ( CommentsFlag != comments_NoComment )
aComm.Add( Y0, Y1, X, X + ItemWidthVisible, 0, 0, 0, 0, { Active : CommentsFlag === comments_ActiveComment ? true : false, CommentId : CommentId } );
else if ( highlight_None != HighLight )
aHigh.Add( Y0, Y1, X, X + ItemWidthVisible, 0, HighLight.r, HighLight.g, HighLight.b, undefined, HighLight );
if ( true === DrawSearch )
aFind.Add( Y0, Y1, X, X + ItemWidthVisible, 0, 0, 0, 0 );
else if ( null !== DrawColl )
aColl.Add( Y0, Y1, X, X + ItemWidthVisible, 0, DrawColl.r, DrawColl.g, DrawColl.b );
if ( para_Drawing != ItemType || Item.Is_Inline() )
X += ItemWidthVisible;
break;
}
case para_Space:
{
// Пробелы в конце строки (и строку состоящую из пробелов) не подчеркиваем, не зачеркиваем и не выделяем
if ( PDSH.Spaces > 0 )
{
if ( CommentsFlag != comments_NoComment )
aComm.Add( Y0, Y1, X, X + ItemWidthVisible, 0, 0, 0, 0, { Active : CommentsFlag === comments_ActiveComment ? true : false, CommentId : CommentId } );
else if ( highlight_None != HighLight )
aHigh.Add( Y0, Y1, X, X + ItemWidthVisible, 0, HighLight.r, HighLight.g, HighLight.b, undefined, HighLight );
PDSH.Spaces--;
}
if ( true === DrawSearch )
aFind.Add( Y0, Y1, X, X + ItemWidthVisible, 0, 0, 0, 0 );
else if ( null !== DrawColl )
aColl.Add( Y0, Y1, X, X + ItemWidthVisible, 0, DrawColl.r, DrawColl.g, DrawColl.b );
X += ItemWidthVisible;
break;
}
case para_End:
{
if ( null !== DrawColl )
aColl.Add( Y0, Y1, X, X + ItemWidthVisible, 0, DrawColl.r, DrawColl.g, DrawColl.b );
X += Item.Get_Width();
break;
}
case para_NewLine:
{
X += ItemWidthVisible;
break;
}
}
for ( var SPos = 0; SPos < SearchMarksCount; SPos++)
{
var Mark = this.SearchMarks[SPos];
var MarkPos = Mark.SearchResult.EndPos.Get(Mark.Depth);
if ( Pos + 1 === MarkPos && true !== Mark.Start )
PDSH.SearchCounter--;
}
}
// Обновим позицию X
PDSH.X = X;
};
ParaRun.prototype.Draw_Elements = function(PDSE)
{
var CurLine = PDSE.Line - this.StartLine;
var CurRange = ( 0 === CurLine ? PDSE.Range - this.StartRange : PDSE.Range );
var CurPage = PDSE.Page;
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
var Para = PDSE.Paragraph;
var pGraphics = PDSE.Graphics;
var BgColor = PDSE.BgColor;
var Theme = PDSE.Theme;
var X = PDSE.X;
var Y = PDSE.Y;
var CurTextPr = this.Get_CompiledPr( false );
pGraphics.SetTextPr( CurTextPr, Theme );
var InfoMathText ;
if(this.Type == para_Math_Run)
{
var ArgSize = this.Parent.Compiled_ArgSz.value,
bNormalText = this.IsNormalText();
var InfoTextPr =
{
TextPr: CurTextPr,
ArgSize: ArgSize,
bNormalText: bNormalText,
bEqArray: this.bEqArray
};
InfoMathText = new CMathInfoTextPr(InfoTextPr);
}
if ( undefined !== CurTextPr.Shd && c_oAscShdNil !== CurTextPr.Shd.Value )
BgColor = CurTextPr.Shd.Get_Color( Para );
var AutoColor = ( undefined != BgColor && false === BgColor.Check_BlackAutoColor() ? new CDocumentColor( 255, 255, 255, false ) : new CDocumentColor( 0, 0, 0, false ) );
var RGBA;
var ReviewType = this.Get_ReviewType();
var ReviewColor = null;
var bPresentation = this.Paragraph && !this.Paragraph.bFromDocument;
if (reviewtype_Add === ReviewType || reviewtype_Remove === ReviewType)
{
ReviewColor = this.Get_ReviewColor();
pGraphics.b_color1(ReviewColor.r, ReviewColor.g, ReviewColor.b, 255);
}
else if (CurTextPr.Unifill)
{
CurTextPr.Unifill.check(PDSE.Theme, PDSE.ColorMap);
RGBA = CurTextPr.Unifill.getRGBAColor();
if ( true === PDSE.VisitedHyperlink && ( undefined === this.Pr.Color && undefined === this.Pr.Unifill || bPresentation) )
{
AscFormat.G_O_VISITED_HLINK_COLOR.check(PDSE.Theme, PDSE.ColorMap);
RGBA = AscFormat.G_O_VISITED_HLINK_COLOR.getRGBAColor();
pGraphics.b_color1( RGBA.R, RGBA.G, RGBA.B, RGBA.A );
}
else
{
if(bPresentation && PDSE.Hyperlink)
{
AscFormat.G_O_HLINK_COLOR.check(PDSE.Theme, PDSE.ColorMap);
RGBA = AscFormat.G_O_HLINK_COLOR.getRGBAColor();
pGraphics.b_color1( RGBA.R, RGBA.G, RGBA.B, RGBA.A );
}
else
{
pGraphics.b_color1( RGBA.R, RGBA.G, RGBA.B, RGBA.A);
}
}
}
else
{
if ( true === PDSE.VisitedHyperlink && ( undefined === this.Pr.Color && undefined === this.Pr.Unifill ) )
{
AscFormat.G_O_VISITED_HLINK_COLOR.check(PDSE.Theme, PDSE.ColorMap);
RGBA = AscFormat.G_O_VISITED_HLINK_COLOR.getRGBAColor();
pGraphics.b_color1( RGBA.R, RGBA.G, RGBA.B, RGBA.A );
}
else if ( true === CurTextPr.Color.Auto )
{
pGraphics.b_color1( AutoColor.r, AutoColor.g, AutoColor.b, 255);
}
else
{
pGraphics.b_color1( CurTextPr.Color.r, CurTextPr.Color.g, CurTextPr.Color.b, 255);
}
}
for ( var Pos = StartPos; Pos < EndPos; Pos++ )
{
var Item = this.Content[Pos];
var ItemType = Item.Type;
var TempY = Y;
switch (CurTextPr.VertAlign)
{
case AscCommon.vertalign_SubScript:
{
Y -= vertalign_Koef_Sub * CurTextPr.FontSize * g_dKoef_pt_to_mm;
break;
}
case AscCommon.vertalign_SuperScript:
{
Y -= vertalign_Koef_Super * CurTextPr.FontSize * g_dKoef_pt_to_mm;
break;
}
}
switch( ItemType )
{
case para_PageNum:
case para_PageCount:
case para_Drawing:
case para_Tab:
case para_Text:
case para_Sym:
case para_FootnoteReference:
case para_FootnoteRef:
case para_Separator:
case para_ContinuationSeparator:
{
if (para_Tab === ItemType)
{
pGraphics.p_color(0, 0, 0, 255);
pGraphics.b_color1(0, 0, 0, 255);
}
if (para_Drawing != ItemType || Item.Is_Inline())
{
Item.Draw(X, Y - this.YOffset, pGraphics, PDSE);
X += Item.Get_WidthVisible();
}
// Внутри отрисовки инлайн-автофигур могут изменится цвета и шрифт, поэтому восстанавливаем настройки
if ((para_Drawing === ItemType && Item.Is_Inline()) || (para_Tab === ItemType))
{
pGraphics.SetTextPr( CurTextPr, Theme );
if (reviewtype_Add === ReviewType || reviewtype_Remove === ReviewType)
{
pGraphics.b_color1(ReviewColor.r, ReviewColor.g, ReviewColor.b, 255);
}
else if (RGBA)
{
pGraphics.b_color1( RGBA.R, RGBA.G, RGBA.B, 255);
pGraphics.p_color( RGBA.R, RGBA.G, RGBA.B, 255);
}
else
{
if ( true === CurTextPr.Color.Auto )
{
pGraphics.b_color1( AutoColor.r, AutoColor.g, AutoColor.b, 255);
pGraphics.p_color( AutoColor.r, AutoColor.g, AutoColor.b, 255);
}
else
{
pGraphics.b_color1( CurTextPr.Color.r, CurTextPr.Color.g, CurTextPr.Color.b, 255);
pGraphics.p_color( CurTextPr.Color.r, CurTextPr.Color.g, CurTextPr.Color.b, 255);
}
}
}
break;
}
case para_Space:
{
Item.Draw( X, Y - this.YOffset, pGraphics );
X += Item.Get_WidthVisible();
break;
}
case para_End:
{
var SectPr = Para.Get_SectionPr();
if (!Para.LogicDocument || Para.LogicDocument !== Para.Parent)
SectPr = undefined;
if ( undefined === SectPr )
{
// Выставляем настройки для символа параграфа
var EndTextPr = Para.Get_CompiledPr2(false).TextPr.Copy();
EndTextPr.Merge(Para.TextPr.Value);
if (reviewtype_Common !== ReviewType)
{
pGraphics.SetTextPr(EndTextPr, PDSE.Theme);
pGraphics.b_color1(ReviewColor.r, ReviewColor.g, ReviewColor.b, 255);
}
else if (EndTextPr.Unifill)
{
EndTextPr.Unifill.check(PDSE.Theme, PDSE.ColorMap);
var RGBAEnd = EndTextPr.Unifill.getRGBAColor();
pGraphics.SetTextPr(EndTextPr, PDSE.Theme);
pGraphics.b_color1(RGBAEnd.R, RGBAEnd.G, RGBAEnd.B, 255);
}
else
{
pGraphics.SetTextPr(EndTextPr, PDSE.Theme);
if (true === EndTextPr.Color.Auto)
pGraphics.b_color1(AutoColor.r, AutoColor.g, AutoColor.b, 255);
else
pGraphics.b_color1(EndTextPr.Color.r, EndTextPr.Color.g, EndTextPr.Color.b, 255);
}
var bEndCell = false;
if (null === Para.Get_DocumentNext() && true === Para.Parent.IsTableCellContent())
bEndCell = true;
Item.Draw(X, Y - this.YOffset, pGraphics, bEndCell, reviewtype_Common !== ReviewType ? true : false);
}
else
{
Item.Draw(X, Y - this.YOffset, pGraphics, false, false);
}
X += Item.Get_Width();
break;
}
case para_NewLine:
{
Item.Draw( X, Y - this.YOffset, pGraphics );
X += Item.WidthVisible;
break;
}
case para_Math_Ampersand:
case para_Math_Text:
case para_Math_BreakOperator:
{
var PosLine = this.ParaMath.GetLinePosition(PDSE.Line, PDSE.Range);
Item.Draw(PosLine.x, PosLine.y, pGraphics, InfoMathText);
X += Item.Get_WidthVisible();
break;
}
case para_Math_Placeholder:
{
if(pGraphics.RENDERER_PDF_FLAG !== true) // если идет печать/ конвертация в PDF плейсхолдер не отрисовываем
{
var PosLine = this.ParaMath.GetLinePosition(PDSE.Line, PDSE.Range);
Item.Draw(PosLine.x, PosLine.y, pGraphics, InfoMathText);
X += Item.Get_WidthVisible();
}
break;
}
}
Y = TempY;
}
// Обновляем позицию
PDSE.X = X;
};
ParaRun.prototype.Draw_Lines = function(PDSL)
{
var CurLine = PDSL.Line - this.StartLine;
var CurRange = ( 0 === CurLine ? PDSL.Range - this.StartRange : PDSL.Range );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
var X = PDSL.X;
var Y = PDSL.Baseline;
var UndOff = PDSL.UnderlineOffset;
var Para = PDSL.Paragraph;
var aStrikeout = PDSL.Strikeout;
var aDStrikeout = PDSL.DStrikeout;
var aUnderline = PDSL.Underline;
var aSpelling = PDSL.Spelling;
var CurTextPr = this.Get_CompiledPr( false );
var StrikeoutY = Y - this.YOffset;
var fontCoeff = 1; // учтем ArgSize
if(this.Type == para_Math_Run)
{
var ArgSize = this.Parent.Compiled_ArgSz;
fontCoeff = MatGetKoeffArgSize(CurTextPr.FontSize, ArgSize.value);
}
switch(CurTextPr.VertAlign)
{
case AscCommon.vertalign_Baseline : StrikeoutY += -CurTextPr.FontSize * fontCoeff * g_dKoef_pt_to_mm * 0.27; break;
case AscCommon.vertalign_SubScript : StrikeoutY += -CurTextPr.FontSize * fontCoeff * vertalign_Koef_Size * g_dKoef_pt_to_mm * 0.27 - vertalign_Koef_Sub * CurTextPr.FontSize * fontCoeff * g_dKoef_pt_to_mm; break;
case AscCommon.vertalign_SuperScript: StrikeoutY += -CurTextPr.FontSize * fontCoeff * vertalign_Koef_Size * g_dKoef_pt_to_mm * 0.27 - vertalign_Koef_Super * CurTextPr.FontSize * fontCoeff * g_dKoef_pt_to_mm; break;
}
var UnderlineY = Y + UndOff - this.YOffset;
var LineW = (CurTextPr.FontSize / 18) * g_dKoef_pt_to_mm;
var BgColor = PDSL.BgColor;
if ( undefined !== CurTextPr.Shd && c_oAscShdNil !== CurTextPr.Shd.Value )
BgColor = CurTextPr.Shd.Get_Color( Para );
var AutoColor = ( undefined != BgColor && false === BgColor.Check_BlackAutoColor() ? new CDocumentColor( 255, 255, 255, false ) : new CDocumentColor( 0, 0, 0, false ) );
var CurColor, RGBA, Theme = this.Paragraph.Get_Theme(), ColorMap = this.Paragraph.Get_ColorMap();
var ReviewType = this.Get_ReviewType();
var bAddReview = reviewtype_Add === ReviewType ? true : false;
var bRemReview = reviewtype_Remove === ReviewType ? true : false;
var ReviewColor = this.Get_ReviewColor();
// Выставляем цвет обводки
var bPresentation = this.Paragraph && !this.Paragraph.bFromDocument;
if ( true === PDSL.VisitedHyperlink && ( undefined === this.Pr.Color && undefined === this.Pr.Unifill || bPresentation) )
{
AscFormat.G_O_VISITED_HLINK_COLOR.check(Theme, ColorMap);
RGBA = AscFormat.G_O_VISITED_HLINK_COLOR.getRGBAColor();
CurColor = new CDocumentColor( RGBA.R, RGBA.G, RGBA.B, RGBA.A );
}
else if ( true === CurTextPr.Color.Auto && !CurTextPr.Unifill)
CurColor = new CDocumentColor( AutoColor.r, AutoColor.g, AutoColor.b );
else
{
if(CurTextPr.Unifill)
{
CurTextPr.Unifill.check(Theme, ColorMap);
RGBA = CurTextPr.Unifill.getRGBAColor();
CurColor = new CDocumentColor( RGBA.R, RGBA.G, RGBA.B );
}
else
{
CurColor = new CDocumentColor( CurTextPr.Color.r, CurTextPr.Color.g, CurTextPr.Color.b );
}
}
var SpellingMarksArray = {};
var SpellingMarksCount = this.SpellingMarks.length;
for ( var SPos = 0; SPos < SpellingMarksCount; SPos++)
{
var Mark = this.SpellingMarks[SPos];
if ( false === Mark.Element.Checked )
{
if ( true === Mark.Start )
{
var MarkPos = Mark.Element.StartPos.Get(Mark.Depth);
if ( undefined === SpellingMarksArray[MarkPos] )
SpellingMarksArray[MarkPos] = 1;
else
SpellingMarksArray[MarkPos] += 1;
}
else
{
var MarkPos = Mark.Element.EndPos.Get(Mark.Depth);
if ( undefined === SpellingMarksArray[MarkPos] )
SpellingMarksArray[MarkPos] = 2;
else
SpellingMarksArray[MarkPos] += 2;
}
}
}
for ( var Pos = StartPos; Pos < EndPos; Pos++ )
{
var Item = this.Content[Pos];
var ItemType = Item.Type;
var ItemWidthVisible = Item.Get_WidthVisible();
if ( 1 === SpellingMarksArray[Pos] || 3 === SpellingMarksArray[Pos] )
PDSL.SpellingCounter++;
switch( ItemType )
{
case para_End:
{
if (this.Paragraph)
{
if (bAddReview)
aUnderline.Add(UnderlineY, UnderlineY, X, X + ItemWidthVisible, LineW, ReviewColor.r, ReviewColor.g, ReviewColor.b);
else if (bRemReview)
aStrikeout.Add(StrikeoutY, StrikeoutY, X, X + ItemWidthVisible, LineW, ReviewColor.r, ReviewColor.g, ReviewColor.b);
}
X += ItemWidthVisible;
break;
}
case para_NewLine:
{
X += ItemWidthVisible;
break;
}
case para_PageNum:
case para_PageCount:
case para_Drawing:
case para_Tab:
case para_Text:
case para_Sym:
case para_FootnoteReference:
case para_FootnoteRef:
case para_Separator:
case para_ContinuationSeparator:
{
if (para_Text === ItemType && null !== this.CompositeInput && Pos >= this.CompositeInput.Pos && Pos < this.CompositeInput.Pos + this.CompositeInput.Length)
{
aUnderline.Add(UnderlineY, UnderlineY, X, X + ItemWidthVisible, LineW, CurColor.r, CurColor.g, CurColor.b, undefined, CurTextPr);
}
if ( para_Drawing != ItemType || Item.Is_Inline() )
{
if (true === bRemReview)
aStrikeout.Add(StrikeoutY, StrikeoutY, X, X + ItemWidthVisible, LineW, ReviewColor.r, ReviewColor.g, ReviewColor.b);
else if (true === CurTextPr.DStrikeout)
aDStrikeout.Add( StrikeoutY, StrikeoutY, X, X + ItemWidthVisible, LineW, CurColor.r, CurColor.g, CurColor.b, undefined, CurTextPr );
else if ( true === CurTextPr.Strikeout )
aStrikeout.Add( StrikeoutY, StrikeoutY, X, X + ItemWidthVisible, LineW, CurColor.r, CurColor.g, CurColor.b, undefined, CurTextPr );
if (true === bAddReview)
aUnderline.Add(UnderlineY, UnderlineY, X, X + ItemWidthVisible, LineW, ReviewColor.r, ReviewColor.g, ReviewColor.b);
else if (true === CurTextPr.Underline)
aUnderline.Add(UnderlineY, UnderlineY, X, X + ItemWidthVisible, LineW, CurColor.r, CurColor.g, CurColor.b, undefined, CurTextPr );
if ( PDSL.SpellingCounter > 0 )
aSpelling.Add( UnderlineY, UnderlineY, X, X + ItemWidthVisible, LineW, 0, 0, 0 );
X += ItemWidthVisible;
}
break;
}
case para_Space:
{
// Пробелы, идущие в конце строки, не подчеркиваем и не зачеркиваем
if ( PDSL.Spaces > 0 )
{
if (true === bRemReview)
aStrikeout.Add(StrikeoutY, StrikeoutY, X, X + ItemWidthVisible, LineW, ReviewColor.r, ReviewColor.g, ReviewColor.b);
else if (true === CurTextPr.DStrikeout)
aDStrikeout.Add( StrikeoutY, StrikeoutY, X, X + ItemWidthVisible, LineW, CurColor.r, CurColor.g, CurColor.b, undefined, CurTextPr );
else if ( true === CurTextPr.Strikeout )
aStrikeout.Add( StrikeoutY, StrikeoutY, X, X + ItemWidthVisible, LineW, CurColor.r, CurColor.g, CurColor.b, undefined, CurTextPr );
if (true === bAddReview)
aUnderline.Add(UnderlineY, UnderlineY, X, X + ItemWidthVisible, LineW, ReviewColor.r, ReviewColor.g, ReviewColor.b);
else if (true === CurTextPr.Underline)
aUnderline.Add( UnderlineY, UnderlineY, X, X + ItemWidthVisible, LineW, CurColor.r, CurColor.g, CurColor.b, undefined, CurTextPr );
PDSL.Spaces--;
}
X += ItemWidthVisible;
break;
}
case para_Math_Text:
case para_Math_BreakOperator:
case para_Math_Ampersand:
{
if (true === bRemReview)
aStrikeout.Add( StrikeoutY, StrikeoutY, X, X + ItemWidthVisible, LineW, ReviewColor.r, ReviewColor.g, ReviewColor.b, undefined, CurTextPr );
else if (true === CurTextPr.DStrikeout)
aDStrikeout.Add( StrikeoutY, StrikeoutY, X, X + ItemWidthVisible, LineW, CurColor.r, CurColor.g, CurColor.b, undefined, CurTextPr );
else if ( true === CurTextPr.Strikeout )
aStrikeout.Add( StrikeoutY, StrikeoutY, X, X + ItemWidthVisible, LineW, CurColor.r, CurColor.g, CurColor.b, undefined, CurTextPr );
X += ItemWidthVisible;
break;
}
case para_Math_Placeholder:
{
var ctrPrp = this.Parent.GetCtrPrp();
if (true === bRemReview)
aStrikeout.Add( StrikeoutY, StrikeoutY, X, X + ItemWidthVisible, LineW, ReviewColor.r, ReviewColor.g, ReviewColor.b, undefined, CurTextPr );
if(true === ctrPrp.DStrikeout)
aDStrikeout.Add( StrikeoutY, StrikeoutY, X, X + ItemWidthVisible, LineW, CurColor.r, CurColor.g, CurColor.b, undefined, CurTextPr );
else if(true === ctrPrp.Strikeout)
aStrikeout.Add( StrikeoutY, StrikeoutY, X, X + ItemWidthVisible, LineW, CurColor.r, CurColor.g, CurColor.b, undefined, CurTextPr );
X += ItemWidthVisible;
break;
}
}
if ( 2 === SpellingMarksArray[Pos + 1] || 3 === SpellingMarksArray[Pos + 1] )
PDSL.SpellingCounter--;
}
if (true === this.Pr.Have_PrChange() && para_Math_Run !== this.Type)
{
var ReviewColor = this.Get_PrReviewColor();
PDSL.RunReview.Add(0, 0, PDSL.X, X, 0, ReviewColor.r, ReviewColor.g, ReviewColor.b, {RunPr: this.Pr});
}
var CollPrChangeColor = this.private_GetCollPrChangeOther();
if (false !== CollPrChangeColor)
PDSL.CollChange.Add(0, 0, PDSL.X, X, 0, CollPrChangeColor.r, CollPrChangeColor.g, CollPrChangeColor.b, {RunPr : this.Pr});
// Обновляем позицию
PDSL.X = X;
};
//-----------------------------------------------------------------------------------
// Функции для работы с курсором
//-----------------------------------------------------------------------------------
// Находится ли курсор в начале рана
ParaRun.prototype.Is_CursorPlaceable = function()
{
return true;
};
ParaRun.prototype.Cursor_Is_Start = function()
{
if ( this.State.ContentPos <= 0 )
return true;
return false;
};
// Проверяем нужно ли поправить позицию курсора
ParaRun.prototype.Cursor_Is_NeededCorrectPos = function()
{
if ( true === this.Is_Empty(false) )
return true;
var NewRangeStart = false;
var RangeEnd = false;
var Pos = this.State.ContentPos;
var LinesLen = this.protected_GetLinesCount();
for ( var CurLine = 0; CurLine < LinesLen; CurLine++ )
{
var RangesLen = this.protected_GetRangesCount(CurLine);
for ( var CurRange = 0; CurRange < RangesLen; CurRange++ )
{
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
if (0 !== CurLine || 0 !== CurRange)
{
if (Pos === StartPos)
{
NewRangeStart = true;
}
}
if (Pos === EndPos)
{
RangeEnd = true;
}
}
if ( true === NewRangeStart )
break;
}
if ( true !== NewRangeStart && true !== RangeEnd && true === this.Cursor_Is_Start() )
return true;
return false;
};
ParaRun.prototype.Cursor_Is_End = function()
{
if ( this.State.ContentPos >= this.Content.length )
return true;
return false;
};
ParaRun.prototype.MoveCursorToStartPos = function()
{
this.State.ContentPos = 0;
};
ParaRun.prototype.MoveCursorToEndPos = function(SelectFromEnd)
{
if ( true === SelectFromEnd )
{
var Selection = this.State.Selection;
Selection.Use = true;
Selection.StartPos = this.Content.length;
Selection.EndPos = this.Content.length;
}
else
{
var CurPos = this.Content.length;
while ( CurPos > 0 )
{
if ( para_End === this.Content[CurPos - 1].Type )
CurPos--;
else
break;
}
this.State.ContentPos = CurPos;
}
};
ParaRun.prototype.Get_ParaContentPosByXY = function(SearchPos, Depth, _CurLine, _CurRange, StepEnd)
{
var Result = false;
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
var CurPos = StartPos;
var InMathText = this.Type == para_Math_Run ? SearchPos.InText == true : false;
for (; CurPos < EndPos; CurPos++ )
{
var Item = this.Content[CurPos];
var ItemType = Item.Type;
var TempDx = 0;
if (para_Drawing != ItemType || true === Item.Is_Inline())
{
TempDx = Item.Get_WidthVisible();
}
if(this.Type == para_Math_Run)
{
var PosLine = this.ParaMath.GetLinePosition(_CurLine, _CurRange);
var loc = this.Content[CurPos].GetLocationOfLetter();
SearchPos.CurX = PosLine.x + loc.x; // позиция формулы в строке + смещение буквы в контенте
}
// Проверяем, попали ли мы в данный элемент
var Diff = SearchPos.X - SearchPos.CurX;
if ((Math.abs( Diff ) < SearchPos.DiffX + 0.001 && (SearchPos.CenterMode || SearchPos.X > SearchPos.CurX)) && InMathText == false)
{
SearchPos.DiffX = Math.abs(Diff);
SearchPos.Pos.Update(CurPos, Depth);
Result = true;
if ( Diff >= - 0.001 && Diff <= TempDx + 0.001 )
{
SearchPos.InTextPos.Update( CurPos, Depth );
SearchPos.InText = true;
}
}
SearchPos.CurX += TempDx;
// Заглушка для знака параграфа и конца строки
Diff = SearchPos.X - SearchPos.CurX;
if ((Math.abs( Diff ) < SearchPos.DiffX + 0.001 && (SearchPos.CenterMode || SearchPos.X > SearchPos.CurX)) && InMathText == false)
{
if ( para_End === ItemType )
{
SearchPos.End = true;
// Если мы ищем позицию для селекта, тогда нужно искать и за знаком параграфа
if ( true === StepEnd )
{
SearchPos.DiffX = Math.abs(Diff);
SearchPos.Pos.Update( this.Content.length, Depth );
Result = true;
}
}
else if ( CurPos === EndPos - 1 && para_NewLine != ItemType )
{
SearchPos.DiffX = Math.abs(Diff);
SearchPos.Pos.Update( EndPos, Depth );
Result = true;
}
}
}
// Такое возможно, если все раны до этого (в том числе и этот) были пустыми, тогда, чтобы не возвращать
// неправильную позицию вернем позицию начала данного путого рана.
if ( SearchPos.DiffX > 1000000 - 1 )
{
SearchPos.DiffX = SearchPos.X - SearchPos.CurX;
SearchPos.Pos.Update( StartPos, Depth );
Result = true;
}
if (this.Type == para_Math_Run) // не только для пустых Run, но и для проверки на конец Run (т.к. Diff не обновляется)
{
//для пустых Run искомая позиция - позиция самого Run
var bEmpty = this.Is_Empty();
var PosLine = this.ParaMath.GetLinePosition(_CurLine, _CurRange);
if(bEmpty)
SearchPos.CurX = PosLine.x + this.pos.x;
Diff = SearchPos.X - SearchPos.CurX;
if(SearchPos.InText == false && (bEmpty || StartPos !== EndPos) && (Math.abs( Diff ) < SearchPos.DiffX + 0.001 && (SearchPos.CenterMode || SearchPos.X > SearchPos.CurX)))
{
SearchPos.DiffX = Math.abs(Diff);
SearchPos.Pos.Update(CurPos, Depth);
Result = true;
}
}
return Result;
};
ParaRun.prototype.Get_ParaContentPos = function(bSelection, bStart, ContentPos, bUseCorrection)
{
var Pos = ( true !== bSelection ? this.State.ContentPos : ( false !== bStart ? this.State.Selection.StartPos : this.State.Selection.EndPos ) );
ContentPos.Add(Pos);
};
ParaRun.prototype.Set_ParaContentPos = function(ContentPos, Depth)
{
var Pos = ContentPos.Get(Depth);
var Count = this.Content.length;
if ( Pos > Count )
Pos = Count;
// TODO: Как только переделаем работу c Para_End переделать здесь
for ( var TempPos = 0; TempPos < Pos; TempPos++ )
{
if ( para_End === this.Content[TempPos].Type )
{
Pos = TempPos;
break;
}
}
if ( Pos < 0 )
Pos = 0;
this.State.ContentPos = Pos;
};
ParaRun.prototype.Get_PosByElement = function(Class, ContentPos, Depth, UseRange, Range, Line)
{
if ( this === Class )
return true;
return false;
};
ParaRun.prototype.Get_ElementByPos = function(ContentPos, Depth)
{
return this;
};
ParaRun.prototype.Get_PosByDrawing = function(Id, ContentPos, Depth)
{
var Count = this.Content.length;
for ( var CurPos = 0; CurPos < Count; CurPos++ )
{
var Item = this.Content[CurPos];
if ( para_Drawing === Item.Type && Id === Item.Get_Id() )
{
ContentPos.Update( CurPos, Depth );
return true;
}
}
return false;
};
ParaRun.prototype.Get_RunElementByPos = function(ContentPos, Depth)
{
if ( undefined !== ContentPos )
{
var CurPos = ContentPos.Get(Depth);
var ContentLen = this.Content.length;
if ( CurPos >= this.Content.length || CurPos < 0 )
return null;
return this.Content[CurPos];
}
else
{
if ( this.Content.length > 0 )
return this.Content[0];
else
return null;
}
};
ParaRun.prototype.Get_LastRunInRange = function(_CurLine, _CurRange)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
return this;
};
ParaRun.prototype.Get_LeftPos = function(SearchPos, ContentPos, Depth, UseContentPos)
{
var CurPos = true === UseContentPos ? ContentPos.Get(Depth) : this.Content.length;
while (true)
{
CurPos--;
var Item = this.Content[CurPos];
if (CurPos < 0 || (!(para_Drawing === Item.Type && false === Item.Is_Inline() && false === SearchPos.IsCheckAnchors()) && !(para_FootnoteReference === Item.Type && true === Item.IsCustomMarkFollows())))
break;
}
if (CurPos >= 0)
{
SearchPos.Found = true;
SearchPos.Pos.Update(CurPos, Depth);
}
};
ParaRun.prototype.Get_RightPos = function(SearchPos, ContentPos, Depth, UseContentPos, StepEnd)
{
var CurPos = ( true === UseContentPos ? ContentPos.Get(Depth) : 0 );
var Count = this.Content.length;
while (true)
{
CurPos++;
// Мы встали в конец рана:
// Если мы перешагнули para_End или para_Drawing Anchor, тогда возвращаем false
// В противном случае true
if (Count === CurPos)
{
if (CurPos === 0)
return;
var PrevItem = this.Content[CurPos - 1];
var PrevItemType = PrevItem.Type;
if ((true !== StepEnd && para_End === PrevItemType) || (para_Drawing === PrevItemType && false === PrevItem.Is_Inline() && false === SearchPos.IsCheckAnchors()) || (para_FootnoteReference === PrevItemType && true === PrevItem.IsCustomMarkFollows()))
return;
break;
}
if (CurPos > Count)
break;
// Минимальное значение CurPos = 1, т.к. мы начинаем со значния >= 0 и добавляем 1
var Item = this.Content[CurPos - 1];
var ItemType = Item.Type;
if (!(true !== StepEnd && para_End === ItemType)
&& !(para_Drawing === Item.Type && false === Item.Is_Inline())
&& !(para_FootnoteReference === Item.Type && true === Item.IsCustomMarkFollows()))
break;
}
if (CurPos <= Count)
{
SearchPos.Found = true;
SearchPos.Pos.Update(CurPos, Depth);
}
};
ParaRun.prototype.Get_WordStartPos = function(SearchPos, ContentPos, Depth, UseContentPos)
{
var CurPos = ( true === UseContentPos ? ContentPos.Get(Depth) - 1 : this.Content.length - 1 );
if ( CurPos < 0 )
return;
SearchPos.Shift = true;
var NeedUpdate = false;
// На первом этапе ищем позицию первого непробельного элемента
if ( 0 === SearchPos.Stage )
{
while ( true )
{
var Item = this.Content[CurPos];
var Type = Item.Type;
var bSpace = false;
if ( para_Space === Type || para_Tab === Type || ( para_Text === Type && true === Item.Is_NBSP() ) || ( para_Drawing === Type && true !== Item.Is_Inline() ) )
bSpace = true;
if ( true === bSpace )
{
CurPos--;
// Выходим из данного рана
if ( CurPos < 0 )
return;
}
else
{
// Если мы остановились на нетекстовом элементе, тогда его и возвращаем
if ( para_Text !== this.Content[CurPos].Type && para_Math_Text !== this.Content[CurPos].Type)
{
SearchPos.Pos.Update( CurPos, Depth );
SearchPos.Found = true;
SearchPos.UpdatePos = true;
return;
}
SearchPos.Pos.Update( CurPos, Depth );
SearchPos.Stage = 1;
SearchPos.Punctuation = this.Content[CurPos].Is_Punctuation();
NeedUpdate = true;
break;
}
}
}
else
{
CurPos = ( true === UseContentPos ? ContentPos.Get(Depth) : this.Content.length );
}
// На втором этапе мы смотрим на каком элементе мы встали: если текст - пунктуация, тогда сдвигаемся
// до конца всех знаков пунктуации
while ( CurPos > 0 )
{
CurPos--;
var Item = this.Content[CurPos];
var TempType = Item.Type;
if ( (para_Text !== TempType && para_Math_Text !== TempType) || true === Item.Is_NBSP() || ( true === SearchPos.Punctuation && true !== Item.Is_Punctuation() ) || ( false === SearchPos.Punctuation && false !== Item.Is_Punctuation() ) )
{
SearchPos.Found = true;
break;
}
else
{
SearchPos.Pos.Update( CurPos, Depth );
NeedUpdate = true;
}
}
SearchPos.UpdatePos = NeedUpdate;
};
ParaRun.prototype.Get_WordEndPos = function(SearchPos, ContentPos, Depth, UseContentPos, StepEnd)
{
var CurPos = ( true === UseContentPos ? ContentPos.Get(Depth) : 0 );
var ContentLen = this.Content.length;
if ( CurPos >= ContentLen )
return;
var NeedUpdate = false;
if ( 0 === SearchPos.Stage )
{
// На первом этапе ищем первый нетекстовый ( и не таб ) элемент
while ( true )
{
var Item = this.Content[CurPos];
var Type = Item.Type;
var bText = false;
if ( (para_Text === Type || para_Math_Text === Type) && true != Item.Is_NBSP() && ( true === SearchPos.First || ( SearchPos.Punctuation === Item.Is_Punctuation() ) ) )
bText = true;
if ( true === bText )
{
if ( true === SearchPos.First )
{
SearchPos.First = false;
SearchPos.Punctuation = Item.Is_Punctuation();
}
CurPos++;
// Отмечаем, что сдвиг уже произошел
SearchPos.Shift = true;
// Выходим из рана
if ( CurPos >= ContentLen )
return;
}
else
{
SearchPos.Stage = 1;
// Первый найденный элемент не текстовый, смещаемся вперед
if ( true === SearchPos.First )
{
// Если первый найденный элемент - конец параграфа, тогда выходим из поиска
if ( para_End === Type )
{
if ( true === StepEnd )
{
SearchPos.Pos.Update( CurPos + 1, Depth );
SearchPos.Found = true;
SearchPos.UpdatePos = true;
}
return;
}
CurPos++;
// Отмечаем, что сдвиг уже произошел
SearchPos.Shift = true;
}
break;
}
}
}
if ( CurPos >= ContentLen )
return;
// На втором этапе мы смотрим на каком элементе мы встали: если это не пробел, тогда
// останавливаемся здесь. В противном случае сдвигаемся вперед, пока не попали на первый
// не пробельный элемент.
if ( !(para_Space === this.Content[CurPos].Type || ( para_Text === this.Content[CurPos].Type && true === this.Content[CurPos].Is_NBSP() ) ) )
{
SearchPos.Pos.Update( CurPos, Depth );
SearchPos.Found = true;
SearchPos.UpdatePos = true;
}
else
{
while ( CurPos < ContentLen - 1 )
{
CurPos++;
var Item = this.Content[CurPos];
var TempType = Item.Type;
if ( (true !== StepEnd && para_End === TempType) || !( para_Space === TempType || ( para_Text === TempType && true === Item.Is_NBSP() ) ) )
{
SearchPos.Found = true;
break;
}
}
// Обновляем позицию в конце каждого рана (хуже от этого не будет)
SearchPos.Pos.Update( CurPos, Depth );
SearchPos.UpdatePos = true;
}
};
ParaRun.prototype.Get_EndRangePos = function(_CurLine, _CurRange, SearchPos, Depth)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
var LastPos = -1;
for ( var CurPos = StartPos; CurPos < EndPos; CurPos++ )
{
var Item = this.Content[CurPos];
var ItemType = Item.Type;
if ( !((para_Drawing === ItemType && true !== Item.Is_Inline()) || para_End === ItemType || (para_NewLine === ItemType && break_Line === Item.BreakType)))
LastPos = CurPos + 1;
}
// Проверяем, попал ли хоть один элемент в данный отрезок, если нет, тогда не регистрируем такой ран
if ( -1 !== LastPos )
{
SearchPos.Pos.Update( LastPos, Depth );
return true;
}
else
return false;
};
ParaRun.prototype.Get_StartRangePos = function(_CurLine, _CurRange, SearchPos, Depth)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
var FirstPos = -1;
for ( var CurPos = EndPos - 1; CurPos >= StartPos; CurPos-- )
{
var Item = this.Content[CurPos];
if ( !(para_Drawing === Item.Type && true !== Item.Is_Inline()) )
FirstPos = CurPos;
}
// Проверяем, попал ли хоть один элемент в данный отрезок, если нет, тогда не регистрируем такой ран
if ( -1 !== FirstPos )
{
SearchPos.Pos.Update( FirstPos, Depth );
return true;
}
else
return false;
};
ParaRun.prototype.Get_StartRangePos2 = function(_CurLine, _CurRange, ContentPos, Depth)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var Pos = this.protected_GetRangeStartPos(CurLine, CurRange);
ContentPos.Update( Pos, Depth );
};
ParaRun.prototype.Get_EndRangePos2 = function(_CurLine, _CurRange, ContentPos, Depth)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = (0 === CurLine ? _CurRange - this.StartRange : _CurRange);
var Pos = this.protected_GetRangeEndPos(CurLine, CurRange);
ContentPos.Update(Pos, Depth);
};
ParaRun.prototype.Get_StartPos = function(ContentPos, Depth)
{
ContentPos.Update( 0, Depth );
};
ParaRun.prototype.Get_EndPos = function(BehindEnd, ContentPos, Depth)
{
var ContentLen = this.Content.length;
if ( true === BehindEnd )
ContentPos.Update( ContentLen, Depth );
else
{
for ( var CurPos = 0; CurPos < ContentLen; CurPos++ )
{
if ( para_End === this.Content[CurPos].Type )
{
ContentPos.Update( CurPos, Depth );
return;
}
}
// Не нашли para_End
ContentPos.Update( ContentLen, Depth );
}
};
//-----------------------------------------------------------------------------------
// Функции для работы с селектом
//-----------------------------------------------------------------------------------
ParaRun.prototype.Set_SelectionContentPos = function(StartContentPos, EndContentPos, Depth, StartFlag, EndFlag)
{
var StartPos = 0;
switch (StartFlag)
{
case 1: StartPos = 0; break;
case -1: StartPos = this.Content.length; break;
case 0: StartPos = StartContentPos.Get(Depth); break;
}
var EndPos = 0;
switch (EndFlag)
{
case 1: EndPos = 0; break;
case -1: EndPos = this.Content.length; break;
case 0: EndPos = EndContentPos.Get(Depth); break;
}
var Selection = this.State.Selection;
Selection.StartPos = StartPos;
Selection.EndPos = EndPos;
Selection.Use = true;
};
ParaRun.prototype.SetContentSelection = function(StartDocPos, EndDocPos, Depth, StartFlag, EndFlag)
{
var StartPos = 0;
switch (StartFlag)
{
case 1: StartPos = 0; break;
case -1: StartPos = this.Content.length; break;
case 0: StartPos = StartDocPos[Depth].Position; break;
}
var EndPos = 0;
switch (EndFlag)
{
case 1: EndPos = 0; break;
case -1: EndPos = this.Content.length; break;
case 0: EndPos = EndDocPos[Depth].Position; break;
}
var Selection = this.State.Selection;
Selection.StartPos = StartPos;
Selection.EndPos = EndPos;
Selection.Use = true;
};
ParaRun.prototype.SetContentPosition = function(DocPos, Depth, Flag)
{
var Pos = 0;
switch (Flag)
{
case 1: Pos = 0; break;
case -1: Pos = this.Content.length; break;
case 0: Pos = DocPos[Depth].Position; break;
}
var nLen = this.Content.length;
if (nLen > 0 && Pos >= nLen && para_End === this.Content[nLen - 1].Type)
Pos = nLen - 1;
this.State.ContentPos = Pos;
};
ParaRun.prototype.Set_SelectionAtEndPos = function()
{
this.Set_SelectionContentPos(null, null, 0, -1, -1);
};
ParaRun.prototype.Set_SelectionAtStartPos = function()
{
this.Set_SelectionContentPos(null, null, 0, 1, 1);
};
ParaRun.prototype.IsSelectionUse = function()
{
return this.State.Selection.Use;
};
ParaRun.prototype.IsSelectedAll = function(Props)
{
var Selection = this.State.Selection;
if ( false === Selection.Use && true !== this.Is_Empty( Props ) )
return false;
var SkipAnchor = Props ? Props.SkipAnchor : false;
var SkipEnd = Props ? Props.SkipEnd : false;
var StartPos = Selection.StartPos;
var EndPos = Selection.EndPos;
if ( EndPos < StartPos )
{
StartPos = Selection.EndPos;
EndPos = Selection.StartPos;
}
for ( var Pos = 0; Pos < StartPos; Pos++ )
{
var Item = this.Content[Pos];
var ItemType = Item.Type;
if ( !( ( true === SkipAnchor && ( para_Drawing === ItemType && true !== Item.Is_Inline() ) ) || ( true === SkipEnd && para_End === ItemType ) ) )
return false;
}
var Count = this.Content.length;
for ( var Pos = EndPos; Pos < Count; Pos++ )
{
var Item = this.Content[Pos];
var ItemType = Item.Type;
if ( !( ( true === SkipAnchor && ( para_Drawing === ItemType && true !== Item.Is_Inline() ) ) || ( true === SkipEnd && para_End === ItemType ) ) )
return false;
}
return true;
};
ParaRun.prototype.Selection_CorrectLeftPos = function(Direction)
{
if ( false === this.Selection.Use || true === this.Is_Empty( { SkipAnchor : true } ) )
return true;
var Selection = this.State.Selection;
var StartPos = Math.min( Selection.StartPos, Selection.EndPos );
var EndPos = Math.max( Selection.StartPos, Selection.EndPos );
for ( var Pos = 0; Pos < StartPos; Pos++ )
{
var Item = this.Content[Pos];
if ( para_Drawing !== Item.Type || true === Item.Is_Inline() )
return false;
}
for ( var Pos = StartPos; Pos < EndPos; Pos++ )
{
var Item = this.Content[Pos];
if ( para_Drawing === Item.Type && true !== Item.Is_Inline() )
{
if ( 1 === Direction )
Selection.StartPos = Pos + 1;
else
Selection.EndPos = Pos + 1;
}
else
return false;
}
return true;
};
ParaRun.prototype.RemoveSelection = function()
{
var Selection = this.State.Selection;
Selection.Use = false;
Selection.StartPos = 0;
Selection.EndPos = 0;
};
ParaRun.prototype.SelectAll = function(Direction)
{
var Selection = this.State.Selection;
Selection.Use = true;
if ( -1 === Direction )
{
Selection.StartPos = this.Content.length;
Selection.EndPos = 0;
}
else
{
Selection.StartPos = 0;
Selection.EndPos = this.Content.length;
}
};
ParaRun.prototype.Selection_DrawRange = function(_CurLine, _CurRange, SelectionDraw)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
var Selection = this.State.Selection;
var SelectionUse = Selection.Use;
var SelectionStartPos = Selection.StartPos;
var SelectionEndPos = Selection.EndPos;
if ( SelectionStartPos > SelectionEndPos )
{
SelectionStartPos = Selection.EndPos;
SelectionEndPos = Selection.StartPos;
}
var FindStart = SelectionDraw.FindStart;
for(var CurPos = StartPos; CurPos < EndPos; CurPos++)
{
var Item = this.Content[CurPos];
var ItemType = Item.Type;
var DrawSelection = false;
if ( true === FindStart )
{
if ( true === Selection.Use && CurPos >= SelectionStartPos && CurPos < SelectionEndPos )
{
FindStart = false;
DrawSelection = true;
}
else
{
if ( para_Drawing !== ItemType || true === Item.Is_Inline() )
SelectionDraw.StartX += Item.Get_WidthVisible();
}
}
else
{
if ( true === Selection.Use && CurPos >= SelectionStartPos && CurPos < SelectionEndPos )
{
DrawSelection = true;
}
}
if ( true === DrawSelection )
{
if (para_Drawing === ItemType && true !== Item.Is_Inline())
{
if (true === SelectionDraw.Draw)
Item.Draw_Selection();
}
else
SelectionDraw.W += Item.Get_WidthVisible();
}
}
SelectionDraw.FindStart = FindStart;
};
ParaRun.prototype.IsSelectionEmpty = function(CheckEnd)
{
var Selection = this.State.Selection;
if (true !== Selection.Use)
return true;
if(this.Type == para_Math_Run && this.IsPlaceholder())
return true;
var StartPos = Selection.StartPos;
var EndPos = Selection.EndPos;
if ( StartPos > EndPos )
{
StartPos = Selection.EndPos;
EndPos = Selection.StartPos;
}
if ( true === CheckEnd )
return ( EndPos > StartPos ? false : true );
else if(this.Type == para_Math_Run && this.Is_Empty())
{
return false;
}
else
{
for ( var CurPos = StartPos; CurPos < EndPos; CurPos++ )
{
var ItemType = this.Content[CurPos].Type;
if (para_End !== ItemType)
return false;
}
}
return true;
};
ParaRun.prototype.Selection_CheckParaEnd = function()
{
var Selection = this.State.Selection;
if ( true !== Selection.Use )
return false;
var StartPos = Selection.StartPos;
var EndPos = Selection.EndPos;
if ( StartPos > EndPos )
{
StartPos = Selection.EndPos;
EndPos = Selection.StartPos;
}
for ( var CurPos = StartPos; CurPos < EndPos; CurPos++ )
{
var Item = this.Content[CurPos];
if ( para_End === Item.Type )
return true;
}
return false;
};
ParaRun.prototype.Selection_CheckParaContentPos = function(ContentPos, Depth, bStart, bEnd)
{
var CurPos = ContentPos.Get(Depth);
if (this.Selection.StartPos <= this.Selection.EndPos && this.Selection.StartPos <= CurPos && CurPos <= this.Selection.EndPos)
{
if ((true !== bEnd) || (true === bEnd && CurPos !== this.Selection.EndPos))
return true;
}
else if (this.Selection.StartPos > this.Selection.EndPos && this.Selection.EndPos <= CurPos && CurPos <= this.Selection.StartPos)
{
if ((true !== bEnd) || (true === bEnd && CurPos !== this.Selection.StartPos))
return true;
}
return false;
};
//-----------------------------------------------------------------------------------
// Функции для работы с настройками текста свойств
//-----------------------------------------------------------------------------------
ParaRun.prototype.Clear_TextFormatting = function( DefHyper )
{
// Highlight и Lang не сбрасываются при очистке текстовых настроек
this.Set_Bold( undefined );
this.Set_Italic( undefined );
this.Set_Strikeout( undefined );
this.Set_Underline( undefined );
this.Set_FontSize( undefined );
this.Set_Color( undefined );
this.Set_Unifill( undefined );
this.Set_VertAlign( undefined );
this.Set_Spacing( undefined );
this.Set_DStrikeout( undefined );
this.Set_Caps( undefined );
this.Set_SmallCaps( undefined );
this.Set_Position( undefined );
this.Set_RFonts2( undefined );
this.Set_RStyle( undefined );
this.Set_Shd( undefined );
this.Set_TextFill( undefined );
this.Set_TextOutline( undefined );
// Насильно заставим пересчитать стиль, т.к. как данная функция вызывается у параграфа, у которого мог смениться стиль
this.Recalc_CompiledPr(true);
};
ParaRun.prototype.Get_TextPr = function()
{
return this.Pr.Copy();
};
ParaRun.prototype.Get_FirstTextPr = function()
{
return this.Pr;
};
ParaRun.prototype.Get_CompiledTextPr = function(Copy)
{
if ( true === this.State.Selection.Use && true === this.Selection_CheckParaEnd() )
{
var ThisTextPr = this.Get_CompiledPr( true );
var Para = this.Paragraph;
var EndTextPr = Para.Get_CompiledPr2(false).TextPr.Copy();
EndTextPr.Merge( Para.TextPr.Value );
ThisTextPr = ThisTextPr.Compare( EndTextPr );
return ThisTextPr;
}
else
{
return this.Get_CompiledPr(Copy);
}
};
ParaRun.prototype.Recalc_CompiledPr = function(RecalcMeasure)
{
this.RecalcInfo.TextPr = true;
// Если изменение какой-то текстовой настройки требует пересчета элементов
if ( true === RecalcMeasure )
this.RecalcInfo.Measure = true;
// Если мы в формуле, тогда ее надо пересчитывать
this.private_RecalcCtrPrp();
};
ParaRun.prototype.Recalc_RunsCompiledPr = function()
{
this.Recalc_CompiledPr(true);
};
ParaRun.prototype.Get_CompiledPr = function(bCopy)
{
if ( true === this.RecalcInfo.TextPr )
{
this.RecalcInfo.TextPr = false;
this.CompiledPr = this.Internal_Compile_Pr();
}
if ( false === bCopy )
return this.CompiledPr;
else
return this.CompiledPr.Copy(); // Отдаем копию объекта, чтобы никто не поменял извне настройки стиля
};
ParaRun.prototype.Internal_Compile_Pr = function ()
{
if ( undefined === this.Paragraph || null === this.Paragraph )
{
// Сюда мы никогда не должны попадать, но на всякий случай,
// чтобы не выпадало ошибок сгенерим дефолтовые настройки
var TextPr = new CTextPr();
TextPr.Init_Default();
this.RecalcInfo.TextPr = true;
return TextPr;
}
// Получим настройки текста, для данного параграфа
var TextPr = this.Paragraph.Get_CompiledPr2(false).TextPr.Copy();
// Если в прямых настройках задан стиль, тогда смержим настройки стиля
if ( undefined != this.Pr.RStyle )
{
var Styles = this.Paragraph.Parent.Get_Styles();
var StyleTextPr = Styles.Get_Pr( this.Pr.RStyle, styletype_Character ).TextPr;
TextPr.Merge( StyleTextPr );
}
if(this.Type == para_Math_Run)
{
if (undefined === this.Parent || null === this.Parent)
{
// Сюда мы никогда не должны попадать, но на всякий случай,
// чтобы не выпадало ошибок сгенерим дефолтовые настройки
var TextPr = new CTextPr();
TextPr.Init_Default();
this.RecalcInfo.TextPr = true;
return TextPr;
}
if(!this.IsNormalText()) // math text
{
// выставим дефолтные текстовые настройки для математических Run
var Styles = this.Paragraph.Parent.Get_Styles();
var StyleId = this.Paragraph.Style_Get();
// скопируем текстовые настройки прежде чем подменим на пустые
var MathFont = {Name : "Cambria Math", Index : -1};
var oShapeStyle = null, oShapeTextPr = null;;
if(Styles && typeof Styles.lastId === "string")
{
StyleId = Styles.lastId;
Styles = Styles.styles;
oShapeStyle = Styles.Get(StyleId);
oShapeTextPr = oShapeStyle.TextPr.Copy();
oShapeStyle.TextPr.RFonts.Merge({Ascii: MathFont});
}
var StyleDefaultTextPr = Styles.Default.TextPr.Copy();
// Ascii - по умолчанию шрифт Cambria Math
// hAnsi, eastAsia, cs - по умолчанию шрифты не Cambria Math, а те, которые компилируются в документе
Styles.Default.TextPr.RFonts.Merge({Ascii: MathFont});
var Pr = Styles.Get_Pr( StyleId, styletype_Paragraph, null, null );
TextPr.RFonts.Set_FromObject(Pr.TextPr.RFonts);
// подменяем обратно
Styles.Default.TextPr = StyleDefaultTextPr;
if(oShapeStyle && oShapeTextPr)
{
oShapeStyle.TextPr = oShapeTextPr;
}
}
if(this.IsPlaceholder())
{
TextPr.Merge(this.Parent.GetCtrPrp());
TextPr.Merge( this.Pr ); // Мержим прямые настройки данного рана
}
else
{
TextPr.Merge( this.Pr ); // Мержим прямые настройки данного рана
if(!this.IsNormalText()) // math text
{
var MPrp = this.MathPrp.GetTxtPrp();
TextPr.Merge(MPrp); // bold, italic
}
}
}
else
{
TextPr.Merge( this.Pr ); // Мержим прямые настройки данного рана
if(this.Pr.Color && !this.Pr.Unifill)
{
TextPr.Unifill = undefined;
}
}
// Для совместимости со старыми версиями запишем FontFamily
TextPr.FontFamily.Name = TextPr.RFonts.Ascii.Name;
TextPr.FontFamily.Index = TextPr.RFonts.Ascii.Index;
return TextPr;
};
// В данной функции мы жестко меняем настройки на те, которые пришли (т.е. полностью удаляем старые)
ParaRun.prototype.Set_Pr = function(TextPr)
{
var OldValue = this.Pr;
this.Pr = TextPr;
History.Add(new CChangesRunTextPr(this, OldValue, TextPr, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(true);
this.protected_UpdateSpellChecking();
this.private_UpdateTrackRevisionOnChangeTextPr(true);
};
ParaRun.prototype.Apply_TextPr = function(TextPr, IncFontSize, ApplyToAll)
{
var bReview = false;
if (this.Paragraph && this.Paragraph.LogicDocument && this.Paragraph.bFromDocument && true === this.Paragraph.LogicDocument.Is_TrackRevisions())
bReview = true;
var ReviewType = this.Get_ReviewType();
var IsPrChange = this.Have_PrChange();
if ( true === ApplyToAll )
{
if (true === bReview && true !== this.Have_PrChange())
this.Add_PrChange();
if ( undefined === IncFontSize )
{
this.Apply_Pr(TextPr);
}
else
{
var _TextPr = new CTextPr();
var CurTextPr = this.Get_CompiledPr( false );
this.private_AddCollPrChangeMine();
this.Set_FontSize( FontSize_IncreaseDecreaseValue( IncFontSize, CurTextPr.FontSize ) );
}
// Дополнительно проверим, если у нас para_End лежит в данном ране и попадает в выделение, тогда
// применим заданные настроки к символу конца параграфа
// TODO: Возможно, стоит на этапе пересчета запонимать, лежит ли para_End в данном ране. Чтобы в каждом
// ране потом не бегать каждый раз по всему массиву в поисках para_End.
var bEnd = false;
var Count = this.Content.length;
for ( var Pos = 0; Pos < Count; Pos++ )
{
if ( para_End === this.Content[Pos].Type )
{
bEnd = true;
break;
}
}
if ( true === bEnd )
{
if ( undefined === IncFontSize )
{
if(!TextPr.AscFill && !TextPr.AscLine && !TextPr.AscUnifill)
{
this.Paragraph.TextPr.Apply_TextPr( TextPr );
}
else
{
var EndTextPr = this.Paragraph.Get_CompiledPr2(false).TextPr.Copy();
EndTextPr.Merge( this.Paragraph.TextPr.Value );
if(TextPr.AscFill)
{
this.Paragraph.TextPr.Set_TextFill(AscFormat.CorrectUniFill(TextPr.AscFill, EndTextPr.TextFill, 1));
}
if(TextPr.AscUnifill)
{
this.Paragraph.TextPr.Set_Unifill(AscFormat.CorrectUniFill(TextPr.AscUnifill, EndTextPr.Unifill, 0));
}
if(TextPr.AscLine)
{
this.Paragraph.TextPr.Set_TextOutline(AscFormat.CorrectUniStroke(TextPr.AscLine, EndTextPr.TextOutline, 0));
}
}
}
else
{
var Para = this.Paragraph;
// Выставляем настройки для символа параграфа
var EndTextPr = Para.Get_CompiledPr2(false).TextPr.Copy();
EndTextPr.Merge( Para.TextPr.Value );
// TODO: Как только перенесем историю изменений TextPr в сам класс CTextPr, переделать тут
Para.TextPr.Set_FontSize( FontSize_IncreaseDecreaseValue( IncFontSize, EndTextPr.FontSize ) );
}
}
}
else
{
var Result = [];
var LRun = this, CRun = null, RRun = null;
if ( true === this.State.Selection.Use )
{
var StartPos = this.State.Selection.StartPos;
var EndPos = this.State.Selection.EndPos;
if (StartPos === EndPos && 0 !== this.Content.length)
{
CRun = this;
LRun = null;
RRun = null;
}
else
{
var Direction = 1;
if (StartPos > EndPos)
{
var Temp = StartPos;
StartPos = EndPos;
EndPos = Temp;
Direction = -1;
}
// Если выделено не до конца, тогда разделяем по последней точке
if (EndPos < this.Content.length)
{
RRun = LRun.Split_Run(EndPos);
RRun.Set_ReviewType(ReviewType);
if (IsPrChange)
RRun.Add_PrChange();
}
// Если выделено не с начала, тогда делим по начальной точке
if (StartPos > 0)
{
CRun = LRun.Split_Run(StartPos);
CRun.Set_ReviewType(ReviewType);
if (IsPrChange)
CRun.Add_PrChange();
}
else
{
CRun = LRun;
LRun = null;
}
if (null !== LRun)
{
LRun.Selection.Use = true;
LRun.Selection.StartPos = LRun.Content.length;
LRun.Selection.EndPos = LRun.Content.length;
}
CRun.SelectAll(Direction);
if (true === bReview && true !== CRun.Have_PrChange())
CRun.Add_PrChange();
if (undefined === IncFontSize)
CRun.Apply_Pr(TextPr);
else
{
var _TextPr = new CTextPr();
var CurTextPr = this.Get_CompiledPr(false);
CRun.private_AddCollPrChangeMine();
CRun.Set_FontSize(FontSize_IncreaseDecreaseValue(IncFontSize, CurTextPr.FontSize));
}
if (null !== RRun)
{
RRun.Selection.Use = true;
RRun.Selection.StartPos = 0;
RRun.Selection.EndPos = 0;
}
// Дополнительно проверим, если у нас para_End лежит в данном ране и попадает в выделение, тогда
// применим заданные настроки к символу конца параграфа
// TODO: Возможно, стоит на этапе пересчета запонимать, лежит ли para_End в данном ране. Чтобы в каждом
// ране потом не бегать каждый раз по всему массиву в поисках para_End.
if (true === this.Selection_CheckParaEnd())
{
if (undefined === IncFontSize)
{
if (!TextPr.AscFill && !TextPr.AscLine && !TextPr.AscUnifill)
{
this.Paragraph.TextPr.Apply_TextPr(TextPr);
}
else
{
var EndTextPr = this.Paragraph.Get_CompiledPr2(false).TextPr.Copy();
EndTextPr.Merge(this.Paragraph.TextPr.Value);
if (TextPr.AscFill)
{
this.Paragraph.TextPr.Set_TextFill(AscFormat.CorrectUniFill(TextPr.AscFill, EndTextPr.TextFill, 1));
}
if (TextPr.AscUnifill)
{
this.Paragraph.TextPr.Set_Unifill(AscFormat.CorrectUniFill(TextPr.AscUnifill, EndTextPr.Unifill, 0));
}
if (TextPr.AscLine)
{
this.Paragraph.TextPr.Set_TextOutline(AscFormat.CorrectUniStroke(TextPr.AscLine, EndTextPr.TextOutline, 0));
}
}
}
else
{
var Para = this.Paragraph;
// Выставляем настройки для символа параграфа
var EndTextPr = Para.Get_CompiledPr2(false).TextPr.Copy();
EndTextPr.Merge(Para.TextPr.Value);
// TODO: Как только перенесем историю изменений TextPr в сам класс CTextPr, переделать тут
Para.TextPr.Set_FontSize(FontSize_IncreaseDecreaseValue(IncFontSize, EndTextPr.FontSize));
}
}
}
}
else
{
var CurPos = this.State.ContentPos;
// Если выделено не до конца, тогда разделяем по последней точке
if ( CurPos < this.Content.length )
{
RRun = LRun.Split_Run(CurPos);
RRun.Set_ReviewType(ReviewType);
if (IsPrChange)
RRun.Add_PrChange();
}
if ( CurPos > 0 )
{
CRun = LRun.Split_Run(CurPos);
CRun.Set_ReviewType(ReviewType);
if (IsPrChange)
CRun.Add_PrChange();
}
else
{
CRun = LRun;
LRun = null;
}
if ( null !== LRun )
LRun.RemoveSelection();
CRun.RemoveSelection();
CRun.MoveCursorToStartPos();
if (true === bReview && true !== CRun.Have_PrChange())
CRun.Add_PrChange();
if ( undefined === IncFontSize )
{
CRun.Apply_Pr( TextPr );
}
else
{
var _TextPr = new CTextPr();
var CurTextPr = this.Get_CompiledPr( false );
CRun.private_AddCollPrChangeMine();
CRun.Set_FontSize( FontSize_IncreaseDecreaseValue( IncFontSize, CurTextPr.FontSize ) );
}
if ( null !== RRun )
RRun.RemoveSelection();
}
Result.push( LRun );
Result.push( CRun );
Result.push( RRun );
return Result;
}
};
ParaRun.prototype.Split_Run = function(Pos)
{
History.Add(new CChangesRunOnStartSplit(this, Pos));
AscCommon.CollaborativeEditing.OnStart_SplitRun(this, Pos);
// Создаем новый ран
var bMathRun = this.Type == para_Math_Run;
var NewRun = new ParaRun(this.Paragraph, bMathRun);
// Копируем настройки
NewRun.Set_Pr(this.Pr.Copy(true));
if(bMathRun)
NewRun.Set_MathPr(this.MathPrp.Copy());
var OldCrPos = this.State.ContentPos;
var OldSSPos = this.State.Selection.StartPos;
var OldSEPos = this.State.Selection.EndPos;
// Разделяем содержимое по ранам
NewRun.Concat_ToContent( this.Content.slice(Pos) );
this.Remove_FromContent( Pos, this.Content.length - Pos, true );
// Подправим точки селекта и текущей позиции
if ( OldCrPos >= Pos )
{
NewRun.State.ContentPos = OldCrPos - Pos;
this.State.ContentPos = this.Content.length;
}
else
{
NewRun.State.ContentPos = 0;
}
if ( OldSSPos >= Pos )
{
NewRun.State.Selection.StartPos = OldSSPos - Pos;
this.State.Selection.StartPos = this.Content.length;
}
else
{
NewRun.State.Selection.StartPos = 0;
}
if ( OldSEPos >= Pos )
{
NewRun.State.Selection.EndPos = OldSEPos - Pos;
this.State.Selection.EndPos = this.Content.length;
}
else
{
NewRun.State.Selection.EndPos = 0;
}
// Если были точки орфографии, тогда переместим их в новый ран
var SpellingMarksCount = this.SpellingMarks.length;
for ( var Index = 0; Index < SpellingMarksCount; Index++ )
{
var Mark = this.SpellingMarks[Index];
var MarkPos = ( true === Mark.Start ? Mark.Element.StartPos.Get(Mark.Depth) : Mark.Element.EndPos.Get(Mark.Depth) );
if ( MarkPos >= Pos )
{
var MarkElement = Mark.Element;
if ( true === Mark.Start )
{
//MarkElement.ClassesS[Mark.Depth] = NewRun;
MarkElement.StartPos.Data[Mark.Depth] -= Pos;
}
else
{
//MarkElement.ClassesE[Mark.Depth] = NewRun;
MarkElement.EndPos.Data[Mark.Depth] -= Pos;
}
NewRun.SpellingMarks.push( Mark );
this.SpellingMarks.splice( Index, 1 );
SpellingMarksCount--;
Index--;
}
}
History.Add(new CChangesRunOnEndSplit(this, NewRun));
AscCommon.CollaborativeEditing.OnEnd_SplitRun(NewRun);
return NewRun;
};
ParaRun.prototype.Clear_TextPr = function()
{
// Данная функция вызывается пока только при изменении стиля параграфа. Оставляем в этой ситуации язык неизмененным,
// а также не трогаем highlight.
var NewTextPr = new CTextPr();
NewTextPr.Lang = this.Pr.Lang.Copy();
NewTextPr.HighLight = this.Pr.Copy_HighLight();
this.Set_Pr( NewTextPr );
};
// В данной функции мы применяем приходящие настройки поверх старых, т.е. старые не удаляем
ParaRun.prototype.Apply_Pr = function(TextPr)
{
this.private_AddCollPrChangeMine();
if(this.Type == para_Math_Run && false === this.IsNormalText())
{
if(null === TextPr.Bold && null === TextPr.Italic)
this.Math_Apply_Style(undefined);
else
{
if(undefined != TextPr.Bold)
{
if(TextPr.Bold == true)
{
if(this.MathPrp.sty == STY_ITALIC || this.MathPrp.sty == undefined)
this.Math_Apply_Style(STY_BI);
else if(this.MathPrp.sty == STY_PLAIN)
this.Math_Apply_Style(STY_BOLD);
}
else if(TextPr.Bold == false || TextPr.Bold == null)
{
if(this.MathPrp.sty == STY_BI || this.MathPrp.sty == undefined)
this.Math_Apply_Style(STY_ITALIC);
else if(this.MathPrp.sty == STY_BOLD)
this.Math_Apply_Style(STY_PLAIN);
}
}
if(undefined != TextPr.Italic)
{
if(TextPr.Italic == true)
{
if(this.MathPrp.sty == STY_BOLD)
this.Math_Apply_Style(STY_BI);
else if(this.MathPrp.sty == STY_PLAIN || this.MathPrp.sty == undefined)
this.Math_Apply_Style(STY_ITALIC);
}
else if(TextPr.Italic == false || TextPr.Italic == null)
{
if(this.MathPrp.sty == STY_BI)
this.Math_Apply_Style(STY_BOLD);
else if(this.MathPrp.sty == STY_ITALIC || this.MathPrp.sty == undefined)
this.Math_Apply_Style(STY_PLAIN);
}
}
}
}
else
{
if ( undefined != TextPr.Bold )
this.Set_Bold( null === TextPr.Bold ? undefined : TextPr.Bold );
if( undefined != TextPr.Italic )
this.Set_Italic( null === TextPr.Italic ? undefined : TextPr.Italic );
}
if ( undefined != TextPr.Strikeout )
this.Set_Strikeout( null === TextPr.Strikeout ? undefined : TextPr.Strikeout );
if ( undefined !== TextPr.Underline )
this.Set_Underline( null === TextPr.Underline ? undefined : TextPr.Underline );
if ( undefined != TextPr.FontSize )
this.Set_FontSize( null === TextPr.FontSize ? undefined : TextPr.FontSize );
if ( undefined !== TextPr.Color && undefined === TextPr.Unifill )
{
this.Set_Color( null === TextPr.Color ? undefined : TextPr.Color );
this.Set_Unifill( undefined );
this.Set_TextFill(undefined);
}
if ( undefined !== TextPr.Unifill )
{
this.Set_Unifill(null === TextPr.Unifill ? undefined : TextPr.Unifill);
this.Set_Color(undefined);
this.Set_TextFill(undefined);
}
else if(undefined !== TextPr.AscUnifill && this.Paragraph)
{
if(!this.Paragraph.bFromDocument)
{
var oCompiledPr = this.Get_CompiledPr(true);
this.Set_Unifill(AscFormat.CorrectUniFill(TextPr.AscUnifill, oCompiledPr.Unifill, 0), AscCommon.isRealObject(TextPr.AscUnifill) && TextPr.AscUnifill.asc_CheckForseSet() );
this.Set_Color(undefined);
this.Set_TextFill(undefined);
}
}
if(undefined !== TextPr.TextFill)
{
this.Set_Unifill(undefined);
this.Set_Color(undefined);
this.Set_TextFill(null === TextPr.TextFill ? undefined : TextPr.TextFill);
}
else if(undefined !== TextPr.AscFill && this.Paragraph)
{
var oMergeUnifill, oColor;
if(this.Paragraph.bFromDocument)
{
var oCompiledPr = this.Get_CompiledPr(true);
if(oCompiledPr.TextFill)
{
oMergeUnifill = oCompiledPr.TextFill;
}
else if(oCompiledPr.Unifill)
{
oMergeUnifill = oCompiledPr.Unifill;
}
else if(oCompiledPr.Color)
{
oColor = oCompiledPr.Color;
oMergeUnifill = AscFormat.CreateUnfilFromRGB(oColor.r, oColor.g, oColor.b);
}
this.Set_Unifill(undefined);
this.Set_Color(undefined);
this.Set_TextFill(AscFormat.CorrectUniFill(TextPr.AscFill, oMergeUnifill, 1), AscCommon.isRealObject(TextPr.AscFill) && TextPr.AscFill.asc_CheckForseSet());
}
}
if(undefined !== TextPr.TextOutline)
{
this.Set_TextOutline(null === TextPr.TextOutline ? undefined : TextPr.TextOutline);
}
else if(undefined !== TextPr.AscLine && this.Paragraph)
{
var oCompiledPr = this.Get_CompiledPr(true);
this.Set_TextOutline(AscFormat.CorrectUniStroke(TextPr.AscLine, oCompiledPr.TextOutline, 0));
}
if ( undefined != TextPr.VertAlign )
this.Set_VertAlign( null === TextPr.VertAlign ? undefined : TextPr.VertAlign );
if ( undefined != TextPr.HighLight )
this.Set_HighLight( null === TextPr.HighLight ? undefined : TextPr.HighLight );
if ( undefined !== TextPr.RStyle )
this.Set_RStyle( null === TextPr.RStyle ? undefined : TextPr.RStyle );
if ( undefined != TextPr.Spacing )
this.Set_Spacing( null === TextPr.Spacing ? undefined : TextPr.Spacing );
if ( undefined != TextPr.DStrikeout )
this.Set_DStrikeout( null === TextPr.DStrikeout ? undefined : TextPr.DStrikeout );
if ( undefined != TextPr.Caps )
this.Set_Caps( null === TextPr.Caps ? undefined : TextPr.Caps );
if ( undefined != TextPr.SmallCaps )
this.Set_SmallCaps( null === TextPr.SmallCaps ? undefined : TextPr.SmallCaps );
if ( undefined != TextPr.Position )
this.Set_Position( null === TextPr.Position ? undefined : TextPr.Position );
if ( undefined != TextPr.RFonts )
{
if(this.Type == para_Math_Run && !this.IsNormalText()) // при смене Font в этом случае (даже на Cambria Math) cs, eastAsia не меняются
{
// только для редактирования
// делаем так для проверки действительно ли нужно сменить Font, чтобы при смене других текстовых настроек не выставился Cambria Math (TextPr.RFonts приходит всегда в виде объекта)
if(TextPr.RFonts.Ascii !== undefined || TextPr.RFonts.HAnsi !== undefined)
{
var RFonts = new CRFonts();
RFonts.Set_All("Cambria Math", -1);
this.Set_RFonts2(RFonts);
}
}
else
this.Set_RFonts2(TextPr.RFonts);
}
if ( undefined != TextPr.Lang )
this.Set_Lang2( TextPr.Lang );
if ( undefined !== TextPr.Shd )
this.Set_Shd( TextPr.Shd );
};
ParaRun.prototype.Have_PrChange = function()
{
return this.Pr.Have_PrChange();
};
ParaRun.prototype.Get_PrReviewColor = function()
{
if (this.Pr.ReviewInfo)
return this.Pr.ReviewInfo.Get_Color();
return REVIEW_COLOR;
};
ParaRun.prototype.Add_PrChange = function()
{
if (false === this.Have_PrChange())
{
this.Pr.Add_PrChange();
History.Add(new CChangesRunPrChange(this,
{
PrChange : undefined,
ReviewInfo : undefined
},
{
PrChange : this.Pr.PrChange,
ReviewInfo : this.Pr.ReviewInfo
}));
this.private_UpdateTrackRevisions();
}
};
ParaRun.prototype.Set_PrChange = function(PrChange, ReviewInfo)
{
History.Add(new CChangesRunPrChange(this,
{
PrChange : this.Pr.PrChange,
ReviewInfo : this.Pr.ReviewInfo ? this.Pr.ReviewInfo.Copy() : undefined
},
{
PrChange : PrChange,
ReviewInfo : ReviewInfo ? ReviewInfo.Copy() : undefined
}));
this.Pr.Set_PrChange(PrChange, ReviewInfo);
this.private_UpdateTrackRevisions();
};
ParaRun.prototype.Remove_PrChange = function()
{
if (true === this.Have_PrChange())
{
History.Add(new CChangesRunPrChange(this,
{
PrChange : this.Pr.PrChange,
ReviewInfo : this.Pr.ReviewInfo
},
{
PrChange : undefined,
ReviewInfo : undefined
}));
this.Pr.Remove_PrChange();
this.private_UpdateTrackRevisions();
}
};
ParaRun.prototype.Reject_PrChange = function()
{
if (true === this.Have_PrChange())
{
this.Set_Pr(this.Pr.PrChange);
this.Remove_PrChange();
}
};
ParaRun.prototype.Accept_PrChange = function()
{
this.Remove_PrChange();
};
ParaRun.prototype.Get_DiffPrChange = function()
{
return this.Pr.Get_DiffPrChange();
};
ParaRun.prototype.Set_Bold = function(Value)
{
if ( Value !== this.Pr.Bold )
{
var OldValue = this.Pr.Bold;
this.Pr.Bold = Value;
History.Add(new CChangesRunBold(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(true);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Get_Bold = function()
{
return this.Get_CompiledPr(false).Bold;
};
ParaRun.prototype.Set_Italic = function(Value)
{
if ( Value !== this.Pr.Italic )
{
var OldValue = this.Pr.Italic;
this.Pr.Italic = Value;
History.Add(new CChangesRunItalic(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(true);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Get_Italic = function()
{
return this.Get_CompiledPr(false).Italic;
};
ParaRun.prototype.Set_Strikeout = function(Value)
{
if ( Value !== this.Pr.Strikeout )
{
var OldValue = this.Pr.Strikeout;
this.Pr.Strikeout = Value;
History.Add(new CChangesRunStrikeout(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(false);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Get_Strikeout = function()
{
return this.Get_CompiledPr(false).Strikeout;
};
ParaRun.prototype.Set_Underline = function(Value)
{
if ( Value !== this.Pr.Underline )
{
var OldValue = this.Pr.Underline;
this.Pr.Underline = Value;
History.Add(new CChangesRunUnderline(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(false);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Get_Underline = function()
{
return this.Get_CompiledPr(false).Underline;
};
ParaRun.prototype.Set_FontSize = function(Value)
{
if ( Value !== this.Pr.FontSize )
{
var OldValue = this.Pr.FontSize;
this.Pr.FontSize = Value;
History.Add(new CChangesRunFontSize(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(true);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Get_FontSize = function()
{
return this.Get_CompiledPr(false).FontSize;
};
ParaRun.prototype.Set_Color = function(Value)
{
if ( ( undefined === Value && undefined !== this.Pr.Color ) || ( Value instanceof CDocumentColor && ( undefined === this.Pr.Color || false === Value.Compare(this.Pr.Color) ) ) )
{
var OldValue = this.Pr.Color;
this.Pr.Color = Value;
History.Add(new CChangesRunColor(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(false);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Set_Unifill = function(Value, bForce)
{
if ( ( undefined === Value && undefined !== this.Pr.Unifill ) || ( Value instanceof AscFormat.CUniFill && ( undefined === this.Pr.Unifill || false === AscFormat.CompareUnifillBool(this.Pr.Unifill, Value) ) ) || bForce )
{
var OldValue = this.Pr.Unifill;
this.Pr.Unifill = Value;
History.Add(new CChangesRunUnifill(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(false);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Set_TextFill = function(Value, bForce)
{
if ( ( undefined === Value && undefined !== this.Pr.TextFill ) || ( Value instanceof AscFormat.CUniFill && ( undefined === this.Pr.TextFill || false === AscFormat.CompareUnifillBool(this.Pr.TextFill.IsIdentical, Value) ) ) || bForce )
{
var OldValue = this.Pr.TextFill;
this.Pr.TextFill = Value;
History.Add(new CChangesRunTextFill(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(false);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Set_TextOutline = function(Value)
{
if ( ( undefined === Value && undefined !== this.Pr.TextOutline ) || ( Value instanceof AscFormat.CLn && ( undefined === this.Pr.TextOutline || false === this.Pr.TextOutline.IsIdentical(Value) ) ) )
{
var OldValue = this.Pr.TextOutline;
this.Pr.TextOutline = Value;
History.Add(new CChangesRunTextOutline(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(false);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Get_Color = function()
{
return this.Get_CompiledPr(false).Color;
};
ParaRun.prototype.Set_VertAlign = function(Value)
{
if ( Value !== this.Pr.VertAlign )
{
var OldValue = this.Pr.VertAlign;
this.Pr.VertAlign = Value;
History.Add(new CChangesRunVertAlign(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(true);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Get_VertAlign = function()
{
return this.Get_CompiledPr(false).VertAlign;
};
ParaRun.prototype.Set_HighLight = function(Value)
{
var OldValue = this.Pr.HighLight;
if ( (undefined === Value && undefined !== OldValue) || ( highlight_None === Value && highlight_None !== OldValue ) || ( Value instanceof CDocumentColor && ( undefined === OldValue || highlight_None === OldValue || false === Value.Compare(OldValue) ) ) )
{
this.Pr.HighLight = Value;
History.Add(new CChangesRunHighLight(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(false);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Get_HighLight = function()
{
return this.Get_CompiledPr(false).HighLight;
};
ParaRun.prototype.Set_RStyle = function(Value)
{
if ( Value !== this.Pr.RStyle )
{
var OldValue = this.Pr.RStyle;
this.Pr.RStyle = Value;
History.Add(new CChangesRunRStyle(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(true);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Get_RStyle = function()
{
return this.Get_CompiledPr(false).RStyle;
};
ParaRun.prototype.Set_Spacing = function(Value)
{
if (Value !== this.Pr.Spacing)
{
var OldValue = this.Pr.Spacing;
this.Pr.Spacing = Value;
History.Add(new CChangesRunSpacing(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(true);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Get_Spacing = function()
{
return this.Get_CompiledPr(false).Spacing;
};
ParaRun.prototype.Set_DStrikeout = function(Value)
{
if ( Value !== this.Pr.Value )
{
var OldValue = this.Pr.DStrikeout;
this.Pr.DStrikeout = Value;
History.Add(new CChangesRunDStrikeout(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(false);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Get_DStrikeout = function()
{
return this.Get_CompiledPr(false).DStrikeout;
};
ParaRun.prototype.Set_Caps = function(Value)
{
if ( Value !== this.Pr.Caps )
{
var OldValue = this.Pr.Caps;
this.Pr.Caps = Value;
History.Add(new CChangesRunCaps(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(true);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Get_Caps = function()
{
return this.Get_CompiledPr(false).Caps;
};
ParaRun.prototype.Set_SmallCaps = function(Value)
{
if ( Value !== this.Pr.SmallCaps )
{
var OldValue = this.Pr.SmallCaps;
this.Pr.SmallCaps = Value;
History.Add(new CChangesRunSmallCaps(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(true);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Get_SmallCaps = function()
{
return this.Get_CompiledPr(false).SmallCaps;
};
ParaRun.prototype.Set_Position = function(Value)
{
if ( Value !== this.Pr.Position )
{
var OldValue = this.Pr.Position;
this.Pr.Position = Value;
History.Add(new CChangesRunPosition(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(false);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
this.YOffset = this.Get_Position();
}
};
ParaRun.prototype.Get_Position = function()
{
return this.Get_CompiledPr(false).Position;
};
ParaRun.prototype.Set_RFonts = function(Value)
{
var OldValue = this.Pr.RFonts;
this.Pr.RFonts = Value;
History.Add(new CChangesRunRFonts(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(true);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
};
ParaRun.prototype.Get_RFonts = function()
{
return this.Get_CompiledPr(false).RFonts;
};
ParaRun.prototype.Set_RFonts2 = function(RFonts)
{
if ( undefined != RFonts )
{
if ( undefined != RFonts.Ascii )
this.Set_RFonts_Ascii( RFonts.Ascii );
if ( undefined != RFonts.HAnsi )
this.Set_RFonts_HAnsi( RFonts.HAnsi );
if ( undefined != RFonts.CS )
this.Set_RFonts_CS( RFonts.CS );
if ( undefined != RFonts.EastAsia )
this.Set_RFonts_EastAsia( RFonts.EastAsia );
if ( undefined != RFonts.Hint )
this.Set_RFonts_Hint( RFonts.Hint );
}
else
{
this.Set_RFonts_Ascii( undefined );
this.Set_RFonts_HAnsi( undefined );
this.Set_RFonts_CS( undefined );
this.Set_RFonts_EastAsia( undefined );
this.Set_RFonts_Hint( undefined );
}
};
ParaRun.prototype.Set_RFont_ForMathRun = function()
{
this.Set_RFonts_Ascii({Name : "Cambria Math", Index : -1});
this.Set_RFonts_CS({Name : "Cambria Math", Index : -1});
this.Set_RFonts_EastAsia({Name : "Cambria Math", Index : -1});
this.Set_RFonts_HAnsi({Name : "Cambria Math", Index : -1});
};
ParaRun.prototype.Set_RFonts_Ascii = function(Value)
{
if ( Value !== this.Pr.RFonts.Ascii )
{
var OldValue = this.Pr.RFonts.Ascii;
this.Pr.RFonts.Ascii = Value;
History.Add(new CChangesRunRFontsAscii(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(true);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Set_RFonts_HAnsi = function(Value)
{
if ( Value !== this.Pr.RFonts.HAnsi )
{
var OldValue = this.Pr.RFonts.HAnsi;
this.Pr.RFonts.HAnsi = Value;
History.Add(new CChangesRunRFontsHAnsi(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(true);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Set_RFonts_CS = function(Value)
{
if ( Value !== this.Pr.RFonts.CS )
{
var OldValue = this.Pr.RFonts.CS;
this.Pr.RFonts.CS = Value;
History.Add(new CChangesRunRFontsCS(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(true);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Set_RFonts_EastAsia = function(Value)
{
if ( Value !== this.Pr.RFonts.EastAsia )
{
var OldValue = this.Pr.RFonts.EastAsia;
this.Pr.RFonts.EastAsia = Value;
History.Add(new CChangesRunRFontsEastAsia(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(true);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Set_RFonts_Hint = function(Value)
{
if ( Value !== this.Pr.RFonts.Hint )
{
var OldValue = this.Pr.RFonts.Hint;
this.Pr.RFonts.Hint = Value;
History.Add(new CChangesRunRFontsHint(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(true);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Set_Lang = function(Value)
{
var OldValue = this.Pr.Lang;
this.Pr.Lang = new CLang();
if ( undefined != Value )
this.Pr.Lang.Set_FromObject( Value );
History.Add(new CChangesRunLang(this, OldValue, this.Pr.Lang, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(false);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
};
ParaRun.prototype.Set_Lang2 = function(Lang)
{
if ( undefined != Lang )
{
if ( undefined != Lang.Bidi )
this.Set_Lang_Bidi( Lang.Bidi );
if ( undefined != Lang.EastAsia )
this.Set_Lang_EastAsia( Lang.EastAsia );
if ( undefined != Lang.Val )
this.Set_Lang_Val( Lang.Val );
this.protected_UpdateSpellChecking();
}
};
ParaRun.prototype.Set_Lang_Bidi = function(Value)
{
if ( Value !== this.Pr.Lang.Bidi )
{
var OldValue = this.Pr.Lang.Bidi;
this.Pr.Lang.Bidi = Value;
History.Add(new CChangesRunLangBidi(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(false);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Set_Lang_EastAsia = function(Value)
{
if ( Value !== this.Pr.Lang.EastAsia )
{
var OldValue = this.Pr.Lang.EastAsia;
this.Pr.Lang.EastAsia = Value;
History.Add(new CChangesRunLangEastAsia(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(false);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Set_Lang_Val = function(Value)
{
if ( Value !== this.Pr.Lang.Val )
{
var OldValue = this.Pr.Lang.Val;
this.Pr.Lang.Val = Value;
History.Add(new CChangesRunLangVal(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(false);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Set_Shd = function(Shd)
{
if ( (undefined === this.Pr.Shd && undefined === Shd) || (undefined !== this.Pr.Shd && undefined !== Shd && true === this.Pr.Shd.Compare( Shd ) ) )
return;
var OldShd = this.Pr.Shd;
if ( undefined !== Shd )
{
this.Pr.Shd = new CDocumentShd();
this.Pr.Shd.Set_FromObject( Shd );
}
else
this.Pr.Shd = undefined;
History.Add(new CChangesRunShd(this, OldShd, this.Pr.Shd, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(false);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
};
//-----------------------------------------------------------------------------------
// Undo/Redo функции
//-----------------------------------------------------------------------------------
ParaRun.prototype.Check_HistoryUninon = function(Data1, Data2)
{
var Type1 = Data1.Type;
var Type2 = Data2.Type;
if ( AscDFH.historyitem_ParaRun_AddItem === Type1 && AscDFH.historyitem_ParaRun_AddItem === Type2 )
{
if ( 1 === Data1.Items.length && 1 === Data2.Items.length && Data1.Pos === Data2.Pos - 1 && para_Text === Data1.Items[0].Type && para_Text === Data2.Items[0].Type )
return true;
}
return false;
};
//-----------------------------------------------------------------------------------
// Функции для совместного редактирования
//-----------------------------------------------------------------------------------
ParaRun.prototype.Write_ToBinary2 = function(Writer)
{
Writer.WriteLong( AscDFH.historyitem_type_ParaRun );
// Long : Type
// String : Id
// String : Paragraph Id
// Variable : CTextPr
// Long : ReviewType
// Bool : isUndefined ReviewInfo
// ->false : ReviewInfo
// Long : Количество элементов
// Array of variable : массив с элементами
Writer.WriteLong(this.Type);
var ParagraphToWrite, PrToWrite, ContentToWrite;
if(this.StartState)
{
ParagraphToWrite = this.StartState.Paragraph;
PrToWrite = this.StartState.Pr;
ContentToWrite = this.StartState.Content;
}
else
{
ParagraphToWrite = this.Paragraph;
PrToWrite = this.Pr;
ContentToWrite = this.Content;
}
Writer.WriteString2( this.Id );
Writer.WriteString2( null !== ParagraphToWrite && undefined !== ParagraphToWrite ? ParagraphToWrite.Get_Id() : "" );
PrToWrite.Write_ToBinary( Writer );
Writer.WriteLong(this.ReviewType);
if (this.ReviewInfo)
{
Writer.WriteBool(false);
this.ReviewInfo.Write_ToBinary(Writer);
}
else
{
Writer.WriteBool(true);
}
var Count = ContentToWrite.length;
Writer.WriteLong( Count );
for ( var Index = 0; Index < Count; Index++ )
{
var Item = ContentToWrite[Index];
Item.Write_ToBinary( Writer );
}
};
ParaRun.prototype.Read_FromBinary2 = function(Reader)
{
// Long : Type
// String : Id
// String : Paragraph Id
// Variable : CTextPr
// Long : ReviewType
// Bool : isUndefined ReviewInfo
// ->false : ReviewInfo
// Long : Количество элементов
// Array of variable : массив с элементами
this.Type = Reader.GetLong();
this.Id = Reader.GetString2();
this.Paragraph = g_oTableId.Get_ById( Reader.GetString2() );
this.Pr = new CTextPr();
this.Pr.Read_FromBinary( Reader );
this.ReviewType = Reader.GetLong();
this.ReviewInfo = new CReviewInfo();
if (false === Reader.GetBool())
this.ReviewInfo.Read_FromBinary(Reader);
if (para_Math_Run == this.Type)
{
this.MathPrp = new CMPrp();
this.size = new CMathSize();
this.pos = new CMathPosition();
}
if(undefined !== editor && true === editor.isDocumentEditor)
{
var Count = Reader.GetLong();
this.Content = [];
for ( var Index = 0; Index < Count; Index++ )
{
var Element = ParagraphContent_Read_FromBinary( Reader );
if ( null !== Element )
this.Content.push( Element );
}
}
};
ParaRun.prototype.Clear_CollaborativeMarks = function()
{
this.CollaborativeMarks.Clear();
this.CollPrChangeOther = false;
};
ParaRun.prototype.private_AddCollPrChangeMine = function()
{
this.CollPrChangeMine = true;
this.CollPrChangeOther = false;
};
ParaRun.prototype.private_IsCollPrChangeMine = function()
{
if (true === this.CollPrChangeMine)
return true;
return false;
};
ParaRun.prototype.private_AddCollPrChangeOther = function(Color)
{
this.CollPrChangeOther = Color;
AscCommon.CollaborativeEditing.Add_ChangedClass(this);
};
ParaRun.prototype.private_GetCollPrChangeOther = function()
{
return this.CollPrChangeOther;
};
ParaRun.prototype.private_RecalcCtrPrp = function()
{
if (para_Math_Run === this.Type && undefined !== this.Parent && null !== this.Parent && null !== this.Parent.ParaMath)
this.Parent.ParaMath.SetRecalcCtrPrp(this);
};
function CParaRunSelection()
{
this.Use = false;
this.StartPos = 0;
this.EndPos = 0;
}
function CParaRunState()
{
this.Selection = new CParaRunSelection();
this.ContentPos = 0;
}
function CParaRunRecalcInfo()
{
this.TextPr = true; // Нужно ли пересчитать скомпилированные настройки
this.Measure = true; // Нужно ли перемерять элементы
this.Recalc = true; // Нужно ли пересчитывать (только если текстовый ран)
this.RunLen = 0;
// Далее идут параметры, которые выставляются после пересчета данного Range, такие как пересчитывать ли нумерацию
this.NumberingItem = null;
this.NumberingUse = false; // Используется ли нумерация в данном ране
this.NumberingAdd = true; // Нужно ли в следующем ране использовать нумерацию
}
CParaRunRecalcInfo.prototype =
{
Reset : function()
{
this.TextPr = true;
this.Measure = true;
this.Recalc = true;
this.RunLen = 0;
}
};
function CParaRunRange(StartPos, EndPos)
{
this.StartPos = StartPos; // Начальная позиция в контенте, с которой начинается данный отрезок
this.EndPos = EndPos; // Конечная позиция в контенте, на которой заканчивается данный отрезок (перед которой)
}
function CParaRunLine()
{
this.Ranges = [];
this.Ranges[0] = new CParaRunRange( 0, 0 );
this.RangesLength = 0;
}
CParaRunLine.prototype =
{
Add_Range : function(RangeIndex, StartPos, EndPos)
{
if ( 0 !== RangeIndex )
{
this.Ranges[RangeIndex] = new CParaRunRange( StartPos, EndPos );
this.RangesLength = RangeIndex + 1;
}
else
{
this.Ranges[0].StartPos = StartPos;
this.Ranges[0].EndPos = EndPos;
this.RangesLength = 1;
}
if ( this.Ranges.length > this.RangesLength )
this.Ranges.legth = this.RangesLength;
},
Copy : function()
{
var NewLine = new CParaRunLine();
NewLine.RangesLength = this.RangesLength;
for ( var CurRange = 0; CurRange < this.RangesLength; CurRange++ )
{
var Range = this.Ranges[CurRange];
NewLine.Ranges[CurRange] = new CParaRunRange( Range.StartPos, Range.EndPos );
}
return NewLine;
},
Compare : function(OtherLine, CurRange)
{
// Сначала проверим наличие данного отрезка в обеих строках
if ( this.RangesLength <= CurRange || OtherLine.RangesLength <= CurRange )
return false;
var OtherRange = OtherLine.Ranges[CurRange];
var ThisRange = this.Ranges[CurRange];
if ( OtherRange.StartPos !== ThisRange.StartPos || OtherRange.EndPos !== ThisRange.EndPos )
return false;
return true;
}
};
// Метка о конце или начале изменений пришедших от других соавторов документа
var pararun_CollaborativeMark_Start = 0x00;
var pararun_CollaborativeMark_End = 0x01;
function CParaRunCollaborativeMark(Pos, Type)
{
this.Pos = Pos;
this.Type = Type;
}
function FontSize_IncreaseDecreaseValue(bIncrease, Value)
{
// Закон изменения размеров :
// 1. Если значение меньше 8, тогда мы увеличиваем/уменьшаем по 1 (от 1 до 8)
// 2. Если значение больше 72, тогда мы увеличиваем/уменьшаем по 10 (от 80 до бесконечности
// 3. Если значение в отрезке [8,72], тогда мы переходим по следующим числам 8,9,10,11,12,14,16,18,20,22,24,26,28,36,48,72
var Sizes = [8,9,10,11,12,14,16,18,20,22,24,26,28,36,48,72];
var NewValue = Value;
if ( true === bIncrease )
{
if ( Value < Sizes[0] )
{
if ( Value >= Sizes[0] - 1 )
NewValue = Sizes[0];
else
NewValue = Math.floor(Value + 1);
}
else if ( Value >= Sizes[Sizes.length - 1] )
{
NewValue = Math.min( 300, Math.floor( Value / 10 + 1 ) * 10 );
}
else
{
for ( var Index = 0; Index < Sizes.length; Index++ )
{
if ( Value < Sizes[Index] )
{
NewValue = Sizes[Index];
break;
}
}
}
}
else
{
if ( Value <= Sizes[0] )
{
NewValue = Math.max( Math.floor( Value - 1 ), 1 );
}
else if ( Value > Sizes[Sizes.length - 1] )
{
if ( Value <= Math.floor( Sizes[Sizes.length - 1] / 10 + 1 ) * 10 )
NewValue = Sizes[Sizes.length - 1];
else
NewValue = Math.floor( Math.ceil(Value / 10) - 1 ) * 10;
}
else
{
for ( var Index = Sizes.length - 1; Index >= 0; Index-- )
{
if ( Value > Sizes[Index] )
{
NewValue = Sizes[Index];
break;
}
}
}
}
return NewValue;
}
function CRunCollaborativeMarks()
{
this.Ranges = [];
this.DrawingObj = {};
}
CRunCollaborativeMarks.prototype =
{
Add : function(PosS, PosE, Color)
{
var Count = this.Ranges.length;
for ( var Index = 0; Index < Count; Index++ )
{
var Range = this.Ranges[Index];
if ( PosS > Range.PosE )
continue;
else if ( PosS >= Range.PosS && PosS <= Range.PosE && PosE >= Range.PosS && PosE <= Range.PosE )
{
if ( true !== Color.Compare(Range.Color) )
{
var _PosE = Range.PosE;
Range.PosE = PosS;
this.Ranges.splice( Index + 1, 0, new CRunCollaborativeRange(PosS, PosE, Color) );
this.Ranges.splice( Index + 2, 0, new CRunCollaborativeRange(PosE, _PosE, Range.Color) );
}
return;
}
else if ( PosE < Range.PosS )
{
this.Ranges.splice( Index, 0, new CRunCollaborativeRange(PosS, PosE, Color) );
return;
}
else if ( PosS < Range.PosS && PosE > Range.PosE )
{
Range.PosS = PosS;
Range.PosE = PosE;
Range.Color = Color;
return;
}
else if ( PosS < Range.PosS ) // && PosE <= Range.PosE )
{
if ( true === Color.Compare(Range.Color) )
Range.PosS = PosS;
else
{
Range.PosS = PosE;
this.Ranges.splice( Index, 0, new CRunCollaborativeRange(PosS, PosE, Color) );
}
return;
}
else //if ( PosS >= Range.PosS && PosE > Range.Pos.E )
{
if ( true === Color.Compare(Range.Color) )
Range.PosE = PosE;
else
{
Range.PosE = PosS;
this.Ranges.splice( Index + 1, 0, new CRunCollaborativeRange(PosS, PosE, Color) );
}
return;
}
}
this.Ranges.push( new CRunCollaborativeRange(PosS, PosE, Color) );
},
Update_OnAdd : function(Pos)
{
var Count = this.Ranges.length;
for ( var Index = 0; Index < Count; Index++ )
{
var Range = this.Ranges[Index];
if ( Pos <= Range.PosS )
{
Range.PosS++;
Range.PosE++;
}
else if ( Pos > Range.PosS && Pos < Range.PosE )
{
var NewRange = new CRunCollaborativeRange( Pos + 1, Range.PosE + 1, Range.Color.Copy() );
this.Ranges.splice( Index + 1, 0, NewRange );
Range.PosE = Pos;
Count++;
Index++;
}
//else if ( Pos < Range.PosE )
// Range.PosE++;
}
},
Update_OnRemove : function(Pos, Count)
{
var Len = this.Ranges.length;
for ( var Index = 0; Index < Len; Index++ )
{
var Range = this.Ranges[Index];
var PosE = Pos + Count;
if ( Pos < Range.PosS )
{
if ( PosE <= Range.PosS )
{
Range.PosS -= Count;
Range.PosE -= Count;
}
else if ( PosE >= Range.PosE )
{
this.Ranges.splice( Index, 1 );
Len--;
Index--;continue;
}
else
{
Range.PosS = Pos;
Range.PosE -= Count;
}
}
else if ( Pos >= Range.PosS && Pos < Range.PosE )
{
if ( PosE >= Range.PosE )
Range.PosE = Pos;
else
Range.PosE -= Count;
}
else
continue;
}
},
Clear : function()
{
this.Ranges = [];
},
Init_Drawing : function()
{
this.DrawingObj = {};
var Count = this.Ranges.length;
for ( var CurPos = 0; CurPos < Count; CurPos++ )
{
var Range = this.Ranges[CurPos];
for ( var Pos = Range.PosS; Pos < Range.PosE; Pos++ )
this.DrawingObj[Pos] = Range.Color;
}
},
Check : function(Pos)
{
if ( undefined !== this.DrawingObj[Pos] )
return this.DrawingObj[Pos];
return null;
}
};
function CRunCollaborativeRange(PosS, PosE, Color)
{
this.PosS = PosS;
this.PosE = PosE;
this.Color = Color;
}
ParaRun.prototype.Math_SetPosition = function(pos, PosInfo)
{
var Line = PosInfo.CurLine,
Range = PosInfo.CurRange;
var CurLine = Line - this.StartLine;
var CurRange = ( 0 === CurLine ? Range - this.StartRange : Range );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
// запомним позицию для Recalculate_CurPos, когда Run пустой
this.pos.x = pos.x;
this.pos.y = pos.y;
for(var Pos = StartPos; Pos < EndPos; Pos++)
{
var Item = this.Content[Pos];
if(PosInfo.DispositionOpers !== null && Item.Type == para_Math_BreakOperator)
{
PosInfo.DispositionOpers.push(pos.x + Item.GapLeft);
}
this.Content[Pos].setPosition(pos);
pos.x += this.Content[Pos].Get_WidthVisible(); // Get_Width => Get_WidthVisible
// Get_WidthVisible - Width + Gaps с учетом настроек состояния
}
};
ParaRun.prototype.Math_Get_StartRangePos = function(_CurLine, _CurRange, SearchPos, Depth, bStartLine)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var Pos = this.State.ContentPos;
var Result = true;
if(bStartLine || StartPos < Pos)
{
SearchPos.Pos.Update(StartPos, Depth);
}
else
{
Result = false;
}
return Result;
};
ParaRun.prototype.Math_Get_EndRangePos = function(_CurLine, _CurRange, SearchPos, Depth, bEndLine)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
var Pos = this.State.ContentPos;
var Result = true;
if(bEndLine || Pos < EndPos)
{
SearchPos.Pos.Update(EndPos, Depth);
}
else
{
Result = false;
}
return Result;
};
ParaRun.prototype.Math_Is_End = function(_CurLine, _CurRange)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
return EndPos == this.Content.length;
};
ParaRun.prototype.IsEmptyRange = function(_CurLine, _CurRange)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
return StartPos == EndPos;
};
ParaRun.prototype.Recalculate_Range_OneLine = function(PRS, ParaPr, Depth)
{
// данная функция используется только для мат объектов, которые на строки не разбиваются
// ParaText (ParagraphContent.js)
// для настройки TextPr
// Measure
// FontClassification.js
// Get_FontClass
var Lng = this.Content.length;
var CurLine = PRS.Line - this.StartLine;
var CurRange = ( 0 === CurLine ? PRS.Range - this.StartRange : PRS.Range );
// обновляем позиции start и end для Range
var RangeStartPos = this.protected_AddRange(CurLine, CurRange);
var RangeEndPos = Lng;
this.Math_RecalculateContent(PRS);
this.protected_FillRange(CurLine, CurRange, RangeStartPos, RangeEndPos);
};
ParaRun.prototype.Math_RecalculateContent = function(PRS)
{
var WidthPoints = this.Parent.Get_WidthPoints();
this.bEqArray = this.Parent.IsEqArray();
var ascent = 0, descent = 0, width = 0;
this.Recalculate_MeasureContent();
var Lng = this.Content.length;
for(var i = 0 ; i < Lng; i++)
{
var Item = this.Content[i];
var size = Item.size,
Type = Item.Type;
var WidthItem = Item.Get_WidthVisible(); // Get_Width => Get_WidthVisible
// Get_WidthVisible - Width + Gaps с учетом настроек состояния
width += WidthItem;
if(ascent < size.ascent)
ascent = size.ascent;
if (descent < size.height - size.ascent)
descent = size.height - size.ascent;
if(this.bEqArray)
{
if(Type === para_Math_Ampersand && true === Item.IsAlignPoint())
{
WidthPoints.AddNewAlignRange();
}
else
{
WidthPoints.UpdatePoint(WidthItem);
}
}
}
this.size.width = width;
this.size.ascent = ascent;
this.size.height = ascent + descent;
};
ParaRun.prototype.Math_Set_EmptyRange = function(_CurLine, _CurRange)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = (0 === CurLine ? _CurRange - this.StartRange : _CurRange);
var RangeStartPos = this.protected_AddRange(CurLine, CurRange);
var RangeEndPos = RangeStartPos;
this.protected_FillRange(CurLine, CurRange, RangeStartPos, RangeEndPos);
};
// в этой функции проставляем состояние Gaps (крайние или нет) для всех операторов, к-ые участвуют в разбиении, чтобы не получилось случайно, что при изменении разбивки формулы на строки произошло, что у оператора не будет проставлен Gap
ParaRun.prototype.UpdateOperators = function(_CurLine, _CurRange, bEmptyGapLeft, bEmptyGapRight)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
for(var Pos = StartPos; Pos < EndPos; Pos++)
{
var _bEmptyGapLeft = bEmptyGapLeft && Pos == StartPos,
_bEmptyGapRight = bEmptyGapRight && Pos == EndPos - 1;
this.Content[Pos].Update_StateGapLeft(_bEmptyGapLeft);
this.Content[Pos].Update_StateGapRight(_bEmptyGapRight);
}
};
ParaRun.prototype.Math_Apply_Style = function(Value)
{
if(Value !== this.MathPrp.sty)
{
var OldValue = this.MathPrp.sty;
this.MathPrp.sty = Value;
History.Add(new CChangesRunMathStyle(this, OldValue, Value));
this.Recalc_CompiledPr(true);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.IsNormalText = function()
{
var comp_MPrp = this.MathPrp.GetCompiled_ScrStyles();
return comp_MPrp.nor === true;
};
ParaRun.prototype.getPropsForWrite = function()
{
var prRPr = null, wRPrp = null;
if(this.Paragraph && false === this.Paragraph.bFromDocument){
prRPr = this.Pr.Copy();
}
else{
wRPrp = this.Pr.Copy();
}
var mathRPrp = this.MathPrp.Copy();
return {wRPrp: wRPrp, mathRPrp: mathRPrp, prRPrp: prRPr};
};
ParaRun.prototype.Get_MathPr = function(bCopy)
{
if(this.Type = para_Math_Run)
{
if(bCopy)
return this.MathPrp.Copy();
else
return this.MathPrp;
}
};
ParaRun.prototype.Math_PreRecalc = function(Parent, ParaMath, ArgSize, RPI, GapsInfo)
{
this.Parent = Parent;
this.Paragraph = ParaMath.Paragraph;
var FontSize = this.Get_CompiledPr(false).FontSize;
if(RPI.bChangeInline)
this.RecalcInfo.Measure = true; // нужно сделать пересчет элементов, например для дроби, т.к. ArgSize у внутренних контентов будет другой => размер
if(RPI.bCorrect_ConvertFontSize) // изменение FontSize после конвертации из старого формата в новый
{
var FontKoef;
if(ArgSize == -1 || ArgSize == -2)
{
var Pr = new CTextPr();
if(this.Pr.FontSize !== null && this.Pr.FontSize !== undefined)
{
FontKoef = MatGetKoeffArgSize(this.Pr.FontSize, ArgSize);
Pr.FontSize = (((this.Pr.FontSize/FontKoef * 2 + 0.5) | 0) / 2);
this.RecalcInfo.TextPr = true;
this.RecalcInfo.Measure = true;
}
if(this.Pr.FontSizeCS !== null && this.Pr.FontSizeCS !== undefined)
{
FontKoef = MatGetKoeffArgSize( this.Pr.FontSizeCS, ArgSize);
Pr.FontSizeCS = (((this.Pr.FontSizeCS/FontKoef * 2 + 0.5) | 0) / 2);
this.RecalcInfo.TextPr = true;
this.RecalcInfo.Measure = true;
}
this.Apply_Pr(Pr);
}
}
for (var Pos = 0 ; Pos < this.Content.length; Pos++ )
{
if( !this.Content[Pos].IsAlignPoint() )
GapsInfo.setGaps(this.Content[Pos], FontSize);
this.Content[Pos].PreRecalc(this, ParaMath);
this.Content[Pos].SetUpdateGaps(false);
}
};
ParaRun.prototype.Math_GetRealFontSize = function(FontSize)
{
var RealFontSize = FontSize ;
if(FontSize !== null && FontSize !== undefined)
{
var ArgSize = this.Parent.Compiled_ArgSz.value;
RealFontSize = FontSize*MatGetKoeffArgSize(FontSize, ArgSize);
}
return RealFontSize;
};
ParaRun.prototype.Math_CompareFontSize = function(ComparableFontSize, bStartLetter)
{
var lng = this.Content.length;
var Letter = this.Content[lng - 1];
if(bStartLetter == true)
Letter = this.Content[0];
var CompiledPr = this.Get_CompiledPr(false);
var LetterFontSize = Letter.Is_LetterCS() ? CompiledPr.FontSizeCS : CompiledPr.FontSize;
return ComparableFontSize == this.Math_GetRealFontSize(LetterFontSize);
};
ParaRun.prototype.Math_EmptyRange = function(_CurLine, _CurRange) // до пересчета нужно узнать будет ли данный Run пустым или нет в данном Range, необходимо для того, чтобы выставить wrapIndent
{
var bEmptyRange = true;
var Lng = this.Content.length;
if(Lng > 0)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
bEmptyRange = this.protected_GetPrevRangeEndPos(CurLine, CurRange) >= Lng;
}
return bEmptyRange;
};
ParaRun.prototype.Math_UpdateGaps = function(_CurLine, _CurRange, GapsInfo)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
var FontSize = this.Get_CompiledPr(false).FontSize;
for(var Pos = StartPos; Pos < EndPos; Pos++)
{
GapsInfo.updateCurrentObject(this.Content[Pos], FontSize);
var bUpdateCurrent = this.Content[Pos].IsNeedUpdateGaps();
if(bUpdateCurrent || GapsInfo.bUpdate)
{
GapsInfo.updateGaps();
}
GapsInfo.bUpdate = bUpdateCurrent;
this.Content[Pos].SetUpdateGaps(false);
}
};
ParaRun.prototype.Math_Can_ModidyForcedBreak = function(Pr, bStart, bEnd)
{
var Pos = this.Math_GetPosForcedBreak(bStart, bEnd);
if(Pos !== null)
{
if(this.MathPrp.IsBreak())
{
Pr.Set_DeleteForcedBreak();
}
else
{
Pr.Set_InsertForcedBreak();
}
}
};
ParaRun.prototype.Math_GetPosForcedBreak = function(bStart, bEnd)
{
var ResultPos = null;
if(this.Content.length > 0)
{
var StartPos = this.Selection.StartPos,
EndPos = this.Selection.EndPos,
bSelect = this.Selection.Use;
if(StartPos > EndPos)
{
StartPos = this.Selection.EndPos;
EndPos = this.Selection.StartPos;
}
var bCheckTwoItem = bSelect == false || (bSelect == true && EndPos == StartPos),
bCheckOneItem = bSelect == true && EndPos - StartPos == 1;
if(bStart)
{
ResultPos = this.Content[0].Type == para_Math_BreakOperator ? 0 : ResultPos;
}
else if(bEnd)
{
var lastPos = this.Content.length - 1;
ResultPos = this.Content[lastPos].Type == para_Math_BreakOperator ? lastPos : ResultPos;
}
else if(bCheckTwoItem)
{
var Pos = bSelect == false ? this.State.ContentPos : StartPos;
var bPrevBreakOperator = Pos > 0 ? this.Content[Pos - 1].Type == para_Math_BreakOperator : false,
bCurrBreakOperator = Pos < this.Content.length ? this.Content[Pos].Type == para_Math_BreakOperator : false;
if(bCurrBreakOperator)
{
ResultPos = Pos
}
else if(bPrevBreakOperator)
{
ResultPos = Pos - 1;
}
}
else if(bCheckOneItem)
{
if(this.Content[StartPos].Type == para_Math_BreakOperator)
{
ResultPos = StartPos;
}
}
}
return ResultPos;
};
ParaRun.prototype.Check_ForcedBreak = function(bStart, bEnd)
{
return this.Math_GetPosForcedBreak(bStart, bEnd) !== null;
};
ParaRun.prototype.Set_MathForcedBreak = function(bInsert)
{
if (bInsert == true && false == this.MathPrp.IsBreak())
{
History.Add(new CChangesRunMathForcedBreak(this, true, undefined));
this.MathPrp.Insert_ForcedBreak();
}
else if (bInsert == false && true == this.MathPrp.IsBreak())
{
History.Add(new CChangesRunMathForcedBreak(this, false, this.MathPrp.Get_AlnAt()));
this.MathPrp.Delete_ForcedBreak();
}
};
ParaRun.prototype.Math_SplitRunForcedBreak = function()
{
var Pos = this.Math_GetPosForcedBreak();
var NewRun = null;
if(Pos != null && Pos > 0) // разбиваем Run на два
{
NewRun = this.Split_Run(Pos);
}
return NewRun;
};
ParaRun.prototype.UpdLastElementForGaps = function(_CurLine, _CurRange, GapsInfo)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
var FontSize = this.Get_CompiledPr(false).FontSize;
var Last = this.Content[EndPos];
GapsInfo.updateCurrentObject(Last, FontSize);
};
ParaRun.prototype.IsPlaceholder = function()
{
return this.Content.length == 1 && this.Content[0].IsPlaceholder();
};
ParaRun.prototype.AddMathPlaceholder = function()
{
var oPlaceholder = new CMathText(false);
oPlaceholder.SetPlaceholder();
this.Add_ToContent(0, oPlaceholder, false);
};
ParaRun.prototype.RemoveMathPlaceholder = function()
{
for (var nPos = 0; nPos < this.Content.length; ++nPos)
{
if (para_Math_Placeholder === this.Content[nPos].Type)
{
this.Remove_FromContent(nPos, 1, true);
nPos--;
}
}
};
ParaRun.prototype.Set_MathPr = function(MPrp)
{
var OldValue = this.MathPrp;
this.MathPrp.Set_Pr(MPrp);
History.Add(new CChangesRunMathPrp(this, OldValue, this.MathPrp));
this.Recalc_CompiledPr(true);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
};
ParaRun.prototype.Set_MathTextPr2 = function(TextPr, MathPr)
{
this.Set_Pr(TextPr.Copy());
this.Set_MathPr(MathPr.Copy());
};
ParaRun.prototype.IsAccent = function()
{
return this.Parent.IsAccent();
};
ParaRun.prototype.GetCompiled_ScrStyles = function()
{
return this.MathPrp.GetCompiled_ScrStyles();
};
ParaRun.prototype.IsEqArray = function()
{
return this.Parent.IsEqArray();
};
ParaRun.prototype.IsForcedBreak = function()
{
var bForcedBreak = false;
if(this.ParaMath!== null)
bForcedBreak = false == this.ParaMath.Is_Inline() && true == this.MathPrp.IsBreak();
return bForcedBreak;
};
ParaRun.prototype.Is_StartForcedBreakOperator = function()
{
var bStartOperator = this.Content.length > 0 && this.Content[0].Type == para_Math_BreakOperator;
return true == this.IsForcedBreak() && true == bStartOperator;
};
ParaRun.prototype.Get_AlignBrk = function(_CurLine, bBrkBefore)
{
// null - break отсутствует
// 0 - break присутствует, alnAt = undefined
// Number = break присутствует, alnAt = Number
// если оператор находится в конце строки и по этому оператору осушествляется принудительный перенос (Forced)
// тогда StartPos = 0, EndPos = 1 (для предыдущей строки), т.к. оператор с принудительным переносом всегда должен находится в начале Run
var CurLine = _CurLine - this.StartLine;
var AlnAt = null;
if(CurLine > 0)
{
var RangesCount = this.protected_GetRangesCount(CurLine - 1);
var StartPos = this.protected_GetRangeStartPos(CurLine - 1, RangesCount - 1);
var EndPos = this.protected_GetRangeEndPos(CurLine - 1, RangesCount - 1);
var bStartBreakOperator = bBrkBefore == true && StartPos == 0 && EndPos == 0;
var bEndBreakOperator = bBrkBefore == false && StartPos == 0 && EndPos == 1;
if(bStartBreakOperator || bEndBreakOperator)
{
AlnAt = false == this.Is_StartForcedBreakOperator() ? null : this.MathPrp.Get_AlignBrk();
}
}
return AlnAt;
};
ParaRun.prototype.Math_Is_InclineLetter = function()
{
var result = false;
if(this.Content.length == 1)
result = this.Content[0].Is_InclineLetter();
return result;
};
ParaRun.prototype.GetMathTextPrForMenu = function()
{
var TextPr = new CTextPr();
if(this.IsPlaceholder())
TextPr.Merge(this.Parent.GetCtrPrp());
TextPr.Merge(this.Pr);
var MathTextPr = this.MathPrp.Copy();
var BI = MathTextPr.GetBoldItalic();
TextPr.Italic = BI.Italic;
TextPr.Bold = BI.Bold;
return TextPr;
};
ParaRun.prototype.ApplyPoints = function(PointsInfo)
{
if(this.Parent.IsEqArray())
{
this.size.width = 0;
for(var Pos = 0; Pos < this.Content.length; Pos++)
{
var Item = this.Content[Pos];
if(Item.Type === para_Math_Ampersand && true === Item.IsAlignPoint())
{
PointsInfo.NextAlignRange();
Item.size.width = PointsInfo.GetAlign();
}
this.size.width += this.Content[Pos].Get_WidthVisible(); // Get_Width => Get_WidthVisible
// Get_WidthVisible - Width + Gaps с учетом настроек состояния
}
}
};
ParaRun.prototype.Get_TextForAutoCorrect = function(AutoCorrectEngine, RunPos)
{
var ActionElement = AutoCorrectEngine.Get_ActionElement();
var nCount = this.Content.length;
for (var nPos = 0; nPos < nCount; nPos++)
{
var Item = this.Content[nPos];
if (para_Math_Text === Item.Type || para_Math_BreakOperator === Item.Type)
{
AutoCorrectEngine.Add_Text(String.fromCharCode(Item.value), this, nPos, RunPos, Item.Pos);
}
else if (para_Math_Ampersand === Item.Type)
{
AutoCorrectEngine.Add_Text('&', this, nPos, RunPos, Item.Pos);
}
if (Item === ActionElement)
{
AutoCorrectEngine.Stop_CollectText();
break;
}
}
if (null === AutoCorrectEngine.TextPr)
AutoCorrectEngine.TextPr = this.Pr.Copy();
if (null == AutoCorrectEngine.MathPr)
AutoCorrectEngine.MathPr = this.MathPrp.Copy();
};
ParaRun.prototype.IsShade = function()
{
var oShd = this.Get_CompiledPr(false).Shd;
return !(oShd === undefined || c_oAscShdNil === oShd.Value);
};
ParaRun.prototype.Get_RangesByPos = function(Pos)
{
var Ranges = [];
var LinesCount = this.protected_GetLinesCount();
for (var LineIndex = 0; LineIndex < LinesCount; LineIndex++)
{
var RangesCount = this.protected_GetRangesCount(LineIndex);
for (var RangeIndex = 0; RangeIndex < RangesCount; RangeIndex++)
{
var StartPos = this.protected_GetRangeStartPos(LineIndex, RangeIndex);
var EndPos = this.protected_GetRangeEndPos(LineIndex, RangeIndex);
if (StartPos <= Pos && Pos <= EndPos)
Ranges.push({Range : (LineIndex === 0 ? RangeIndex + this.StartRange : RangeIndex), Line : LineIndex + this.StartLine});
}
}
return Ranges;
};
ParaRun.prototype.CompareDrawingsLogicPositions = function(CompareObject)
{
var Drawing1 = CompareObject.Drawing1;
var Drawing2 = CompareObject.Drawing2;
for (var Pos = 0, Count = this.Content.length; Pos < Count; Pos++)
{
var Item = this.Content[Pos];
if (Item === Drawing1)
{
CompareObject.Result = 1;
return;
}
else if (Item === Drawing2)
{
CompareObject.Result = -1;
return;
}
}
};
ParaRun.prototype.Get_ReviewType = function()
{
return this.ReviewType;
};
ParaRun.prototype.Get_ReviewInfo = function()
{
return this.ReviewInfo;
};
ParaRun.prototype.Get_ReviewColor = function()
{
if (this.ReviewInfo)
return this.ReviewInfo.Get_Color();
return REVIEW_COLOR;
};
ParaRun.prototype.Set_ReviewType = function(Value)
{
if (Value !== this.ReviewType)
{
var OldReviewType = this.ReviewType;
var OldReviewInfo = this.ReviewInfo.Copy();
this.ReviewType = Value;
this.ReviewInfo.Update();
History.Add(new CChangesRunReviewType(this,
{
ReviewType : OldReviewType,
ReviewInfo : OldReviewInfo
},
{
ReviewType : this.ReviewType,
ReviewInfo : this.ReviewInfo.Copy()
}));
this.private_UpdateTrackRevisions();
}
};
ParaRun.prototype.Set_ReviewTypeWithInfo = function(ReviewType, ReviewInfo)
{
History.Add(new CChangesRunReviewType(this,
{
ReviewType : this.ReviewType,
ReviewInfo : this.ReviewInfo ? this.ReviewInfo.Copy() : undefined
},
{
ReviewType : ReviewType,
ReviewInfo : ReviewInfo ? ReviewInfo.Copy() : undefined
}));
this.ReviewType = ReviewType;
this.ReviewInfo = ReviewInfo;
this.private_UpdateTrackRevisions();
};
ParaRun.prototype.Get_Parent = function()
{
if (!this.Paragraph)
return null;
var ContentPos = this.Paragraph.Get_PosByElement(this);
if (null == ContentPos || undefined == ContentPos || ContentPos.Get_Depth() < 0)
return null;
ContentPos.Decrease_Depth(1);
return this.Paragraph.Get_ElementByPos(ContentPos);
};
ParaRun.prototype.private_GetPosInParent = function(_Parent)
{
var Parent = (_Parent? _Parent : this.Get_Parent());
if (!Parent)
return -1;
// Ищем данный элемент в родительском классе
var RunPos = -1;
for (var Pos = 0, Count = Parent.Content.length; Pos < Count; Pos++)
{
if (this === Parent.Content[Pos])
{
RunPos = Pos;
break;
}
}
return RunPos;
};
ParaRun.prototype.Make_ThisElementCurrent = function(bUpdateStates)
{
if (this.Is_UseInDocument())
{
var ContentPos = this.Paragraph.Get_PosByElement(this);
ContentPos.Add(this.State.ContentPos);
this.Paragraph.Set_ParaContentPos(ContentPos, true, -1, -1);
this.Paragraph.Document_SetThisElementCurrent(true === bUpdateStates ? true : false);
}
};
ParaRun.prototype.GetAllParagraphs = function(Props, ParaArray)
{
var ContentLen = this.Content.length;
for (var CurPos = 0; CurPos < ContentLen; CurPos++)
{
if (para_Drawing == this.Content[CurPos].Type)
this.Content[CurPos].GetAllParagraphs(Props, ParaArray);
}
};
ParaRun.prototype.Check_RevisionsChanges = function(Checker, ContentPos, Depth)
{
if (this.Is_Empty())
return;
if (true !== Checker.Is_ParaEndRun() && true !== Checker.Is_CheckOnlyTextPr())
{
var ReviewType = this.Get_ReviewType();
if (ReviewType !== Checker.Get_AddRemoveType() || (reviewtype_Common !== ReviewType && this.ReviewInfo.Get_UserId() !== Checker.Get_AddRemoveUserId()))
{
Checker.Flush_AddRemoveChange();
ContentPos.Update(0, Depth);
if (reviewtype_Add === ReviewType || reviewtype_Remove === ReviewType)
Checker.Start_AddRemove(ReviewType, ContentPos);
}
if (reviewtype_Add === ReviewType || reviewtype_Remove === ReviewType)
{
var Text = "";
var ContentLen = this.Content.length;
for (var CurPos = 0; CurPos < ContentLen; CurPos++)
{
var Item = this.Content[CurPos];
var ItemType = Item.Type;
switch (ItemType)
{
case para_Drawing:
{
Checker.Add_Text(Text);
Text = "";
Checker.Add_Drawing(Item);
break;
}
case para_Text :
{
Text += String.fromCharCode(Item.Value);
break;
}
case para_Math_Text:
{
Text += String.fromCharCode(Item.getCodeChr());
break;
}
case para_Space:
case para_Tab :
{
Text += " ";
break;
}
}
}
Checker.Add_Text(Text);
ContentPos.Update(this.Content.length, Depth);
Checker.Set_AddRemoveEndPos(ContentPos);
Checker.Update_AddRemoveReviewInfo(this.ReviewInfo);
}
}
var HavePrChange = this.Have_PrChange();
var DiffPr = this.Get_DiffPrChange();
if (HavePrChange !== Checker.Have_PrChange() || true !== Checker.Compare_PrChange(DiffPr) || this.Pr.ReviewInfo.Get_UserId() !== Checker.Get_PrChangeUserId())
{
Checker.Flush_TextPrChange();
ContentPos.Update(0, Depth);
if (true === HavePrChange)
{
Checker.Start_PrChange(DiffPr, ContentPos);
}
}
if (true === HavePrChange)
{
ContentPos.Update(this.Content.length, Depth);
Checker.Set_PrChangeEndPos(ContentPos);
Checker.Update_PrChangeReviewInfo(this.Pr.ReviewInfo);
}
};
ParaRun.prototype.private_UpdateTrackRevisionOnChangeContent = function(bUpdateInfo)
{
if (reviewtype_Common !== this.Get_ReviewType())
{
this.private_UpdateTrackRevisions();
if (true === bUpdateInfo && this.Paragraph && this.Paragraph.LogicDocument && this.Paragraph.bFromDocument && true === this.Paragraph.LogicDocument.Is_TrackRevisions() && this.ReviewInfo && true === this.ReviewInfo.Is_CurrentUser())
{
var OldReviewInfo = this.ReviewInfo.Copy();
this.ReviewInfo.Update();
History.Add(new CChangesRunContentReviewInfo(this, OldReviewInfo, this.ReviewInfo.Copy()));
}
}
};
ParaRun.prototype.private_UpdateTrackRevisionOnChangeTextPr = function(bUpdateInfo)
{
if (true === this.Have_PrChange())
{
this.private_UpdateTrackRevisions();
if (true === bUpdateInfo && this.Paragraph && this.Paragraph.bFromDocument && this.Paragraph.LogicDocument && true === this.Paragraph.LogicDocument.Is_TrackRevisions())
{
var OldReviewInfo = this.Pr.ReviewInfo.Copy();
this.Pr.ReviewInfo.Update();
History.Add(new CChangesRunPrReviewInfo(this, OldReviewInfo, this.Pr.ReviewInfo.Copy()));
}
}
};
ParaRun.prototype.private_UpdateTrackRevisions = function()
{
if (this.Paragraph && this.Paragraph.bFromDocument && this.Paragraph.LogicDocument && this.Paragraph.LogicDocument.Get_TrackRevisionsManager)
{
var RevisionsManager = this.Paragraph.LogicDocument.Get_TrackRevisionsManager();
RevisionsManager.Check_Paragraph(this.Paragraph);
}
};
ParaRun.prototype.AcceptRevisionChanges = function(Type, bAll)
{
var Parent = this.Get_Parent();
var RunPos = this.private_GetPosInParent();
var ReviewType = this.Get_ReviewType();
var HavePrChange = this.Have_PrChange();
// Нет изменений в данном ране
if (reviewtype_Common === ReviewType && true !== HavePrChange)
return;
if (true === this.Selection.Use || true === bAll)
{
var StartPos = this.Selection.StartPos;
var EndPos = this.Selection.EndPos;
if (StartPos > EndPos)
{
StartPos = this.Selection.EndPos;
EndPos = this.Selection.StartPos;
}
if (true === bAll)
{
StartPos = 0;
EndPos = this.Content.length;
}
var CenterRun = null, CenterRunPos = RunPos;
if (0 === StartPos && this.Content.length === EndPos)
{
CenterRun = this;
}
else if (StartPos > 0 && this.Content.length === EndPos)
{
CenterRun = this.Split2(StartPos, Parent, RunPos);
CenterRunPos = RunPos + 1;
}
else if (0 === StartPos && this.Content.length > EndPos)
{
CenterRun = this;
this.Split2(EndPos, Parent, RunPos);
}
else
{
this.Split2(EndPos, Parent, RunPos);
CenterRun = this.Split2(StartPos, Parent, RunPos);
CenterRunPos = RunPos + 1;
}
if (true === HavePrChange && (undefined === Type || c_oAscRevisionsChangeType.TextPr === Type))
{
CenterRun.Remove_PrChange();
}
if (reviewtype_Add === ReviewType && (undefined === Type || c_oAscRevisionsChangeType.TextAdd === Type))
{
CenterRun.Set_ReviewType(reviewtype_Common);
}
else if (reviewtype_Remove === ReviewType && (undefined === Type || c_oAscRevisionsChangeType.TextRem === Type))
{
Parent.Remove_FromContent(CenterRunPos, 1);
if (Parent.Get_ContentLength() <= 0)
{
Parent.RemoveSelection();
Parent.Add_ToContent(0, new ParaRun());
Parent.MoveCursorToStartPos();
}
}
}
};
ParaRun.prototype.RejectRevisionChanges = function(Type, bAll)
{
var Parent = this.Get_Parent();
var RunPos = this.private_GetPosInParent();
var ReviewType = this.Get_ReviewType();
var HavePrChange = this.Have_PrChange();
// Нет изменений в данном ране
if (reviewtype_Common === ReviewType && true !== HavePrChange)
return;
if (true === this.Selection.Use || true === bAll)
{
var StartPos = this.Selection.StartPos;
var EndPos = this.Selection.EndPos;
if (StartPos > EndPos)
{
StartPos = this.Selection.EndPos;
EndPos = this.Selection.StartPos;
}
if (true === bAll)
{
StartPos = 0;
EndPos = this.Content.length;
}
var CenterRun = null, CenterRunPos = RunPos;
if (0 === StartPos && this.Content.length === EndPos)
{
CenterRun = this;
}
else if (StartPos > 0 && this.Content.length === EndPos)
{
CenterRun = this.Split2(StartPos, Parent, RunPos);
CenterRunPos = RunPos + 1;
}
else if (0 === StartPos && this.Content.length > EndPos)
{
CenterRun = this;
this.Split2(EndPos, Parent, RunPos);
}
else
{
this.Split2(EndPos, Parent, RunPos);
CenterRun = this.Split2(StartPos, Parent, RunPos);
CenterRunPos = RunPos + 1;
}
if (true === HavePrChange && (undefined === Type || c_oAscRevisionsChangeType.TextPr === Type))
{
CenterRun.Set_Pr(CenterRun.Pr.PrChange);
}
if (reviewtype_Add === ReviewType && (undefined === Type || c_oAscRevisionsChangeType.TextAdd === Type))
{
Parent.Remove_FromContent(CenterRunPos, 1);
if (Parent.Get_ContentLength() <= 0)
{
Parent.RemoveSelection();
Parent.Add_ToContent(0, new ParaRun());
Parent.MoveCursorToStartPos();
}
}
else if (reviewtype_Remove === ReviewType && (undefined === Type || c_oAscRevisionsChangeType.TextRem === Type))
{
CenterRun.Set_ReviewType(reviewtype_Common);
}
}
};
ParaRun.prototype.Is_InHyperlink = function()
{
if (!this.Paragraph)
return false;
var ContentPos = this.Paragraph.Get_PosByElement(this);
var Classes = this.Paragraph.Get_ClassesByPos(ContentPos);
var bHyper = false;
var bRun = false;
for (var Index = 0, Count = Classes.length; Index < Count; Index++)
{
var Item = Classes[Index];
if (Item === this)
{
bRun = true;
break;
}
else if (Item instanceof ParaHyperlink)
{
bHyper = true;
}
}
return (bHyper && bRun);
};
ParaRun.prototype.Get_ClassesByPos = function(Classes, ContentPos, Depth)
{
Classes.push(this);
};
ParaRun.prototype.GetDocumentPositionFromObject = function(PosArray)
{
if (!PosArray)
PosArray = [];
if (this.Paragraph)
{
var ParaContentPos = this.Paragraph.Get_PosByElement(this);
if (null !== ParaContentPos)
{
var Depth = ParaContentPos.Get_Depth();
while (Depth > 0)
{
var Pos = ParaContentPos.Get(Depth);
ParaContentPos.Decrease_Depth(1);
var Class = this.Paragraph.Get_ElementByPos(ParaContentPos);
Depth--;
PosArray.splice(0, 0, {Class : Class, Position : Pos});
}
PosArray.splice(0, 0, {Class : this.Paragraph, Position : ParaContentPos.Get(0)});
}
this.Paragraph.GetDocumentPositionFromObject(PosArray);
}
return PosArray;
};
ParaRun.prototype.Is_UseInParagraph = function()
{
if (!this.Paragraph)
return false;
var ContentPos = this.Paragraph.Get_PosByElement(this);
if (!ContentPos)
return false;
return true;
};
ParaRun.prototype.Displace_BreakOperator = function(isForward, bBrkBefore, CountOperators)
{
var bResult = true;
var bFirstItem = this.State.ContentPos == 0 || this.State.ContentPos == 1,
bLastItem = this.State.ContentPos == this.Content.length - 1 || this.State.ContentPos == this.Content.length;
if(true === this.Is_StartForcedBreakOperator() && bFirstItem == true)
{
var AlnAt = this.MathPrp.Get_AlnAt();
var NotIncrease = AlnAt == CountOperators && isForward == true;
if(NotIncrease == false)
{
this.MathPrp.Displace_Break(isForward);
var NewAlnAt = this.MathPrp.Get_AlnAt();
if(AlnAt !== NewAlnAt)
{
History.Add(new CChangesRunMathAlnAt(this, AlnAt, NewAlnAt));
}
}
}
else
{
bResult = (bLastItem && bBrkBefore) || (bFirstItem && !bBrkBefore) ? false : true;
}
return bResult; // применили смещение к данному Run
};
ParaRun.prototype.Math_UpdateLineMetrics = function(PRS, ParaPr)
{
var LineRule = ParaPr.Spacing.LineRule;
// Пересчитаем метрику строки относительно размера данного текста
if ( PRS.LineTextAscent < this.TextAscent )
PRS.LineTextAscent = this.TextAscent;
if ( PRS.LineTextAscent2 < this.TextAscent2 )
PRS.LineTextAscent2 = this.TextAscent2;
if ( PRS.LineTextDescent < this.TextDescent )
PRS.LineTextDescent = this.TextDescent;
if ( Asc.linerule_Exact === LineRule )
{
// Смещение не учитывается в метриках строки, когда расстояние между строк точное
if ( PRS.LineAscent < this.TextAscent )
PRS.LineAscent = this.TextAscent;
if ( PRS.LineDescent < this.TextDescent )
PRS.LineDescent = this.TextDescent;
}
else
{
if ( PRS.LineAscent < this.TextAscent + this.YOffset )
PRS.LineAscent = this.TextAscent + this.YOffset;
if ( PRS.LineDescent < this.TextDescent - this.YOffset )
PRS.LineDescent = this.TextDescent - this.YOffset;
}
};
ParaRun.prototype.Set_CompositeInput = function(oCompositeInput)
{
this.CompositeInput = oCompositeInput;
};
ParaRun.prototype.Get_FootnotesList = function(oEngine)
{
for (var nIndex = 0, nCount = this.Content.length; nIndex < nCount; ++nIndex)
{
var oItem = this.Content[nIndex];
if (para_FootnoteReference === oItem.Type)
{
oEngine.Add(oItem.Get_Footnote(), oItem, this);
}
}
};
ParaRun.prototype.Is_UseInDocument = function()
{
return (this.Paragraph && true === this.Paragraph.Is_UseInDocument() && true === this.Is_UseInParagraph() ? true : false);
};
ParaRun.prototype.GetParaEnd = function()
{
for (var nIndex = 0, nCount = this.Content.length; nIndex < nCount; ++nIndex)
{
if (this.Content[nIndex].Type === para_End)
return this.Content[nIndex];
}
return null;
};
ParaRun.prototype.RemoveElement = function(oElement)
{
for (var nIndex = 0, nCount = this.Content.length; nIndex < nCount; ++nIndex)
{
if (oElement === this.Content[nIndex])
return this.Remove_FromContent(nIndex, 1, true);
}
};
ParaRun.prototype.GotoFootnoteRef = function(isNext, isCurrent, isStepOver)
{
var nPos = 0;
if (true === isCurrent)
{
if (true === this.Selection.Use)
nPos = Math.min(this.Selection.StartPos, this.Selection.EndPos);
else
nPos = this.State.ContentPos;
}
else
{
if (true === isNext)
nPos = 0;
else
nPos = this.Content.length - 1;
}
var nResult = 0;
if (true === isNext)
{
for (var nIndex = nPos, nCount = this.Content.length; nIndex < nCount; ++nIndex)
{
if (para_FootnoteReference === this.Content[nIndex].Type && ((true !== isCurrent && true === isStepOver) || (true === isCurrent && (true === this.Selection.Use || nPos !== nIndex))))
{
if (this.Paragraph && this.Paragraph.bFromDocument && this.Paragraph.LogicDocument)
this.Paragraph.LogicDocument.RemoveSelection();
this.State.ContentPos = nIndex;
this.Make_ThisElementCurrent(true);
return -1;
}
nResult++;
}
}
else
{
for (var nIndex = Math.min(nPos, this.Content.length - 1); nIndex >= 0; --nIndex)
{
if (para_FootnoteReference === this.Content[nIndex].Type && ((true !== isCurrent && true === isStepOver) || (true === isCurrent && (true === this.Selection.Use || nPos !== nIndex))))
{
if (this.Paragraph && this.Paragraph.bFromDocument && this.Paragraph.LogicDocument)
this.Paragraph.LogicDocument.RemoveSelection();
this.State.ContentPos = nIndex;
this.Make_ThisElementCurrent(true);
return -1;
}
nResult++;
}
}
return nResult;
};
ParaRun.prototype.GetFootnoteRefsInRange = function(arrFootnotes, _CurLine, _CurRange)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = (0 === CurLine ? _CurRange - this.StartRange : _CurRange);
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
for (var CurPos = StartPos; CurPos < EndPos; CurPos++)
{
if (para_FootnoteReference === this.Content[CurPos].Type)
arrFootnotes.push(this.Content[CurPos]);
}
};
ParaRun.prototype.GetAllContentControls = function(arrContentControls)
{
if (!arrContentControls)
return;
for (var nIndex = 0, nCount = this.Content.length; nIndex < nCount; ++nIndex)
{
var oItem = this.Content[nIndex];
if (para_Drawing === oItem.Type || para_FootnoteReference === oItem.Type)
{
oItem.GetAllContentControls(arrContentControls);
}
}
};
function CParaRunStartState(Run)
{
this.Paragraph = Run.Paragraph;
this.Pr = Run.Pr.Copy();
this.Content = [];
for(var i = 0; i < Run.Content.length; ++i)
{
this.Content.push(Run.Content[i]);
}
}
function CReviewInfo()
{
this.Editor = editor;
this.UserId = "";
this.UserName = "";
this.DateTime = "";
}
CReviewInfo.prototype.Update = function()
{
if (this.Editor && this.Editor.DocInfo)
{
this.UserId = this.Editor.DocInfo.get_UserId();
this.UserName = this.Editor.DocInfo.get_UserName();
this.DateTime = (new Date()).getTime();
}
};
CReviewInfo.prototype.Copy = function()
{
var Info = new CReviewInfo();
Info.UserId = this.UserId;
Info.UserName = this.UserName;
Info.DateTime = this.DateTime;
return Info;
};
CReviewInfo.prototype.Get_UserId = function()
{
return this.UserId;
};
CReviewInfo.prototype.Get_UserName = function()
{
return this.UserName;
};
CReviewInfo.prototype.Get_DateTime = function()
{
return this.DateTime;
};
CReviewInfo.prototype.Write_ToBinary = function(Writer)
{
Writer.WriteString2(this.UserId);
Writer.WriteString2(this.UserName);
Writer.WriteString2(this.DateTime);
};
CReviewInfo.prototype.Read_FromBinary = function(Reader)
{
this.UserId = Reader.GetString2();
this.UserName = Reader.GetString2();
this.DateTime = parseInt(Reader.GetString2());
};
CReviewInfo.prototype.Get_Color = function()
{
if (!this.UserId && !this.UserName)
return REVIEW_COLOR;
return AscCommon.getUserColorById(this.UserId, this.UserName, true, false);
};
CReviewInfo.prototype.Is_CurrentUser = function()
{
if (this.Editor)
{
var UserId = this.Editor.DocInfo.get_UserId();
return (UserId === this.UserId);
}
return true;
};
CReviewInfo.prototype.Get_UserId = function()
{
return this.UserId;
};
function CanUpdatePosition(Para, Run) {
return (Para && true === Para.Is_UseInDocument() && true === Run.Is_UseInParagraph());
}
//--------------------------------------------------------export----------------------------------------------------
window['AscCommonWord'] = window['AscCommonWord'] || {};
window['AscCommonWord'].ParaRun = ParaRun;
window['AscCommonWord'].CanUpdatePosition = CanUpdatePosition;
| word/Editor/Run.js | /*
* (c) Copyright Ascensio System SIA 2010-2017
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia,
* EU, LV-1021.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
"use strict";
// Import
var g_oTableId = AscCommon.g_oTableId;
var g_oTextMeasurer = AscCommon.g_oTextMeasurer;
var History = AscCommon.History;
var c_oAscShdNil = Asc.c_oAscShdNil;
var reviewtype_Common = 0x00;
var reviewtype_Remove = 0x01;
var reviewtype_Add = 0x02;
/**
*
* @param Paragraph
* @param bMathRun
* @constructor
* @extends {CParagraphContentWithContentBase}
*/
function ParaRun(Paragraph, bMathRun)
{
CParagraphContentWithContentBase.call(this);
this.Id = AscCommon.g_oIdCounter.Get_NewId(); // Id данного элемента
this.Type = para_Run; // тип данного элемента
this.Paragraph = Paragraph; // Ссылка на параграф
this.Pr = new CTextPr(); // Текстовые настройки данного run
this.Content = []; // Содержимое данного run
this.State = new CParaRunState(); // Положение курсора и селекта в данного run
this.Selection = this.State.Selection;
this.CompiledPr = new CTextPr(); // Скомпилированные настройки
this.RecalcInfo = new CParaRunRecalcInfo(); // Флаги для пересчета (там же флаг пересчета стиля)
this.TextAscent = 0; // текстовый ascent + linegap
this.TextAscent = 0; // текстовый ascent + linegap
this.TextDescent = 0; // текстовый descent
this.TextHeight = 0; // высота текста
this.TextAscent2 = 0; // текстовый ascent
this.Ascent = 0; // общий ascent
this.Descent = 0; // общий descent
this.YOffset = 0; // смещение по Y
this.CollPrChangeMine = false;
this.CollPrChangeOther = false;
this.CollaborativeMarks = new CRunCollaborativeMarks();
this.m_oContentChanges = new AscCommon.CContentChanges(); // список изменений(добавление/удаление элементов)
this.NearPosArray = [];
this.SearchMarks = [];
this.SpellingMarks = [];
this.ReviewType = reviewtype_Common;
this.ReviewInfo = new CReviewInfo();
if (editor && !editor.isPresentationEditor && editor.WordControl && editor.WordControl.m_oLogicDocument && true === editor.WordControl.m_oLogicDocument.Is_TrackRevisions())
{
this.ReviewType = reviewtype_Add;
this.ReviewInfo.Update();
}
if(bMathRun)
{
this.Type = para_Math_Run;
// запомним позицию для Recalculate_CurPos, когда Run пустой
this.pos = new CMathPosition();
this.ParaMath = null;
this.Parent = null;
this.ArgSize = 0;
this.size = new CMathSize();
this.MathPrp = new CMPrp();
this.bEqArray = false;
}
this.StartState = null;
this.CompositeInput = null;
// Добавляем данный класс в таблицу Id (обязательно в конце конструктора)
g_oTableId.Add( this, this.Id );
if(this.Paragraph && !this.Paragraph.bFromDocument)
{
this.Save_StartState();
}
}
ParaRun.prototype = Object.create(CParagraphContentWithContentBase.prototype);
ParaRun.prototype.constructor = ParaRun;
ParaRun.prototype.Get_Type = function()
{
return this.Type;
};
//-----------------------------------------------------------------------------------
// Функции для работы с Id
//-----------------------------------------------------------------------------------
ParaRun.prototype.Get_Id = function()
{
return this.Id;
};
ParaRun.prototype.GetParagraph = function()
{
return this.Paragraph;
};
ParaRun.prototype.SetParagraph = function(Paragraph)
{
this.Paragraph = Paragraph;
};
ParaRun.prototype.Set_ParaMath = function(ParaMath, Parent)
{
this.ParaMath = ParaMath;
this.Parent = Parent;
for(var i = 0; i < this.Content.length; i++)
{
this.Content[i].relate(this);
}
};
ParaRun.prototype.Save_StartState = function()
{
this.StartState = new CParaRunStartState(this);
};
//-----------------------------------------------------------------------------------
// Функции для работы с содержимым данного рана
//-----------------------------------------------------------------------------------
ParaRun.prototype.Copy = function(Selected)
{
var bMath = this.Type == para_Math_Run ? true : false;
var NewRun = new ParaRun(this.Paragraph, bMath);
NewRun.Set_Pr( this.Pr.Copy() );
if (this.Paragraph && this.Paragraph.bFromDocument && this.Paragraph.LogicDocument && true === this.Paragraph.LogicDocument.Is_TrackRevisions())
NewRun.Set_ReviewType(reviewtype_Add);
if(true === bMath)
NewRun.Set_MathPr(this.MathPrp.Copy());
var StartPos = 0;
var EndPos = this.Content.length;
if (true === Selected && true === this.State.Selection.Use)
{
StartPos = this.State.Selection.StartPos;
EndPos = this.State.Selection.EndPos;
if (StartPos > EndPos)
{
StartPos = this.State.Selection.EndPos;
EndPos = this.State.Selection.StartPos;
}
}
else if (true === Selected && true !== this.State.Selection.Use)
EndPos = -1;
for ( var CurPos = StartPos; CurPos < EndPos; CurPos++ )
{
var Item = this.Content[CurPos];
// TODO: Как только перенесем para_End в сам параграф (как и нумерацию) убрать здесь
if ( para_End !== Item.Type )
NewRun.Add_ToContent( CurPos - StartPos, Item.Copy(), false );
}
return NewRun;
};
ParaRun.prototype.Copy2 = function()
{
var NewRun = new ParaRun(this.Paragraph);
NewRun.Set_Pr( this.Pr.Copy() );
var StartPos = 0;
var EndPos = this.Content.length;
for ( var CurPos = StartPos; CurPos < EndPos; CurPos++ )
{
var Item = this.Content[CurPos];
NewRun.Add_ToContent( CurPos - StartPos, Item.Copy(), false );
}
return NewRun;
};
ParaRun.prototype.CopyContent = function(Selected)
{
return [this.Copy(Selected)];
};
ParaRun.prototype.GetAllDrawingObjects = function(DrawingObjs)
{
var Count = this.Content.length;
for ( var Index = 0; Index < Count; Index++ )
{
var Item = this.Content[Index];
if ( para_Drawing === Item.Type )
{
DrawingObjs.push(Item);
Item.GetAllDrawingObjects(DrawingObjs);
}
}
};
ParaRun.prototype.Clear_ContentChanges = function()
{
this.m_oContentChanges.Clear();
};
ParaRun.prototype.Add_ContentChanges = function(Changes)
{
this.m_oContentChanges.Add( Changes );
};
ParaRun.prototype.Refresh_ContentChanges = function()
{
this.m_oContentChanges.Refresh();
};
ParaRun.prototype.Get_Text = function(Text)
{
if ( null === Text.Text )
return;
var ContentLen = this.Content.length;
for ( var CurPos = 0; CurPos < ContentLen; CurPos++ )
{
var Item = this.Content[CurPos];
var ItemType = Item.Type;
var bBreak = false;
switch ( ItemType )
{
case para_Drawing:
case para_PageNum:
case para_PageCount:
{
if (true === Text.BreakOnNonText)
{
Text.Text = null;
bBreak = true;
}
break;
}
case para_End:
{
if (true === Text.BreakOnNonText)
{
Text.Text = null;
bBreak = true;
}
if (true === Text.ParaEndToSpace)
Text.Text += " ";
break;
}
case para_Text : Text.Text += String.fromCharCode(Item.Value); break;
case para_Space:
case para_Tab : Text.Text += " "; break;
}
if ( true === bBreak )
break;
}
};
// Проверяем пустой ли ран
ParaRun.prototype.Is_Empty = function(Props)
{
var SkipAnchor = (undefined !== Props ? Props.SkipAnchor : false);
var SkipEnd = (undefined !== Props ? Props.SkipEnd : false);
var SkipPlcHldr= (undefined !== Props ? Props.SkipPlcHldr: false);
var SkipNewLine= (undefined !== Props ? Props.SkipNewLine: false);
var Count = this.Content.length;
if (true !== SkipAnchor && true !== SkipEnd && true !== SkipPlcHldr && true !== SkipNewLine)
{
if ( Count > 0 )
return false;
else
return true;
}
else
{
for ( var CurPos = 0; CurPos < this.Content.length; CurPos++ )
{
var Item = this.Content[CurPos];
var ItemType = Item.Type;
if ((true !== SkipAnchor || para_Drawing !== ItemType || false !== Item.Is_Inline()) && (true !== SkipEnd || para_End !== ItemType) && (true !== SkipPlcHldr || true !== Item.IsPlaceholder()) && (true !== SkipNewLine || para_NewLine !== ItemType))
return false;
}
return true;
}
};
ParaRun.prototype.Is_CheckingNearestPos = function()
{
if (this.NearPosArray.length > 0)
return true;
return false;
};
// Начинается ли данный ран с новой строки
ParaRun.prototype.Is_StartFromNewLine = function()
{
if (this.protected_GetLinesCount() < 2 || 0 !== this.protected_GetRangeStartPos(1, 0))
return false;
return true;
};
// Добавляем элемент в текущую позицию
ParaRun.prototype.Add = function(Item, bMath)
{
if (undefined !== Item.Parent)
Item.Parent = this;
if (this.Paragraph && this.Paragraph.LogicDocument && this.Paragraph.bFromDocument)
{
// Специальный код, связанный с обработкой изменения языка ввода при наборе.
if (true === this.Paragraph.LogicDocument.CheckLanguageOnTextAdd && editor)
{
var nRequiredLanguage = editor.asc_getKeyboardLanguage();
var nCurrentLanguage = this.Get_CompiledPr(false).Lang.Val;
if (-1 !== nRequiredLanguage && nRequiredLanguage !== nCurrentLanguage)
{
var NewLang = new CLang();
NewLang.Val = nRequiredLanguage;
if (this.Is_Empty())
{
this.Set_Lang(NewLang);
}
else
{
var NewRun = this.private_SplitRunInCurPos();
if (NewRun)
{
NewRun.Set_Lang(NewLang);
NewRun.MoveCursorToStartPos();
NewRun.Add(Item, bMath);
NewRun.Make_ThisElementCurrent();
return;
}
}
}
}
// Специальный код, связанный с работой сносок:
// 1. При добавлении сноски мы ее оборачиваем в отдельный ран со специальным стилем.
// 2. Если мы находимся в ране со специальным стилем сносок и следующий или предыдущий элемент и есть сноска, тогда
// мы добавляем элемент (если это не ссылка на сноску) в новый ран без стиля для сносок.
var oStyles = this.Paragraph.LogicDocument.Get_Styles();
if (para_FootnoteRef === Item.Type || para_FootnoteReference === Item.Type)
{
if (this.Is_Empty())
{
this.Set_RStyle(oStyles.GetDefaultFootnoteReference());
}
else
{
var NewRun = this.private_SplitRunInCurPos();
if (NewRun)
{
NewRun.Set_VertAlign(undefined);
NewRun.Set_RStyle(oStyles.GetDefaultFootnoteReference());
NewRun.MoveCursorToStartPos();
NewRun.Add(Item, bMath);
NewRun.Make_ThisElementCurrent();
return;
}
}
}
else if (true === this.private_IsCurPosNearFootnoteReference())
{
var NewRun = this.private_SplitRunInCurPos();
if (NewRun)
{
NewRun.Set_VertAlign(AscCommon.vertalign_Baseline);
NewRun.MoveCursorToStartPos();
NewRun.Add(Item, bMath);
NewRun.Make_ThisElementCurrent();
return;
}
}
}
var TrackRevisions = false;
if (this.Paragraph && this.Paragraph.LogicDocument)
TrackRevisions = this.Paragraph.LogicDocument.Is_TrackRevisions();
var ReviewType = this.Get_ReviewType();
if ((true === TrackRevisions && (reviewtype_Add !== ReviewType || true !== this.ReviewInfo.Is_CurrentUser())) || (false === TrackRevisions && reviewtype_Common !== ReviewType))
{
var DstReviewType = true === TrackRevisions ? reviewtype_Add : reviewtype_Common;
// Если мы стоим в конце рана, тогда проверяем следующий элемент родительского класса, аналогично если мы стоим
// в начале рана, проверяем предыдущий элемент родительского класса.
var Parent = this.Get_Parent();
if (null === Parent)
return;
// Ищем данный элемент в родительском классе
var RunPos = this.private_GetPosInParent(Parent);
if (-1 === RunPos)
return;
var CurPos = this.State.ContentPos;
if (0 === CurPos && RunPos > 0)
{
var PrevElement = Parent.Content[RunPos - 1];
if (para_Run === PrevElement.Type && DstReviewType === PrevElement.Get_ReviewType() && true === this.Pr.Is_Equal(PrevElement.Pr) && PrevElement.ReviewInfo && true === PrevElement.ReviewInfo.Is_CurrentUser())
{
PrevElement.State.ContentPos = PrevElement.Content.length;
PrevElement.private_AddItemToRun(PrevElement.Content.length, Item);
PrevElement.Make_ThisElementCurrent();
return;
}
}
if (this.Content.length === CurPos && (RunPos < Parent.Content.length - 2 || (RunPos < Parent.Content.length - 1 && !(Parent instanceof Paragraph))))
{
var NextElement = Parent.Content[RunPos + 1];
if (para_Run === NextElement.Type && DstReviewType === NextElement.Get_ReviewType() && true === this.Pr.Is_Equal(NextElement.Pr) && NextElement.ReviewInfo && true === NextElement.ReviewInfo.Is_CurrentUser())
{
NextElement.State.ContentPos = 0;
NextElement.private_AddItemToRun(0, Item);
NextElement.Make_ThisElementCurrent();
return;
}
}
// Если мы дошли до сюда, значит нам надо создать новый ран
var NewRun = new ParaRun(this.Paragraph, bMath);
NewRun.Set_Pr(this.Pr.Copy());
NewRun.Set_ReviewType(DstReviewType);
NewRun.private_AddItemToRun(0, Item);
if (0 === CurPos)
Parent.Add_ToContent(RunPos, NewRun);
else if (this.Content.length === CurPos)
Parent.Add_ToContent(RunPos + 1, NewRun);
else
{
var OldReviewInfo = (this.ReviewInfo ? this.ReviewInfo.Copy() : undefined);
var OldReviewType = this.ReviewType;
// Нужно разделить данный ран в текущей позиции
var RightRun = this.Split2(CurPos);
Parent.Add_ToContent(RunPos + 1, NewRun);
Parent.Add_ToContent(RunPos + 2, RightRun);
this.Set_ReviewTypeWithInfo(OldReviewType, OldReviewInfo);
RightRun.Set_ReviewTypeWithInfo(OldReviewType, OldReviewInfo);
}
NewRun.Make_ThisElementCurrent();
}
else if(this.Type == para_Math_Run && this.State.ContentPos == 0 && true === this.Is_StartForcedBreakOperator()) // если в начале текущего Run идет принудительный перенос => создаем новый Run
{
var NewRun = new ParaRun(this.Paragraph, bMath);
NewRun.Set_Pr(this.Pr.Copy());
NewRun.private_AddItemToRun(0, Item);
// Ищем данный элемент в родительском классе
var RunPos = this.private_GetPosInParent(this.Parent);
this.Parent.Internal_Content_Add(RunPos, NewRun, true);
}
else
{
this.private_AddItemToRun(this.State.ContentPos, Item);
}
};
ParaRun.prototype.private_SplitRunInCurPos = function()
{
var NewRun = null;
var Parent = this.Get_Parent();
var RunPos = this.private_GetPosInParent();
if (null !== Parent && -1 !== RunPos)
{
// Если мы стоим в начале рана, тогда добавим новый ран в начало, если мы стоим в конце рана, тогда
// добавим новый ран после текущего, а если мы в середине рана, тогда надо разбивать текущий ран.
NewRun = new ParaRun(this.Paragraph, para_Math_Run === this.Type);
NewRun.Set_Pr(this.Pr.Copy());
var CurPos = this.State.ContentPos;
if (0 === CurPos)
{
Parent.Add_ToContent(RunPos, NewRun);
}
else if (this.Content.length === CurPos)
{
Parent.Add_ToContent(RunPos + 1, NewRun);
}
else
{
// Нужно разделить данный ран в текущей позиции
var RightRun = this.Split2(CurPos);
Parent.Add_ToContent(RunPos + 1, NewRun);
Parent.Add_ToContent(RunPos + 2, RightRun);
}
}
return NewRun;
};
ParaRun.prototype.private_IsCurPosNearFootnoteReference = function()
{
if (this.Paragraph && this.Paragraph.LogicDocument && this.Paragraph.bFromDocument)
{
var oStyles = this.Paragraph.LogicDocument.Get_Styles();
var nCurPos = this.State.ContentPos;
if (this.Get_RStyle() === oStyles.GetDefaultFootnoteReference()
&& ((nCurPos > 0 && this.Content[nCurPos - 1] && (para_FootnoteRef === this.Content[nCurPos - 1].Type || para_FootnoteReference === this.Content[nCurPos - 1].Type))
|| (nCurPos < this.Content.length && this.Content[nCurPos] && (para_FootnoteRef === this.Content[nCurPos].Type || para_FootnoteReference === this.Content[nCurPos].Type))))
return true;
}
return false;
};
ParaRun.prototype.private_AddItemToRun = function(nPos, Item)
{
if (para_FootnoteReference === Item.Type && true === Item.IsCustomMarkFollows() && undefined !== Item.GetCustomText())
{
this.Add_ToContent(nPos, Item, true);
var sCustomText = Item.GetCustomText();
for (var nIndex = 0, nLen = sCustomText.length; nIndex < nLen; ++nIndex)
{
var nChar = sCustomText.charAt(nIndex);
if (" " === nChar)
this.Add_ToContent(nPos + 1 + nIndex, new ParaSpace(), true);
else
this.Add_ToContent(nPos + 1 + nIndex, new ParaText(nChar), true);
}
}
else
{
this.Add_ToContent(nPos, Item, true);
}
};
ParaRun.prototype.Remove = function(Direction, bOnAddText)
{
var TrackRevisions = null;
if (this.Paragraph && this.Paragraph.LogicDocument)
TrackRevisions = this.Paragraph.LogicDocument.Is_TrackRevisions();
var Selection = this.State.Selection;
var ReviewType = this.Get_ReviewType();
if (true === TrackRevisions && reviewtype_Add !== ReviewType)
{
if (reviewtype_Remove === ReviewType)
{
// Тут мы ничего не делаем, просто перешагиваем через удаленный текст
if (true !== Selection.Use)
{
var CurPos = this.State.ContentPos;
// Просто перешагиваем через элемент
if (Direction < 0)
{
// Пропускаем все Flow-объекты
while (CurPos > 0 && para_Drawing === this.Content[CurPos - 1].Type && false === this.Content[CurPos - 1].Is_Inline())
CurPos--;
if (CurPos <= 0)
return false;
this.State.ContentPos--;
}
else
{
if (CurPos >= this.Content.length || para_End === this.Content[CurPos].Type)
return false;
this.State.ContentPos++;
}
this.Make_ThisElementCurrent();
}
else
{
// Ничего не делаем
}
}
else
{
if (true === Selection.Use)
{
// Мы должны данный ран разбить в начальной и конечной точках выделения и центральный ран пометить как
// удаленный.
var StartPos = Selection.StartPos;
var EndPos = Selection.EndPos;
if (StartPos > EndPos)
{
StartPos = Selection.EndPos;
EndPos = Selection.StartPos;
}
var Parent = this.Get_Parent();
var RunPos = this.private_GetPosInParent(Parent);
if (-1 !== RunPos)
{
var DeletedRun = null;
if (StartPos <= 0 && EndPos >= this.Content.length)
DeletedRun = this;
else if (StartPos <= 0)
{
this.Split2(EndPos, Parent, RunPos);
DeletedRun = this;
}
else if (EndPos >= this.Content.length)
{
DeletedRun = this.Split2(StartPos, Parent, RunPos);
}
else
{
this.Split2(EndPos, Parent, RunPos);
DeletedRun = this.Split2(StartPos, Parent, RunPos);
}
DeletedRun.Set_ReviewType(reviewtype_Remove);
}
}
else
{
var Parent = this.Get_Parent();
var RunPos = this.private_GetPosInParent(Parent);
var CurPos = this.State.ContentPos;
if (Direction < 0)
{
// Пропускаем все Flow-объекты
while (CurPos > 0 && para_Drawing === this.Content[CurPos - 1].Type && false === this.Content[CurPos - 1].Is_Inline())
CurPos--;
if (CurPos <= 0)
return false;
// Проверяем, возможно предыдущий элемент - инлайн картинка, тогда мы его не удаляем, а выделяем как картинку
if (para_Drawing == this.Content[CurPos - 1].Type && true === this.Content[CurPos - 1].Is_Inline())
{
return this.Paragraph.Parent.Select_DrawingObject(this.Content[CurPos - 1].Get_Id());
}
if (1 === CurPos && 1 === this.Content.length)
{
this.Set_ReviewType(reviewtype_Remove);
this.State.ContentPos = CurPos - 1;
this.Make_ThisElementCurrent();
return true;
}
else if (1 === CurPos && Parent && RunPos > 0)
{
var PrevElement = Parent.Content[RunPos - 1];
if (para_Run === PrevElement.Type && reviewtype_Remove === PrevElement.Get_ReviewType() && true === this.Pr.Is_Equal(PrevElement.Pr))
{
var Item = this.Content[CurPos - 1];
this.Remove_FromContent(CurPos - 1, 1, true);
PrevElement.Add_ToContent(PrevElement.Content.length, Item);
PrevElement.State.ContentPos = PrevElement.Content.length - 1;
PrevElement.Make_ThisElementCurrent();
return true;
}
}
else if (CurPos === this.Content.length && Parent && RunPos < Parent.Content.length - 1)
{
var NextElement = Parent.Content[RunPos + 1];
if (para_Run === NextElement.Type && reviewtype_Remove === NextElement.Get_ReviewType() && true === this.Pr.Is_Equal(NextElement.Pr))
{
var Item = this.Content[CurPos - 1];
this.Remove_FromContent(CurPos - 1, 1, true);
NextElement.Add_ToContent(0, Item);
this.State.ContentPos = CurPos - 1;
this.Make_ThisElementCurrent();
return true;
}
}
// Если мы дошли до сюда, значит данный элемент нужно выделять в отдельный ран
var RRun = this.Split2(CurPos, Parent, RunPos);
var CRun = this.Split2(CurPos - 1, Parent, RunPos);
CRun.Set_ReviewType(reviewtype_Remove);
this.State.ContentPos = CurPos - 1;
this.Make_ThisElementCurrent();
}
else
{
if (CurPos >= this.Content.length || para_End === this.Content[CurPos].Type)
return false;
// Проверяем, возможно следующий элемент - инлайн картинка, тогда мы его не удаляем, а выделяем как картинку
if (para_Drawing == this.Content[CurPos].Type && true === this.Content[CurPos].Is_Inline())
{
return this.Paragraph.Parent.Select_DrawingObject(this.Content[CurPos].Get_Id());
}
if (CurPos === this.Content.length - 1 && 0 === CurPos)
{
this.Set_ReviewType(reviewtype_Remove);
this.State.ContentPos = 1;
this.Make_ThisElementCurrent();
return true;
}
else if (0 === CurPos && Parent && RunPos > 0)
{
var PrevElement = Parent.Content[RunPos - 1];
if (para_Run === PrevElement.Type && reviewtype_Remove === PrevElement.Get_ReviewType() && true === this.Pr.Is_Equal(PrevElement.Pr))
{
var Item = this.Content[CurPos];
this.Remove_FromContent(CurPos, 1, true);
PrevElement.Add_ToContent(PrevElement.Content.length, Item);
this.State.ContentPos = CurPos;
this.Make_ThisElementCurrent();
return true;
}
}
else if (CurPos === this.Content.length - 1 && Parent && RunPos < Parent.Content.length - 1)
{
var NextElement = Parent.Content[RunPos + 1];
if (para_Run === NextElement.Type && reviewtype_Remove === NextElement.Get_ReviewType() && true === this.Pr.Is_Equal(NextElement.Pr))
{
var Item = this.Content[CurPos];
this.Remove_FromContent(CurPos, 1, true);
NextElement.Add_ToContent(0, Item);
NextElement.State.ContentPos = 1;
NextElement.Make_ThisElementCurrent();
return true;
}
}
// Если мы дошли до сюда, значит данный элемент нужно выделять в отдельный ран
var RRun = this.Split2(CurPos + 1, Parent, RunPos);
var CRun = this.Split2(CurPos, Parent, RunPos);
CRun.Set_ReviewType(reviewtype_Remove);
RRun.State.ContentPos = 0;
RRun.Make_ThisElementCurrent();
}
}
}
}
else
{
if (true === Selection.Use)
{
var StartPos = Selection.StartPos;
var EndPos = Selection.EndPos;
if (StartPos > EndPos)
{
var Temp = StartPos;
StartPos = EndPos;
EndPos = Temp;
}
// Если в выделение попадает ParaEnd, тогда удаляем все кроме этого элемента
if (true === this.Selection_CheckParaEnd())
{
for (var CurPos = EndPos - 1; CurPos >= StartPos; CurPos--)
{
if (para_End !== this.Content[CurPos].Type)
this.Remove_FromContent(CurPos, 1, true);
}
}
else
{
this.Remove_FromContent(StartPos, EndPos - StartPos, true);
}
this.RemoveSelection();
this.State.ContentPos = StartPos;
}
else
{
var CurPos = this.State.ContentPos;
if (Direction < 0)
{
// Пропускаем все Flow-объекты
while (CurPos > 0 && para_Drawing === this.Content[CurPos - 1].Type && false === this.Content[CurPos - 1].Is_Inline())
CurPos--;
if (CurPos <= 0)
return false;
// Проверяем, возможно предыдущий элемент - инлайн картинка, тогда мы его не удаляем, а выделяем как картинку
if (para_Drawing == this.Content[CurPos - 1].Type && true === this.Content[CurPos - 1].Is_Inline())
{
return this.Paragraph.Parent.Select_DrawingObject(this.Content[CurPos - 1].Get_Id());
}
this.Remove_FromContent(CurPos - 1, 1, true);
this.State.ContentPos = CurPos - 1;
}
else
{
while (CurPos < this.Content.length && para_Drawing === this.Content[CurPos].Type && false === this.Content[CurPos].Is_Inline())
CurPos++;
if (CurPos >= this.Content.length || para_End === this.Content[CurPos].Type)
return false;
// Проверяем, возможно следующий элемент - инлайн картинка, тогда мы его не удаляем, а выделяем как картинку
if (para_Drawing == this.Content[CurPos].Type && true === this.Content[CurPos].Is_Inline())
{
return this.Paragraph.Parent.Select_DrawingObject(this.Content[CurPos].Get_Id());
}
this.Remove_FromContent(CurPos, 1, true);
this.State.ContentPos = CurPos;
}
}
}
return true;
};
ParaRun.prototype.Remove_ParaEnd = function()
{
var Pos = -1;
var ContentLen = this.Content.length;
for ( var CurPos = 0; CurPos < ContentLen; CurPos++ )
{
if ( para_End === this.Content[CurPos].Type )
{
Pos = CurPos;
break;
}
}
if ( -1 === Pos )
return false;
this.Remove_FromContent( Pos, ContentLen - Pos, true );
return true;
};
/**
* Обновляем позиции селекта, курсора и переносов строк при добавлении элемента в контент данного рана.
* @param Pos
*/
ParaRun.prototype.private_UpdatePositionsOnAdd = function(Pos)
{
// Обновляем текущую позицию
if (this.State.ContentPos >= Pos)
this.State.ContentPos++;
// Обновляем начало и конец селекта
if (true === this.State.Selection.Use)
{
if (this.State.Selection.StartPos >= Pos)
this.State.Selection.StartPos++;
if (this.State.Selection.EndPos >= Pos)
this.State.Selection.EndPos++;
}
// Также передвинем всем метки переносов страниц и строк
var LinesCount = this.protected_GetLinesCount();
for (var CurLine = 0; CurLine < LinesCount; CurLine++)
{
var RangesCount = this.protected_GetRangesCount(CurLine);
for (var CurRange = 0; CurRange < RangesCount; CurRange++)
{
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
if (StartPos > Pos)
StartPos++;
if (EndPos > Pos)
EndPos++;
this.protected_FillRange(CurLine, CurRange, StartPos, EndPos);
}
// Особый случай, когда мы добавляем элемент в самый последний ран
if (Pos === this.Content.length - 1 && LinesCount - 1 === CurLine)
{
this.protected_FillRangeEndPos(CurLine, RangesCount - 1, this.protected_GetRangeEndPos(CurLine, RangesCount - 1) + 1);
}
}
};
/**
* Обновляем позиции селекта, курсора и переносов строк при удалении элементов из контента данного рана.
* @param Pos
* @param Count
*/
ParaRun.prototype.private_UpdatePositionsOnRemove = function(Pos, Count)
{
// Обновим текущую позицию
if (this.State.ContentPos > Pos + Count)
this.State.ContentPos -= Count;
else if (this.State.ContentPos > Pos)
this.State.ContentPos = Pos;
// Обновим начало и конец селекта
if (true === this.State.Selection.Use)
{
if (this.State.Selection.StartPos <= this.State.Selection.EndPos)
{
if (this.State.Selection.StartPos > Pos + Count)
this.State.Selection.StartPos -= Count;
else if (this.State.Selection.StartPos > Pos)
this.State.Selection.StartPos = Pos;
if (this.State.Selection.EndPos >= Pos + Count)
this.State.Selection.EndPos -= Count;
else if (this.State.Selection.EndPos > Pos)
this.State.Selection.EndPos = Math.max(0, Pos - 1);
}
else
{
if (this.State.Selection.StartPos >= Pos + Count)
this.State.Selection.StartPos -= Count;
else if (this.State.Selection.StartPos > Pos)
this.State.Selection.StartPos = Math.max(0, Pos - 1);
if (this.State.Selection.EndPos > Pos + Count)
this.State.Selection.EndPos -= Count;
else if (this.State.Selection.EndPos > Pos)
this.State.Selection.EndPos = Pos;
}
}
// Также передвинем всем метки переносов страниц и строк
var LinesCount = this.protected_GetLinesCount();
for (var CurLine = 0; CurLine < LinesCount; CurLine++)
{
var RangesCount = this.protected_GetRangesCount(CurLine);
for (var CurRange = 0; CurRange < RangesCount; CurRange++)
{
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
if (StartPos > Pos + Count)
StartPos -= Count;
else if (StartPos > Pos)
StartPos = Math.max(0, Pos);
if (EndPos >= Pos + Count)
EndPos -= Count;
else if (EndPos >= Pos)
EndPos = Math.max(0, Pos);
this.protected_FillRange(CurLine, CurRange, StartPos, EndPos);
}
}
};
ParaRun.prototype.private_UpdateCompositeInputPositionsOnAdd = function(Pos)
{
if (null !== this.CompositeInput)
{
if (Pos <= this.CompositeInput.Pos)
this.CompositeInput.Pos++;
else if (Pos < this.CompositeInput.Pos + this.CompositeInput.Length)
this.CompositeInput.Length++;
}
};
ParaRun.prototype.private_UpdateCompositeInputPositionsOnRemove = function(Pos, Count)
{
if (null !== this.CompositeInput)
{
if (Pos + Count <= this.CompositeInput.Pos)
{
this.CompositeInput.Pos -= Count;
}
else if (Pos < this.CompositeInput.Pos)
{
this.CompositeInput.Pos = Pos;
this.CompositeInput.Length = Math.max(0, this.CompositeInput.Length - (Count - (this.CompositeInput.Pos - Pos)));
}
else if (Pos + Count < this.CompositeInput.Pos + this.CompositeInput.Length)
{
this.CompositeInput.Length = Math.max(0, this.CompositeInput.Length - Count);
}
else if (Pos < this.CompositeInput.Pos + this.CompositeInput.Length)
{
this.CompositeInput.Length = Math.max(0, Pos - this.CompositeInput.Pos);
}
}
};
// Добавляем элемент в позицию с сохранием в историю
ParaRun.prototype.Add_ToContent = function(Pos, Item, UpdatePosition)
{
History.Add(new CChangesRunAddItem(this, Pos, [Item], true));
this.Content.splice( Pos, 0, Item );
if (true === UpdatePosition)
this.private_UpdatePositionsOnAdd(Pos);
// Обновляем позиции в NearestPos
var NearPosLen = this.NearPosArray.length;
for ( var Index = 0; Index < NearPosLen; Index++ )
{
var RunNearPos = this.NearPosArray[Index];
var ContentPos = RunNearPos.NearPos.ContentPos;
var Depth = RunNearPos.Depth;
if ( ContentPos.Data[Depth] >= Pos )
ContentPos.Data[Depth]++;
}
// Обновляем позиции в поиске
var SearchMarksCount = this.SearchMarks.length;
for ( var Index = 0; Index < SearchMarksCount; Index++ )
{
var Mark = this.SearchMarks[Index];
var ContentPos = ( true === Mark.Start ? Mark.SearchResult.StartPos : Mark.SearchResult.EndPos );
var Depth = Mark.Depth;
if ( ContentPos.Data[Depth] >= Pos )
ContentPos.Data[Depth]++;
}
// Обновляем позиции для орфографии
var SpellingMarksCount = this.SpellingMarks.length;
for ( var Index = 0; Index < SpellingMarksCount; Index++ )
{
var Mark = this.SpellingMarks[Index];
var ContentPos = ( true === Mark.Start ? Mark.Element.StartPos : Mark.Element.EndPos );
var Depth = Mark.Depth;
if ( ContentPos.Data[Depth] >= Pos )
ContentPos.Data[Depth]++;
}
this.protected_UpdateSpellChecking();
this.private_UpdateTrackRevisionOnChangeContent(true);
// Обновляем позиции меток совместного редактирования
this.CollaborativeMarks.Update_OnAdd( Pos );
// Отмечаем, что надо перемерить элементы в данном ране
this.RecalcInfo.Measure = true;
};
ParaRun.prototype.Remove_FromContent = function(Pos, Count, UpdatePosition)
{
// Получим массив удаляемых элементов
var DeletedItems = this.Content.slice( Pos, Pos + Count );
History.Add(new CChangesRunRemoveItem(this, Pos, DeletedItems));
this.Content.splice( Pos, Count );
if (true === UpdatePosition)
this.private_UpdatePositionsOnRemove(Pos, Count);
// Обновляем позиции в NearestPos
var NearPosLen = this.NearPosArray.length;
for ( var Index = 0; Index < NearPosLen; Index++ )
{
var RunNearPos = this.NearPosArray[Index];
var ContentPos = RunNearPos.NearPos.ContentPos;
var Depth = RunNearPos.Depth;
if ( ContentPos.Data[Depth] > Pos + Count )
ContentPos.Data[Depth] -= Count;
else if ( ContentPos.Data[Depth] > Pos )
ContentPos.Data[Depth] = Math.max( 0 , Pos );
}
// Обновляем позиции в поиске
var SearchMarksCount = this.SearchMarks.length;
for ( var Index = 0; Index < SearchMarksCount; Index++ )
{
var Mark = this.SearchMarks[Index];
var ContentPos = ( true === Mark.Start ? Mark.SearchResult.StartPos : Mark.SearchResult.EndPos );
var Depth = Mark.Depth;
if ( ContentPos.Data[Depth] > Pos + Count )
ContentPos.Data[Depth] -= Count;
else if ( ContentPos.Data[Depth] > Pos )
ContentPos.Data[Depth] = Math.max( 0 , Pos );
}
// Обновляем позиции для орфографии
var SpellingMarksCount = this.SpellingMarks.length;
for ( var Index = 0; Index < SpellingMarksCount; Index++ )
{
var Mark = this.SpellingMarks[Index];
var ContentPos = ( true === Mark.Start ? Mark.Element.StartPos : Mark.Element.EndPos );
var Depth = Mark.Depth;
if ( ContentPos.Data[Depth] > Pos + Count )
ContentPos.Data[Depth] -= Count;
else if ( ContentPos.Data[Depth] > Pos )
ContentPos.Data[Depth] = Math.max( 0 , Pos );
}
this.protected_UpdateSpellChecking();
this.private_UpdateTrackRevisionOnChangeContent(true);
// Обновляем позиции меток совместного редактирования
this.CollaborativeMarks.Update_OnRemove( Pos, Count );
// Отмечаем, что надо перемерить элементы в данном ране
this.RecalcInfo.Measure = true;
};
ParaRun.prototype.Concat_ToContent = function(NewItems)
{
var StartPos = this.Content.length;
this.Content = this.Content.concat( NewItems );
History.Add(new CChangesRunAddItem(this, StartPos, NewItems, false));
this.private_UpdateTrackRevisionOnChangeContent(true);
// Отмечаем, что надо перемерить элементы в данном ране
this.RecalcInfo.Measure = true;
};
// Определим строку и отрезок текущей позиции
ParaRun.prototype.Get_CurrentParaPos = function()
{
var Pos = this.State.ContentPos;
if (-1 === this.StartLine)
return new CParaPos(-1, -1, -1, -1);
var CurLine = 0;
var CurRange = 0;
var LinesCount = this.protected_GetLinesCount();
for (; CurLine < LinesCount; CurLine++)
{
var RangesCount = this.protected_GetRangesCount(CurLine);
for (CurRange = 0; CurRange < RangesCount; CurRange++)
{
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
if ( Pos < EndPos && Pos >= StartPos )
return new CParaPos((CurLine === 0 ? CurRange + this.StartRange : CurRange), CurLine + this.StartLine, 0, 0);
}
}
// Значит курсор стоит в самом конце, поэтому посылаем последний отрезок
if(this.Type == para_Math_Run && LinesCount > 1)
{
var Line = LinesCount - 1,
Range = this.protected_GetRangesCount(LinesCount - 1) - 1;
StartPos = this.protected_GetRangeStartPos(Line, Range);
EndPos = this.protected_GetRangeEndPos(Line, Range);
// учтем, что в одной строке в формуле может быть только один Range
while(StartPos == EndPos && Line > 0 && this.Content.length !== 0) // == this.Content.length, т.к. последний Range
{
Line--;
StartPos = this.protected_GetRangeStartPos(Line, Range);
EndPos = this.protected_GetRangeEndPos(Line, Range);
}
return new CParaPos((this.protected_GetRangesCount(Line) - 1), Line + this.StartLine, 0, 0 );
}
return new CParaPos((LinesCount <= 1 ? this.protected_GetRangesCount(0) - 1 + this.StartRange : this.protected_GetRangesCount(LinesCount - 1) - 1), LinesCount - 1 + this.StartLine, 0, 0 );
};
ParaRun.prototype.Get_ParaPosByContentPos = function(ContentPos, Depth)
{
if (this.StartRange < 0 || this.StartLine < 0)
return new CParaPos(0, 0, 0, 0);
var Pos = ContentPos.Get(Depth);
var CurLine = 0;
var CurRange = 0;
var LinesCount = this.protected_GetLinesCount();
if (LinesCount <= 0)
return new CParaPos(0, 0, 0, 0);
for (; CurLine < LinesCount; CurLine++)
{
var RangesCount = this.protected_GetRangesCount(CurLine);
for (CurRange = 0; CurRange < RangesCount; CurRange++)
{
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
var bUpdateMathRun = Pos == EndPos && StartPos == EndPos && EndPos == this.Content.length && this.Type == para_Math_Run; // для para_Run позиция может быть после последнего элемента (пример: Run, за ним идет мат объект)
if (Pos < EndPos && Pos >= StartPos || bUpdateMathRun)
return new CParaPos((CurLine === 0 ? CurRange + this.StartRange : CurRange), CurLine + this.StartLine, 0, 0);
}
}
return new CParaPos((LinesCount === 1 ? this.protected_GetRangesCount(0) - 1 + this.StartRange : this.protected_GetRangesCount(0) - 1), LinesCount - 1 + this.StartLine, 0, 0);
};
ParaRun.prototype.Recalculate_CurPos = function(X, Y, CurrentRun, _CurRange, _CurLine, CurPage, UpdateCurPos, UpdateTarget, ReturnTarget)
{
var Para = this.Paragraph;
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
var Pos = StartPos;
var _EndPos = ( true === CurrentRun ? Math.min( EndPos, this.State.ContentPos ) : EndPos );
if(this.Type == para_Math_Run)
{
var Lng = this.Content.length;
Pos = _EndPos;
var LocParaMath = this.ParaMath.GetLinePosition(_CurLine, _CurRange);
X = LocParaMath.x;
Y = LocParaMath.y;
var MATH_Y = Y;
var loc;
if(Lng == 0)
{
X += this.pos.x;
Y += this.pos.y;
}
else if(Pos < EndPos)
{
loc = this.Content[Pos].GetLocationOfLetter();
X += loc.x;
Y += loc.y;
}
else if(!(StartPos == EndPos)) // исключаем этот случай StartPos == EndPos && EndPos == Pos, это возможно когда конец Run находится в начале строки, при этом ни одна из букв этого Run не входит в эту строку
{
var Letter = this.Content[Pos - 1];
loc = Letter.GetLocationOfLetter();
X += loc.x + Letter.Get_WidthVisible();
Y += loc.y;
}
}
else
{
for ( ; Pos < _EndPos; Pos++ )
{
var Item = this.Content[Pos];
var ItemType = Item.Type;
if (para_Drawing === ItemType && drawing_Inline !== Item.DrawingType)
continue;
X += Item.Get_WidthVisible();
}
}
var bNearFootnoteReference = this.private_IsCurPosNearFootnoteReference();
if ( true === CurrentRun && Pos === this.State.ContentPos )
{
if ( true === UpdateCurPos )
{
// Обновляем позицию курсора в параграфе
Para.CurPos.X = X;
Para.CurPos.Y = Y;
Para.CurPos.PagesPos = CurPage;
if ( true === UpdateTarget )
{
var CurTextPr = this.Get_CompiledPr(false);
var dFontKoef = bNearFootnoteReference ? 1 : CurTextPr.Get_FontKoef();
g_oTextMeasurer.SetTextPr(CurTextPr, this.Paragraph.Get_Theme());
g_oTextMeasurer.SetFontSlot(fontslot_ASCII, dFontKoef);
var Height = g_oTextMeasurer.GetHeight();
var Descender = Math.abs(g_oTextMeasurer.GetDescender());
var Ascender = Height - Descender;
Para.DrawingDocument.SetTargetSize( Height );
var RGBA;
Para.DrawingDocument.UpdateTargetTransform(Para.Get_ParentTextTransform());
if(CurTextPr.TextFill)
{
CurTextPr.TextFill.check(Para.Get_Theme(), Para.Get_ColorMap());
var oColor = CurTextPr.TextFill.getRGBAColor();
Para.DrawingDocument.SetTargetColor( oColor.R, oColor.G, oColor.B );
}
else if(CurTextPr.Unifill)
{
CurTextPr.Unifill.check(Para.Get_Theme(), Para.Get_ColorMap());
RGBA = CurTextPr.Unifill.getRGBAColor();
Para.DrawingDocument.SetTargetColor( RGBA.R, RGBA.G, RGBA.B );
}
else
{
if ( true === CurTextPr.Color.Auto )
{
// Выясним какая заливка у нашего текста
var Pr = Para.Get_CompiledPr();
var BgColor = undefined;
if ( undefined !== Pr.ParaPr.Shd && c_oAscShdNil !== Pr.ParaPr.Shd.Value )
{
if(Pr.ParaPr.Shd.Unifill)
{
Pr.ParaPr.Shd.Unifill.check(this.Paragraph.Get_Theme(), this.Paragraph.Get_ColorMap());
var RGBA = Pr.ParaPr.Shd.Unifill.getRGBAColor();
BgColor = new CDocumentColor(RGBA.R, RGBA.G, RGBA.B, false);
}
else
{
BgColor = Pr.ParaPr.Shd.Color;
}
}
else
{
// Нам надо выяснить заливку у родительского класса (возможно мы находимся в ячейке таблицы с забивкой)
BgColor = Para.Parent.Get_TextBackGroundColor();
if ( undefined !== CurTextPr.Shd && c_oAscShdNil !== CurTextPr.Shd.Value )
BgColor = CurTextPr.Shd.Get_Color( this.Paragraph );
}
// Определим автоцвет относительно заливки
var AutoColor = ( undefined != BgColor && false === BgColor.Check_BlackAutoColor() ? new CDocumentColor( 255, 255, 255, false ) : new CDocumentColor( 0, 0, 0, false ) );
Para.DrawingDocument.SetTargetColor( AutoColor.r, AutoColor.g, AutoColor.b );
}
else
Para.DrawingDocument.SetTargetColor( CurTextPr.Color.r, CurTextPr.Color.g, CurTextPr.Color.b );
}
var TargetY = Y - Ascender - CurTextPr.Position;
if (!bNearFootnoteReference)
{
switch (CurTextPr.VertAlign)
{
case AscCommon.vertalign_SubScript:
{
TargetY -= CurTextPr.FontSize * g_dKoef_pt_to_mm * vertalign_Koef_Sub;
break;
}
case AscCommon.vertalign_SuperScript:
{
TargetY -= CurTextPr.FontSize * g_dKoef_pt_to_mm * vertalign_Koef_Super;
break;
}
}
}
var PageAbs = Para.Get_AbsolutePage(CurPage);
// TODO: Тут делаем, чтобы курсор не выходил за границы буквицы. На самом деле, надо делать, чтобы
// курсор не выходил за границы строки, но для этого надо делать обрезку по строкам, а без нее
// такой вариант будет смотреться плохо.
if (para_Math_Run === this.Type && null !== this.Parent && true !== this.Parent.bRoot && this.Parent.bMath_OneLine)
{
var oBounds = this.Parent.Get_Bounds();
var __Y0 = TargetY, __Y1 = TargetY + Height;
// пока так
// TO DO : переделать
var YY = this.Parent.pos.y - this.Parent.size.ascent,
XX = this.Parent.pos.x;
var ___Y0 = MATH_Y + YY - 0.2 * oBounds.H;
var ___Y1 = MATH_Y + YY + 1.4 * oBounds.H;
__Y0 = Math.max( __Y0, ___Y0 );
__Y1 = Math.min( __Y1, ___Y1 );
Para.DrawingDocument.SetTargetSize( __Y1 - __Y0 );
Para.DrawingDocument.UpdateTarget( X, __Y0, PageAbs );
}
else if ( undefined != Para.Get_FramePr() )
{
var __Y0 = TargetY, __Y1 = TargetY + Height;
var ___Y0 = Para.Pages[CurPage].Y + Para.Lines[CurLine].Top;
var ___Y1 = Para.Pages[CurPage].Y + Para.Lines[CurLine].Bottom;
__Y0 = Math.max( __Y0, ___Y0 );
__Y1 = Math.min( __Y1, ___Y1 );
Para.DrawingDocument.SetTargetSize( __Y1 - __Y0 );
Para.DrawingDocument.UpdateTarget( X, __Y0, PageAbs );
}
else
{
Para.DrawingDocument.UpdateTarget(X, TargetY, PageAbs);
}
}
}
if ( true === ReturnTarget )
{
var CurTextPr = this.Get_CompiledPr(false);
var dFontKoef = bNearFootnoteReference ? 1 : CurTextPr.Get_FontKoef();
g_oTextMeasurer.SetTextPr(CurTextPr, this.Paragraph.Get_Theme());
g_oTextMeasurer.SetFontSlot(fontslot_ASCII, dFontKoef);
var Height = g_oTextMeasurer.GetHeight();
var Descender = Math.abs(g_oTextMeasurer.GetDescender());
var Ascender = Height - Descender;
var TargetY = Y - Ascender - CurTextPr.Position;
if (!bNearFootnoteReference)
{
switch (CurTextPr.VertAlign)
{
case AscCommon.vertalign_SubScript:
{
TargetY -= CurTextPr.FontSize * g_dKoef_pt_to_mm * vertalign_Koef_Sub;
break;
}
case AscCommon.vertalign_SuperScript:
{
TargetY -= CurTextPr.FontSize * g_dKoef_pt_to_mm * vertalign_Koef_Super;
break;
}
}
}
return { X : X, Y : TargetY, Height : Height, PageNum : Para.Get_AbsolutePage(CurPage), Internal : { Line : CurLine, Page : CurPage, Range : CurRange } };
}
else
return { X : X, Y : Y, PageNum : Para.Get_AbsolutePage(CurPage), Internal : { Line : CurLine, Page : CurPage, Range : CurRange } };
}
return { X : X, Y: Y, PageNum : Para.Get_AbsolutePage(CurPage), Internal : { Line : CurLine, Page : CurPage, Range : CurRange } };
};
// Проверяем, произошло ли простейшее изменение (набор или удаление текста)
ParaRun.prototype.Is_SimpleChanges = function(Changes)
{
var ParaPos = null;
var Count = Changes.length;
for (var Index = 0; Index < Count; Index++)
{
var Data = Changes[Index].Data;
if (undefined === Data.Items || 1 !== Data.Items.length)
return false;
var Type = Data.Type;
var Item = Data.Items[0];
if (undefined === Item)
return false;
if (AscDFH.historyitem_ParaRun_AddItem !== Type && AscDFH.historyitem_ParaRun_RemoveItem !== Type)
return false;
// Добавление/удаление картинок может изменить размер строки. Добавление/удаление переноса строки/страницы/колонки
// нельзя обсчитывать функцией Recalculate_Fast.
// TODO: Но на самом деле стоило бы сделать нормальную проверку на высоту строки в функции Recalculate_Fast
var ItemType = Item.Type;
if (para_Drawing === ItemType || para_NewLine === ItemType || para_FootnoteRef === ItemType || para_FootnoteReference === ItemType)
return false;
// Проверяем, что все изменения произошли в одном и том же отрезке
var CurParaPos = this.Get_SimpleChanges_ParaPos([Changes[Index]]);
if (null === CurParaPos)
return false;
if (null === ParaPos)
ParaPos = CurParaPos;
else if (ParaPos.Line !== CurParaPos.Line || ParaPos.Range !== CurParaPos.Range)
return false;
}
return true;
};
/**
* Проверяем произошло ли простое изменение параграфа, сейчас главное, чтобы это было не добавлениe/удаление картинки
* или ссылки на сноску. На вход приходит либо массив изменений, либо одно изменение (можно не в массиве).
*/
ParaRun.prototype.Is_ParagraphSimpleChanges = function(_Changes)
{
var Changes = _Changes;
if (!_Changes.length)
Changes = [_Changes];
var ChangesCount = Changes.length;
for (var ChangesIndex = 0; ChangesIndex < ChangesCount; ChangesIndex++)
{
var Data = Changes[ChangesIndex].Data;
var ChangeType = Data.Type;
if (AscDFH.historyitem_ParaRun_AddItem === ChangeType || AscDFH.historyitem_ParaRun_RemoveItem === ChangeType)
{
for (var ItemIndex = 0, ItemsCount = Data.Items.length; ItemIndex < ItemsCount; ItemIndex++)
{
var Item = Data.Items[ItemIndex];
if (para_Drawing === Item.Type || para_FootnoteReference === Item.Type)
return false;
}
}
}
return true;
};
// Возвращаем строку и отрезок, в котором произошли простейшие изменения
ParaRun.prototype.Get_SimpleChanges_ParaPos = function(Changes)
{
var Change = Changes[0].Data;
var Type = Changes[0].Data.Type;
var Pos = Change.Pos;
var CurLine = 0;
var CurRange = 0;
var LinesCount = this.protected_GetLinesCount();
for (; CurLine < LinesCount; CurLine++)
{
var RangesCount = this.protected_GetRangesCount(CurLine);
for (CurRange = 0; CurRange < RangesCount; CurRange++)
{
var RangeStartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var RangeEndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
if ( ( AscDFH.historyitem_ParaRun_AddItem === Type && Pos < RangeEndPos && Pos >= RangeStartPos ) || ( AscDFH.historyitem_ParaRun_RemoveItem === Type && Pos < RangeEndPos && Pos >= RangeStartPos ) || ( AscDFH.historyitem_ParaRun_RemoveItem === Type && Pos >= RangeEndPos && CurLine === LinesCount - 1 && CurRange === RangesCount - 1 ) )
{
// Если отрезок остается пустым, тогда надо все заново пересчитывать
if ( RangeStartPos === RangeEndPos )
return null;
return new CParaPos( ( CurLine === 0 ? CurRange + this.StartRange : CurRange ), CurLine + this.StartLine, 0, 0 );
}
}
}
// Если отрезок остается пустым, тогда надо все заново пересчитывать
if (this.protected_GetRangeStartPos(0, 0) === this.protected_GetRangeEndPos(0, 0))
return null;
return new CParaPos( this.StartRange, this.StartLine, 0, 0 );
};
ParaRun.prototype.Split = function (ContentPos, Depth)
{
var CurPos = ContentPos.Get(Depth);
return this.Split2( CurPos );
};
ParaRun.prototype.Split2 = function(CurPos, Parent, ParentPos)
{
History.Add(new CChangesRunOnStartSplit(this, CurPos));
AscCommon.CollaborativeEditing.OnStart_SplitRun(this, CurPos);
// Если задается Parent и ParentPos, тогда ран автоматически добавляется в родительский класс
var UpdateParent = (undefined !== Parent && undefined !== ParentPos && this === Parent.Content[ParentPos] ? true : false);
var UpdateSelection = (true === UpdateParent && true === Parent.IsSelectionUse() && true === this.IsSelectionUse() ? true : false);
// Создаем новый ран
var bMathRun = this.Type == para_Math_Run;
var NewRun = new ParaRun(this.Paragraph, bMathRun);
// Копируем настройки
NewRun.Set_Pr(this.Pr.Copy(true));
NewRun.Set_ReviewType(this.ReviewType);
NewRun.CollPrChangeMine = this.CollPrChangeMine;
NewRun.CollPrChangeOther = this.CollPrChangeOther;
if(bMathRun)
NewRun.Set_MathPr(this.MathPrp.Copy());
// TODO: Как только избавимся от para_End переделать тут
// Проверим, если наш ран содержит para_End, тогда мы должны para_End переметить в правый ран
var CheckEndPos = -1;
var CheckEndPos2 = Math.min( CurPos, this.Content.length );
for ( var Pos = 0; Pos < CheckEndPos2; Pos++ )
{
if ( para_End === this.Content[Pos].Type )
{
CheckEndPos = Pos;
break;
}
}
if ( -1 !== CheckEndPos )
CurPos = CheckEndPos;
var ParentOldSelectionStartPos, ParentOldSelectionEndPos, OldSelectionStartPos, OldSelectionEndPos;
if (true === UpdateSelection)
{
ParentOldSelectionStartPos = Parent.Selection.StartPos;
ParentOldSelectionEndPos = Parent.Selection.EndPos;
OldSelectionStartPos = this.Selection.StartPos;
OldSelectionEndPos = this.Selection.EndPos;
}
if (true === UpdateParent)
{
Parent.Add_ToContent(ParentPos + 1, NewRun);
// Обновим массив NearPosArray
for (var Index = 0, Count = this.NearPosArray.length; Index < Count; Index++)
{
var RunNearPos = this.NearPosArray[Index];
var ContentPos = RunNearPos.NearPos.ContentPos;
var Depth = RunNearPos.Depth;
var Pos = ContentPos.Get(Depth);
if (Pos >= CurPos)
{
ContentPos.Update2(Pos - CurPos, Depth);
ContentPos.Update2(ParentPos + 1, Depth - 1);
this.NearPosArray.splice(Index, 1);
Count--;
Index--;
NewRun.NearPosArray.push(RunNearPos);
if (this.Paragraph)
{
for (var ParaIndex = 0, ParaCount = this.Paragraph.NearPosArray.length; ParaIndex < ParaCount; ParaIndex++)
{
var ParaNearPos = this.Paragraph.NearPosArray[ParaIndex];
if (ParaNearPos.Classes[ParaNearPos.Classes.length - 1] === this)
ParaNearPos.Classes[ParaNearPos.Classes.length - 1] = NewRun;
}
}
}
}
}
// Разделяем содержимое по ранам
NewRun.Concat_ToContent( this.Content.slice(CurPos) );
this.Remove_FromContent( CurPos, this.Content.length - CurPos, true );
// Если были точки орфографии, тогда переместим их в новый ран
var SpellingMarksCount = this.SpellingMarks.length;
for ( var Index = 0; Index < SpellingMarksCount; Index++ )
{
var Mark = this.SpellingMarks[Index];
var MarkPos = ( true === Mark.Start ? Mark.Element.StartPos.Get(Mark.Depth) : Mark.Element.EndPos.Get(Mark.Depth) );
if ( MarkPos >= CurPos )
{
var MarkElement = Mark.Element;
if ( true === Mark.Start )
{
MarkElement.StartPos.Data[Mark.Depth] -= CurPos;
}
else
{
MarkElement.EndPos.Data[Mark.Depth] -= CurPos;
}
NewRun.SpellingMarks.push( Mark );
this.SpellingMarks.splice( Index, 1 );
SpellingMarksCount--;
Index--;
}
}
if (true === UpdateSelection)
{
if (ParentOldSelectionStartPos <= ParentPos && ParentPos <= ParentOldSelectionEndPos)
Parent.Selection.EndPos = ParentOldSelectionEndPos + 1;
else if (ParentOldSelectionEndPos <= ParentPos && ParentPos <= ParentOldSelectionStartPos)
Parent.Selection.StartPos = ParentOldSelectionStartPos + 1;
if (OldSelectionStartPos <= CurPos && CurPos <= OldSelectionEndPos)
{
this.Selection.EndPos = this.Content.length;
NewRun.Selection.Use = true;
NewRun.Selection.StartPos = 0;
NewRun.Selection.EndPos = OldSelectionEndPos - CurPos;
}
else if (OldSelectionEndPos <= CurPos && CurPos <= OldSelectionStartPos)
{
this.Selection.StartPos = this.Content.length;
NewRun.Selection.Use = true;
NewRun.Selection.EndPos = 0;
NewRun.Selection.StartPos = OldSelectionStartPos - CurPos;
}
}
History.Add(new CChangesRunOnEndSplit(this, NewRun));
AscCommon.CollaborativeEditing.OnEnd_SplitRun(NewRun);
return NewRun;
};
ParaRun.prototype.Check_NearestPos = function(ParaNearPos, Depth)
{
var RunNearPos = new CParagraphElementNearPos();
RunNearPos.NearPos = ParaNearPos.NearPos;
RunNearPos.Depth = Depth;
this.NearPosArray.push( RunNearPos );
ParaNearPos.Classes.push( this );
};
ParaRun.prototype.Get_DrawingObjectRun = function(Id)
{
var ContentLen = this.Content.length;
for ( var CurPos = 0; CurPos < ContentLen; CurPos++ )
{
var Element = this.Content[CurPos];
if ( para_Drawing === Element.Type && Id === Element.Get_Id() )
return this;
}
return null;
};
ParaRun.prototype.Get_DrawingObjectContentPos = function(Id, ContentPos, Depth)
{
var ContentLen = this.Content.length;
for ( var CurPos = 0; CurPos < ContentLen; CurPos++ )
{
var Element = this.Content[CurPos];
if ( para_Drawing === Element.Type && Id === Element.Get_Id() )
{
ContentPos.Update( CurPos, Depth );
return true;
}
}
return false;
};
ParaRun.prototype.Get_DrawingObjectSimplePos = function(Id)
{
var ContentLen = this.Content.length;
for (var CurPos = 0; CurPos < ContentLen; CurPos++)
{
var Element = this.Content[CurPos];
if (para_Drawing === Element.Type && Id === Element.Get_Id())
return CurPos;
}
return -1;
};
ParaRun.prototype.Remove_DrawingObject = function(Id)
{
var ContentLen = this.Content.length;
for ( var CurPos = 0; CurPos < ContentLen; CurPos++ )
{
var Element = this.Content[CurPos];
if ( para_Drawing === Element.Type && Id === Element.Get_Id() )
{
var TrackRevisions = null;
if (this.Paragraph && this.Paragraph.LogicDocument && this.Paragraph.bFromDocument)
TrackRevisions = this.Paragraph.LogicDocument.Is_TrackRevisions();
if (true === TrackRevisions)
{
var ReviewType = this.Get_ReviewType();
if (reviewtype_Common === ReviewType)
{
// Разбиваем ран на две части
var StartPos = CurPos;
var EndPos = CurPos + 1;
var Parent = this.Get_Parent();
var RunPos = this.private_GetPosInParent(Parent);
if (-1 !== RunPos && Parent)
{
var DeletedRun = null;
if (StartPos <= 0 && EndPos >= this.Content.length)
DeletedRun = this;
else if (StartPos <= 0)
{
this.Split2(EndPos, Parent, RunPos);
DeletedRun = this;
}
else if (EndPos >= this.Content.length)
{
DeletedRun = this.Split2(StartPos, Parent, RunPos);
}
else
{
this.Split2(EndPos, Parent, RunPos);
DeletedRun = this.Split2(StartPos, Parent, RunPos);
}
DeletedRun.Set_ReviewType(reviewtype_Remove);
}
}
else if (reviewtype_Add === ReviewType)
{
this.Remove_FromContent(CurPos, 1, true);
}
else if (reviewtype_Remove === ReviewType)
{
// Ничего не делаем
}
}
else
{
this.Remove_FromContent(CurPos, 1, true);
}
return;
}
}
};
ParaRun.prototype.Get_Layout = function(DrawingLayout, UseContentPos, ContentPos, Depth)
{
var CurLine = DrawingLayout.Line - this.StartLine;
var CurRange = ( 0 === CurLine ? DrawingLayout.Range - this.StartRange : DrawingLayout.Range );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
var CurContentPos = ( true === UseContentPos ? ContentPos.Get(Depth) : -1 );
var CurPos = StartPos;
for ( ; CurPos < EndPos; CurPos++ )
{
if ( CurContentPos === CurPos )
break;
var Item = this.Content[CurPos];
var ItemType = Item.Type;
var WidthVisible = Item.Get_WidthVisible();
switch ( ItemType )
{
case para_Text:
case para_Space:
case para_PageNum:
case para_PageCount:
{
DrawingLayout.LastW = WidthVisible;
break;
}
case para_Drawing:
{
if ( true === Item.Is_Inline() || true === DrawingLayout.Paragraph.Parent.Is_DrawingShape() )
{
DrawingLayout.LastW = WidthVisible;
}
break;
}
}
DrawingLayout.X += WidthVisible;
}
if (CurContentPos === CurPos)
DrawingLayout.Layout = true;
};
ParaRun.prototype.Get_NextRunElements = function(RunElements, UseContentPos, Depth)
{
var StartPos = ( true === UseContentPos ? RunElements.ContentPos.Get(Depth) : 0 );
var ContentLen = this.Content.length;
for ( var CurPos = StartPos; CurPos < ContentLen; CurPos++ )
{
var Item = this.Content[CurPos];
if (RunElements.CheckType(Item.Type))
{
RunElements.Elements.push( Item );
RunElements.Count--;
if ( RunElements.Count <= 0 )
return;
}
}
};
ParaRun.prototype.Get_PrevRunElements = function(RunElements, UseContentPos, Depth)
{
var StartPos = ( true === UseContentPos ? RunElements.ContentPos.Get(Depth) - 1 : this.Content.length - 1 );
var ContentLen = this.Content.length;
for ( var CurPos = StartPos; CurPos >= 0; CurPos-- )
{
var Item = this.Content[CurPos];
var ItemType = Item.Type;
if (RunElements.CheckType(Item.Type))
{
RunElements.Elements.push( Item );
RunElements.Count--;
if ( RunElements.Count <= 0 )
return;
}
}
};
ParaRun.prototype.CollectDocumentStatistics = function(ParaStats)
{
var Count = this.Content.length;
for (var Index = 0; Index < Count; Index++)
{
var Item = this.Content[Index];
var ItemType = Item.Type;
var bSymbol = false;
var bSpace = false;
var bNewWord = false;
if ((para_Text === ItemType && false === Item.Is_NBSP()) || (para_PageNum === ItemType || para_PageCount === ItemType))
{
if (false === ParaStats.Word)
bNewWord = true;
bSymbol = true;
bSpace = false;
ParaStats.Word = true;
ParaStats.EmptyParagraph = false;
}
else if ((para_Text === ItemType && true === Item.Is_NBSP()) || para_Space === ItemType || para_Tab === ItemType)
{
bSymbol = true;
bSpace = true;
ParaStats.Word = false;
}
if (true === bSymbol)
ParaStats.Stats.Add_Symbol(bSpace);
if (true === bNewWord)
ParaStats.Stats.Add_Word();
}
};
ParaRun.prototype.Create_FontMap = function(Map)
{
// для Math_Para_Pun argSize учитывается, когда мержатся текстовые настройки в Internal_Compile_Pr()
if ( undefined !== this.Paragraph && null !== this.Paragraph )
{
var TextPr;
var FontSize, FontSizeCS;
if(this.Type === para_Math_Run)
{
TextPr = this.Get_CompiledPr(false);
FontSize = TextPr.FontSize;
FontSizeCS = TextPr.FontSizeCS;
if(null !== this.Parent && undefined !== this.Parent && null !== this.Parent.ParaMath && undefined !== this.Parent.ParaMath)
{
TextPr.FontSize = this.Math_GetRealFontSize(TextPr.FontSize);
TextPr.FontSizeCS = this.Math_GetRealFontSize(TextPr.FontSizeCS);
}
}
else
TextPr = this.Get_CompiledPr(false);
TextPr.Document_CreateFontMap(Map, this.Paragraph.Get_Theme().themeElements.fontScheme);
var Count = this.Content.length;
for (var Index = 0; Index < Count; Index++)
{
var Item = this.Content[Index];
if (para_Drawing === Item.Type)
Item.documentCreateFontMap(Map);
else if (para_FootnoteReference === Item.Type)
Item.CreateDocumentFontMap(Map);
}
if(this.Type === para_Math_Run)
{
TextPr.FontSize = FontSize;
TextPr.FontSizeCS = FontSizeCS;
}
}
};
ParaRun.prototype.Get_AllFontNames = function(AllFonts)
{
this.Pr.Document_Get_AllFontNames( AllFonts );
var Count = this.Content.length;
for (var Index = 0; Index < Count; Index++)
{
var Item = this.Content[Index];
if ( para_Drawing === Item.Type )
Item.documentGetAllFontNames( AllFonts );
}
};
ParaRun.prototype.GetSelectedText = function(bAll, bClearText, oPr)
{
var StartPos = 0;
var EndPos = 0;
if ( true === bAll )
{
StartPos = 0;
EndPos = this.Content.length;
}
else if ( true === this.Selection.Use )
{
StartPos = this.State.Selection.StartPos;
EndPos = this.State.Selection.EndPos;
if ( StartPos > EndPos )
{
var Temp = EndPos;
EndPos = StartPos;
StartPos = Temp;
}
}
var Str = "";
for ( var Pos = StartPos; Pos < EndPos; Pos++ )
{
var Item = this.Content[Pos];
var ItemType = Item.Type;
switch ( ItemType )
{
case para_Drawing:
case para_Numbering:
case para_PresentationNumbering:
case para_PageNum:
case para_PageCount:
{
if ( true === bClearText )
return null;
break;
}
case para_Text :
{
Str += AscCommon.encodeSurrogateChar(Item.Value);
break;
}
case para_Space:
case para_Tab : Str += " "; break;
case para_End:
{
if (oPr && true === oPr.NewLineParagraph)
{
Str += '\r\n';
}
break;
}
}
}
return Str;
};
ParaRun.prototype.Get_SelectionDirection = function()
{
if (true !== this.Selection.Use)
return 0;
if (this.Selection.StartPos <= this.Selection.EndPos)
return 1;
return -1;
};
ParaRun.prototype.Can_AddDropCap = function()
{
var Count = this.Content.length;
for ( var Pos = 0; Pos < Count; Pos++ )
{
var Item = this.Content[Pos];
var ItemType = Item.Type;
switch ( ItemType )
{
case para_Text:
return true;
case para_Space:
case para_Tab:
case para_PageNum:
case para_PageCount:
return false;
}
}
return null;
};
ParaRun.prototype.Get_TextForDropCap = function(DropCapText, UseContentPos, ContentPos, Depth)
{
var EndPos = ( true === UseContentPos ? ContentPos.Get(Depth) : this.Content.length );
for ( var Pos = 0; Pos < EndPos; Pos++ )
{
var Item = this.Content[Pos];
var ItemType = Item.Type;
if ( true === DropCapText.Check )
{
if (para_Space === ItemType || para_Tab === ItemType || para_PageNum === ItemType || para_PageCount === ItemType || para_Drawing === ItemType || para_End === ItemType)
{
DropCapText.Mixed = true;
return;
}
}
else
{
if ( para_Text === ItemType )
{
DropCapText.Runs.push(this);
DropCapText.Text.push(Item);
this.Remove_FromContent( Pos, 1, true );
Pos--;
EndPos--;
if ( true === DropCapText.Mixed )
return;
}
}
}
};
ParaRun.prototype.Get_StartTabsCount = function(TabsCounter)
{
var ContentLen = this.Content.length;
for ( var Pos = 0; Pos < ContentLen; Pos++ )
{
var Item = this.Content[Pos];
var ItemType = Item.Type;
if ( para_Tab === ItemType )
{
TabsCounter.Count++;
TabsCounter.Pos.push( Pos );
}
else if ( para_Text === ItemType || para_Space === ItemType || (para_Drawing === ItemType && true === Item.Is_Inline() ) || para_PageNum === ItemType || para_PageCount === ItemType || para_Math === ItemType )
return false;
}
return true;
};
ParaRun.prototype.Remove_StartTabs = function(TabsCounter)
{
var ContentLen = this.Content.length;
for ( var Pos = 0; Pos < ContentLen; Pos++ )
{
var Item = this.Content[Pos];
var ItemType = Item.Type;
if ( para_Tab === ItemType )
{
this.Remove_FromContent( Pos, 1, true );
TabsCounter.Count--;
Pos--;
ContentLen--;
}
else if ( para_Text === ItemType || para_Space === ItemType || (para_Drawing === ItemType && true === Item.Is_Inline() ) || para_PageNum === ItemType || para_PageCount === ItemType || para_Math === ItemType )
return false;
}
return true;
};
//-----------------------------------------------------------------------------------
// Функции пересчета
//-----------------------------------------------------------------------------------
// Пересчитываем размеры всех элементов
ParaRun.prototype.Recalculate_MeasureContent = function()
{
if ( false === this.RecalcInfo.Measure )
return;
var Pr = this.Get_CompiledPr(false);
var Theme = this.Paragraph.Get_Theme();
g_oTextMeasurer.SetTextPr(Pr, Theme);
g_oTextMeasurer.SetFontSlot(fontslot_ASCII);
// Запрашиваем текущие метрики шрифта, под TextAscent мы будем понимать ascent + linegap(которые записаны в шрифте)
this.TextHeight = g_oTextMeasurer.GetHeight();
this.TextDescent = Math.abs( g_oTextMeasurer.GetDescender() );
this.TextAscent = this.TextHeight - this.TextDescent;
this.TextAscent2 = g_oTextMeasurer.GetAscender();
this.YOffset = Pr.Position;
var ContentLength = this.Content.length;
var InfoMathText;
if(para_Math_Run == this.Type)
{
var InfoTextPr =
{
TextPr: Pr,
ArgSize: this.Parent.Compiled_ArgSz.value,
bNormalText: this.IsNormalText(),
bEqArray: this.Parent.IsEqArray()
};
InfoMathText = new CMathInfoTextPr(InfoTextPr);
}
for ( var Pos = 0; Pos < ContentLength; Pos++ )
{
var Item = this.Content[Pos];
var ItemType = Item.Type;
if (para_Drawing === ItemType)
{
Item.Parent = this.Paragraph;
Item.DocumentContent = this.Paragraph.Parent;
Item.DrawingDocument = this.Paragraph.Parent.DrawingDocument;
}
// TODO: Как только избавимся от para_End переделать здесь
if ( para_End === ItemType )
{
var EndTextPr = this.Paragraph.Get_CompiledPr2(false).TextPr.Copy();
EndTextPr.Merge(this.Paragraph.TextPr.Value);
g_oTextMeasurer.SetTextPr( EndTextPr, this.Paragraph.Get_Theme());
Item.Measure( g_oTextMeasurer, EndTextPr );
continue;
}
Item.Measure( g_oTextMeasurer, Pr, InfoMathText, this);
if (para_Drawing === Item.Type)
{
// После автофигур надо заново выставлять настройки
g_oTextMeasurer.SetTextPr(Pr, Theme);
g_oTextMeasurer.SetFontSlot(fontslot_ASCII);
}
}
this.RecalcInfo.Recalc = true;
this.RecalcInfo.Measure = false;
};
ParaRun.prototype.Recalculate_Measure2 = function(Metrics)
{
var TAscent = Metrics.Ascent;
var TDescent = Metrics.Descent;
var Count = this.Content.length;
for ( var Index = 0; Index < Count; Index++ )
{
var Item = this.Content[Index];
var ItemType = Item.Type;
if ( para_Text === ItemType )
{
var Temp = g_oTextMeasurer.Measure2(String.fromCharCode(Item.Value));
if ( null === TAscent || TAscent < Temp.Ascent )
TAscent = Temp.Ascent;
if ( null === TDescent || TDescent > Temp.Ascent - Temp.Height )
TDescent = Temp.Ascent - Temp.Height;
}
}
Metrics.Ascent = TAscent;
Metrics.Descent = TDescent;
};
ParaRun.prototype.Recalculate_Range = function(PRS, ParaPr, Depth)
{
if ( this.Paragraph !== PRS.Paragraph )
{
this.Paragraph = PRS.Paragraph;
this.RecalcInfo.TextPr = true;
this.RecalcInfo.Measure = true;
this.protected_UpdateSpellChecking();
}
// Сначала измеряем элементы (можно вызывать каждый раз, внутри разруливается, чтобы измерялось 1 раз)
this.Recalculate_MeasureContent();
var CurLine = PRS.Line - this.StartLine;
var CurRange = ( 0 === CurLine ? PRS.Range - this.StartRange : PRS.Range );
// Если мы рассчитываем первый отрезок в первой строке, тогда нам нужно обновить информацию о нумерации
if ( 0 === CurRange && 0 === CurLine )
{
var PrevRecalcInfo = PRS.RunRecalcInfoLast;
// Либо до этого ничего не было (изначально первая строка и первый отрезок), либо мы заново пересчитываем
// первую строку и первый отрезок (из-за обтекания, например).
if ( null === PrevRecalcInfo )
this.RecalcInfo.NumberingAdd = true;
else
this.RecalcInfo.NumberingAdd = PrevRecalcInfo.NumberingAdd;
this.RecalcInfo.NumberingUse = false;
this.RecalcInfo.NumberingItem = null;
}
// Сохраняем ссылку на информацию пересчета данного рана
PRS.RunRecalcInfoLast = this.RecalcInfo;
// Добавляем информацию о новом отрезке
var RangeStartPos = this.protected_AddRange(CurLine, CurRange);
var RangeEndPos = 0;
var Para = PRS.Paragraph;
var MoveToLBP = PRS.MoveToLBP;
var NewRange = PRS.NewRange;
var ForceNewPage = PRS.ForceNewPage;
var NewPage = PRS.NewPage;
var End = PRS.End;
var Word = PRS.Word;
var StartWord = PRS.StartWord;
var FirstItemOnLine = PRS.FirstItemOnLine;
var EmptyLine = PRS.EmptyLine;
var RangesCount = PRS.RangesCount;
var SpaceLen = PRS.SpaceLen;
var WordLen = PRS.WordLen;
var X = PRS.X;
var XEnd = PRS.XEnd;
var ParaLine = PRS.Line;
var ParaRange = PRS.Range;
var bMathWordLarge = PRS.bMathWordLarge;
var OperGapRight = PRS.OperGapRight;
var OperGapLeft = PRS.OperGapLeft;
var bInsideOper = PRS.bInsideOper;
var bContainCompareOper = PRS.bContainCompareOper;
var bEndRunToContent = PRS.bEndRunToContent;
var bNoOneBreakOperator = PRS.bNoOneBreakOperator;
var bForcedBreak = PRS.bForcedBreak;
var Pos = RangeStartPos;
var ContentLen = this.Content.length;
var XRange = PRS.XRange;
var oSectionPr = undefined;
if (false === StartWord && true === FirstItemOnLine && XEnd - X < 0.001 && RangesCount > 0)
{
NewRange = true;
RangeEndPos = Pos;
}
else
{
for (; Pos < ContentLen; Pos++)
{
var Item = this.Content[Pos];
var ItemType = Item.Type;
// Проверяем, не нужно ли добавить нумерацию к данному элементу
if (true === this.RecalcInfo.NumberingAdd && true === Item.Can_AddNumbering())
X = this.private_RecalculateNumbering(PRS, Item, ParaPr, X);
switch (ItemType)
{
case para_Sym:
case para_Text:
case para_FootnoteReference:
case para_FootnoteRef:
case para_Separator:
case para_ContinuationSeparator:
{
// Отмечаем, что началось слово
StartWord = true;
if (para_ContinuationSeparator === ItemType || para_Separator === ItemType)
Item.UpdateWidth(PRS);
if (true !== PRS.IsFastRecalculate())
{
if (para_FootnoteReference === ItemType)
{
Item.UpdateNumber(PRS);
PRS.AddFootnoteReference(Item, PRS.GetCurrentContentPos(Pos));
}
else if (para_FootnoteRef === ItemType)
{
Item.UpdateNumber(PRS.TopDocument);
}
}
// При проверке, убирается ли слово, мы должны учитывать ширину предшествующих пробелов.
var LetterLen = Item.Width / TEXTWIDTH_DIVIDER;//var LetterLen = Item.Get_Width();
if (true !== Word)
{
// Слово только началось. Делаем следующее:
// 1) Если до него на строке ничего не было и данная строка не
// имеет разрывов, тогда не надо проверять убирается ли слово в строке.
// 2) В противном случае, проверяем убирается ли слово в промежутке.
// Если слово только началось, и до него на строке ничего не было, и в строке нет разрывов, тогда не надо проверять убирается ли оно на строке.
if (true !== FirstItemOnLine || false === Para.Internal_Check_Ranges(ParaLine, ParaRange))
{
if (X + SpaceLen + LetterLen > XEnd)
{
NewRange = true;
RangeEndPos = Pos;
}
}
if (true !== NewRange)
{
// Отмечаем начало нового слова
PRS.Set_LineBreakPos(Pos);
// Если текущий символ с переносом, например, дефис, тогда на нем заканчивается слово
if (Item.Flags & PARATEXT_FLAGS_SPACEAFTER)//if ( true === Item.Is_SpaceAfter() )
{
// Добавляем длину пробелов до слова и ширину самого слова.
X += SpaceLen + LetterLen;
Word = false;
FirstItemOnLine = false;
EmptyLine = false;
SpaceLen = 0;
WordLen = 0;
}
else
{
Word = true;
WordLen = LetterLen;
}
}
}
else
{
if(X + SpaceLen + WordLen + LetterLen > XEnd)
{
if(true === FirstItemOnLine)
{
// Слово оказалось единственным элементом в промежутке, и, все равно,
// не умещается целиком. Делаем следующее:
//
//
// 1) Если у нас строка без вырезов, тогда ставим перенос строки на
// текущей позиции.
// 2) Если у нас строка с вырезом, и данный вырез не последний, тогда
// ставим перенос внутри строки в начале слова.
// 3) Если у нас строка с вырезом и вырез последний, тогда ставим перенос
// строки в начале слова.
if (false === Para.Internal_Check_Ranges(ParaLine, ParaRange))
{
// Слово не убирается в отрезке. Переносим слово в следующий отрезок
MoveToLBP = true;
NewRange = true;
}
else
{
EmptyLine = false;
X += WordLen;
// Слово не убирается в отрезке, но, поскольку, слово 1 на строке и отрезок тоже 1,
// делим слово в данном месте
NewRange = true;
RangeEndPos = Pos;
}
}
else
{
// Слово не убирается в отрезке. Переносим слово в следующий отрезок
MoveToLBP = true;
NewRange = true;
}
}
if (true !== NewRange)
{
// Мы убираемся в пределах данной строки. Прибавляем ширину буквы к ширине слова
WordLen += LetterLen;
// Если текущий символ с переносом, например, дефис, тогда на нем заканчивается слово
if (Item.Flags & PARATEXT_FLAGS_SPACEAFTER)//if ( true === Item.Is_SpaceAfter() )
{
// Добавляем длину пробелов до слова и ширину самого слова.
X += SpaceLen + WordLen;
Word = false;
FirstItemOnLine = false;
EmptyLine = false;
SpaceLen = 0;
WordLen = 0;
}
}
}
break;
}
case para_Math_Text:
case para_Math_Ampersand:
case para_Math_Placeholder:
{
// Отмечаем, что началось слово
StartWord = true;
// При проверке, убирается ли слово, мы должны учитывать ширину предшествующих пробелов.
var LetterLen = Item.Get_Width2() / TEXTWIDTH_DIVIDER;//var LetterLen = Item.Get_Width();
if (true !== Word)
{
// Если слово только началось, и до него на строке ничего не было, и в строке нет разрывов, тогда не надо проверять убирается ли оно на строке.
if (true !== FirstItemOnLine /*|| false === Para.Internal_Check_Ranges(ParaLine, ParaRange)*/)
{
if (X + SpaceLen + LetterLen > XEnd)
{
NewRange = true;
RangeEndPos = Pos;
}
else if(bForcedBreak == true)
{
MoveToLBP = true;
NewRange = true;
PRS.Set_LineBreakPos(Pos);
}
}
if(true !== NewRange)
{
if(this.Parent.bRoot == true)
PRS.Set_LineBreakPos(Pos);
WordLen += LetterLen;
Word = true;
}
}
else
{
if(X + SpaceLen + WordLen + LetterLen > XEnd)
{
if(true === FirstItemOnLine /*&& true === Para.Internal_Check_Ranges(ParaLine, ParaRange)*/)
{
// Слово оказалось единственным элементом в промежутке, и, все равно, не умещается целиком.
// для Формулы слово не разбиваем, перенос не делаем, пишем в одну строку (слово выйдет за границу как в Ворде)
bMathWordLarge = true;
}
else
{
// Слово не убирается в отрезке. Переносим слово в следующий отрезок
MoveToLBP = true;
NewRange = true;
}
}
if (true !== NewRange)
{
// Мы убираемся в пределах данной строки. Прибавляем ширину буквы к ширине слова
WordLen += LetterLen;
}
}
break;
}
case para_Space:
{
FirstItemOnLine = false;
if (true === Word)
{
// Добавляем длину пробелов до слова + длина самого слова. Не надо проверять
// убирается ли слово, мы это проверяем при добавленнии букв.
X += SpaceLen + WordLen;
Word = false;
EmptyLine = false;
SpaceLen = 0;
WordLen = 0;
}
// На пробеле не делаем перенос. Перенос строки или внутристрочный
// перенос делаем при добавлении любого непробельного символа
SpaceLen += Item.Width / TEXTWIDTH_DIVIDER;//SpaceLen += Item.Get_Width();
break;
}
case para_Math_BreakOperator:
{
var BrkLen = Item.Get_Width2()/TEXTWIDTH_DIVIDER;
var bCompareOper = Item.Is_CompareOperator();
var bOperBefore = this.ParaMath.Is_BrkBinBefore() == true;
var bOperInEndContent = bOperBefore === false && bEndRunToContent === true && Pos == ContentLen - 1 && Word == true, // необходимо для того, чтобы у контентов мат объектов (к-ые могут разбиваться на строки) не было отметки Set_LineBreakPos, иначе скобка (или GapLeft), перед которой стоит break_Operator, перенесется на следующую строку (без текста !)
bLowPriority = bCompareOper == false && bContainCompareOper == false;
if(Pos == 0 && true === this.IsForcedBreak()) // принудительный перенос срабатывает всегда
{
if(FirstItemOnLine === true && Word == false && bNoOneBreakOperator == true) // первый оператор в строке
{
WordLen += BrkLen;
}
else if(bOperBefore)
{
X += SpaceLen + WordLen;
WordLen = 0;
SpaceLen = 0;
NewRange = true;
RangeEndPos = Pos;
}
else
{
if(FirstItemOnLine == false && X + SpaceLen + WordLen + BrkLen > XEnd)
{
MoveToLBP = true;
NewRange = true;
}
else
{
X += SpaceLen + WordLen;
Word = false;
MoveToLBP = true;
NewRange = true;
PRS.Set_LineBreakPos(1);
}
}
}
else if(bOperInEndContent || bLowPriority) // у этого break Operator приоритет низкий(в контенте на данном уровне есть другие операторы с более высоким приоритетом) => по нему не разбиваем, обрабатываем как обычную букву
{
if(X + SpaceLen + WordLen + BrkLen > XEnd)
{
if(FirstItemOnLine == true)
{
bMathWordLarge = true;
}
else
{
// Слово не убирается в отрезке. Переносим слово в следующий отрезок
MoveToLBP = true;
NewRange = true;
}
}
else
{
WordLen += BrkLen;
}
}
else
{
var WorLenCompareOper = WordLen + X - XRange + (bOperBefore ? SpaceLen : BrkLen);
var bOverXEnd, bOverXEndMWordLarge;
var bNotUpdBreakOper = false;
var bCompareWrapIndent = PRS.bFirstLine == true ? WorLenCompareOper > PRS.WrapIndent : true;
if(PRS.bPriorityOper == true && bCompareOper == true && bContainCompareOper == true && bCompareWrapIndent == true && !(Word == false && FirstItemOnLine === true)) // (Word == true && FirstItemOnLine == true) - не первый элемент в строке
bContainCompareOper = false;
if(bOperBefore) // оператор "до" => оператор находится в начале строки
{
bOverXEnd = X + WordLen + SpaceLen + BrkLen > XEnd; // BrkLen прибавляем дла случая, если идут подряд Brk Operators в конце
bOverXEndMWordLarge = X + WordLen + SpaceLen > XEnd; // ширину самого оператора не учитываем при расчете bMathWordLarge, т.к. он будет находится на следующей строке
if(bOverXEnd && (true !== FirstItemOnLine || true === Word))
{
// если вышли за границы не обновляем параметр bInsideOper, т.к. если уже были breakOperator, то, соответственно, он уже выставлен в true
// а если на этом уровне не было breakOperator, то и обновлять его нне нужо
if(FirstItemOnLine === false)
{
MoveToLBP = true;
NewRange = true;
}
else
{
if(Word == true && bOverXEndMWordLarge == true)
{
bMathWordLarge = true;
}
X += SpaceLen + WordLen;
if(PRS.bBreakPosInLWord == true)
{
PRS.Set_LineBreakPos(Pos);
}
else
{
bNotUpdBreakOper = true;
}
RangeEndPos = Pos;
SpaceLen = 0;
WordLen = 0;
NewRange = true;
EmptyLine = false;
}
}
else
{
if(FirstItemOnLine === false)
bInsideOper = true;
if(Word == false && FirstItemOnLine == true )
{
SpaceLen += BrkLen;
}
else
{
// проверка на FirstItemOnLine == false нужна для случая, если иду подряд несколько breakOperator
// в этом случае Word == false && FirstItemOnLine == false, нужно также поставить отметку для потенциального переноса
X += SpaceLen + WordLen;
PRS.Set_LineBreakPos(Pos);
EmptyLine = false;
WordLen = BrkLen;
SpaceLen = 0;
}
// в первой строке может не быть ни одного break Operator, при этом слово не выходит за границы, т.о. обновляем FirstItemOnLine также и на Word = true
// т.к. оператор идет в начале строки, то соответственно слово в стоке не будет первым, если в строке больше одного оператора
if(bNoOneBreakOperator == false || Word == true)
FirstItemOnLine = false;
}
}
else // оператор "после" => оператор находится в конце строки
{
bOverXEnd = X + WordLen + BrkLen - Item.GapRight > XEnd;
bOverXEndMWordLarge = bOverXEnd;
if(bOverXEnd && FirstItemOnLine === false) // Слово не убирается в отрезке. Переносим слово в следующий отрезок
{
MoveToLBP = true;
NewRange = true;
if(Word == false)
PRS.Set_LineBreakPos(Pos);
}
else
{
bInsideOper = true;
// осуществляем здесь, чтобы не изменить GapRight в случае, когда новое слово не убирается на break_Operator
OperGapRight = Item.GapRight;
if(bOverXEndMWordLarge == true) // FirstItemOnLine == true
{
bMathWordLarge = true;
}
X += BrkLen + WordLen;
EmptyLine = false;
SpaceLen = 0;
WordLen = 0;
var bNotUpdate = bOverXEnd == true && PRS.bBreakPosInLWord == false;
// FirstItemOnLine == true
if(bNotUpdate == false) // LineBreakPos обновляем здесь, т.к. слово может начаться с мат объекта, а не с Run, в мат объекте нет соответствующей проверки
{
PRS.Set_LineBreakPos(Pos+1);
}
else
{
bNotUpdBreakOper = true;
}
FirstItemOnLine = false;
Word = false;
}
}
}
if(bNotUpdBreakOper == false)
bNoOneBreakOperator = false;
break;
}
case para_Drawing:
{
if(oSectionPr === undefined)
{
oSectionPr = Para.Get_SectPr();
}
Item.CheckRecalcAutoFit(oSectionPr);
if (true === Item.Is_Inline() || true === Para.Parent.Is_DrawingShape())
{
// TODO: Нельзя что-то писать в историю во время пересчета, это действие надо делать при открытии
// if (true !== Item.Is_Inline())
// Item.Set_DrawingType(drawing_Inline);
if (true === StartWord)
FirstItemOnLine = false;
Item.YOffset = this.YOffset;
// Если до этого было слово, тогда не надо проверять убирается ли оно, но если стояли пробелы,
// тогда мы их учитываем при проверке убирается ли данный элемент, и добавляем только если
// данный элемент убирается
if (true === Word || WordLen > 0)
{
// Добавляем длину пробелов до слова + длина самого слова. Не надо проверять
// убирается ли слово, мы это проверяем при добавленнии букв.
X += SpaceLen + WordLen;
Word = false;
EmptyLine = false;
SpaceLen = 0;
WordLen = 0;
}
var DrawingWidth = Item.Get_Width();
if (X + SpaceLen + DrawingWidth > XEnd && ( false === FirstItemOnLine || false === Para.Internal_Check_Ranges(ParaLine, ParaRange) ))
{
// Автофигура не убирается, ставим перенос перед ней
NewRange = true;
RangeEndPos = Pos;
}
else
{
// Добавляем длину пробелов до автофигуры
X += SpaceLen + DrawingWidth;
FirstItemOnLine = false;
EmptyLine = false;
}
SpaceLen = 0;
}
else if (!Item.IsSkipOnRecalculate())
{
// Основная обработка происходит в Recalculate_Range_Spaces. Здесь обрабатывается единственный случай,
// когда после второго пересчета с уже добавленной картинкой оказывается, что место в параграфе, где
// идет картинка ушло на следующую страницу. В этом случае мы ставим перенос страницы перед картинкой.
var LogicDocument = Para.Parent;
var LDRecalcInfo = LogicDocument.RecalcInfo;
var DrawingObjects = LogicDocument.DrawingObjects;
var CurPage = PRS.Page;
if (true === LDRecalcInfo.Check_FlowObject(Item) && true === LDRecalcInfo.Is_PageBreakBefore())
{
LDRecalcInfo.Reset();
// Добавляем разрыв страницы. Если это первая страница, тогда ставим разрыв страницы в начале параграфа,
// если нет, тогда в начале текущей строки.
if (null != Para.Get_DocumentPrev() && true != Para.Parent.IsTableCellContent() && 0 === CurPage)
{
Para.Recalculate_Drawing_AddPageBreak(0, 0, true);
PRS.RecalcResult = recalcresult_NextPage | recalcresultflags_Page;
PRS.NewRange = true;
return;
}
else
{
if (ParaLine != Para.Pages[CurPage].FirstLine)
{
Para.Recalculate_Drawing_AddPageBreak(ParaLine, CurPage, false);
PRS.RecalcResult = recalcresult_NextPage | recalcresultflags_Page;
PRS.NewRange = true;
return;
}
else
{
RangeEndPos = Pos;
NewRange = true;
ForceNewPage = true;
}
}
// Если до этого было слово, тогда не надо проверять убирается ли оно
if (true === Word || WordLen > 0)
{
// Добавляем длину пробелов до слова + длина самого слова. Не надо проверять
// убирается ли слово, мы это проверяем при добавленнии букв.
X += SpaceLen + WordLen;
Word = false;
SpaceLen = 0;
WordLen = 0;
}
}
}
break;
}
case para_PageCount:
case para_PageNum:
{
if (para_PageCount === ItemType)
{
var oHdrFtr = Para.Parent.Is_HdrFtr(true);
if (oHdrFtr)
oHdrFtr.Add_PageCountElement(Item);
}
else if (para_PageNum === ItemType)
{
var LogicDocument = Para.LogicDocument;
var SectionPage = LogicDocument.Get_SectionPageNumInfo2(Para.Get_AbsolutePage(PRS.Page)).CurPage;
Item.Set_Page(SectionPage);
}
// Если до этого было слово, тогда не надо проверять убирается ли оно, но если стояли пробелы,
// тогда мы их учитываем при проверке убирается ли данный элемент, и добавляем только если
// данный элемент убирается
if (true === Word || WordLen > 0)
{
// Добавляем длину пробелов до слова + длина самого слова. Не надо проверять
// убирается ли слово, мы это проверяем при добавленнии букв.
X += SpaceLen + WordLen;
Word = false;
EmptyLine = false;
SpaceLen = 0;
WordLen = 0;
}
// Если на строке начиналось какое-то слово, тогда данная строка уже не пустая
if (true === StartWord)
FirstItemOnLine = false;
var PageNumWidth = Item.Get_Width();
if (X + SpaceLen + PageNumWidth > XEnd && ( false === FirstItemOnLine || false === Para.Internal_Check_Ranges(ParaLine, ParaRange) ))
{
// Данный элемент не убирается, ставим перенос перед ним
NewRange = true;
RangeEndPos = Pos;
}
else
{
// Добавляем длину пробелов до слова и ширину данного элемента
X += SpaceLen + PageNumWidth;
FirstItemOnLine = false;
EmptyLine = false;
}
SpaceLen = 0;
break;
}
case para_Tab:
{
// Сначала проверяем, если у нас уже есть таб, которым мы должны рассчитать, тогда высчитываем
// его ширину.
X = this.Internal_Recalculate_LastTab(PRS.LastTab, X, XEnd, Word, WordLen, SpaceLen);
// Добавляем длину пробелов до слова + длина самого слова. Не надо проверять
// убирается ли слово, мы это проверяем при добавленнии букв.
X += SpaceLen + WordLen;
Word = false;
SpaceLen = 0;
WordLen = 0;
var TabPos = Para.private_RecalculateGetTabPos(X, ParaPr, PRS.Page, false);
var NewX = TabPos.NewX;
var TabValue = TabPos.TabValue;
// Если таб не левый, значит он не может быть сразу рассчитан, а если левый, тогда
// рассчитываем его сразу здесь
if (tab_Left !== TabValue)
{
PRS.LastTab.TabPos = NewX;
PRS.LastTab.Value = TabValue;
PRS.LastTab.X = X;
PRS.LastTab.Item = Item;
Item.Width = 0;
Item.WidthVisible = 0;
}
else
{
if (true !== TabPos.DefaultTab && NewX > XEnd - 0.001 && XEnd < 558.7 && PRS.Range >= PRS.RangesCount - 1)
{
Para.Lines[PRS.Line].Ranges[PRS.Range].XEnd = 558.7;
XEnd = 558.7;
PRS.BadLeftTab = true;
}
// Так работает Word: он не переносит на новую строку табы, начинающиеся в допустимом отрезке, а
// заканчивающиеся вне его. Поэтому мы проверяем именно, где таб начинается, а не заканчивается.
// (bug 32345)
if (X > XEnd && ( false === FirstItemOnLine || false === Para.Internal_Check_Ranges(ParaLine, ParaRange) ))
{
WordLen = NewX - X;
RangeEndPos = Pos;
NewRange = true;
}
else
{
Item.Width = NewX - X;
Item.WidthVisible = NewX - X;
X = NewX;
}
}
// Если перенос идет по строке, а не из-за обтекания, тогда разрываем перед табом, а если
// из-за обтекания, тогда разрываем перед последним словом, идущим перед табом
if (RangesCount === CurRange)
{
if (true === StartWord)
{
FirstItemOnLine = false;
EmptyLine = false;
}
}
// Считаем, что с таба начинается слово
PRS.Set_LineBreakPos(Pos);
StartWord = true;
Word = true;
break;
}
case para_NewLine:
{
// Сначала проверяем, если у нас уже есть таб, которым мы должны рассчитать, тогда высчитываем
// его ширину.
X = this.Internal_Recalculate_LastTab(PRS.LastTab, X, XEnd, Word, WordLen, SpaceLen);
X += WordLen;
if (true === Word)
{
EmptyLine = false;
Word = false;
X += SpaceLen;
SpaceLen = 0;
}
if (break_Page === Item.BreakType || break_Column === Item.BreakType)
{
PRS.BreakPageLine = true;
if (break_Page === Item.BreakType)
PRS.BreakRealPageLine = true;
// PageBreak вне самого верхнего документа не надо учитывать
if (!(Para.Parent instanceof CDocument) || true !== Para.Is_Inline())
{
// TODO: Продумать, как избавиться от данного элемента, т.к. удалять его при пересчете нельзя,
// иначе будут проблемы с совместным редактированием.
Item.Flags.Use = false;
continue;
}
if (break_Page === Item.BreakType && true === Para.Check_BreakPageEnd(Item))
continue;
Item.Flags.NewLine = true;
NewPage = true;
NewRange = true;
}
else
{
NewRange = true;
EmptyLine = false;
// здесь оставляем проверку, т.к. в случае, если после неинлайновой формулы нах-ся инлайновая необходимо в любом случае сделать перенос (проверка в private_RecalculateRange(), где выставляется PRS.ForceNewLine = true не пройдет)
if (true === PRS.MathNotInline)
PRS.ForceNewLine = true;
}
RangeEndPos = Pos + 1;
break;
}
case para_End:
{
if (true === Word)
{
FirstItemOnLine = false;
EmptyLine = false;
}
X += WordLen;
if (true === Word)
{
X += SpaceLen;
SpaceLen = 0;
WordLen = 0;
}
X = this.Internal_Recalculate_LastTab(PRS.LastTab, X, XEnd, Word, WordLen, SpaceLen);
NewRange = true;
End = true;
RangeEndPos = Pos + 1;
break;
}
}
if (true === NewRange)
break;
}
}
PRS.MoveToLBP = MoveToLBP;
PRS.NewRange = NewRange;
PRS.ForceNewPage = ForceNewPage;
PRS.NewPage = NewPage;
PRS.End = End;
PRS.Word = Word;
PRS.StartWord = StartWord;
PRS.FirstItemOnLine = FirstItemOnLine;
PRS.EmptyLine = EmptyLine;
PRS.SpaceLen = SpaceLen;
PRS.WordLen = WordLen;
PRS.bMathWordLarge = bMathWordLarge;
PRS.OperGapRight = OperGapRight;
PRS.OperGapLeft = OperGapLeft;
PRS.X = X;
PRS.XEnd = XEnd;
PRS.bInsideOper = bInsideOper;
PRS.bContainCompareOper = bContainCompareOper;
PRS.bEndRunToContent = bEndRunToContent;
PRS.bNoOneBreakOperator = bNoOneBreakOperator;
PRS.bForcedBreak = bForcedBreak;
if(this.Type == para_Math_Run)
{
if(true === NewRange)
{
var WidthLine = X - XRange;
if(this.ParaMath.Is_BrkBinBefore() == false)
WidthLine += SpaceLen;
this.ParaMath.UpdateWidthLine(PRS, WidthLine);
}
else
{
// для пустого Run, обновляем LineBreakPos на случай, если пустой Run находится между break_operator (мат. объект) и мат объектом
if(this.Content.length == 0)
{
if(PRS.bForcedBreak == true)
{
PRS.MoveToLBP = true;
PRS.NewRange = true;
PRS.Set_LineBreakPos(0);
}
else if(this.ParaMath.Is_BrkBinBefore() == false && Word == false && PRS.bBreakBox == true)
{
PRS.Set_LineBreakPos(Pos);
PRS.X += SpaceLen;
PRS.SpaceLen = 0;
}
}
// запоминаем конец Run
PRS.PosEndRun.Set(PRS.CurPos);
PRS.PosEndRun.Update2(this.Content.length, Depth);
}
}
if ( Pos >= ContentLen )
{
RangeEndPos = Pos;
}
this.protected_FillRange(CurLine, CurRange, RangeStartPos, RangeEndPos);
this.RecalcInfo.Recalc = false;
};
ParaRun.prototype.Recalculate_Set_RangeEndPos = function(PRS, PRP, Depth)
{
var CurLine = PRS.Line - this.StartLine;
var CurRange = ( 0 === CurLine ? PRS.Range - this.StartRange : PRS.Range );
var CurPos = PRP.Get(Depth);
this.protected_FillRangeEndPos(CurLine, CurRange, CurPos);
};
ParaRun.prototype.Recalculate_LineMetrics = function(PRS, ParaPr, _CurLine, _CurRange, ContentMetrics)
{
var Para = PRS.Paragraph;
// Если заданный отрезок пустой, тогда мы не должны учитывать метрики данного рана.
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
var UpdateLineMetricsText = false;
var LineRule = ParaPr.Spacing.LineRule;
for (var CurPos = StartPos; CurPos < EndPos; CurPos++)
{
var Item = this.Content[CurPos];
if (Item === Para.Numbering.Item)
{
PRS.LineAscent = Para.Numbering.LineAscent;
}
switch (Item.Type)
{
case para_Sym:
case para_Text:
case para_PageNum:
case para_PageCount:
case para_FootnoteReference:
case para_FootnoteRef:
case para_Separator:
case para_ContinuationSeparator:
{
UpdateLineMetricsText = true;
break;
}
case para_Math_Text:
case para_Math_Ampersand:
case para_Math_Placeholder:
case para_Math_BreakOperator:
{
ContentMetrics.UpdateMetrics(Item.size);
break;
}
case para_Space:
{
break;
}
case para_Drawing:
{
if (true === Item.Is_Inline() || true === Para.Parent.Is_DrawingShape())
{
// Обновим метрики строки
if (Asc.linerule_Exact === LineRule)
{
if (PRS.LineAscent < Item.Height)
PRS.LineAscent = Item.Height;
}
else
{
if (PRS.LineAscent < Item.Height + this.YOffset)
PRS.LineAscent = Item.Height + this.YOffset;
if (PRS.LineDescent < -this.YOffset)
PRS.LineDescent = -this.YOffset;
}
}
break;
}
case para_End:
{
// TODO: Тут можно сделать проверку на пустую строку.
break;
}
}
}
if ( true === UpdateLineMetricsText)
{
// Пересчитаем метрику строки относительно размера данного текста
if ( PRS.LineTextAscent < this.TextAscent )
PRS.LineTextAscent = this.TextAscent;
if ( PRS.LineTextAscent2 < this.TextAscent2 )
PRS.LineTextAscent2 = this.TextAscent2;
if ( PRS.LineTextDescent < this.TextDescent )
PRS.LineTextDescent = this.TextDescent;
if ( Asc.linerule_Exact === LineRule )
{
// Смещение не учитывается в метриках строки, когда расстояние между строк точное
if ( PRS.LineAscent < this.TextAscent )
PRS.LineAscent = this.TextAscent;
if ( PRS.LineDescent < this.TextDescent )
PRS.LineDescent = this.TextDescent;
}
else
{
if ( PRS.LineAscent < this.TextAscent + this.YOffset )
PRS.LineAscent = this.TextAscent + this.YOffset;
if ( PRS.LineDescent < this.TextDescent - this.YOffset )
PRS.LineDescent = this.TextDescent - this.YOffset;
}
}
};
ParaRun.prototype.Recalculate_Range_Width = function(PRSC, _CurLine, _CurRange)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
for ( var Pos = StartPos; Pos < EndPos; Pos++ )
{
var Item = this.Content[Pos];
var ItemType = Item.Type;
switch( ItemType )
{
case para_Sym:
case para_Text:
case para_FootnoteReference:
case para_FootnoteRef:
case para_Separator:
case para_ContinuationSeparator:
{
PRSC.Letters++;
if ( true !== PRSC.Word )
{
PRSC.Word = true;
PRSC.Words++;
}
PRSC.Range.W += Item.Width / TEXTWIDTH_DIVIDER;//Item.Get_Width();
PRSC.Range.W += PRSC.SpaceLen;
PRSC.SpaceLen = 0;
// Пробелы перед первым словом в строке не считаем
if (PRSC.Words > 1)
PRSC.Spaces += PRSC.SpacesCount;
else
PRSC.SpacesSkip += PRSC.SpacesCount;
PRSC.SpacesCount = 0;
// Если текущий символ, например, дефис, тогда на нем заканчивается слово
if (Item.Flags & PARATEXT_FLAGS_SPACEAFTER)//if ( true === Item.Is_SpaceAfter() )
PRSC.Word = false;
break;
}
case para_Math_Text:
case para_Math_Placeholder:
case para_Math_Ampersand:
case para_Math_BreakOperator:
{
PRSC.Letters++;
PRSC.Range.W += Item.Get_Width() / TEXTWIDTH_DIVIDER; // Get_Width рассчитываем ширину с учетом состояний Gaps
break;
}
case para_Space:
{
if ( true === PRSC.Word )
{
PRSC.Word = false;
PRSC.SpacesCount = 1;
PRSC.SpaceLen = Item.Width / TEXTWIDTH_DIVIDER;//Item.Get_Width();
}
else
{
PRSC.SpacesCount++;
PRSC.SpaceLen += Item.Width / TEXTWIDTH_DIVIDER;//Item.Get_Width();
}
break;
}
case para_Drawing:
{
PRSC.Words++;
PRSC.Range.W += PRSC.SpaceLen;
if (PRSC.Words > 1)
PRSC.Spaces += PRSC.SpacesCount;
else
PRSC.SpacesSkip += PRSC.SpacesCount;
PRSC.Word = false;
PRSC.SpacesCount = 0;
PRSC.SpaceLen = 0;
if ( true === Item.Is_Inline() || true === PRSC.Paragraph.Parent.Is_DrawingShape() )
PRSC.Range.W += Item.Get_Width();
break;
}
case para_PageNum:
case para_PageCount:
{
PRSC.Words++;
PRSC.Range.W += PRSC.SpaceLen;
if (PRSC.Words > 1)
PRSC.Spaces += PRSC.SpacesCount;
else
PRSC.SpacesSkip += PRSC.SpacesCount;
PRSC.Word = false;
PRSC.SpacesCount = 0;
PRSC.SpaceLen = 0;
PRSC.Range.W += Item.Get_Width();
break;
}
case para_Tab:
{
PRSC.Range.W += Item.Get_Width();
PRSC.Range.W += PRSC.SpaceLen;
// Учитываем только слова и пробелы, идущие после последнего таба
PRSC.LettersSkip += PRSC.Letters;
PRSC.SpacesSkip += PRSC.Spaces;
PRSC.Words = 0;
PRSC.Spaces = 0;
PRSC.Letters = 0;
PRSC.SpaceLen = 0;
PRSC.SpacesCount = 0;
PRSC.Word = false;
break;
}
case para_NewLine:
{
if (true === PRSC.Word && PRSC.Words > 1)
PRSC.Spaces += PRSC.SpacesCount;
PRSC.SpacesCount = 0;
PRSC.Word = false;
break;
}
case para_End:
{
if ( true === PRSC.Word )
PRSC.Spaces += PRSC.SpacesCount;
PRSC.Range.WEnd = Item.Get_WidthVisible();
break;
}
}
}
};
ParaRun.prototype.Recalculate_Range_Spaces = function(PRSA, _CurLine, _CurRange, CurPage)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
for ( var Pos = StartPos; Pos < EndPos; Pos++ )
{
var Item = this.Content[Pos];
var ItemType = Item.Type;
switch( ItemType )
{
case para_Sym:
case para_Text:
case para_FootnoteReference:
case para_FootnoteRef:
case para_Separator:
case para_ContinuationSeparator:
{
var WidthVisible = 0;
if ( 0 !== PRSA.LettersSkip )
{
WidthVisible = Item.Width / TEXTWIDTH_DIVIDER;//WidthVisible = Item.Get_Width();
PRSA.LettersSkip--;
}
else
WidthVisible = Item.Width / TEXTWIDTH_DIVIDER + PRSA.JustifyWord;//WidthVisible = Item.Get_Width() + PRSA.JustifyWord;
Item.WidthVisible = (WidthVisible * TEXTWIDTH_DIVIDER) | 0;//Item.Set_WidthVisible(WidthVisible);
if (para_FootnoteReference === ItemType)
{
var oFootnote = Item.Get_Footnote();
oFootnote.UpdatePositionInfo(this.Paragraph, this, _CurLine, _CurRange, PRSA.X, WidthVisible);
}
PRSA.X += WidthVisible;
PRSA.LastW = WidthVisible;
break;
}
case para_Math_Text:
case para_Math_Placeholder:
case para_Math_BreakOperator:
case para_Math_Ampersand:
{
var WidthVisible = Item.Get_Width() / TEXTWIDTH_DIVIDER; // Get_Width рассчитываем ширину с учетом состояний Gaps
Item.WidthVisible = (WidthVisible * TEXTWIDTH_DIVIDER)| 0;//Item.Set_WidthVisible(WidthVisible);
PRSA.X += WidthVisible;
PRSA.LastW = WidthVisible;
break;
}
case para_Space:
{
var WidthVisible = Item.Width / TEXTWIDTH_DIVIDER;//WidthVisible = Item.Get_Width();
if ( 0 !== PRSA.SpacesSkip )
{
PRSA.SpacesSkip--;
}
else if ( 0 !== PRSA.SpacesCounter )
{
WidthVisible += PRSA.JustifySpace;
PRSA.SpacesCounter--;
}
Item.WidthVisible = (WidthVisible * TEXTWIDTH_DIVIDER) | 0;//Item.Set_WidthVisible(WidthVisible);
PRSA.X += WidthVisible;
PRSA.LastW = WidthVisible;
break;
}
case para_Drawing:
{
var Para = PRSA.Paragraph;
var PageAbs = Para.private_GetAbsolutePageIndex(CurPage);
var PageRel = Para.private_GetRelativePageIndex(CurPage);
var ColumnAbs = Para.Get_AbsoluteColumn(CurPage);
var LogicDocument = this.Paragraph.LogicDocument;
var LD_PageLimits = LogicDocument.Get_PageLimits(PageAbs);
var LD_PageFields = LogicDocument.Get_PageFields(PageAbs);
var Page_Width = LD_PageLimits.XLimit;
var Page_Height = LD_PageLimits.YLimit;
var DrawingObjects = Para.Parent.DrawingObjects;
var PageLimits = Para.Parent.Get_PageLimits(PageRel);
var PageFields = Para.Parent.Get_PageFields(PageRel);
var X_Left_Field = PageFields.X;
var Y_Top_Field = PageFields.Y;
var X_Right_Field = PageFields.XLimit;
var Y_Bottom_Field = PageFields.YLimit;
var X_Left_Margin = PageFields.X - PageLimits.X;
var Y_Top_Margin = PageFields.Y - PageLimits.Y;
var X_Right_Margin = PageLimits.XLimit - PageFields.XLimit;
var Y_Bottom_Margin = PageLimits.YLimit - PageFields.YLimit;
if (true === Para.Parent.IsTableCellContent() && (true !== Item.Use_TextWrap() || false === Item.Is_LayoutInCell()))
{
X_Left_Field = LD_PageFields.X;
Y_Top_Field = LD_PageFields.Y;
X_Right_Field = LD_PageFields.XLimit;
Y_Bottom_Field = LD_PageFields.YLimit;
X_Left_Margin = X_Left_Field;
X_Right_Margin = Page_Width - X_Right_Field;
Y_Bottom_Margin = Page_Height - Y_Bottom_Field;
Y_Top_Margin = Y_Top_Field;
}
var _CurPage = 0;
if (0 !== PageAbs && CurPage > ColumnAbs)
_CurPage = CurPage - ColumnAbs;
var ColumnStartX = (0 === CurPage ? Para.X_ColumnStart : Para.Pages[_CurPage].X );
var ColumnEndX = (0 === CurPage ? Para.X_ColumnEnd : Para.Pages[_CurPage].XLimit);
var Top_Margin = Y_Top_Margin;
var Bottom_Margin = Y_Bottom_Margin;
var Page_H = Page_Height;
if ( true === Para.Parent.IsTableCellContent() && true == Item.Use_TextWrap() )
{
Top_Margin = 0;
Bottom_Margin = 0;
Page_H = 0;
}
var PageLimitsOrigin = Para.Parent.Get_PageLimits(PageRel);
if (true === Para.Parent.IsTableCellContent() && false === Item.Is_LayoutInCell())
{
PageLimitsOrigin = LogicDocument.Get_PageLimits(PageAbs);
var PageFieldsOrigin = LogicDocument.Get_PageFields(PageAbs);
ColumnStartX = PageFieldsOrigin.X;
ColumnEndX = PageFieldsOrigin.XLimit;
}
if ( true != Item.Use_TextWrap() )
{
PageFields.X = X_Left_Field;
PageFields.Y = Y_Top_Field;
PageFields.XLimit = X_Right_Field;
PageFields.YLimit = Y_Bottom_Field;
PageLimits.X = 0;
PageLimits.Y = 0;
PageLimits.XLimit = Page_Width;
PageLimits.YLimit = Page_Height;
}
if ( true === Item.Is_Inline() || true === Para.Parent.Is_DrawingShape() )
{
Item.Update_Position(PRSA.Paragraph, new CParagraphLayout( PRSA.X, PRSA.Y , PageAbs, PRSA.LastW, ColumnStartX, ColumnEndX, X_Left_Margin, X_Right_Margin, Page_Width, Top_Margin, Bottom_Margin, Page_H, PageFields.X, PageFields.Y, Para.Pages[CurPage].Y + Para.Lines[CurLine].Y - Para.Lines[CurLine].Metrics.Ascent, Para.Pages[CurPage].Y), PageLimits, PageLimitsOrigin, _CurLine);
Item.Reset_SavedPosition();
PRSA.X += Item.WidthVisible;
PRSA.LastW = Item.WidthVisible;
}
else if (!Item.IsSkipOnRecalculate())
{
Para.Pages[CurPage].Add_Drawing(Item);
if ( true === PRSA.RecalcFast )
{
// Если у нас быстрый пересчет, тогда мы не трогаем плавающие картинки
// TODO: Если здесь привязка к символу, тогда быстрый пересчет надо отменить
break;
}
if (true === PRSA.RecalcFast2)
{
// Тут мы должны сравнить положение картинок
var oRecalcObj = Item.SaveRecalculateObject();
Item.Update_Position(PRSA.Paragraph, new CParagraphLayout( PRSA.X, PRSA.Y , PageAbs, PRSA.LastW, ColumnStartX, ColumnEndX, X_Left_Margin, X_Right_Margin, Page_Width, Top_Margin, Bottom_Margin, Page_H, PageFields.X, PageFields.Y, Para.Pages[CurPage].Y + Para.Lines[CurLine].Y - Para.Lines[CurLine].Metrics.Ascent, Para.Pages[_CurPage].Y), PageLimits, PageLimitsOrigin, _CurLine);
if (Math.abs(Item.X - oRecalcObj.X) > 0.001 || Math.abs(Item.Y - oRecalcObj.Y) > 0.001 || Item.PageNum !== oRecalcObj.PageNum)
{
// Положение картинок не совпало, отправляем пересчет текущей страницы.
PRSA.RecalcResult = recalcresult_CurPage | recalcresultflags_Page;
return;
}
break;
}
// У нас Flow-объект. Если он с обтеканием, тогда мы останавливаем пересчет и
// запоминаем текущий объект. В функции Internal_Recalculate_2 пересчитываем
// его позицию и сообщаем ее внешнему классу.
if ( true === Item.Use_TextWrap() )
{
var LogicDocument = Para.Parent;
var LDRecalcInfo = Para.Parent.RecalcInfo;
if ( true === LDRecalcInfo.Can_RecalcObject() )
{
// Обновляем позицию объекта
Item.Update_Position(PRSA.Paragraph, new CParagraphLayout( PRSA.X, PRSA.Y , PageAbs, PRSA.LastW, ColumnStartX, ColumnEndX, X_Left_Margin, X_Right_Margin, Page_Width, Top_Margin, Bottom_Margin, Page_H, PageFields.X, PageFields.Y, Para.Pages[CurPage].Y + Para.Lines[CurLine].Y - Para.Lines[CurLine].Metrics.Ascent, Para.Pages[_CurPage].Y), PageLimits, PageLimitsOrigin, _CurLine);
LDRecalcInfo.Set_FlowObject( Item, 0, recalcresult_NextElement, -1 );
// TODO: Добавить проверку на не попадание в предыдущие колонки
if (0 === PRSA.CurPage && Item.wrappingPolygon.top > PRSA.PageY + 0.001 && Item.wrappingPolygon.left > PRSA.PageX + 0.001)
PRSA.RecalcResult = recalcresult_CurPagePara;
else
PRSA.RecalcResult = recalcresult_CurPage | recalcresultflags_Page;
return;
}
else if ( true === LDRecalcInfo.Check_FlowObject(Item) )
{
// Если мы находимся с таблице, тогда делаем как Word, не пересчитываем предыдущую страницу,
// даже если это необходимо. Такое поведение нужно для точного определения рассчиталась ли
// данная страница окончательно или нет. Если у нас будет ветка с переходом на предыдущую страницу,
// тогда не рассчитав следующую страницу мы о конечном рассчете текущей страницы не узнаем.
// Если данный объект нашли, значит он уже был рассчитан и нам надо проверить номер страницы.
// Заметим, что даже если картинка привязана к колонке, и после пересчета место привязки картинки
// сдвигается в следующую колонку, мы проверяем все равно только реальную страницу (без
// учета колонок, так делает и Word).
if ( Item.PageNum === PageAbs )
{
// Все нормально, можно продолжить пересчет
LDRecalcInfo.Reset();
Item.Reset_SavedPosition();
}
else if ( true === Para.Parent.IsTableCellContent() )
{
// Картинка не на нужной странице, но так как это таблица
// мы пересчитываем заново текущую страницу, а не предыдущую
// Обновляем позицию объекта
Item.Update_Position(PRSA.Paragraph, new CParagraphLayout( PRSA.X, PRSA.Y, PageAbs, PRSA.LastW, ColumnStartX, ColumnEndX, X_Left_Margin, X_Right_Margin, Page_Width, Top_Margin, Bottom_Margin, Page_H, PageFields.X, PageFields.Y, Para.Pages[CurPage].Y + Para.Lines[CurLine].Y - Para.Lines[CurLine].Metrics.Ascent, Para.Pages[_CurPage].Y), PageLimits, PageLimitsOrigin, _CurLine);
LDRecalcInfo.Set_FlowObject( Item, 0, recalcresult_NextElement, -1 );
LDRecalcInfo.Set_PageBreakBefore( false );
PRSA.RecalcResult = recalcresult_CurPage | recalcresultflags_Page;
return;
}
else
{
LDRecalcInfo.Set_PageBreakBefore( true );
DrawingObjects.removeById( Item.PageNum, Item.Get_Id() );
PRSA.RecalcResult = recalcresult_PrevPage | recalcresultflags_Page;
return;
}
}
else
{
// Либо данный элемент уже обработан, либо будет обработан в будущем
}
continue;
}
else
{
// Картинка ложится на или под текст, в данном случае пересчет можно спокойно продолжать
// Здесь под верхом параграфа понимаем верх первой строки, а не значение, с которого начинается пересчет.
var ParagraphTop = Para.Lines[Para.Pages[_CurPage].StartLine].Top + Para.Pages[_CurPage].Y;
Item.Update_Position(PRSA.Paragraph, new CParagraphLayout( PRSA.X, PRSA.Y , PageAbs, PRSA.LastW, ColumnStartX, ColumnEndX, X_Left_Margin, X_Right_Margin, Page_Width, Top_Margin, Bottom_Margin, Page_H, PageFields.X, PageFields.Y, Para.Pages[CurPage].Y + Para.Lines[CurLine].Y - Para.Lines[CurLine].Metrics.Ascent, ParagraphTop), PageLimits, PageLimitsOrigin, _CurLine);
Item.Reset_SavedPosition();
}
}
break;
}
case para_PageNum:
case para_PageCount:
{
PRSA.X += Item.WidthVisible;
PRSA.LastW = Item.WidthVisible;
break;
}
case para_Tab:
{
PRSA.X += Item.WidthVisible;
break;
}
case para_End:
{
var SectPr = PRSA.Paragraph.Get_SectionPr();
if (!PRSA.Paragraph.LogicDocument || PRSA.Paragraph.LogicDocument !== PRSA.Paragraph.Parent || !PRSA.Paragraph.bFromDocument)
SectPr = undefined;
if ( undefined !== SectPr )
{
// Нас интересует следующая секция
var LogicDocument = PRSA.Paragraph.LogicDocument;
var NextSectPr = LogicDocument.SectionsInfo.Get_SectPr(PRSA.Paragraph.Index + 1).SectPr;
Item.Update_SectionPr(NextSectPr, PRSA.XEnd - PRSA.X);
}
else
Item.Clear_SectionPr();
PRSA.X += Item.Get_Width();
break;
}
case para_NewLine:
{
if (break_Page === Item.BreakType || break_Column === Item.BreakType)
Item.Update_String(PRSA.XEnd - PRSA.X);
PRSA.X += Item.WidthVisible;
break;
}
}
}
};
ParaRun.prototype.Recalculate_PageEndInfo = function(PRSI, _CurLine, _CurRange)
{
};
ParaRun.prototype.private_RecalculateNumbering = function(PRS, Item, ParaPr, _X)
{
var X = PRS.Recalculate_Numbering(Item, this, ParaPr, _X);
// Запоминаем, что на данном элементе была добавлена нумерация
this.RecalcInfo.NumberingAdd = false;
this.RecalcInfo.NumberingUse = true;
this.RecalcInfo.NumberingItem = PRS.Paragraph.Numbering;
return X;
};
ParaRun.prototype.Internal_Recalculate_LastTab = function(LastTab, X, XEnd, Word, WordLen, SpaceLen)
{
if ( -1 !== LastTab.Value )
{
var TempXPos = X;
if ( true === Word || WordLen > 0 )
TempXPos += SpaceLen + WordLen;
var TabItem = LastTab.Item;
var TabStartX = LastTab.X;
var TabRangeW = TempXPos - TabStartX;
var TabValue = LastTab.Value;
var TabPos = LastTab.TabPos;
var TabCalcW = 0;
if ( tab_Right === TabValue )
TabCalcW = Math.max( TabPos - (TabStartX + TabRangeW), 0 );
else if ( tab_Center === TabValue )
TabCalcW = Math.max( TabPos - (TabStartX + TabRangeW / 2), 0 );
if ( X + TabCalcW > XEnd )
TabCalcW = XEnd - X;
TabItem.Width = TabCalcW;
TabItem.WidthVisible = TabCalcW;
LastTab.Reset();
return X + TabCalcW;
}
return X;
};
ParaRun.prototype.Refresh_RecalcData = function(Data)
{
var Para = this.Paragraph;
if(this.Type == para_Math_Run)
{
if(this.Parent !== null && this.Parent !== undefined)
{
this.Parent.Refresh_RecalcData();
}
}
else if ( -1 !== this.StartLine && undefined !== Para )
{
var CurLine = this.StartLine;
var PagesCount = Para.Pages.length;
for (var CurPage = 0 ; CurPage < PagesCount; CurPage++ )
{
var Page = Para.Pages[CurPage];
if ( Page.StartLine <= CurLine && Page.EndLine >= CurLine )
{
Para.Refresh_RecalcData2(CurPage);
return;
}
}
Para.Refresh_RecalcData2(0);
}
};
ParaRun.prototype.Refresh_RecalcData2 = function()
{
this.Refresh_RecalcData();
};
ParaRun.prototype.SaveRecalculateObject = function(Copy)
{
var RecalcObj = new CRunRecalculateObject(this.StartLine, this.StartRange);
RecalcObj.Save_Lines( this, Copy );
RecalcObj.Save_RunContent( this, Copy );
return RecalcObj;
};
ParaRun.prototype.LoadRecalculateObject = function(RecalcObj)
{
RecalcObj.Load_Lines(this);
RecalcObj.Load_RunContent(this);
};
ParaRun.prototype.PrepareRecalculateObject = function()
{
this.protected_ClearLines();
var Count = this.Content.length;
for (var Index = 0; Index < Count; Index++)
{
var Item = this.Content[Index];
var ItemType = Item.Type;
if (para_PageNum === ItemType || para_Drawing === ItemType)
Item.PrepareRecalculateObject();
}
};
ParaRun.prototype.Is_EmptyRange = function(_CurLine, _CurRange)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
if ( EndPos <= StartPos )
return true;
return false;
};
ParaRun.prototype.Check_Range_OnlyMath = function(Checker, _CurRange, _CurLine)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
for (var Pos = StartPos; Pos < EndPos; Pos++)
{
var Item = this.Content[Pos];
var ItemType = Item.Type;
if (para_End === ItemType || para_NewLine === ItemType || (para_Drawing === ItemType && true !== Item.Is_Inline()))
continue;
else
{
Checker.Result = false;
Checker.Math = null;
break;
}
}
};
ParaRun.prototype.Check_MathPara = function(Checker)
{
var Count = this.Content.length;
if ( Count <= 0 )
return;
var Item = ( Checker.Direction > 0 ? this.Content[0] : this.Content[Count - 1] );
var ItemType = Item.Type;
if ( para_End === ItemType || para_NewLine === ItemType )
{
Checker.Result = true;
Checker.Found = true;
}
else
{
Checker.Result = false;
Checker.Found = true;
}
};
ParaRun.prototype.Check_PageBreak = function()
{
var Count = this.Content.length;
for (var Pos = 0; Pos < Count; Pos++)
{
var Item = this.Content[Pos];
if (para_NewLine === Item.Type && (break_Page === Item.BreakType || break_Column === Item.BreakType))
return true;
}
return false;
};
ParaRun.prototype.Check_BreakPageEnd = function(PBChecker)
{
var ContentLen = this.Content.length;
for ( var CurPos = 0; CurPos < ContentLen; CurPos++ )
{
var Item = this.Content[CurPos];
if ( true === PBChecker.FindPB )
{
if ( Item === PBChecker.PageBreak )
{
PBChecker.FindPB = false;
PBChecker.PageBreak.Flags.NewLine = true;
}
}
else
{
var ItemType = Item.Type;
if ( para_End === ItemType )
return true;
else if ( para_Drawing !== ItemType || drawing_Anchor !== Item.Get_DrawingType() )
return false;
}
}
return true;
};
ParaRun.prototype.RecalculateMinMaxContentWidth = function(MinMax)
{
this.Recalculate_MeasureContent();
var bWord = MinMax.bWord;
var nWordLen = MinMax.nWordLen;
var nSpaceLen = MinMax.nSpaceLen;
var nMinWidth = MinMax.nMinWidth;
var nMaxWidth = MinMax.nMaxWidth;
var nCurMaxWidth = MinMax.nCurMaxWidth;
var nMaxHeight = MinMax.nMaxHeight;
var bCheckTextHeight = false;
var Count = this.Content.length;
for ( var Pos = 0; Pos < Count; Pos++ )
{
var Item = this.Content[Pos];
var ItemType = Item.Type;
switch( ItemType )
{
case para_Text:
{
var ItemWidth = Item.Width / TEXTWIDTH_DIVIDER;//var ItemWidth = Item.Get_Width();
if ( false === bWord )
{
bWord = true;
nWordLen = ItemWidth;
}
else
{
nWordLen += ItemWidth;
if (Item.Flags & PARATEXT_FLAGS_SPACEAFTER)
{
if ( nMinWidth < nWordLen )
nMinWidth = nWordLen;
bWord = false;
nWordLen = 0;
}
}
if ( nSpaceLen > 0 )
{
nCurMaxWidth += nSpaceLen;
nSpaceLen = 0;
}
nCurMaxWidth += ItemWidth;
bCheckTextHeight = true;
break;
}
case para_Math_Text:
case para_Math_Ampersand:
case para_Math_Placeholder:
{
var ItemWidth = Item.Get_Width() / TEXTWIDTH_DIVIDER;
if ( false === bWord )
{
bWord = true;
nWordLen = ItemWidth;
}
else
{
nWordLen += ItemWidth;
}
nCurMaxWidth += ItemWidth;
bCheckTextHeight = true;
break;
}
case para_Space:
{
if ( true === bWord )
{
if ( nMinWidth < nWordLen )
nMinWidth = nWordLen;
bWord = false;
nWordLen = 0;
}
// Мы сразу не добавляем ширину пробелов к максимальной ширине, потому что
// пробелы, идущие в конце параграфа или перед переносом строки(явным), не
// должны учитываться.
nSpaceLen += Item.Width / TEXTWIDTH_DIVIDER;//nSpaceLen += Item.Get_Width();
bCheckTextHeight = true;
break;
}
case para_Math_BreakOperator:
{
if ( true === bWord )
{
if ( nMinWidth < nWordLen )
nMinWidth = nWordLen;
bWord = false;
nWordLen = 0;
}
nCurMaxWidth += Item.Get_Width() / TEXTWIDTH_DIVIDER;
bCheckTextHeight = true;
break;
}
case para_Drawing:
{
if ( true === bWord )
{
if ( nMinWidth < nWordLen )
nMinWidth = nWordLen;
bWord = false;
nWordLen = 0;
}
if ((true === Item.Is_Inline() || true === this.Paragraph.Parent.Is_DrawingShape()) && Item.Width > nMinWidth)
{
nMinWidth = Item.Width;
}
else if (true === Item.Use_TextWrap())
{
var DrawingW = Item.getXfrmExtX();
if (DrawingW > nMinWidth)
nMinWidth = DrawingW;
}
if ((true === Item.Is_Inline() || true === this.Paragraph.Parent.Is_DrawingShape()) && Item.Height > nMaxHeight)
{
nMaxHeight = Item.Height;
}
else if (true === Item.Use_TextWrap())
{
var DrawingH = Item.getXfrmExtY();
if (DrawingH > nMaxHeight)
nMaxHeight = DrawingH;
}
if ( nSpaceLen > 0 )
{
nCurMaxWidth += nSpaceLen;
nSpaceLen = 0;
}
if ( true === Item.Is_Inline() || true === this.Paragraph.Parent.Is_DrawingShape() )
nCurMaxWidth += Item.Width;
break;
}
case para_PageNum:
case para_PageCount:
{
if ( true === bWord )
{
if ( nMinWidth < nWordLen )
nMinWidth = nWordLen;
bWord = false;
nWordLen = 0;
}
if ( Item.Width > nMinWidth )
nMinWidth = Item.Get_Width();
if ( nSpaceLen > 0 )
{
nCurMaxWidth += nSpaceLen;
nSpaceLen = 0;
}
nCurMaxWidth += Item.Get_Width();
bCheckTextHeight = true;
break;
}
case para_Tab:
{
nWordLen += Item.Width;
if ( nMinWidth < nWordLen )
nMinWidth = nWordLen;
bWord = false;
nWordLen = 0;
if ( nSpaceLen > 0 )
{
nCurMaxWidth += nSpaceLen;
nSpaceLen = 0;
}
nCurMaxWidth += Item.Width;
bCheckTextHeight = true;
break;
}
case para_NewLine:
{
if ( nMinWidth < nWordLen )
nMinWidth = nWordLen;
bWord = false;
nWordLen = 0;
nSpaceLen = 0;
if ( nCurMaxWidth > nMaxWidth )
nMaxWidth = nCurMaxWidth;
nCurMaxWidth = 0;
bCheckTextHeight = true;
break;
}
case para_End:
{
if ( nMinWidth < nWordLen )
nMinWidth = nWordLen;
if ( nCurMaxWidth > nMaxWidth )
nMaxWidth = nCurMaxWidth;
if (nMaxHeight < 0.001)
bCheckTextHeight = true;
break;
}
}
}
if (true === bCheckTextHeight && nMaxHeight < this.TextAscent + this.TextDescent)
nMaxHeight = this.TextAscent + this.TextDescent;
MinMax.bWord = bWord;
MinMax.nWordLen = nWordLen;
MinMax.nSpaceLen = nSpaceLen;
MinMax.nMinWidth = nMinWidth;
MinMax.nMaxWidth = nMaxWidth;
MinMax.nCurMaxWidth = nCurMaxWidth;
MinMax.nMaxHeight = nMaxHeight;
};
ParaRun.prototype.Get_Range_VisibleWidth = function(RangeW, _CurLine, _CurRange)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
for ( var Pos = StartPos; Pos < EndPos; Pos++ )
{
var Item = this.Content[Pos];
var ItemType = Item.Type;
switch( ItemType )
{
case para_Sym:
case para_Text:
case para_Space:
case para_Math_Text:
case para_Math_Ampersand:
case para_Math_Placeholder:
case para_Math_BreakOperator:
{
RangeW.W += Item.Get_WidthVisible();
break;
}
case para_Drawing:
{
if ( true === Item.Is_Inline() )
RangeW.W += Item.Width;
break;
}
case para_PageNum:
case para_PageCount:
case para_Tab:
{
RangeW.W += Item.Width;
break;
}
case para_NewLine:
{
RangeW.W += Item.WidthVisible;
break;
}
case para_End:
{
RangeW.W += Item.Get_WidthVisible();
RangeW.End = true;
break;
}
}
}
};
ParaRun.prototype.Shift_Range = function(Dx, Dy, _CurLine, _CurRange)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
for ( var CurPos = StartPos; CurPos < EndPos; CurPos++ )
{
var Item = this.Content[CurPos];
if ( para_Drawing === Item.Type )
Item.Shift( Dx, Dy );
}
};
//-----------------------------------------------------------------------------------
// Функции отрисовки
//-----------------------------------------------------------------------------------
ParaRun.prototype.Draw_HighLights = function(PDSH)
{
var pGraphics = PDSH.Graphics;
var CurLine = PDSH.Line - this.StartLine;
var CurRange = ( 0 === CurLine ? PDSH.Range - this.StartRange : PDSH.Range );
var aHigh = PDSH.High;
var aColl = PDSH.Coll;
var aFind = PDSH.Find;
var aComm = PDSH.Comm;
var aShd = PDSH.Shd;
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
var Para = PDSH.Paragraph;
var SearchResults = Para.SearchResults;
var bDrawFind = PDSH.DrawFind;
var bDrawColl = PDSH.DrawColl;
var oCompiledPr = this.Get_CompiledPr(false);
var oShd = oCompiledPr.Shd;
var bDrawShd = ( oShd === undefined || c_oAscShdNil === oShd.Value ? false : true );
var ShdColor = ( true === bDrawShd ? oShd.Get_Color( PDSH.Paragraph ) : null );
if(this.Type == para_Math_Run && this.IsPlaceholder())
bDrawShd = false;
var X = PDSH.X;
var Y0 = PDSH.Y0;
var Y1 = PDSH.Y1;
var CommentsCount = PDSH.Comments.length;
var CommentId = ( CommentsCount > 0 ? PDSH.Comments[CommentsCount - 1] : null );
var CommentsFlag = PDSH.CommentsFlag;
var HighLight = oCompiledPr.HighLight;
var SearchMarksCount = this.SearchMarks.length;
this.CollaborativeMarks.Init_Drawing();
for ( var Pos = StartPos; Pos < EndPos; Pos++ )
{
var Item = this.Content[Pos];
var ItemType = Item.Type;
var ItemWidthVisible = Item.Get_WidthVisible();
// Определим попадание в поиск и совместное редактирование. Попадание в комментарий определять не надо,
// т.к. класс CParaRun попадает или не попадает в комментарий целиком.
for ( var SPos = 0; SPos < SearchMarksCount; SPos++)
{
var Mark = this.SearchMarks[SPos];
var MarkPos = Mark.SearchResult.StartPos.Get(Mark.Depth);
if ( Pos === MarkPos && true === Mark.Start )
PDSH.SearchCounter++;
}
var DrawSearch = ( PDSH.SearchCounter > 0 && true === bDrawFind ? true : false );
var DrawColl = this.CollaborativeMarks.Check( Pos );
if ( true === bDrawShd )
aShd.Add( Y0, Y1, X, X + ItemWidthVisible, 0, ShdColor.r, ShdColor.g, ShdColor.b, undefined, oShd );
switch( ItemType )
{
case para_PageNum:
case para_PageCount:
case para_Drawing:
case para_Tab:
case para_Text:
case para_Math_Text:
case para_Math_Placeholder:
case para_Math_BreakOperator:
case para_Math_Ampersand:
case para_Sym:
case para_FootnoteReference:
case para_FootnoteRef:
case para_Separator:
case para_ContinuationSeparator:
{
if ( para_Drawing === ItemType && !Item.Is_Inline() )
break;
if ( CommentsFlag != comments_NoComment )
aComm.Add( Y0, Y1, X, X + ItemWidthVisible, 0, 0, 0, 0, { Active : CommentsFlag === comments_ActiveComment ? true : false, CommentId : CommentId } );
else if ( highlight_None != HighLight )
aHigh.Add( Y0, Y1, X, X + ItemWidthVisible, 0, HighLight.r, HighLight.g, HighLight.b, undefined, HighLight );
if ( true === DrawSearch )
aFind.Add( Y0, Y1, X, X + ItemWidthVisible, 0, 0, 0, 0 );
else if ( null !== DrawColl )
aColl.Add( Y0, Y1, X, X + ItemWidthVisible, 0, DrawColl.r, DrawColl.g, DrawColl.b );
if ( para_Drawing != ItemType || Item.Is_Inline() )
X += ItemWidthVisible;
break;
}
case para_Space:
{
// Пробелы в конце строки (и строку состоящую из пробелов) не подчеркиваем, не зачеркиваем и не выделяем
if ( PDSH.Spaces > 0 )
{
if ( CommentsFlag != comments_NoComment )
aComm.Add( Y0, Y1, X, X + ItemWidthVisible, 0, 0, 0, 0, { Active : CommentsFlag === comments_ActiveComment ? true : false, CommentId : CommentId } );
else if ( highlight_None != HighLight )
aHigh.Add( Y0, Y1, X, X + ItemWidthVisible, 0, HighLight.r, HighLight.g, HighLight.b, undefined, HighLight );
PDSH.Spaces--;
}
if ( true === DrawSearch )
aFind.Add( Y0, Y1, X, X + ItemWidthVisible, 0, 0, 0, 0 );
else if ( null !== DrawColl )
aColl.Add( Y0, Y1, X, X + ItemWidthVisible, 0, DrawColl.r, DrawColl.g, DrawColl.b );
X += ItemWidthVisible;
break;
}
case para_End:
{
if ( null !== DrawColl )
aColl.Add( Y0, Y1, X, X + ItemWidthVisible, 0, DrawColl.r, DrawColl.g, DrawColl.b );
X += Item.Get_Width();
break;
}
case para_NewLine:
{
X += ItemWidthVisible;
break;
}
}
for ( var SPos = 0; SPos < SearchMarksCount; SPos++)
{
var Mark = this.SearchMarks[SPos];
var MarkPos = Mark.SearchResult.EndPos.Get(Mark.Depth);
if ( Pos + 1 === MarkPos && true !== Mark.Start )
PDSH.SearchCounter--;
}
}
// Обновим позицию X
PDSH.X = X;
};
ParaRun.prototype.Draw_Elements = function(PDSE)
{
var CurLine = PDSE.Line - this.StartLine;
var CurRange = ( 0 === CurLine ? PDSE.Range - this.StartRange : PDSE.Range );
var CurPage = PDSE.Page;
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
var Para = PDSE.Paragraph;
var pGraphics = PDSE.Graphics;
var BgColor = PDSE.BgColor;
var Theme = PDSE.Theme;
var X = PDSE.X;
var Y = PDSE.Y;
var CurTextPr = this.Get_CompiledPr( false );
pGraphics.SetTextPr( CurTextPr, Theme );
var InfoMathText ;
if(this.Type == para_Math_Run)
{
var ArgSize = this.Parent.Compiled_ArgSz.value,
bNormalText = this.IsNormalText();
var InfoTextPr =
{
TextPr: CurTextPr,
ArgSize: ArgSize,
bNormalText: bNormalText,
bEqArray: this.bEqArray
};
InfoMathText = new CMathInfoTextPr(InfoTextPr);
}
if ( undefined !== CurTextPr.Shd && c_oAscShdNil !== CurTextPr.Shd.Value )
BgColor = CurTextPr.Shd.Get_Color( Para );
var AutoColor = ( undefined != BgColor && false === BgColor.Check_BlackAutoColor() ? new CDocumentColor( 255, 255, 255, false ) : new CDocumentColor( 0, 0, 0, false ) );
var RGBA;
var ReviewType = this.Get_ReviewType();
var ReviewColor = null;
var bPresentation = this.Paragraph && !this.Paragraph.bFromDocument;
if (reviewtype_Add === ReviewType || reviewtype_Remove === ReviewType)
{
ReviewColor = this.Get_ReviewColor();
pGraphics.b_color1(ReviewColor.r, ReviewColor.g, ReviewColor.b, 255);
}
else if (CurTextPr.Unifill)
{
CurTextPr.Unifill.check(PDSE.Theme, PDSE.ColorMap);
RGBA = CurTextPr.Unifill.getRGBAColor();
if ( true === PDSE.VisitedHyperlink && ( undefined === this.Pr.Color && undefined === this.Pr.Unifill || bPresentation) )
{
AscFormat.G_O_VISITED_HLINK_COLOR.check(PDSE.Theme, PDSE.ColorMap);
RGBA = AscFormat.G_O_VISITED_HLINK_COLOR.getRGBAColor();
pGraphics.b_color1( RGBA.R, RGBA.G, RGBA.B, RGBA.A );
}
else
{
if(bPresentation && PDSE.Hyperlink)
{
AscFormat.G_O_HLINK_COLOR.check(PDSE.Theme, PDSE.ColorMap);
RGBA = AscFormat.G_O_HLINK_COLOR.getRGBAColor();
pGraphics.b_color1( RGBA.R, RGBA.G, RGBA.B, RGBA.A );
}
else
{
pGraphics.b_color1( RGBA.R, RGBA.G, RGBA.B, RGBA.A);
}
}
}
else
{
if ( true === PDSE.VisitedHyperlink && ( undefined === this.Pr.Color && undefined === this.Pr.Unifill ) )
{
AscFormat.G_O_VISITED_HLINK_COLOR.check(PDSE.Theme, PDSE.ColorMap);
RGBA = AscFormat.G_O_VISITED_HLINK_COLOR.getRGBAColor();
pGraphics.b_color1( RGBA.R, RGBA.G, RGBA.B, RGBA.A );
}
else if ( true === CurTextPr.Color.Auto )
{
pGraphics.b_color1( AutoColor.r, AutoColor.g, AutoColor.b, 255);
}
else
{
pGraphics.b_color1( CurTextPr.Color.r, CurTextPr.Color.g, CurTextPr.Color.b, 255);
}
}
for ( var Pos = StartPos; Pos < EndPos; Pos++ )
{
var Item = this.Content[Pos];
var ItemType = Item.Type;
var TempY = Y;
switch (CurTextPr.VertAlign)
{
case AscCommon.vertalign_SubScript:
{
Y -= vertalign_Koef_Sub * CurTextPr.FontSize * g_dKoef_pt_to_mm;
break;
}
case AscCommon.vertalign_SuperScript:
{
Y -= vertalign_Koef_Super * CurTextPr.FontSize * g_dKoef_pt_to_mm;
break;
}
}
switch( ItemType )
{
case para_PageNum:
case para_PageCount:
case para_Drawing:
case para_Tab:
case para_Text:
case para_Sym:
case para_FootnoteReference:
case para_FootnoteRef:
case para_Separator:
case para_ContinuationSeparator:
{
if (para_Tab === ItemType)
{
pGraphics.p_color(0, 0, 0, 255);
pGraphics.b_color1(0, 0, 0, 255);
}
if (para_Drawing != ItemType || Item.Is_Inline())
{
Item.Draw(X, Y - this.YOffset, pGraphics, PDSE);
X += Item.Get_WidthVisible();
}
// Внутри отрисовки инлайн-автофигур могут изменится цвета и шрифт, поэтому восстанавливаем настройки
if ((para_Drawing === ItemType && Item.Is_Inline()) || (para_Tab === ItemType))
{
pGraphics.SetTextPr( CurTextPr, Theme );
if (reviewtype_Add === ReviewType || reviewtype_Remove === ReviewType)
{
pGraphics.b_color1(ReviewColor.r, ReviewColor.g, ReviewColor.b, 255);
}
else if (RGBA)
{
pGraphics.b_color1( RGBA.R, RGBA.G, RGBA.B, 255);
pGraphics.p_color( RGBA.R, RGBA.G, RGBA.B, 255);
}
else
{
if ( true === CurTextPr.Color.Auto )
{
pGraphics.b_color1( AutoColor.r, AutoColor.g, AutoColor.b, 255);
pGraphics.p_color( AutoColor.r, AutoColor.g, AutoColor.b, 255);
}
else
{
pGraphics.b_color1( CurTextPr.Color.r, CurTextPr.Color.g, CurTextPr.Color.b, 255);
pGraphics.p_color( CurTextPr.Color.r, CurTextPr.Color.g, CurTextPr.Color.b, 255);
}
}
}
break;
}
case para_Space:
{
Item.Draw( X, Y - this.YOffset, pGraphics );
X += Item.Get_WidthVisible();
break;
}
case para_End:
{
var SectPr = Para.Get_SectionPr();
if (!Para.LogicDocument || Para.LogicDocument !== Para.Parent)
SectPr = undefined;
if ( undefined === SectPr )
{
// Выставляем настройки для символа параграфа
var EndTextPr = Para.Get_CompiledPr2(false).TextPr.Copy();
EndTextPr.Merge(Para.TextPr.Value);
if (reviewtype_Common !== ReviewType)
{
pGraphics.SetTextPr(EndTextPr, PDSE.Theme);
pGraphics.b_color1(ReviewColor.r, ReviewColor.g, ReviewColor.b, 255);
}
else if (EndTextPr.Unifill)
{
EndTextPr.Unifill.check(PDSE.Theme, PDSE.ColorMap);
var RGBAEnd = EndTextPr.Unifill.getRGBAColor();
pGraphics.SetTextPr(EndTextPr, PDSE.Theme);
pGraphics.b_color1(RGBAEnd.R, RGBAEnd.G, RGBAEnd.B, 255);
}
else
{
pGraphics.SetTextPr(EndTextPr, PDSE.Theme);
if (true === EndTextPr.Color.Auto)
pGraphics.b_color1(AutoColor.r, AutoColor.g, AutoColor.b, 255);
else
pGraphics.b_color1(EndTextPr.Color.r, EndTextPr.Color.g, EndTextPr.Color.b, 255);
}
var bEndCell = false;
if (null === Para.Get_DocumentNext() && true === Para.Parent.IsTableCellContent())
bEndCell = true;
Item.Draw(X, Y - this.YOffset, pGraphics, bEndCell, reviewtype_Common !== ReviewType ? true : false);
}
else
{
Item.Draw(X, Y - this.YOffset, pGraphics, false, false);
}
X += Item.Get_Width();
break;
}
case para_NewLine:
{
Item.Draw( X, Y - this.YOffset, pGraphics );
X += Item.WidthVisible;
break;
}
case para_Math_Ampersand:
case para_Math_Text:
case para_Math_BreakOperator:
{
var PosLine = this.ParaMath.GetLinePosition(PDSE.Line, PDSE.Range);
Item.Draw(PosLine.x, PosLine.y, pGraphics, InfoMathText);
X += Item.Get_WidthVisible();
break;
}
case para_Math_Placeholder:
{
if(pGraphics.RENDERER_PDF_FLAG !== true) // если идет печать/ конвертация в PDF плейсхолдер не отрисовываем
{
var PosLine = this.ParaMath.GetLinePosition(PDSE.Line, PDSE.Range);
Item.Draw(PosLine.x, PosLine.y, pGraphics, InfoMathText);
X += Item.Get_WidthVisible();
}
break;
}
}
Y = TempY;
}
// Обновляем позицию
PDSE.X = X;
};
ParaRun.prototype.Draw_Lines = function(PDSL)
{
var CurLine = PDSL.Line - this.StartLine;
var CurRange = ( 0 === CurLine ? PDSL.Range - this.StartRange : PDSL.Range );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
var X = PDSL.X;
var Y = PDSL.Baseline;
var UndOff = PDSL.UnderlineOffset;
var Para = PDSL.Paragraph;
var aStrikeout = PDSL.Strikeout;
var aDStrikeout = PDSL.DStrikeout;
var aUnderline = PDSL.Underline;
var aSpelling = PDSL.Spelling;
var CurTextPr = this.Get_CompiledPr( false );
var StrikeoutY = Y - this.YOffset;
var fontCoeff = 1; // учтем ArgSize
if(this.Type == para_Math_Run)
{
var ArgSize = this.Parent.Compiled_ArgSz;
fontCoeff = MatGetKoeffArgSize(CurTextPr.FontSize, ArgSize.value);
}
switch(CurTextPr.VertAlign)
{
case AscCommon.vertalign_Baseline : StrikeoutY += -CurTextPr.FontSize * fontCoeff * g_dKoef_pt_to_mm * 0.27; break;
case AscCommon.vertalign_SubScript : StrikeoutY += -CurTextPr.FontSize * fontCoeff * vertalign_Koef_Size * g_dKoef_pt_to_mm * 0.27 - vertalign_Koef_Sub * CurTextPr.FontSize * fontCoeff * g_dKoef_pt_to_mm; break;
case AscCommon.vertalign_SuperScript: StrikeoutY += -CurTextPr.FontSize * fontCoeff * vertalign_Koef_Size * g_dKoef_pt_to_mm * 0.27 - vertalign_Koef_Super * CurTextPr.FontSize * fontCoeff * g_dKoef_pt_to_mm; break;
}
var UnderlineY = Y + UndOff - this.YOffset;
var LineW = (CurTextPr.FontSize / 18) * g_dKoef_pt_to_mm;
var BgColor = PDSL.BgColor;
if ( undefined !== CurTextPr.Shd && c_oAscShdNil !== CurTextPr.Shd.Value )
BgColor = CurTextPr.Shd.Get_Color( Para );
var AutoColor = ( undefined != BgColor && false === BgColor.Check_BlackAutoColor() ? new CDocumentColor( 255, 255, 255, false ) : new CDocumentColor( 0, 0, 0, false ) );
var CurColor, RGBA, Theme = this.Paragraph.Get_Theme(), ColorMap = this.Paragraph.Get_ColorMap();
var ReviewType = this.Get_ReviewType();
var bAddReview = reviewtype_Add === ReviewType ? true : false;
var bRemReview = reviewtype_Remove === ReviewType ? true : false;
var ReviewColor = this.Get_ReviewColor();
// Выставляем цвет обводки
if ( true === PDSL.VisitedHyperlink && ( undefined === this.Pr.Color && undefined === this.Pr.Unifill ) )
CurColor = new CDocumentColor( 128, 0, 151 );
else if ( true === CurTextPr.Color.Auto && !CurTextPr.Unifill)
CurColor = new CDocumentColor( AutoColor.r, AutoColor.g, AutoColor.b );
else
{
if(CurTextPr.Unifill)
{
CurTextPr.Unifill.check(Theme, ColorMap);
RGBA = CurTextPr.Unifill.getRGBAColor();
CurColor = new CDocumentColor( RGBA.R, RGBA.G, RGBA.B );
}
else
{
CurColor = new CDocumentColor( CurTextPr.Color.r, CurTextPr.Color.g, CurTextPr.Color.b );
}
}
var SpellingMarksArray = {};
var SpellingMarksCount = this.SpellingMarks.length;
for ( var SPos = 0; SPos < SpellingMarksCount; SPos++)
{
var Mark = this.SpellingMarks[SPos];
if ( false === Mark.Element.Checked )
{
if ( true === Mark.Start )
{
var MarkPos = Mark.Element.StartPos.Get(Mark.Depth);
if ( undefined === SpellingMarksArray[MarkPos] )
SpellingMarksArray[MarkPos] = 1;
else
SpellingMarksArray[MarkPos] += 1;
}
else
{
var MarkPos = Mark.Element.EndPos.Get(Mark.Depth);
if ( undefined === SpellingMarksArray[MarkPos] )
SpellingMarksArray[MarkPos] = 2;
else
SpellingMarksArray[MarkPos] += 2;
}
}
}
for ( var Pos = StartPos; Pos < EndPos; Pos++ )
{
var Item = this.Content[Pos];
var ItemType = Item.Type;
var ItemWidthVisible = Item.Get_WidthVisible();
if ( 1 === SpellingMarksArray[Pos] || 3 === SpellingMarksArray[Pos] )
PDSL.SpellingCounter++;
switch( ItemType )
{
case para_End:
{
if (this.Paragraph)
{
if (bAddReview)
aUnderline.Add(UnderlineY, UnderlineY, X, X + ItemWidthVisible, LineW, ReviewColor.r, ReviewColor.g, ReviewColor.b);
else if (bRemReview)
aStrikeout.Add(StrikeoutY, StrikeoutY, X, X + ItemWidthVisible, LineW, ReviewColor.r, ReviewColor.g, ReviewColor.b);
}
X += ItemWidthVisible;
break;
}
case para_NewLine:
{
X += ItemWidthVisible;
break;
}
case para_PageNum:
case para_PageCount:
case para_Drawing:
case para_Tab:
case para_Text:
case para_Sym:
case para_FootnoteReference:
case para_FootnoteRef:
case para_Separator:
case para_ContinuationSeparator:
{
if (para_Text === ItemType && null !== this.CompositeInput && Pos >= this.CompositeInput.Pos && Pos < this.CompositeInput.Pos + this.CompositeInput.Length)
{
aUnderline.Add(UnderlineY, UnderlineY, X, X + ItemWidthVisible, LineW, CurColor.r, CurColor.g, CurColor.b, undefined, CurTextPr);
}
if ( para_Drawing != ItemType || Item.Is_Inline() )
{
if (true === bRemReview)
aStrikeout.Add(StrikeoutY, StrikeoutY, X, X + ItemWidthVisible, LineW, ReviewColor.r, ReviewColor.g, ReviewColor.b);
else if (true === CurTextPr.DStrikeout)
aDStrikeout.Add( StrikeoutY, StrikeoutY, X, X + ItemWidthVisible, LineW, CurColor.r, CurColor.g, CurColor.b, undefined, CurTextPr );
else if ( true === CurTextPr.Strikeout )
aStrikeout.Add( StrikeoutY, StrikeoutY, X, X + ItemWidthVisible, LineW, CurColor.r, CurColor.g, CurColor.b, undefined, CurTextPr );
if (true === bAddReview)
aUnderline.Add(UnderlineY, UnderlineY, X, X + ItemWidthVisible, LineW, ReviewColor.r, ReviewColor.g, ReviewColor.b);
else if (true === CurTextPr.Underline)
aUnderline.Add(UnderlineY, UnderlineY, X, X + ItemWidthVisible, LineW, CurColor.r, CurColor.g, CurColor.b, undefined, CurTextPr );
if ( PDSL.SpellingCounter > 0 )
aSpelling.Add( UnderlineY, UnderlineY, X, X + ItemWidthVisible, LineW, 0, 0, 0 );
X += ItemWidthVisible;
}
break;
}
case para_Space:
{
// Пробелы, идущие в конце строки, не подчеркиваем и не зачеркиваем
if ( PDSL.Spaces > 0 )
{
if (true === bRemReview)
aStrikeout.Add(StrikeoutY, StrikeoutY, X, X + ItemWidthVisible, LineW, ReviewColor.r, ReviewColor.g, ReviewColor.b);
else if (true === CurTextPr.DStrikeout)
aDStrikeout.Add( StrikeoutY, StrikeoutY, X, X + ItemWidthVisible, LineW, CurColor.r, CurColor.g, CurColor.b, undefined, CurTextPr );
else if ( true === CurTextPr.Strikeout )
aStrikeout.Add( StrikeoutY, StrikeoutY, X, X + ItemWidthVisible, LineW, CurColor.r, CurColor.g, CurColor.b, undefined, CurTextPr );
if (true === bAddReview)
aUnderline.Add(UnderlineY, UnderlineY, X, X + ItemWidthVisible, LineW, ReviewColor.r, ReviewColor.g, ReviewColor.b);
else if (true === CurTextPr.Underline)
aUnderline.Add( UnderlineY, UnderlineY, X, X + ItemWidthVisible, LineW, CurColor.r, CurColor.g, CurColor.b, undefined, CurTextPr );
PDSL.Spaces--;
}
X += ItemWidthVisible;
break;
}
case para_Math_Text:
case para_Math_BreakOperator:
case para_Math_Ampersand:
{
if (true === bRemReview)
aStrikeout.Add( StrikeoutY, StrikeoutY, X, X + ItemWidthVisible, LineW, ReviewColor.r, ReviewColor.g, ReviewColor.b, undefined, CurTextPr );
else if (true === CurTextPr.DStrikeout)
aDStrikeout.Add( StrikeoutY, StrikeoutY, X, X + ItemWidthVisible, LineW, CurColor.r, CurColor.g, CurColor.b, undefined, CurTextPr );
else if ( true === CurTextPr.Strikeout )
aStrikeout.Add( StrikeoutY, StrikeoutY, X, X + ItemWidthVisible, LineW, CurColor.r, CurColor.g, CurColor.b, undefined, CurTextPr );
X += ItemWidthVisible;
break;
}
case para_Math_Placeholder:
{
var ctrPrp = this.Parent.GetCtrPrp();
if (true === bRemReview)
aStrikeout.Add( StrikeoutY, StrikeoutY, X, X + ItemWidthVisible, LineW, ReviewColor.r, ReviewColor.g, ReviewColor.b, undefined, CurTextPr );
if(true === ctrPrp.DStrikeout)
aDStrikeout.Add( StrikeoutY, StrikeoutY, X, X + ItemWidthVisible, LineW, CurColor.r, CurColor.g, CurColor.b, undefined, CurTextPr );
else if(true === ctrPrp.Strikeout)
aStrikeout.Add( StrikeoutY, StrikeoutY, X, X + ItemWidthVisible, LineW, CurColor.r, CurColor.g, CurColor.b, undefined, CurTextPr );
X += ItemWidthVisible;
break;
}
}
if ( 2 === SpellingMarksArray[Pos + 1] || 3 === SpellingMarksArray[Pos + 1] )
PDSL.SpellingCounter--;
}
if (true === this.Pr.Have_PrChange() && para_Math_Run !== this.Type)
{
var ReviewColor = this.Get_PrReviewColor();
PDSL.RunReview.Add(0, 0, PDSL.X, X, 0, ReviewColor.r, ReviewColor.g, ReviewColor.b, {RunPr: this.Pr});
}
var CollPrChangeColor = this.private_GetCollPrChangeOther();
if (false !== CollPrChangeColor)
PDSL.CollChange.Add(0, 0, PDSL.X, X, 0, CollPrChangeColor.r, CollPrChangeColor.g, CollPrChangeColor.b, {RunPr : this.Pr});
// Обновляем позицию
PDSL.X = X;
};
//-----------------------------------------------------------------------------------
// Функции для работы с курсором
//-----------------------------------------------------------------------------------
// Находится ли курсор в начале рана
ParaRun.prototype.Is_CursorPlaceable = function()
{
return true;
};
ParaRun.prototype.Cursor_Is_Start = function()
{
if ( this.State.ContentPos <= 0 )
return true;
return false;
};
// Проверяем нужно ли поправить позицию курсора
ParaRun.prototype.Cursor_Is_NeededCorrectPos = function()
{
if ( true === this.Is_Empty(false) )
return true;
var NewRangeStart = false;
var RangeEnd = false;
var Pos = this.State.ContentPos;
var LinesLen = this.protected_GetLinesCount();
for ( var CurLine = 0; CurLine < LinesLen; CurLine++ )
{
var RangesLen = this.protected_GetRangesCount(CurLine);
for ( var CurRange = 0; CurRange < RangesLen; CurRange++ )
{
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
if (0 !== CurLine || 0 !== CurRange)
{
if (Pos === StartPos)
{
NewRangeStart = true;
}
}
if (Pos === EndPos)
{
RangeEnd = true;
}
}
if ( true === NewRangeStart )
break;
}
if ( true !== NewRangeStart && true !== RangeEnd && true === this.Cursor_Is_Start() )
return true;
return false;
};
ParaRun.prototype.Cursor_Is_End = function()
{
if ( this.State.ContentPos >= this.Content.length )
return true;
return false;
};
ParaRun.prototype.MoveCursorToStartPos = function()
{
this.State.ContentPos = 0;
};
ParaRun.prototype.MoveCursorToEndPos = function(SelectFromEnd)
{
if ( true === SelectFromEnd )
{
var Selection = this.State.Selection;
Selection.Use = true;
Selection.StartPos = this.Content.length;
Selection.EndPos = this.Content.length;
}
else
{
var CurPos = this.Content.length;
while ( CurPos > 0 )
{
if ( para_End === this.Content[CurPos - 1].Type )
CurPos--;
else
break;
}
this.State.ContentPos = CurPos;
}
};
ParaRun.prototype.Get_ParaContentPosByXY = function(SearchPos, Depth, _CurLine, _CurRange, StepEnd)
{
var Result = false;
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
var CurPos = StartPos;
var InMathText = this.Type == para_Math_Run ? SearchPos.InText == true : false;
for (; CurPos < EndPos; CurPos++ )
{
var Item = this.Content[CurPos];
var ItemType = Item.Type;
var TempDx = 0;
if (para_Drawing != ItemType || true === Item.Is_Inline())
{
TempDx = Item.Get_WidthVisible();
}
if(this.Type == para_Math_Run)
{
var PosLine = this.ParaMath.GetLinePosition(_CurLine, _CurRange);
var loc = this.Content[CurPos].GetLocationOfLetter();
SearchPos.CurX = PosLine.x + loc.x; // позиция формулы в строке + смещение буквы в контенте
}
// Проверяем, попали ли мы в данный элемент
var Diff = SearchPos.X - SearchPos.CurX;
if ((Math.abs( Diff ) < SearchPos.DiffX + 0.001 && (SearchPos.CenterMode || SearchPos.X > SearchPos.CurX)) && InMathText == false)
{
SearchPos.DiffX = Math.abs(Diff);
SearchPos.Pos.Update(CurPos, Depth);
Result = true;
if ( Diff >= - 0.001 && Diff <= TempDx + 0.001 )
{
SearchPos.InTextPos.Update( CurPos, Depth );
SearchPos.InText = true;
}
}
SearchPos.CurX += TempDx;
// Заглушка для знака параграфа и конца строки
Diff = SearchPos.X - SearchPos.CurX;
if ((Math.abs( Diff ) < SearchPos.DiffX + 0.001 && (SearchPos.CenterMode || SearchPos.X > SearchPos.CurX)) && InMathText == false)
{
if ( para_End === ItemType )
{
SearchPos.End = true;
// Если мы ищем позицию для селекта, тогда нужно искать и за знаком параграфа
if ( true === StepEnd )
{
SearchPos.DiffX = Math.abs(Diff);
SearchPos.Pos.Update( this.Content.length, Depth );
Result = true;
}
}
else if ( CurPos === EndPos - 1 && para_NewLine != ItemType )
{
SearchPos.DiffX = Math.abs(Diff);
SearchPos.Pos.Update( EndPos, Depth );
Result = true;
}
}
}
// Такое возможно, если все раны до этого (в том числе и этот) были пустыми, тогда, чтобы не возвращать
// неправильную позицию вернем позицию начала данного путого рана.
if ( SearchPos.DiffX > 1000000 - 1 )
{
SearchPos.DiffX = SearchPos.X - SearchPos.CurX;
SearchPos.Pos.Update( StartPos, Depth );
Result = true;
}
if (this.Type == para_Math_Run) // не только для пустых Run, но и для проверки на конец Run (т.к. Diff не обновляется)
{
//для пустых Run искомая позиция - позиция самого Run
var bEmpty = this.Is_Empty();
var PosLine = this.ParaMath.GetLinePosition(_CurLine, _CurRange);
if(bEmpty)
SearchPos.CurX = PosLine.x + this.pos.x;
Diff = SearchPos.X - SearchPos.CurX;
if(SearchPos.InText == false && (bEmpty || StartPos !== EndPos) && (Math.abs( Diff ) < SearchPos.DiffX + 0.001 && (SearchPos.CenterMode || SearchPos.X > SearchPos.CurX)))
{
SearchPos.DiffX = Math.abs(Diff);
SearchPos.Pos.Update(CurPos, Depth);
Result = true;
}
}
return Result;
};
ParaRun.prototype.Get_ParaContentPos = function(bSelection, bStart, ContentPos, bUseCorrection)
{
var Pos = ( true !== bSelection ? this.State.ContentPos : ( false !== bStart ? this.State.Selection.StartPos : this.State.Selection.EndPos ) );
ContentPos.Add(Pos);
};
ParaRun.prototype.Set_ParaContentPos = function(ContentPos, Depth)
{
var Pos = ContentPos.Get(Depth);
var Count = this.Content.length;
if ( Pos > Count )
Pos = Count;
// TODO: Как только переделаем работу c Para_End переделать здесь
for ( var TempPos = 0; TempPos < Pos; TempPos++ )
{
if ( para_End === this.Content[TempPos].Type )
{
Pos = TempPos;
break;
}
}
if ( Pos < 0 )
Pos = 0;
this.State.ContentPos = Pos;
};
ParaRun.prototype.Get_PosByElement = function(Class, ContentPos, Depth, UseRange, Range, Line)
{
if ( this === Class )
return true;
return false;
};
ParaRun.prototype.Get_ElementByPos = function(ContentPos, Depth)
{
return this;
};
ParaRun.prototype.Get_PosByDrawing = function(Id, ContentPos, Depth)
{
var Count = this.Content.length;
for ( var CurPos = 0; CurPos < Count; CurPos++ )
{
var Item = this.Content[CurPos];
if ( para_Drawing === Item.Type && Id === Item.Get_Id() )
{
ContentPos.Update( CurPos, Depth );
return true;
}
}
return false;
};
ParaRun.prototype.Get_RunElementByPos = function(ContentPos, Depth)
{
if ( undefined !== ContentPos )
{
var CurPos = ContentPos.Get(Depth);
var ContentLen = this.Content.length;
if ( CurPos >= this.Content.length || CurPos < 0 )
return null;
return this.Content[CurPos];
}
else
{
if ( this.Content.length > 0 )
return this.Content[0];
else
return null;
}
};
ParaRun.prototype.Get_LastRunInRange = function(_CurLine, _CurRange)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
return this;
};
ParaRun.prototype.Get_LeftPos = function(SearchPos, ContentPos, Depth, UseContentPos)
{
var CurPos = true === UseContentPos ? ContentPos.Get(Depth) : this.Content.length;
while (true)
{
CurPos--;
var Item = this.Content[CurPos];
if (CurPos < 0 || (!(para_Drawing === Item.Type && false === Item.Is_Inline() && false === SearchPos.IsCheckAnchors()) && !(para_FootnoteReference === Item.Type && true === Item.IsCustomMarkFollows())))
break;
}
if (CurPos >= 0)
{
SearchPos.Found = true;
SearchPos.Pos.Update(CurPos, Depth);
}
};
ParaRun.prototype.Get_RightPos = function(SearchPos, ContentPos, Depth, UseContentPos, StepEnd)
{
var CurPos = ( true === UseContentPos ? ContentPos.Get(Depth) : 0 );
var Count = this.Content.length;
while (true)
{
CurPos++;
// Мы встали в конец рана:
// Если мы перешагнули para_End или para_Drawing Anchor, тогда возвращаем false
// В противном случае true
if (Count === CurPos)
{
if (CurPos === 0)
return;
var PrevItem = this.Content[CurPos - 1];
var PrevItemType = PrevItem.Type;
if ((true !== StepEnd && para_End === PrevItemType) || (para_Drawing === PrevItemType && false === PrevItem.Is_Inline() && false === SearchPos.IsCheckAnchors()) || (para_FootnoteReference === PrevItemType && true === PrevItem.IsCustomMarkFollows()))
return;
break;
}
if (CurPos > Count)
break;
// Минимальное значение CurPos = 1, т.к. мы начинаем со значния >= 0 и добавляем 1
var Item = this.Content[CurPos - 1];
var ItemType = Item.Type;
if (!(true !== StepEnd && para_End === ItemType)
&& !(para_Drawing === Item.Type && false === Item.Is_Inline())
&& !(para_FootnoteReference === Item.Type && true === Item.IsCustomMarkFollows()))
break;
}
if (CurPos <= Count)
{
SearchPos.Found = true;
SearchPos.Pos.Update(CurPos, Depth);
}
};
ParaRun.prototype.Get_WordStartPos = function(SearchPos, ContentPos, Depth, UseContentPos)
{
var CurPos = ( true === UseContentPos ? ContentPos.Get(Depth) - 1 : this.Content.length - 1 );
if ( CurPos < 0 )
return;
SearchPos.Shift = true;
var NeedUpdate = false;
// На первом этапе ищем позицию первого непробельного элемента
if ( 0 === SearchPos.Stage )
{
while ( true )
{
var Item = this.Content[CurPos];
var Type = Item.Type;
var bSpace = false;
if ( para_Space === Type || para_Tab === Type || ( para_Text === Type && true === Item.Is_NBSP() ) || ( para_Drawing === Type && true !== Item.Is_Inline() ) )
bSpace = true;
if ( true === bSpace )
{
CurPos--;
// Выходим из данного рана
if ( CurPos < 0 )
return;
}
else
{
// Если мы остановились на нетекстовом элементе, тогда его и возвращаем
if ( para_Text !== this.Content[CurPos].Type && para_Math_Text !== this.Content[CurPos].Type)
{
SearchPos.Pos.Update( CurPos, Depth );
SearchPos.Found = true;
SearchPos.UpdatePos = true;
return;
}
SearchPos.Pos.Update( CurPos, Depth );
SearchPos.Stage = 1;
SearchPos.Punctuation = this.Content[CurPos].Is_Punctuation();
NeedUpdate = true;
break;
}
}
}
else
{
CurPos = ( true === UseContentPos ? ContentPos.Get(Depth) : this.Content.length );
}
// На втором этапе мы смотрим на каком элементе мы встали: если текст - пунктуация, тогда сдвигаемся
// до конца всех знаков пунктуации
while ( CurPos > 0 )
{
CurPos--;
var Item = this.Content[CurPos];
var TempType = Item.Type;
if ( (para_Text !== TempType && para_Math_Text !== TempType) || true === Item.Is_NBSP() || ( true === SearchPos.Punctuation && true !== Item.Is_Punctuation() ) || ( false === SearchPos.Punctuation && false !== Item.Is_Punctuation() ) )
{
SearchPos.Found = true;
break;
}
else
{
SearchPos.Pos.Update( CurPos, Depth );
NeedUpdate = true;
}
}
SearchPos.UpdatePos = NeedUpdate;
};
ParaRun.prototype.Get_WordEndPos = function(SearchPos, ContentPos, Depth, UseContentPos, StepEnd)
{
var CurPos = ( true === UseContentPos ? ContentPos.Get(Depth) : 0 );
var ContentLen = this.Content.length;
if ( CurPos >= ContentLen )
return;
var NeedUpdate = false;
if ( 0 === SearchPos.Stage )
{
// На первом этапе ищем первый нетекстовый ( и не таб ) элемент
while ( true )
{
var Item = this.Content[CurPos];
var Type = Item.Type;
var bText = false;
if ( (para_Text === Type || para_Math_Text === Type) && true != Item.Is_NBSP() && ( true === SearchPos.First || ( SearchPos.Punctuation === Item.Is_Punctuation() ) ) )
bText = true;
if ( true === bText )
{
if ( true === SearchPos.First )
{
SearchPos.First = false;
SearchPos.Punctuation = Item.Is_Punctuation();
}
CurPos++;
// Отмечаем, что сдвиг уже произошел
SearchPos.Shift = true;
// Выходим из рана
if ( CurPos >= ContentLen )
return;
}
else
{
SearchPos.Stage = 1;
// Первый найденный элемент не текстовый, смещаемся вперед
if ( true === SearchPos.First )
{
// Если первый найденный элемент - конец параграфа, тогда выходим из поиска
if ( para_End === Type )
{
if ( true === StepEnd )
{
SearchPos.Pos.Update( CurPos + 1, Depth );
SearchPos.Found = true;
SearchPos.UpdatePos = true;
}
return;
}
CurPos++;
// Отмечаем, что сдвиг уже произошел
SearchPos.Shift = true;
}
break;
}
}
}
if ( CurPos >= ContentLen )
return;
// На втором этапе мы смотрим на каком элементе мы встали: если это не пробел, тогда
// останавливаемся здесь. В противном случае сдвигаемся вперед, пока не попали на первый
// не пробельный элемент.
if ( !(para_Space === this.Content[CurPos].Type || ( para_Text === this.Content[CurPos].Type && true === this.Content[CurPos].Is_NBSP() ) ) )
{
SearchPos.Pos.Update( CurPos, Depth );
SearchPos.Found = true;
SearchPos.UpdatePos = true;
}
else
{
while ( CurPos < ContentLen - 1 )
{
CurPos++;
var Item = this.Content[CurPos];
var TempType = Item.Type;
if ( (true !== StepEnd && para_End === TempType) || !( para_Space === TempType || ( para_Text === TempType && true === Item.Is_NBSP() ) ) )
{
SearchPos.Found = true;
break;
}
}
// Обновляем позицию в конце каждого рана (хуже от этого не будет)
SearchPos.Pos.Update( CurPos, Depth );
SearchPos.UpdatePos = true;
}
};
ParaRun.prototype.Get_EndRangePos = function(_CurLine, _CurRange, SearchPos, Depth)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
var LastPos = -1;
for ( var CurPos = StartPos; CurPos < EndPos; CurPos++ )
{
var Item = this.Content[CurPos];
var ItemType = Item.Type;
if ( !((para_Drawing === ItemType && true !== Item.Is_Inline()) || para_End === ItemType || (para_NewLine === ItemType && break_Line === Item.BreakType)))
LastPos = CurPos + 1;
}
// Проверяем, попал ли хоть один элемент в данный отрезок, если нет, тогда не регистрируем такой ран
if ( -1 !== LastPos )
{
SearchPos.Pos.Update( LastPos, Depth );
return true;
}
else
return false;
};
ParaRun.prototype.Get_StartRangePos = function(_CurLine, _CurRange, SearchPos, Depth)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
var FirstPos = -1;
for ( var CurPos = EndPos - 1; CurPos >= StartPos; CurPos-- )
{
var Item = this.Content[CurPos];
if ( !(para_Drawing === Item.Type && true !== Item.Is_Inline()) )
FirstPos = CurPos;
}
// Проверяем, попал ли хоть один элемент в данный отрезок, если нет, тогда не регистрируем такой ран
if ( -1 !== FirstPos )
{
SearchPos.Pos.Update( FirstPos, Depth );
return true;
}
else
return false;
};
ParaRun.prototype.Get_StartRangePos2 = function(_CurLine, _CurRange, ContentPos, Depth)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var Pos = this.protected_GetRangeStartPos(CurLine, CurRange);
ContentPos.Update( Pos, Depth );
};
ParaRun.prototype.Get_EndRangePos2 = function(_CurLine, _CurRange, ContentPos, Depth)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = (0 === CurLine ? _CurRange - this.StartRange : _CurRange);
var Pos = this.protected_GetRangeEndPos(CurLine, CurRange);
ContentPos.Update(Pos, Depth);
};
ParaRun.prototype.Get_StartPos = function(ContentPos, Depth)
{
ContentPos.Update( 0, Depth );
};
ParaRun.prototype.Get_EndPos = function(BehindEnd, ContentPos, Depth)
{
var ContentLen = this.Content.length;
if ( true === BehindEnd )
ContentPos.Update( ContentLen, Depth );
else
{
for ( var CurPos = 0; CurPos < ContentLen; CurPos++ )
{
if ( para_End === this.Content[CurPos].Type )
{
ContentPos.Update( CurPos, Depth );
return;
}
}
// Не нашли para_End
ContentPos.Update( ContentLen, Depth );
}
};
//-----------------------------------------------------------------------------------
// Функции для работы с селектом
//-----------------------------------------------------------------------------------
ParaRun.prototype.Set_SelectionContentPos = function(StartContentPos, EndContentPos, Depth, StartFlag, EndFlag)
{
var StartPos = 0;
switch (StartFlag)
{
case 1: StartPos = 0; break;
case -1: StartPos = this.Content.length; break;
case 0: StartPos = StartContentPos.Get(Depth); break;
}
var EndPos = 0;
switch (EndFlag)
{
case 1: EndPos = 0; break;
case -1: EndPos = this.Content.length; break;
case 0: EndPos = EndContentPos.Get(Depth); break;
}
var Selection = this.State.Selection;
Selection.StartPos = StartPos;
Selection.EndPos = EndPos;
Selection.Use = true;
};
ParaRun.prototype.SetContentSelection = function(StartDocPos, EndDocPos, Depth, StartFlag, EndFlag)
{
var StartPos = 0;
switch (StartFlag)
{
case 1: StartPos = 0; break;
case -1: StartPos = this.Content.length; break;
case 0: StartPos = StartDocPos[Depth].Position; break;
}
var EndPos = 0;
switch (EndFlag)
{
case 1: EndPos = 0; break;
case -1: EndPos = this.Content.length; break;
case 0: EndPos = EndDocPos[Depth].Position; break;
}
var Selection = this.State.Selection;
Selection.StartPos = StartPos;
Selection.EndPos = EndPos;
Selection.Use = true;
};
ParaRun.prototype.SetContentPosition = function(DocPos, Depth, Flag)
{
var Pos = 0;
switch (Flag)
{
case 1: Pos = 0; break;
case -1: Pos = this.Content.length; break;
case 0: Pos = DocPos[Depth].Position; break;
}
var nLen = this.Content.length;
if (nLen > 0 && Pos >= nLen && para_End === this.Content[nLen - 1].Type)
Pos = nLen - 1;
this.State.ContentPos = Pos;
};
ParaRun.prototype.Set_SelectionAtEndPos = function()
{
this.Set_SelectionContentPos(null, null, 0, -1, -1);
};
ParaRun.prototype.Set_SelectionAtStartPos = function()
{
this.Set_SelectionContentPos(null, null, 0, 1, 1);
};
ParaRun.prototype.IsSelectionUse = function()
{
return this.State.Selection.Use;
};
ParaRun.prototype.IsSelectedAll = function(Props)
{
var Selection = this.State.Selection;
if ( false === Selection.Use && true !== this.Is_Empty( Props ) )
return false;
var SkipAnchor = Props ? Props.SkipAnchor : false;
var SkipEnd = Props ? Props.SkipEnd : false;
var StartPos = Selection.StartPos;
var EndPos = Selection.EndPos;
if ( EndPos < StartPos )
{
StartPos = Selection.EndPos;
EndPos = Selection.StartPos;
}
for ( var Pos = 0; Pos < StartPos; Pos++ )
{
var Item = this.Content[Pos];
var ItemType = Item.Type;
if ( !( ( true === SkipAnchor && ( para_Drawing === ItemType && true !== Item.Is_Inline() ) ) || ( true === SkipEnd && para_End === ItemType ) ) )
return false;
}
var Count = this.Content.length;
for ( var Pos = EndPos; Pos < Count; Pos++ )
{
var Item = this.Content[Pos];
var ItemType = Item.Type;
if ( !( ( true === SkipAnchor && ( para_Drawing === ItemType && true !== Item.Is_Inline() ) ) || ( true === SkipEnd && para_End === ItemType ) ) )
return false;
}
return true;
};
ParaRun.prototype.Selection_CorrectLeftPos = function(Direction)
{
if ( false === this.Selection.Use || true === this.Is_Empty( { SkipAnchor : true } ) )
return true;
var Selection = this.State.Selection;
var StartPos = Math.min( Selection.StartPos, Selection.EndPos );
var EndPos = Math.max( Selection.StartPos, Selection.EndPos );
for ( var Pos = 0; Pos < StartPos; Pos++ )
{
var Item = this.Content[Pos];
if ( para_Drawing !== Item.Type || true === Item.Is_Inline() )
return false;
}
for ( var Pos = StartPos; Pos < EndPos; Pos++ )
{
var Item = this.Content[Pos];
if ( para_Drawing === Item.Type && true !== Item.Is_Inline() )
{
if ( 1 === Direction )
Selection.StartPos = Pos + 1;
else
Selection.EndPos = Pos + 1;
}
else
return false;
}
return true;
};
ParaRun.prototype.RemoveSelection = function()
{
var Selection = this.State.Selection;
Selection.Use = false;
Selection.StartPos = 0;
Selection.EndPos = 0;
};
ParaRun.prototype.SelectAll = function(Direction)
{
var Selection = this.State.Selection;
Selection.Use = true;
if ( -1 === Direction )
{
Selection.StartPos = this.Content.length;
Selection.EndPos = 0;
}
else
{
Selection.StartPos = 0;
Selection.EndPos = this.Content.length;
}
};
ParaRun.prototype.Selection_DrawRange = function(_CurLine, _CurRange, SelectionDraw)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
var Selection = this.State.Selection;
var SelectionUse = Selection.Use;
var SelectionStartPos = Selection.StartPos;
var SelectionEndPos = Selection.EndPos;
if ( SelectionStartPos > SelectionEndPos )
{
SelectionStartPos = Selection.EndPos;
SelectionEndPos = Selection.StartPos;
}
var FindStart = SelectionDraw.FindStart;
for(var CurPos = StartPos; CurPos < EndPos; CurPos++)
{
var Item = this.Content[CurPos];
var ItemType = Item.Type;
var DrawSelection = false;
if ( true === FindStart )
{
if ( true === Selection.Use && CurPos >= SelectionStartPos && CurPos < SelectionEndPos )
{
FindStart = false;
DrawSelection = true;
}
else
{
if ( para_Drawing !== ItemType || true === Item.Is_Inline() )
SelectionDraw.StartX += Item.Get_WidthVisible();
}
}
else
{
if ( true === Selection.Use && CurPos >= SelectionStartPos && CurPos < SelectionEndPos )
{
DrawSelection = true;
}
}
if ( true === DrawSelection )
{
if (para_Drawing === ItemType && true !== Item.Is_Inline())
{
if (true === SelectionDraw.Draw)
Item.Draw_Selection();
}
else
SelectionDraw.W += Item.Get_WidthVisible();
}
}
SelectionDraw.FindStart = FindStart;
};
ParaRun.prototype.IsSelectionEmpty = function(CheckEnd)
{
var Selection = this.State.Selection;
if (true !== Selection.Use)
return true;
if(this.Type == para_Math_Run && this.IsPlaceholder())
return true;
var StartPos = Selection.StartPos;
var EndPos = Selection.EndPos;
if ( StartPos > EndPos )
{
StartPos = Selection.EndPos;
EndPos = Selection.StartPos;
}
if ( true === CheckEnd )
return ( EndPos > StartPos ? false : true );
else if(this.Type == para_Math_Run && this.Is_Empty())
{
return false;
}
else
{
for ( var CurPos = StartPos; CurPos < EndPos; CurPos++ )
{
var ItemType = this.Content[CurPos].Type;
if (para_End !== ItemType)
return false;
}
}
return true;
};
ParaRun.prototype.Selection_CheckParaEnd = function()
{
var Selection = this.State.Selection;
if ( true !== Selection.Use )
return false;
var StartPos = Selection.StartPos;
var EndPos = Selection.EndPos;
if ( StartPos > EndPos )
{
StartPos = Selection.EndPos;
EndPos = Selection.StartPos;
}
for ( var CurPos = StartPos; CurPos < EndPos; CurPos++ )
{
var Item = this.Content[CurPos];
if ( para_End === Item.Type )
return true;
}
return false;
};
ParaRun.prototype.Selection_CheckParaContentPos = function(ContentPos, Depth, bStart, bEnd)
{
var CurPos = ContentPos.Get(Depth);
if (this.Selection.StartPos <= this.Selection.EndPos && this.Selection.StartPos <= CurPos && CurPos <= this.Selection.EndPos)
{
if ((true !== bEnd) || (true === bEnd && CurPos !== this.Selection.EndPos))
return true;
}
else if (this.Selection.StartPos > this.Selection.EndPos && this.Selection.EndPos <= CurPos && CurPos <= this.Selection.StartPos)
{
if ((true !== bEnd) || (true === bEnd && CurPos !== this.Selection.StartPos))
return true;
}
return false;
};
//-----------------------------------------------------------------------------------
// Функции для работы с настройками текста свойств
//-----------------------------------------------------------------------------------
ParaRun.prototype.Clear_TextFormatting = function( DefHyper )
{
// Highlight и Lang не сбрасываются при очистке текстовых настроек
this.Set_Bold( undefined );
this.Set_Italic( undefined );
this.Set_Strikeout( undefined );
this.Set_Underline( undefined );
this.Set_FontSize( undefined );
this.Set_Color( undefined );
this.Set_Unifill( undefined );
this.Set_VertAlign( undefined );
this.Set_Spacing( undefined );
this.Set_DStrikeout( undefined );
this.Set_Caps( undefined );
this.Set_SmallCaps( undefined );
this.Set_Position( undefined );
this.Set_RFonts2( undefined );
this.Set_RStyle( undefined );
this.Set_Shd( undefined );
this.Set_TextFill( undefined );
this.Set_TextOutline( undefined );
// Насильно заставим пересчитать стиль, т.к. как данная функция вызывается у параграфа, у которого мог смениться стиль
this.Recalc_CompiledPr(true);
};
ParaRun.prototype.Get_TextPr = function()
{
return this.Pr.Copy();
};
ParaRun.prototype.Get_FirstTextPr = function()
{
return this.Pr;
};
ParaRun.prototype.Get_CompiledTextPr = function(Copy)
{
if ( true === this.State.Selection.Use && true === this.Selection_CheckParaEnd() )
{
var ThisTextPr = this.Get_CompiledPr( true );
var Para = this.Paragraph;
var EndTextPr = Para.Get_CompiledPr2(false).TextPr.Copy();
EndTextPr.Merge( Para.TextPr.Value );
ThisTextPr = ThisTextPr.Compare( EndTextPr );
return ThisTextPr;
}
else
{
return this.Get_CompiledPr(Copy);
}
};
ParaRun.prototype.Recalc_CompiledPr = function(RecalcMeasure)
{
this.RecalcInfo.TextPr = true;
// Если изменение какой-то текстовой настройки требует пересчета элементов
if ( true === RecalcMeasure )
this.RecalcInfo.Measure = true;
// Если мы в формуле, тогда ее надо пересчитывать
this.private_RecalcCtrPrp();
};
ParaRun.prototype.Recalc_RunsCompiledPr = function()
{
this.Recalc_CompiledPr(true);
};
ParaRun.prototype.Get_CompiledPr = function(bCopy)
{
if ( true === this.RecalcInfo.TextPr )
{
this.RecalcInfo.TextPr = false;
this.CompiledPr = this.Internal_Compile_Pr();
}
if ( false === bCopy )
return this.CompiledPr;
else
return this.CompiledPr.Copy(); // Отдаем копию объекта, чтобы никто не поменял извне настройки стиля
};
ParaRun.prototype.Internal_Compile_Pr = function ()
{
if ( undefined === this.Paragraph || null === this.Paragraph )
{
// Сюда мы никогда не должны попадать, но на всякий случай,
// чтобы не выпадало ошибок сгенерим дефолтовые настройки
var TextPr = new CTextPr();
TextPr.Init_Default();
this.RecalcInfo.TextPr = true;
return TextPr;
}
// Получим настройки текста, для данного параграфа
var TextPr = this.Paragraph.Get_CompiledPr2(false).TextPr.Copy();
// Если в прямых настройках задан стиль, тогда смержим настройки стиля
if ( undefined != this.Pr.RStyle )
{
var Styles = this.Paragraph.Parent.Get_Styles();
var StyleTextPr = Styles.Get_Pr( this.Pr.RStyle, styletype_Character ).TextPr;
TextPr.Merge( StyleTextPr );
}
if(this.Type == para_Math_Run)
{
if (undefined === this.Parent || null === this.Parent)
{
// Сюда мы никогда не должны попадать, но на всякий случай,
// чтобы не выпадало ошибок сгенерим дефолтовые настройки
var TextPr = new CTextPr();
TextPr.Init_Default();
this.RecalcInfo.TextPr = true;
return TextPr;
}
if(!this.IsNormalText()) // math text
{
// выставим дефолтные текстовые настройки для математических Run
var Styles = this.Paragraph.Parent.Get_Styles();
var StyleId = this.Paragraph.Style_Get();
// скопируем текстовые настройки прежде чем подменим на пустые
var MathFont = {Name : "Cambria Math", Index : -1};
var oShapeStyle = null, oShapeTextPr = null;;
if(Styles && typeof Styles.lastId === "string")
{
StyleId = Styles.lastId;
Styles = Styles.styles;
oShapeStyle = Styles.Get(StyleId);
oShapeTextPr = oShapeStyle.TextPr.Copy();
oShapeStyle.TextPr.RFonts.Merge({Ascii: MathFont});
}
var StyleDefaultTextPr = Styles.Default.TextPr.Copy();
// Ascii - по умолчанию шрифт Cambria Math
// hAnsi, eastAsia, cs - по умолчанию шрифты не Cambria Math, а те, которые компилируются в документе
Styles.Default.TextPr.RFonts.Merge({Ascii: MathFont});
var Pr = Styles.Get_Pr( StyleId, styletype_Paragraph, null, null );
TextPr.RFonts.Set_FromObject(Pr.TextPr.RFonts);
// подменяем обратно
Styles.Default.TextPr = StyleDefaultTextPr;
if(oShapeStyle && oShapeTextPr)
{
oShapeStyle.TextPr = oShapeTextPr;
}
}
if(this.IsPlaceholder())
{
TextPr.Merge(this.Parent.GetCtrPrp());
TextPr.Merge( this.Pr ); // Мержим прямые настройки данного рана
}
else
{
TextPr.Merge( this.Pr ); // Мержим прямые настройки данного рана
if(!this.IsNormalText()) // math text
{
var MPrp = this.MathPrp.GetTxtPrp();
TextPr.Merge(MPrp); // bold, italic
}
}
}
else
{
TextPr.Merge( this.Pr ); // Мержим прямые настройки данного рана
if(this.Pr.Color && !this.Pr.Unifill)
{
TextPr.Unifill = undefined;
}
}
// Для совместимости со старыми версиями запишем FontFamily
TextPr.FontFamily.Name = TextPr.RFonts.Ascii.Name;
TextPr.FontFamily.Index = TextPr.RFonts.Ascii.Index;
return TextPr;
};
// В данной функции мы жестко меняем настройки на те, которые пришли (т.е. полностью удаляем старые)
ParaRun.prototype.Set_Pr = function(TextPr)
{
var OldValue = this.Pr;
this.Pr = TextPr;
History.Add(new CChangesRunTextPr(this, OldValue, TextPr, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(true);
this.protected_UpdateSpellChecking();
this.private_UpdateTrackRevisionOnChangeTextPr(true);
};
ParaRun.prototype.Apply_TextPr = function(TextPr, IncFontSize, ApplyToAll)
{
var bReview = false;
if (this.Paragraph && this.Paragraph.LogicDocument && this.Paragraph.bFromDocument && true === this.Paragraph.LogicDocument.Is_TrackRevisions())
bReview = true;
var ReviewType = this.Get_ReviewType();
var IsPrChange = this.Have_PrChange();
if ( true === ApplyToAll )
{
if (true === bReview && true !== this.Have_PrChange())
this.Add_PrChange();
if ( undefined === IncFontSize )
{
this.Apply_Pr(TextPr);
}
else
{
var _TextPr = new CTextPr();
var CurTextPr = this.Get_CompiledPr( false );
this.private_AddCollPrChangeMine();
this.Set_FontSize( FontSize_IncreaseDecreaseValue( IncFontSize, CurTextPr.FontSize ) );
}
// Дополнительно проверим, если у нас para_End лежит в данном ране и попадает в выделение, тогда
// применим заданные настроки к символу конца параграфа
// TODO: Возможно, стоит на этапе пересчета запонимать, лежит ли para_End в данном ране. Чтобы в каждом
// ране потом не бегать каждый раз по всему массиву в поисках para_End.
var bEnd = false;
var Count = this.Content.length;
for ( var Pos = 0; Pos < Count; Pos++ )
{
if ( para_End === this.Content[Pos].Type )
{
bEnd = true;
break;
}
}
if ( true === bEnd )
{
if ( undefined === IncFontSize )
{
if(!TextPr.AscFill && !TextPr.AscLine && !TextPr.AscUnifill)
{
this.Paragraph.TextPr.Apply_TextPr( TextPr );
}
else
{
var EndTextPr = this.Paragraph.Get_CompiledPr2(false).TextPr.Copy();
EndTextPr.Merge( this.Paragraph.TextPr.Value );
if(TextPr.AscFill)
{
this.Paragraph.TextPr.Set_TextFill(AscFormat.CorrectUniFill(TextPr.AscFill, EndTextPr.TextFill, 1));
}
if(TextPr.AscUnifill)
{
this.Paragraph.TextPr.Set_Unifill(AscFormat.CorrectUniFill(TextPr.AscUnifill, EndTextPr.Unifill, 0));
}
if(TextPr.AscLine)
{
this.Paragraph.TextPr.Set_TextOutline(AscFormat.CorrectUniStroke(TextPr.AscLine, EndTextPr.TextOutline, 0));
}
}
}
else
{
var Para = this.Paragraph;
// Выставляем настройки для символа параграфа
var EndTextPr = Para.Get_CompiledPr2(false).TextPr.Copy();
EndTextPr.Merge( Para.TextPr.Value );
// TODO: Как только перенесем историю изменений TextPr в сам класс CTextPr, переделать тут
Para.TextPr.Set_FontSize( FontSize_IncreaseDecreaseValue( IncFontSize, EndTextPr.FontSize ) );
}
}
}
else
{
var Result = [];
var LRun = this, CRun = null, RRun = null;
if ( true === this.State.Selection.Use )
{
var StartPos = this.State.Selection.StartPos;
var EndPos = this.State.Selection.EndPos;
if (StartPos === EndPos && 0 !== this.Content.length)
{
CRun = this;
LRun = null;
RRun = null;
}
else
{
var Direction = 1;
if (StartPos > EndPos)
{
var Temp = StartPos;
StartPos = EndPos;
EndPos = Temp;
Direction = -1;
}
// Если выделено не до конца, тогда разделяем по последней точке
if (EndPos < this.Content.length)
{
RRun = LRun.Split_Run(EndPos);
RRun.Set_ReviewType(ReviewType);
if (IsPrChange)
RRun.Add_PrChange();
}
// Если выделено не с начала, тогда делим по начальной точке
if (StartPos > 0)
{
CRun = LRun.Split_Run(StartPos);
CRun.Set_ReviewType(ReviewType);
if (IsPrChange)
CRun.Add_PrChange();
}
else
{
CRun = LRun;
LRun = null;
}
if (null !== LRun)
{
LRun.Selection.Use = true;
LRun.Selection.StartPos = LRun.Content.length;
LRun.Selection.EndPos = LRun.Content.length;
}
CRun.SelectAll(Direction);
if (true === bReview && true !== CRun.Have_PrChange())
CRun.Add_PrChange();
if (undefined === IncFontSize)
CRun.Apply_Pr(TextPr);
else
{
var _TextPr = new CTextPr();
var CurTextPr = this.Get_CompiledPr(false);
CRun.private_AddCollPrChangeMine();
CRun.Set_FontSize(FontSize_IncreaseDecreaseValue(IncFontSize, CurTextPr.FontSize));
}
if (null !== RRun)
{
RRun.Selection.Use = true;
RRun.Selection.StartPos = 0;
RRun.Selection.EndPos = 0;
}
// Дополнительно проверим, если у нас para_End лежит в данном ране и попадает в выделение, тогда
// применим заданные настроки к символу конца параграфа
// TODO: Возможно, стоит на этапе пересчета запонимать, лежит ли para_End в данном ране. Чтобы в каждом
// ране потом не бегать каждый раз по всему массиву в поисках para_End.
if (true === this.Selection_CheckParaEnd())
{
if (undefined === IncFontSize)
{
if (!TextPr.AscFill && !TextPr.AscLine && !TextPr.AscUnifill)
{
this.Paragraph.TextPr.Apply_TextPr(TextPr);
}
else
{
var EndTextPr = this.Paragraph.Get_CompiledPr2(false).TextPr.Copy();
EndTextPr.Merge(this.Paragraph.TextPr.Value);
if (TextPr.AscFill)
{
this.Paragraph.TextPr.Set_TextFill(AscFormat.CorrectUniFill(TextPr.AscFill, EndTextPr.TextFill, 1));
}
if (TextPr.AscUnifill)
{
this.Paragraph.TextPr.Set_Unifill(AscFormat.CorrectUniFill(TextPr.AscUnifill, EndTextPr.Unifill, 0));
}
if (TextPr.AscLine)
{
this.Paragraph.TextPr.Set_TextOutline(AscFormat.CorrectUniStroke(TextPr.AscLine, EndTextPr.TextOutline, 0));
}
}
}
else
{
var Para = this.Paragraph;
// Выставляем настройки для символа параграфа
var EndTextPr = Para.Get_CompiledPr2(false).TextPr.Copy();
EndTextPr.Merge(Para.TextPr.Value);
// TODO: Как только перенесем историю изменений TextPr в сам класс CTextPr, переделать тут
Para.TextPr.Set_FontSize(FontSize_IncreaseDecreaseValue(IncFontSize, EndTextPr.FontSize));
}
}
}
}
else
{
var CurPos = this.State.ContentPos;
// Если выделено не до конца, тогда разделяем по последней точке
if ( CurPos < this.Content.length )
{
RRun = LRun.Split_Run(CurPos);
RRun.Set_ReviewType(ReviewType);
if (IsPrChange)
RRun.Add_PrChange();
}
if ( CurPos > 0 )
{
CRun = LRun.Split_Run(CurPos);
CRun.Set_ReviewType(ReviewType);
if (IsPrChange)
CRun.Add_PrChange();
}
else
{
CRun = LRun;
LRun = null;
}
if ( null !== LRun )
LRun.RemoveSelection();
CRun.RemoveSelection();
CRun.MoveCursorToStartPos();
if (true === bReview && true !== CRun.Have_PrChange())
CRun.Add_PrChange();
if ( undefined === IncFontSize )
{
CRun.Apply_Pr( TextPr );
}
else
{
var _TextPr = new CTextPr();
var CurTextPr = this.Get_CompiledPr( false );
CRun.private_AddCollPrChangeMine();
CRun.Set_FontSize( FontSize_IncreaseDecreaseValue( IncFontSize, CurTextPr.FontSize ) );
}
if ( null !== RRun )
RRun.RemoveSelection();
}
Result.push( LRun );
Result.push( CRun );
Result.push( RRun );
return Result;
}
};
ParaRun.prototype.Split_Run = function(Pos)
{
History.Add(new CChangesRunOnStartSplit(this, Pos));
AscCommon.CollaborativeEditing.OnStart_SplitRun(this, Pos);
// Создаем новый ран
var bMathRun = this.Type == para_Math_Run;
var NewRun = new ParaRun(this.Paragraph, bMathRun);
// Копируем настройки
NewRun.Set_Pr(this.Pr.Copy(true));
if(bMathRun)
NewRun.Set_MathPr(this.MathPrp.Copy());
var OldCrPos = this.State.ContentPos;
var OldSSPos = this.State.Selection.StartPos;
var OldSEPos = this.State.Selection.EndPos;
// Разделяем содержимое по ранам
NewRun.Concat_ToContent( this.Content.slice(Pos) );
this.Remove_FromContent( Pos, this.Content.length - Pos, true );
// Подправим точки селекта и текущей позиции
if ( OldCrPos >= Pos )
{
NewRun.State.ContentPos = OldCrPos - Pos;
this.State.ContentPos = this.Content.length;
}
else
{
NewRun.State.ContentPos = 0;
}
if ( OldSSPos >= Pos )
{
NewRun.State.Selection.StartPos = OldSSPos - Pos;
this.State.Selection.StartPos = this.Content.length;
}
else
{
NewRun.State.Selection.StartPos = 0;
}
if ( OldSEPos >= Pos )
{
NewRun.State.Selection.EndPos = OldSEPos - Pos;
this.State.Selection.EndPos = this.Content.length;
}
else
{
NewRun.State.Selection.EndPos = 0;
}
// Если были точки орфографии, тогда переместим их в новый ран
var SpellingMarksCount = this.SpellingMarks.length;
for ( var Index = 0; Index < SpellingMarksCount; Index++ )
{
var Mark = this.SpellingMarks[Index];
var MarkPos = ( true === Mark.Start ? Mark.Element.StartPos.Get(Mark.Depth) : Mark.Element.EndPos.Get(Mark.Depth) );
if ( MarkPos >= Pos )
{
var MarkElement = Mark.Element;
if ( true === Mark.Start )
{
//MarkElement.ClassesS[Mark.Depth] = NewRun;
MarkElement.StartPos.Data[Mark.Depth] -= Pos;
}
else
{
//MarkElement.ClassesE[Mark.Depth] = NewRun;
MarkElement.EndPos.Data[Mark.Depth] -= Pos;
}
NewRun.SpellingMarks.push( Mark );
this.SpellingMarks.splice( Index, 1 );
SpellingMarksCount--;
Index--;
}
}
History.Add(new CChangesRunOnEndSplit(this, NewRun));
AscCommon.CollaborativeEditing.OnEnd_SplitRun(NewRun);
return NewRun;
};
ParaRun.prototype.Clear_TextPr = function()
{
// Данная функция вызывается пока только при изменении стиля параграфа. Оставляем в этой ситуации язык неизмененным,
// а также не трогаем highlight.
var NewTextPr = new CTextPr();
NewTextPr.Lang = this.Pr.Lang.Copy();
NewTextPr.HighLight = this.Pr.Copy_HighLight();
this.Set_Pr( NewTextPr );
};
// В данной функции мы применяем приходящие настройки поверх старых, т.е. старые не удаляем
ParaRun.prototype.Apply_Pr = function(TextPr)
{
this.private_AddCollPrChangeMine();
if(this.Type == para_Math_Run && false === this.IsNormalText())
{
if(null === TextPr.Bold && null === TextPr.Italic)
this.Math_Apply_Style(undefined);
else
{
if(undefined != TextPr.Bold)
{
if(TextPr.Bold == true)
{
if(this.MathPrp.sty == STY_ITALIC || this.MathPrp.sty == undefined)
this.Math_Apply_Style(STY_BI);
else if(this.MathPrp.sty == STY_PLAIN)
this.Math_Apply_Style(STY_BOLD);
}
else if(TextPr.Bold == false || TextPr.Bold == null)
{
if(this.MathPrp.sty == STY_BI || this.MathPrp.sty == undefined)
this.Math_Apply_Style(STY_ITALIC);
else if(this.MathPrp.sty == STY_BOLD)
this.Math_Apply_Style(STY_PLAIN);
}
}
if(undefined != TextPr.Italic)
{
if(TextPr.Italic == true)
{
if(this.MathPrp.sty == STY_BOLD)
this.Math_Apply_Style(STY_BI);
else if(this.MathPrp.sty == STY_PLAIN || this.MathPrp.sty == undefined)
this.Math_Apply_Style(STY_ITALIC);
}
else if(TextPr.Italic == false || TextPr.Italic == null)
{
if(this.MathPrp.sty == STY_BI)
this.Math_Apply_Style(STY_BOLD);
else if(this.MathPrp.sty == STY_ITALIC || this.MathPrp.sty == undefined)
this.Math_Apply_Style(STY_PLAIN);
}
}
}
}
else
{
if ( undefined != TextPr.Bold )
this.Set_Bold( null === TextPr.Bold ? undefined : TextPr.Bold );
if( undefined != TextPr.Italic )
this.Set_Italic( null === TextPr.Italic ? undefined : TextPr.Italic );
}
if ( undefined != TextPr.Strikeout )
this.Set_Strikeout( null === TextPr.Strikeout ? undefined : TextPr.Strikeout );
if ( undefined !== TextPr.Underline )
this.Set_Underline( null === TextPr.Underline ? undefined : TextPr.Underline );
if ( undefined != TextPr.FontSize )
this.Set_FontSize( null === TextPr.FontSize ? undefined : TextPr.FontSize );
if ( undefined !== TextPr.Color && undefined === TextPr.Unifill )
{
this.Set_Color( null === TextPr.Color ? undefined : TextPr.Color );
this.Set_Unifill( undefined );
this.Set_TextFill(undefined);
}
if ( undefined !== TextPr.Unifill )
{
this.Set_Unifill(null === TextPr.Unifill ? undefined : TextPr.Unifill);
this.Set_Color(undefined);
this.Set_TextFill(undefined);
}
else if(undefined !== TextPr.AscUnifill && this.Paragraph)
{
if(!this.Paragraph.bFromDocument)
{
var oCompiledPr = this.Get_CompiledPr(true);
this.Set_Unifill(AscFormat.CorrectUniFill(TextPr.AscUnifill, oCompiledPr.Unifill, 0), AscCommon.isRealObject(TextPr.AscUnifill) && TextPr.AscUnifill.asc_CheckForseSet() );
this.Set_Color(undefined);
this.Set_TextFill(undefined);
}
}
if(undefined !== TextPr.TextFill)
{
this.Set_Unifill(undefined);
this.Set_Color(undefined);
this.Set_TextFill(null === TextPr.TextFill ? undefined : TextPr.TextFill);
}
else if(undefined !== TextPr.AscFill && this.Paragraph)
{
var oMergeUnifill, oColor;
if(this.Paragraph.bFromDocument)
{
var oCompiledPr = this.Get_CompiledPr(true);
if(oCompiledPr.TextFill)
{
oMergeUnifill = oCompiledPr.TextFill;
}
else if(oCompiledPr.Unifill)
{
oMergeUnifill = oCompiledPr.Unifill;
}
else if(oCompiledPr.Color)
{
oColor = oCompiledPr.Color;
oMergeUnifill = AscFormat.CreateUnfilFromRGB(oColor.r, oColor.g, oColor.b);
}
this.Set_Unifill(undefined);
this.Set_Color(undefined);
this.Set_TextFill(AscFormat.CorrectUniFill(TextPr.AscFill, oMergeUnifill, 1), AscCommon.isRealObject(TextPr.AscFill) && TextPr.AscFill.asc_CheckForseSet());
}
}
if(undefined !== TextPr.TextOutline)
{
this.Set_TextOutline(null === TextPr.TextOutline ? undefined : TextPr.TextOutline);
}
else if(undefined !== TextPr.AscLine && this.Paragraph)
{
var oCompiledPr = this.Get_CompiledPr(true);
this.Set_TextOutline(AscFormat.CorrectUniStroke(TextPr.AscLine, oCompiledPr.TextOutline, 0));
}
if ( undefined != TextPr.VertAlign )
this.Set_VertAlign( null === TextPr.VertAlign ? undefined : TextPr.VertAlign );
if ( undefined != TextPr.HighLight )
this.Set_HighLight( null === TextPr.HighLight ? undefined : TextPr.HighLight );
if ( undefined !== TextPr.RStyle )
this.Set_RStyle( null === TextPr.RStyle ? undefined : TextPr.RStyle );
if ( undefined != TextPr.Spacing )
this.Set_Spacing( null === TextPr.Spacing ? undefined : TextPr.Spacing );
if ( undefined != TextPr.DStrikeout )
this.Set_DStrikeout( null === TextPr.DStrikeout ? undefined : TextPr.DStrikeout );
if ( undefined != TextPr.Caps )
this.Set_Caps( null === TextPr.Caps ? undefined : TextPr.Caps );
if ( undefined != TextPr.SmallCaps )
this.Set_SmallCaps( null === TextPr.SmallCaps ? undefined : TextPr.SmallCaps );
if ( undefined != TextPr.Position )
this.Set_Position( null === TextPr.Position ? undefined : TextPr.Position );
if ( undefined != TextPr.RFonts )
{
if(this.Type == para_Math_Run && !this.IsNormalText()) // при смене Font в этом случае (даже на Cambria Math) cs, eastAsia не меняются
{
// только для редактирования
// делаем так для проверки действительно ли нужно сменить Font, чтобы при смене других текстовых настроек не выставился Cambria Math (TextPr.RFonts приходит всегда в виде объекта)
if(TextPr.RFonts.Ascii !== undefined || TextPr.RFonts.HAnsi !== undefined)
{
var RFonts = new CRFonts();
RFonts.Set_All("Cambria Math", -1);
this.Set_RFonts2(RFonts);
}
}
else
this.Set_RFonts2(TextPr.RFonts);
}
if ( undefined != TextPr.Lang )
this.Set_Lang2( TextPr.Lang );
if ( undefined !== TextPr.Shd )
this.Set_Shd( TextPr.Shd );
};
ParaRun.prototype.Have_PrChange = function()
{
return this.Pr.Have_PrChange();
};
ParaRun.prototype.Get_PrReviewColor = function()
{
if (this.Pr.ReviewInfo)
return this.Pr.ReviewInfo.Get_Color();
return REVIEW_COLOR;
};
ParaRun.prototype.Add_PrChange = function()
{
if (false === this.Have_PrChange())
{
this.Pr.Add_PrChange();
History.Add(new CChangesRunPrChange(this,
{
PrChange : undefined,
ReviewInfo : undefined
},
{
PrChange : this.Pr.PrChange,
ReviewInfo : this.Pr.ReviewInfo
}));
this.private_UpdateTrackRevisions();
}
};
ParaRun.prototype.Set_PrChange = function(PrChange, ReviewInfo)
{
History.Add(new CChangesRunPrChange(this,
{
PrChange : this.Pr.PrChange,
ReviewInfo : this.Pr.ReviewInfo ? this.Pr.ReviewInfo.Copy() : undefined
},
{
PrChange : PrChange,
ReviewInfo : ReviewInfo ? ReviewInfo.Copy() : undefined
}));
this.Pr.Set_PrChange(PrChange, ReviewInfo);
this.private_UpdateTrackRevisions();
};
ParaRun.prototype.Remove_PrChange = function()
{
if (true === this.Have_PrChange())
{
History.Add(new CChangesRunPrChange(this,
{
PrChange : this.Pr.PrChange,
ReviewInfo : this.Pr.ReviewInfo
},
{
PrChange : undefined,
ReviewInfo : undefined
}));
this.Pr.Remove_PrChange();
this.private_UpdateTrackRevisions();
}
};
ParaRun.prototype.Reject_PrChange = function()
{
if (true === this.Have_PrChange())
{
this.Set_Pr(this.Pr.PrChange);
this.Remove_PrChange();
}
};
ParaRun.prototype.Accept_PrChange = function()
{
this.Remove_PrChange();
};
ParaRun.prototype.Get_DiffPrChange = function()
{
return this.Pr.Get_DiffPrChange();
};
ParaRun.prototype.Set_Bold = function(Value)
{
if ( Value !== this.Pr.Bold )
{
var OldValue = this.Pr.Bold;
this.Pr.Bold = Value;
History.Add(new CChangesRunBold(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(true);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Get_Bold = function()
{
return this.Get_CompiledPr(false).Bold;
};
ParaRun.prototype.Set_Italic = function(Value)
{
if ( Value !== this.Pr.Italic )
{
var OldValue = this.Pr.Italic;
this.Pr.Italic = Value;
History.Add(new CChangesRunItalic(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(true);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Get_Italic = function()
{
return this.Get_CompiledPr(false).Italic;
};
ParaRun.prototype.Set_Strikeout = function(Value)
{
if ( Value !== this.Pr.Strikeout )
{
var OldValue = this.Pr.Strikeout;
this.Pr.Strikeout = Value;
History.Add(new CChangesRunStrikeout(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(false);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Get_Strikeout = function()
{
return this.Get_CompiledPr(false).Strikeout;
};
ParaRun.prototype.Set_Underline = function(Value)
{
if ( Value !== this.Pr.Underline )
{
var OldValue = this.Pr.Underline;
this.Pr.Underline = Value;
History.Add(new CChangesRunUnderline(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(false);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Get_Underline = function()
{
return this.Get_CompiledPr(false).Underline;
};
ParaRun.prototype.Set_FontSize = function(Value)
{
if ( Value !== this.Pr.FontSize )
{
var OldValue = this.Pr.FontSize;
this.Pr.FontSize = Value;
History.Add(new CChangesRunFontSize(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(true);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Get_FontSize = function()
{
return this.Get_CompiledPr(false).FontSize;
};
ParaRun.prototype.Set_Color = function(Value)
{
if ( ( undefined === Value && undefined !== this.Pr.Color ) || ( Value instanceof CDocumentColor && ( undefined === this.Pr.Color || false === Value.Compare(this.Pr.Color) ) ) )
{
var OldValue = this.Pr.Color;
this.Pr.Color = Value;
History.Add(new CChangesRunColor(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(false);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Set_Unifill = function(Value, bForce)
{
if ( ( undefined === Value && undefined !== this.Pr.Unifill ) || ( Value instanceof AscFormat.CUniFill && ( undefined === this.Pr.Unifill || false === AscFormat.CompareUnifillBool(this.Pr.Unifill, Value) ) ) || bForce )
{
var OldValue = this.Pr.Unifill;
this.Pr.Unifill = Value;
History.Add(new CChangesRunUnifill(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(false);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Set_TextFill = function(Value, bForce)
{
if ( ( undefined === Value && undefined !== this.Pr.TextFill ) || ( Value instanceof AscFormat.CUniFill && ( undefined === this.Pr.TextFill || false === AscFormat.CompareUnifillBool(this.Pr.TextFill.IsIdentical, Value) ) ) || bForce )
{
var OldValue = this.Pr.TextFill;
this.Pr.TextFill = Value;
History.Add(new CChangesRunTextFill(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(false);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Set_TextOutline = function(Value)
{
if ( ( undefined === Value && undefined !== this.Pr.TextOutline ) || ( Value instanceof AscFormat.CLn && ( undefined === this.Pr.TextOutline || false === this.Pr.TextOutline.IsIdentical(Value) ) ) )
{
var OldValue = this.Pr.TextOutline;
this.Pr.TextOutline = Value;
History.Add(new CChangesRunTextOutline(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(false);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Get_Color = function()
{
return this.Get_CompiledPr(false).Color;
};
ParaRun.prototype.Set_VertAlign = function(Value)
{
if ( Value !== this.Pr.VertAlign )
{
var OldValue = this.Pr.VertAlign;
this.Pr.VertAlign = Value;
History.Add(new CChangesRunVertAlign(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(true);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Get_VertAlign = function()
{
return this.Get_CompiledPr(false).VertAlign;
};
ParaRun.prototype.Set_HighLight = function(Value)
{
var OldValue = this.Pr.HighLight;
if ( (undefined === Value && undefined !== OldValue) || ( highlight_None === Value && highlight_None !== OldValue ) || ( Value instanceof CDocumentColor && ( undefined === OldValue || highlight_None === OldValue || false === Value.Compare(OldValue) ) ) )
{
this.Pr.HighLight = Value;
History.Add(new CChangesRunHighLight(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(false);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Get_HighLight = function()
{
return this.Get_CompiledPr(false).HighLight;
};
ParaRun.prototype.Set_RStyle = function(Value)
{
if ( Value !== this.Pr.RStyle )
{
var OldValue = this.Pr.RStyle;
this.Pr.RStyle = Value;
History.Add(new CChangesRunRStyle(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(true);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Get_RStyle = function()
{
return this.Get_CompiledPr(false).RStyle;
};
ParaRun.prototype.Set_Spacing = function(Value)
{
if (Value !== this.Pr.Spacing)
{
var OldValue = this.Pr.Spacing;
this.Pr.Spacing = Value;
History.Add(new CChangesRunSpacing(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(true);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Get_Spacing = function()
{
return this.Get_CompiledPr(false).Spacing;
};
ParaRun.prototype.Set_DStrikeout = function(Value)
{
if ( Value !== this.Pr.Value )
{
var OldValue = this.Pr.DStrikeout;
this.Pr.DStrikeout = Value;
History.Add(new CChangesRunDStrikeout(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(false);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Get_DStrikeout = function()
{
return this.Get_CompiledPr(false).DStrikeout;
};
ParaRun.prototype.Set_Caps = function(Value)
{
if ( Value !== this.Pr.Caps )
{
var OldValue = this.Pr.Caps;
this.Pr.Caps = Value;
History.Add(new CChangesRunCaps(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(true);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Get_Caps = function()
{
return this.Get_CompiledPr(false).Caps;
};
ParaRun.prototype.Set_SmallCaps = function(Value)
{
if ( Value !== this.Pr.SmallCaps )
{
var OldValue = this.Pr.SmallCaps;
this.Pr.SmallCaps = Value;
History.Add(new CChangesRunSmallCaps(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(true);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Get_SmallCaps = function()
{
return this.Get_CompiledPr(false).SmallCaps;
};
ParaRun.prototype.Set_Position = function(Value)
{
if ( Value !== this.Pr.Position )
{
var OldValue = this.Pr.Position;
this.Pr.Position = Value;
History.Add(new CChangesRunPosition(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(false);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
this.YOffset = this.Get_Position();
}
};
ParaRun.prototype.Get_Position = function()
{
return this.Get_CompiledPr(false).Position;
};
ParaRun.prototype.Set_RFonts = function(Value)
{
var OldValue = this.Pr.RFonts;
this.Pr.RFonts = Value;
History.Add(new CChangesRunRFonts(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(true);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
};
ParaRun.prototype.Get_RFonts = function()
{
return this.Get_CompiledPr(false).RFonts;
};
ParaRun.prototype.Set_RFonts2 = function(RFonts)
{
if ( undefined != RFonts )
{
if ( undefined != RFonts.Ascii )
this.Set_RFonts_Ascii( RFonts.Ascii );
if ( undefined != RFonts.HAnsi )
this.Set_RFonts_HAnsi( RFonts.HAnsi );
if ( undefined != RFonts.CS )
this.Set_RFonts_CS( RFonts.CS );
if ( undefined != RFonts.EastAsia )
this.Set_RFonts_EastAsia( RFonts.EastAsia );
if ( undefined != RFonts.Hint )
this.Set_RFonts_Hint( RFonts.Hint );
}
else
{
this.Set_RFonts_Ascii( undefined );
this.Set_RFonts_HAnsi( undefined );
this.Set_RFonts_CS( undefined );
this.Set_RFonts_EastAsia( undefined );
this.Set_RFonts_Hint( undefined );
}
};
ParaRun.prototype.Set_RFont_ForMathRun = function()
{
this.Set_RFonts_Ascii({Name : "Cambria Math", Index : -1});
this.Set_RFonts_CS({Name : "Cambria Math", Index : -1});
this.Set_RFonts_EastAsia({Name : "Cambria Math", Index : -1});
this.Set_RFonts_HAnsi({Name : "Cambria Math", Index : -1});
};
ParaRun.prototype.Set_RFonts_Ascii = function(Value)
{
if ( Value !== this.Pr.RFonts.Ascii )
{
var OldValue = this.Pr.RFonts.Ascii;
this.Pr.RFonts.Ascii = Value;
History.Add(new CChangesRunRFontsAscii(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(true);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Set_RFonts_HAnsi = function(Value)
{
if ( Value !== this.Pr.RFonts.HAnsi )
{
var OldValue = this.Pr.RFonts.HAnsi;
this.Pr.RFonts.HAnsi = Value;
History.Add(new CChangesRunRFontsHAnsi(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(true);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Set_RFonts_CS = function(Value)
{
if ( Value !== this.Pr.RFonts.CS )
{
var OldValue = this.Pr.RFonts.CS;
this.Pr.RFonts.CS = Value;
History.Add(new CChangesRunRFontsCS(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(true);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Set_RFonts_EastAsia = function(Value)
{
if ( Value !== this.Pr.RFonts.EastAsia )
{
var OldValue = this.Pr.RFonts.EastAsia;
this.Pr.RFonts.EastAsia = Value;
History.Add(new CChangesRunRFontsEastAsia(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(true);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Set_RFonts_Hint = function(Value)
{
if ( Value !== this.Pr.RFonts.Hint )
{
var OldValue = this.Pr.RFonts.Hint;
this.Pr.RFonts.Hint = Value;
History.Add(new CChangesRunRFontsHint(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(true);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Set_Lang = function(Value)
{
var OldValue = this.Pr.Lang;
this.Pr.Lang = new CLang();
if ( undefined != Value )
this.Pr.Lang.Set_FromObject( Value );
History.Add(new CChangesRunLang(this, OldValue, this.Pr.Lang, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(false);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
};
ParaRun.prototype.Set_Lang2 = function(Lang)
{
if ( undefined != Lang )
{
if ( undefined != Lang.Bidi )
this.Set_Lang_Bidi( Lang.Bidi );
if ( undefined != Lang.EastAsia )
this.Set_Lang_EastAsia( Lang.EastAsia );
if ( undefined != Lang.Val )
this.Set_Lang_Val( Lang.Val );
this.protected_UpdateSpellChecking();
}
};
ParaRun.prototype.Set_Lang_Bidi = function(Value)
{
if ( Value !== this.Pr.Lang.Bidi )
{
var OldValue = this.Pr.Lang.Bidi;
this.Pr.Lang.Bidi = Value;
History.Add(new CChangesRunLangBidi(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(false);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Set_Lang_EastAsia = function(Value)
{
if ( Value !== this.Pr.Lang.EastAsia )
{
var OldValue = this.Pr.Lang.EastAsia;
this.Pr.Lang.EastAsia = Value;
History.Add(new CChangesRunLangEastAsia(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(false);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Set_Lang_Val = function(Value)
{
if ( Value !== this.Pr.Lang.Val )
{
var OldValue = this.Pr.Lang.Val;
this.Pr.Lang.Val = Value;
History.Add(new CChangesRunLangVal(this, OldValue, Value, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(false);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.Set_Shd = function(Shd)
{
if ( (undefined === this.Pr.Shd && undefined === Shd) || (undefined !== this.Pr.Shd && undefined !== Shd && true === this.Pr.Shd.Compare( Shd ) ) )
return;
var OldShd = this.Pr.Shd;
if ( undefined !== Shd )
{
this.Pr.Shd = new CDocumentShd();
this.Pr.Shd.Set_FromObject( Shd );
}
else
this.Pr.Shd = undefined;
History.Add(new CChangesRunShd(this, OldShd, this.Pr.Shd, this.private_IsCollPrChangeMine()));
this.Recalc_CompiledPr(false);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
};
//-----------------------------------------------------------------------------------
// Undo/Redo функции
//-----------------------------------------------------------------------------------
ParaRun.prototype.Check_HistoryUninon = function(Data1, Data2)
{
var Type1 = Data1.Type;
var Type2 = Data2.Type;
if ( AscDFH.historyitem_ParaRun_AddItem === Type1 && AscDFH.historyitem_ParaRun_AddItem === Type2 )
{
if ( 1 === Data1.Items.length && 1 === Data2.Items.length && Data1.Pos === Data2.Pos - 1 && para_Text === Data1.Items[0].Type && para_Text === Data2.Items[0].Type )
return true;
}
return false;
};
//-----------------------------------------------------------------------------------
// Функции для совместного редактирования
//-----------------------------------------------------------------------------------
ParaRun.prototype.Write_ToBinary2 = function(Writer)
{
Writer.WriteLong( AscDFH.historyitem_type_ParaRun );
// Long : Type
// String : Id
// String : Paragraph Id
// Variable : CTextPr
// Long : ReviewType
// Bool : isUndefined ReviewInfo
// ->false : ReviewInfo
// Long : Количество элементов
// Array of variable : массив с элементами
Writer.WriteLong(this.Type);
var ParagraphToWrite, PrToWrite, ContentToWrite;
if(this.StartState)
{
ParagraphToWrite = this.StartState.Paragraph;
PrToWrite = this.StartState.Pr;
ContentToWrite = this.StartState.Content;
}
else
{
ParagraphToWrite = this.Paragraph;
PrToWrite = this.Pr;
ContentToWrite = this.Content;
}
Writer.WriteString2( this.Id );
Writer.WriteString2( null !== ParagraphToWrite && undefined !== ParagraphToWrite ? ParagraphToWrite.Get_Id() : "" );
PrToWrite.Write_ToBinary( Writer );
Writer.WriteLong(this.ReviewType);
if (this.ReviewInfo)
{
Writer.WriteBool(false);
this.ReviewInfo.Write_ToBinary(Writer);
}
else
{
Writer.WriteBool(true);
}
var Count = ContentToWrite.length;
Writer.WriteLong( Count );
for ( var Index = 0; Index < Count; Index++ )
{
var Item = ContentToWrite[Index];
Item.Write_ToBinary( Writer );
}
};
ParaRun.prototype.Read_FromBinary2 = function(Reader)
{
// Long : Type
// String : Id
// String : Paragraph Id
// Variable : CTextPr
// Long : ReviewType
// Bool : isUndefined ReviewInfo
// ->false : ReviewInfo
// Long : Количество элементов
// Array of variable : массив с элементами
this.Type = Reader.GetLong();
this.Id = Reader.GetString2();
this.Paragraph = g_oTableId.Get_ById( Reader.GetString2() );
this.Pr = new CTextPr();
this.Pr.Read_FromBinary( Reader );
this.ReviewType = Reader.GetLong();
this.ReviewInfo = new CReviewInfo();
if (false === Reader.GetBool())
this.ReviewInfo.Read_FromBinary(Reader);
if (para_Math_Run == this.Type)
{
this.MathPrp = new CMPrp();
this.size = new CMathSize();
this.pos = new CMathPosition();
}
if(undefined !== editor && true === editor.isDocumentEditor)
{
var Count = Reader.GetLong();
this.Content = [];
for ( var Index = 0; Index < Count; Index++ )
{
var Element = ParagraphContent_Read_FromBinary( Reader );
if ( null !== Element )
this.Content.push( Element );
}
}
};
ParaRun.prototype.Clear_CollaborativeMarks = function()
{
this.CollaborativeMarks.Clear();
this.CollPrChangeOther = false;
};
ParaRun.prototype.private_AddCollPrChangeMine = function()
{
this.CollPrChangeMine = true;
this.CollPrChangeOther = false;
};
ParaRun.prototype.private_IsCollPrChangeMine = function()
{
if (true === this.CollPrChangeMine)
return true;
return false;
};
ParaRun.prototype.private_AddCollPrChangeOther = function(Color)
{
this.CollPrChangeOther = Color;
AscCommon.CollaborativeEditing.Add_ChangedClass(this);
};
ParaRun.prototype.private_GetCollPrChangeOther = function()
{
return this.CollPrChangeOther;
};
ParaRun.prototype.private_RecalcCtrPrp = function()
{
if (para_Math_Run === this.Type && undefined !== this.Parent && null !== this.Parent && null !== this.Parent.ParaMath)
this.Parent.ParaMath.SetRecalcCtrPrp(this);
};
function CParaRunSelection()
{
this.Use = false;
this.StartPos = 0;
this.EndPos = 0;
}
function CParaRunState()
{
this.Selection = new CParaRunSelection();
this.ContentPos = 0;
}
function CParaRunRecalcInfo()
{
this.TextPr = true; // Нужно ли пересчитать скомпилированные настройки
this.Measure = true; // Нужно ли перемерять элементы
this.Recalc = true; // Нужно ли пересчитывать (только если текстовый ран)
this.RunLen = 0;
// Далее идут параметры, которые выставляются после пересчета данного Range, такие как пересчитывать ли нумерацию
this.NumberingItem = null;
this.NumberingUse = false; // Используется ли нумерация в данном ране
this.NumberingAdd = true; // Нужно ли в следующем ране использовать нумерацию
}
CParaRunRecalcInfo.prototype =
{
Reset : function()
{
this.TextPr = true;
this.Measure = true;
this.Recalc = true;
this.RunLen = 0;
}
};
function CParaRunRange(StartPos, EndPos)
{
this.StartPos = StartPos; // Начальная позиция в контенте, с которой начинается данный отрезок
this.EndPos = EndPos; // Конечная позиция в контенте, на которой заканчивается данный отрезок (перед которой)
}
function CParaRunLine()
{
this.Ranges = [];
this.Ranges[0] = new CParaRunRange( 0, 0 );
this.RangesLength = 0;
}
CParaRunLine.prototype =
{
Add_Range : function(RangeIndex, StartPos, EndPos)
{
if ( 0 !== RangeIndex )
{
this.Ranges[RangeIndex] = new CParaRunRange( StartPos, EndPos );
this.RangesLength = RangeIndex + 1;
}
else
{
this.Ranges[0].StartPos = StartPos;
this.Ranges[0].EndPos = EndPos;
this.RangesLength = 1;
}
if ( this.Ranges.length > this.RangesLength )
this.Ranges.legth = this.RangesLength;
},
Copy : function()
{
var NewLine = new CParaRunLine();
NewLine.RangesLength = this.RangesLength;
for ( var CurRange = 0; CurRange < this.RangesLength; CurRange++ )
{
var Range = this.Ranges[CurRange];
NewLine.Ranges[CurRange] = new CParaRunRange( Range.StartPos, Range.EndPos );
}
return NewLine;
},
Compare : function(OtherLine, CurRange)
{
// Сначала проверим наличие данного отрезка в обеих строках
if ( this.RangesLength <= CurRange || OtherLine.RangesLength <= CurRange )
return false;
var OtherRange = OtherLine.Ranges[CurRange];
var ThisRange = this.Ranges[CurRange];
if ( OtherRange.StartPos !== ThisRange.StartPos || OtherRange.EndPos !== ThisRange.EndPos )
return false;
return true;
}
};
// Метка о конце или начале изменений пришедших от других соавторов документа
var pararun_CollaborativeMark_Start = 0x00;
var pararun_CollaborativeMark_End = 0x01;
function CParaRunCollaborativeMark(Pos, Type)
{
this.Pos = Pos;
this.Type = Type;
}
function FontSize_IncreaseDecreaseValue(bIncrease, Value)
{
// Закон изменения размеров :
// 1. Если значение меньше 8, тогда мы увеличиваем/уменьшаем по 1 (от 1 до 8)
// 2. Если значение больше 72, тогда мы увеличиваем/уменьшаем по 10 (от 80 до бесконечности
// 3. Если значение в отрезке [8,72], тогда мы переходим по следующим числам 8,9,10,11,12,14,16,18,20,22,24,26,28,36,48,72
var Sizes = [8,9,10,11,12,14,16,18,20,22,24,26,28,36,48,72];
var NewValue = Value;
if ( true === bIncrease )
{
if ( Value < Sizes[0] )
{
if ( Value >= Sizes[0] - 1 )
NewValue = Sizes[0];
else
NewValue = Math.floor(Value + 1);
}
else if ( Value >= Sizes[Sizes.length - 1] )
{
NewValue = Math.min( 300, Math.floor( Value / 10 + 1 ) * 10 );
}
else
{
for ( var Index = 0; Index < Sizes.length; Index++ )
{
if ( Value < Sizes[Index] )
{
NewValue = Sizes[Index];
break;
}
}
}
}
else
{
if ( Value <= Sizes[0] )
{
NewValue = Math.max( Math.floor( Value - 1 ), 1 );
}
else if ( Value > Sizes[Sizes.length - 1] )
{
if ( Value <= Math.floor( Sizes[Sizes.length - 1] / 10 + 1 ) * 10 )
NewValue = Sizes[Sizes.length - 1];
else
NewValue = Math.floor( Math.ceil(Value / 10) - 1 ) * 10;
}
else
{
for ( var Index = Sizes.length - 1; Index >= 0; Index-- )
{
if ( Value > Sizes[Index] )
{
NewValue = Sizes[Index];
break;
}
}
}
}
return NewValue;
}
function CRunCollaborativeMarks()
{
this.Ranges = [];
this.DrawingObj = {};
}
CRunCollaborativeMarks.prototype =
{
Add : function(PosS, PosE, Color)
{
var Count = this.Ranges.length;
for ( var Index = 0; Index < Count; Index++ )
{
var Range = this.Ranges[Index];
if ( PosS > Range.PosE )
continue;
else if ( PosS >= Range.PosS && PosS <= Range.PosE && PosE >= Range.PosS && PosE <= Range.PosE )
{
if ( true !== Color.Compare(Range.Color) )
{
var _PosE = Range.PosE;
Range.PosE = PosS;
this.Ranges.splice( Index + 1, 0, new CRunCollaborativeRange(PosS, PosE, Color) );
this.Ranges.splice( Index + 2, 0, new CRunCollaborativeRange(PosE, _PosE, Range.Color) );
}
return;
}
else if ( PosE < Range.PosS )
{
this.Ranges.splice( Index, 0, new CRunCollaborativeRange(PosS, PosE, Color) );
return;
}
else if ( PosS < Range.PosS && PosE > Range.PosE )
{
Range.PosS = PosS;
Range.PosE = PosE;
Range.Color = Color;
return;
}
else if ( PosS < Range.PosS ) // && PosE <= Range.PosE )
{
if ( true === Color.Compare(Range.Color) )
Range.PosS = PosS;
else
{
Range.PosS = PosE;
this.Ranges.splice( Index, 0, new CRunCollaborativeRange(PosS, PosE, Color) );
}
return;
}
else //if ( PosS >= Range.PosS && PosE > Range.Pos.E )
{
if ( true === Color.Compare(Range.Color) )
Range.PosE = PosE;
else
{
Range.PosE = PosS;
this.Ranges.splice( Index + 1, 0, new CRunCollaborativeRange(PosS, PosE, Color) );
}
return;
}
}
this.Ranges.push( new CRunCollaborativeRange(PosS, PosE, Color) );
},
Update_OnAdd : function(Pos)
{
var Count = this.Ranges.length;
for ( var Index = 0; Index < Count; Index++ )
{
var Range = this.Ranges[Index];
if ( Pos <= Range.PosS )
{
Range.PosS++;
Range.PosE++;
}
else if ( Pos > Range.PosS && Pos < Range.PosE )
{
var NewRange = new CRunCollaborativeRange( Pos + 1, Range.PosE + 1, Range.Color.Copy() );
this.Ranges.splice( Index + 1, 0, NewRange );
Range.PosE = Pos;
Count++;
Index++;
}
//else if ( Pos < Range.PosE )
// Range.PosE++;
}
},
Update_OnRemove : function(Pos, Count)
{
var Len = this.Ranges.length;
for ( var Index = 0; Index < Len; Index++ )
{
var Range = this.Ranges[Index];
var PosE = Pos + Count;
if ( Pos < Range.PosS )
{
if ( PosE <= Range.PosS )
{
Range.PosS -= Count;
Range.PosE -= Count;
}
else if ( PosE >= Range.PosE )
{
this.Ranges.splice( Index, 1 );
Len--;
Index--;continue;
}
else
{
Range.PosS = Pos;
Range.PosE -= Count;
}
}
else if ( Pos >= Range.PosS && Pos < Range.PosE )
{
if ( PosE >= Range.PosE )
Range.PosE = Pos;
else
Range.PosE -= Count;
}
else
continue;
}
},
Clear : function()
{
this.Ranges = [];
},
Init_Drawing : function()
{
this.DrawingObj = {};
var Count = this.Ranges.length;
for ( var CurPos = 0; CurPos < Count; CurPos++ )
{
var Range = this.Ranges[CurPos];
for ( var Pos = Range.PosS; Pos < Range.PosE; Pos++ )
this.DrawingObj[Pos] = Range.Color;
}
},
Check : function(Pos)
{
if ( undefined !== this.DrawingObj[Pos] )
return this.DrawingObj[Pos];
return null;
}
};
function CRunCollaborativeRange(PosS, PosE, Color)
{
this.PosS = PosS;
this.PosE = PosE;
this.Color = Color;
}
ParaRun.prototype.Math_SetPosition = function(pos, PosInfo)
{
var Line = PosInfo.CurLine,
Range = PosInfo.CurRange;
var CurLine = Line - this.StartLine;
var CurRange = ( 0 === CurLine ? Range - this.StartRange : Range );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
// запомним позицию для Recalculate_CurPos, когда Run пустой
this.pos.x = pos.x;
this.pos.y = pos.y;
for(var Pos = StartPos; Pos < EndPos; Pos++)
{
var Item = this.Content[Pos];
if(PosInfo.DispositionOpers !== null && Item.Type == para_Math_BreakOperator)
{
PosInfo.DispositionOpers.push(pos.x + Item.GapLeft);
}
this.Content[Pos].setPosition(pos);
pos.x += this.Content[Pos].Get_WidthVisible(); // Get_Width => Get_WidthVisible
// Get_WidthVisible - Width + Gaps с учетом настроек состояния
}
};
ParaRun.prototype.Math_Get_StartRangePos = function(_CurLine, _CurRange, SearchPos, Depth, bStartLine)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var Pos = this.State.ContentPos;
var Result = true;
if(bStartLine || StartPos < Pos)
{
SearchPos.Pos.Update(StartPos, Depth);
}
else
{
Result = false;
}
return Result;
};
ParaRun.prototype.Math_Get_EndRangePos = function(_CurLine, _CurRange, SearchPos, Depth, bEndLine)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
var Pos = this.State.ContentPos;
var Result = true;
if(bEndLine || Pos < EndPos)
{
SearchPos.Pos.Update(EndPos, Depth);
}
else
{
Result = false;
}
return Result;
};
ParaRun.prototype.Math_Is_End = function(_CurLine, _CurRange)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
return EndPos == this.Content.length;
};
ParaRun.prototype.IsEmptyRange = function(_CurLine, _CurRange)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
return StartPos == EndPos;
};
ParaRun.prototype.Recalculate_Range_OneLine = function(PRS, ParaPr, Depth)
{
// данная функция используется только для мат объектов, которые на строки не разбиваются
// ParaText (ParagraphContent.js)
// для настройки TextPr
// Measure
// FontClassification.js
// Get_FontClass
var Lng = this.Content.length;
var CurLine = PRS.Line - this.StartLine;
var CurRange = ( 0 === CurLine ? PRS.Range - this.StartRange : PRS.Range );
// обновляем позиции start и end для Range
var RangeStartPos = this.protected_AddRange(CurLine, CurRange);
var RangeEndPos = Lng;
this.Math_RecalculateContent(PRS);
this.protected_FillRange(CurLine, CurRange, RangeStartPos, RangeEndPos);
};
ParaRun.prototype.Math_RecalculateContent = function(PRS)
{
var WidthPoints = this.Parent.Get_WidthPoints();
this.bEqArray = this.Parent.IsEqArray();
var ascent = 0, descent = 0, width = 0;
this.Recalculate_MeasureContent();
var Lng = this.Content.length;
for(var i = 0 ; i < Lng; i++)
{
var Item = this.Content[i];
var size = Item.size,
Type = Item.Type;
var WidthItem = Item.Get_WidthVisible(); // Get_Width => Get_WidthVisible
// Get_WidthVisible - Width + Gaps с учетом настроек состояния
width += WidthItem;
if(ascent < size.ascent)
ascent = size.ascent;
if (descent < size.height - size.ascent)
descent = size.height - size.ascent;
if(this.bEqArray)
{
if(Type === para_Math_Ampersand && true === Item.IsAlignPoint())
{
WidthPoints.AddNewAlignRange();
}
else
{
WidthPoints.UpdatePoint(WidthItem);
}
}
}
this.size.width = width;
this.size.ascent = ascent;
this.size.height = ascent + descent;
};
ParaRun.prototype.Math_Set_EmptyRange = function(_CurLine, _CurRange)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = (0 === CurLine ? _CurRange - this.StartRange : _CurRange);
var RangeStartPos = this.protected_AddRange(CurLine, CurRange);
var RangeEndPos = RangeStartPos;
this.protected_FillRange(CurLine, CurRange, RangeStartPos, RangeEndPos);
};
// в этой функции проставляем состояние Gaps (крайние или нет) для всех операторов, к-ые участвуют в разбиении, чтобы не получилось случайно, что при изменении разбивки формулы на строки произошло, что у оператора не будет проставлен Gap
ParaRun.prototype.UpdateOperators = function(_CurLine, _CurRange, bEmptyGapLeft, bEmptyGapRight)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
for(var Pos = StartPos; Pos < EndPos; Pos++)
{
var _bEmptyGapLeft = bEmptyGapLeft && Pos == StartPos,
_bEmptyGapRight = bEmptyGapRight && Pos == EndPos - 1;
this.Content[Pos].Update_StateGapLeft(_bEmptyGapLeft);
this.Content[Pos].Update_StateGapRight(_bEmptyGapRight);
}
};
ParaRun.prototype.Math_Apply_Style = function(Value)
{
if(Value !== this.MathPrp.sty)
{
var OldValue = this.MathPrp.sty;
this.MathPrp.sty = Value;
History.Add(new CChangesRunMathStyle(this, OldValue, Value));
this.Recalc_CompiledPr(true);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
}
};
ParaRun.prototype.IsNormalText = function()
{
var comp_MPrp = this.MathPrp.GetCompiled_ScrStyles();
return comp_MPrp.nor === true;
};
ParaRun.prototype.getPropsForWrite = function()
{
var prRPr = null, wRPrp = null;
if(this.Paragraph && false === this.Paragraph.bFromDocument){
prRPr = this.Pr.Copy();
}
else{
wRPrp = this.Pr.Copy();
}
var mathRPrp = this.MathPrp.Copy();
return {wRPrp: wRPrp, mathRPrp: mathRPrp, prRPrp: prRPr};
};
ParaRun.prototype.Get_MathPr = function(bCopy)
{
if(this.Type = para_Math_Run)
{
if(bCopy)
return this.MathPrp.Copy();
else
return this.MathPrp;
}
};
ParaRun.prototype.Math_PreRecalc = function(Parent, ParaMath, ArgSize, RPI, GapsInfo)
{
this.Parent = Parent;
this.Paragraph = ParaMath.Paragraph;
var FontSize = this.Get_CompiledPr(false).FontSize;
if(RPI.bChangeInline)
this.RecalcInfo.Measure = true; // нужно сделать пересчет элементов, например для дроби, т.к. ArgSize у внутренних контентов будет другой => размер
if(RPI.bCorrect_ConvertFontSize) // изменение FontSize после конвертации из старого формата в новый
{
var FontKoef;
if(ArgSize == -1 || ArgSize == -2)
{
var Pr = new CTextPr();
if(this.Pr.FontSize !== null && this.Pr.FontSize !== undefined)
{
FontKoef = MatGetKoeffArgSize(this.Pr.FontSize, ArgSize);
Pr.FontSize = (((this.Pr.FontSize/FontKoef * 2 + 0.5) | 0) / 2);
this.RecalcInfo.TextPr = true;
this.RecalcInfo.Measure = true;
}
if(this.Pr.FontSizeCS !== null && this.Pr.FontSizeCS !== undefined)
{
FontKoef = MatGetKoeffArgSize( this.Pr.FontSizeCS, ArgSize);
Pr.FontSizeCS = (((this.Pr.FontSizeCS/FontKoef * 2 + 0.5) | 0) / 2);
this.RecalcInfo.TextPr = true;
this.RecalcInfo.Measure = true;
}
this.Apply_Pr(Pr);
}
}
for (var Pos = 0 ; Pos < this.Content.length; Pos++ )
{
if( !this.Content[Pos].IsAlignPoint() )
GapsInfo.setGaps(this.Content[Pos], FontSize);
this.Content[Pos].PreRecalc(this, ParaMath);
this.Content[Pos].SetUpdateGaps(false);
}
};
ParaRun.prototype.Math_GetRealFontSize = function(FontSize)
{
var RealFontSize = FontSize ;
if(FontSize !== null && FontSize !== undefined)
{
var ArgSize = this.Parent.Compiled_ArgSz.value;
RealFontSize = FontSize*MatGetKoeffArgSize(FontSize, ArgSize);
}
return RealFontSize;
};
ParaRun.prototype.Math_CompareFontSize = function(ComparableFontSize, bStartLetter)
{
var lng = this.Content.length;
var Letter = this.Content[lng - 1];
if(bStartLetter == true)
Letter = this.Content[0];
var CompiledPr = this.Get_CompiledPr(false);
var LetterFontSize = Letter.Is_LetterCS() ? CompiledPr.FontSizeCS : CompiledPr.FontSize;
return ComparableFontSize == this.Math_GetRealFontSize(LetterFontSize);
};
ParaRun.prototype.Math_EmptyRange = function(_CurLine, _CurRange) // до пересчета нужно узнать будет ли данный Run пустым или нет в данном Range, необходимо для того, чтобы выставить wrapIndent
{
var bEmptyRange = true;
var Lng = this.Content.length;
if(Lng > 0)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
bEmptyRange = this.protected_GetPrevRangeEndPos(CurLine, CurRange) >= Lng;
}
return bEmptyRange;
};
ParaRun.prototype.Math_UpdateGaps = function(_CurLine, _CurRange, GapsInfo)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
var FontSize = this.Get_CompiledPr(false).FontSize;
for(var Pos = StartPos; Pos < EndPos; Pos++)
{
GapsInfo.updateCurrentObject(this.Content[Pos], FontSize);
var bUpdateCurrent = this.Content[Pos].IsNeedUpdateGaps();
if(bUpdateCurrent || GapsInfo.bUpdate)
{
GapsInfo.updateGaps();
}
GapsInfo.bUpdate = bUpdateCurrent;
this.Content[Pos].SetUpdateGaps(false);
}
};
ParaRun.prototype.Math_Can_ModidyForcedBreak = function(Pr, bStart, bEnd)
{
var Pos = this.Math_GetPosForcedBreak(bStart, bEnd);
if(Pos !== null)
{
if(this.MathPrp.IsBreak())
{
Pr.Set_DeleteForcedBreak();
}
else
{
Pr.Set_InsertForcedBreak();
}
}
};
ParaRun.prototype.Math_GetPosForcedBreak = function(bStart, bEnd)
{
var ResultPos = null;
if(this.Content.length > 0)
{
var StartPos = this.Selection.StartPos,
EndPos = this.Selection.EndPos,
bSelect = this.Selection.Use;
if(StartPos > EndPos)
{
StartPos = this.Selection.EndPos;
EndPos = this.Selection.StartPos;
}
var bCheckTwoItem = bSelect == false || (bSelect == true && EndPos == StartPos),
bCheckOneItem = bSelect == true && EndPos - StartPos == 1;
if(bStart)
{
ResultPos = this.Content[0].Type == para_Math_BreakOperator ? 0 : ResultPos;
}
else if(bEnd)
{
var lastPos = this.Content.length - 1;
ResultPos = this.Content[lastPos].Type == para_Math_BreakOperator ? lastPos : ResultPos;
}
else if(bCheckTwoItem)
{
var Pos = bSelect == false ? this.State.ContentPos : StartPos;
var bPrevBreakOperator = Pos > 0 ? this.Content[Pos - 1].Type == para_Math_BreakOperator : false,
bCurrBreakOperator = Pos < this.Content.length ? this.Content[Pos].Type == para_Math_BreakOperator : false;
if(bCurrBreakOperator)
{
ResultPos = Pos
}
else if(bPrevBreakOperator)
{
ResultPos = Pos - 1;
}
}
else if(bCheckOneItem)
{
if(this.Content[StartPos].Type == para_Math_BreakOperator)
{
ResultPos = StartPos;
}
}
}
return ResultPos;
};
ParaRun.prototype.Check_ForcedBreak = function(bStart, bEnd)
{
return this.Math_GetPosForcedBreak(bStart, bEnd) !== null;
};
ParaRun.prototype.Set_MathForcedBreak = function(bInsert)
{
if (bInsert == true && false == this.MathPrp.IsBreak())
{
History.Add(new CChangesRunMathForcedBreak(this, true, undefined));
this.MathPrp.Insert_ForcedBreak();
}
else if (bInsert == false && true == this.MathPrp.IsBreak())
{
History.Add(new CChangesRunMathForcedBreak(this, false, this.MathPrp.Get_AlnAt()));
this.MathPrp.Delete_ForcedBreak();
}
};
ParaRun.prototype.Math_SplitRunForcedBreak = function()
{
var Pos = this.Math_GetPosForcedBreak();
var NewRun = null;
if(Pos != null && Pos > 0) // разбиваем Run на два
{
NewRun = this.Split_Run(Pos);
}
return NewRun;
};
ParaRun.prototype.UpdLastElementForGaps = function(_CurLine, _CurRange, GapsInfo)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = ( 0 === CurLine ? _CurRange - this.StartRange : _CurRange );
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
var FontSize = this.Get_CompiledPr(false).FontSize;
var Last = this.Content[EndPos];
GapsInfo.updateCurrentObject(Last, FontSize);
};
ParaRun.prototype.IsPlaceholder = function()
{
return this.Content.length == 1 && this.Content[0].IsPlaceholder();
};
ParaRun.prototype.AddMathPlaceholder = function()
{
var oPlaceholder = new CMathText(false);
oPlaceholder.SetPlaceholder();
this.Add_ToContent(0, oPlaceholder, false);
};
ParaRun.prototype.RemoveMathPlaceholder = function()
{
for (var nPos = 0; nPos < this.Content.length; ++nPos)
{
if (para_Math_Placeholder === this.Content[nPos].Type)
{
this.Remove_FromContent(nPos, 1, true);
nPos--;
}
}
};
ParaRun.prototype.Set_MathPr = function(MPrp)
{
var OldValue = this.MathPrp;
this.MathPrp.Set_Pr(MPrp);
History.Add(new CChangesRunMathPrp(this, OldValue, this.MathPrp));
this.Recalc_CompiledPr(true);
this.private_UpdateTrackRevisionOnChangeTextPr(true);
};
ParaRun.prototype.Set_MathTextPr2 = function(TextPr, MathPr)
{
this.Set_Pr(TextPr.Copy());
this.Set_MathPr(MathPr.Copy());
};
ParaRun.prototype.IsAccent = function()
{
return this.Parent.IsAccent();
};
ParaRun.prototype.GetCompiled_ScrStyles = function()
{
return this.MathPrp.GetCompiled_ScrStyles();
};
ParaRun.prototype.IsEqArray = function()
{
return this.Parent.IsEqArray();
};
ParaRun.prototype.IsForcedBreak = function()
{
var bForcedBreak = false;
if(this.ParaMath!== null)
bForcedBreak = false == this.ParaMath.Is_Inline() && true == this.MathPrp.IsBreak();
return bForcedBreak;
};
ParaRun.prototype.Is_StartForcedBreakOperator = function()
{
var bStartOperator = this.Content.length > 0 && this.Content[0].Type == para_Math_BreakOperator;
return true == this.IsForcedBreak() && true == bStartOperator;
};
ParaRun.prototype.Get_AlignBrk = function(_CurLine, bBrkBefore)
{
// null - break отсутствует
// 0 - break присутствует, alnAt = undefined
// Number = break присутствует, alnAt = Number
// если оператор находится в конце строки и по этому оператору осушествляется принудительный перенос (Forced)
// тогда StartPos = 0, EndPos = 1 (для предыдущей строки), т.к. оператор с принудительным переносом всегда должен находится в начале Run
var CurLine = _CurLine - this.StartLine;
var AlnAt = null;
if(CurLine > 0)
{
var RangesCount = this.protected_GetRangesCount(CurLine - 1);
var StartPos = this.protected_GetRangeStartPos(CurLine - 1, RangesCount - 1);
var EndPos = this.protected_GetRangeEndPos(CurLine - 1, RangesCount - 1);
var bStartBreakOperator = bBrkBefore == true && StartPos == 0 && EndPos == 0;
var bEndBreakOperator = bBrkBefore == false && StartPos == 0 && EndPos == 1;
if(bStartBreakOperator || bEndBreakOperator)
{
AlnAt = false == this.Is_StartForcedBreakOperator() ? null : this.MathPrp.Get_AlignBrk();
}
}
return AlnAt;
};
ParaRun.prototype.Math_Is_InclineLetter = function()
{
var result = false;
if(this.Content.length == 1)
result = this.Content[0].Is_InclineLetter();
return result;
};
ParaRun.prototype.GetMathTextPrForMenu = function()
{
var TextPr = new CTextPr();
if(this.IsPlaceholder())
TextPr.Merge(this.Parent.GetCtrPrp());
TextPr.Merge(this.Pr);
var MathTextPr = this.MathPrp.Copy();
var BI = MathTextPr.GetBoldItalic();
TextPr.Italic = BI.Italic;
TextPr.Bold = BI.Bold;
return TextPr;
};
ParaRun.prototype.ApplyPoints = function(PointsInfo)
{
if(this.Parent.IsEqArray())
{
this.size.width = 0;
for(var Pos = 0; Pos < this.Content.length; Pos++)
{
var Item = this.Content[Pos];
if(Item.Type === para_Math_Ampersand && true === Item.IsAlignPoint())
{
PointsInfo.NextAlignRange();
Item.size.width = PointsInfo.GetAlign();
}
this.size.width += this.Content[Pos].Get_WidthVisible(); // Get_Width => Get_WidthVisible
// Get_WidthVisible - Width + Gaps с учетом настроек состояния
}
}
};
ParaRun.prototype.Get_TextForAutoCorrect = function(AutoCorrectEngine, RunPos)
{
var ActionElement = AutoCorrectEngine.Get_ActionElement();
var nCount = this.Content.length;
for (var nPos = 0; nPos < nCount; nPos++)
{
var Item = this.Content[nPos];
if (para_Math_Text === Item.Type || para_Math_BreakOperator === Item.Type)
{
AutoCorrectEngine.Add_Text(String.fromCharCode(Item.value), this, nPos, RunPos, Item.Pos);
}
else if (para_Math_Ampersand === Item.Type)
{
AutoCorrectEngine.Add_Text('&', this, nPos, RunPos, Item.Pos);
}
if (Item === ActionElement)
{
AutoCorrectEngine.Stop_CollectText();
break;
}
}
if (null === AutoCorrectEngine.TextPr)
AutoCorrectEngine.TextPr = this.Pr.Copy();
if (null == AutoCorrectEngine.MathPr)
AutoCorrectEngine.MathPr = this.MathPrp.Copy();
};
ParaRun.prototype.IsShade = function()
{
var oShd = this.Get_CompiledPr(false).Shd;
return !(oShd === undefined || c_oAscShdNil === oShd.Value);
};
ParaRun.prototype.Get_RangesByPos = function(Pos)
{
var Ranges = [];
var LinesCount = this.protected_GetLinesCount();
for (var LineIndex = 0; LineIndex < LinesCount; LineIndex++)
{
var RangesCount = this.protected_GetRangesCount(LineIndex);
for (var RangeIndex = 0; RangeIndex < RangesCount; RangeIndex++)
{
var StartPos = this.protected_GetRangeStartPos(LineIndex, RangeIndex);
var EndPos = this.protected_GetRangeEndPos(LineIndex, RangeIndex);
if (StartPos <= Pos && Pos <= EndPos)
Ranges.push({Range : (LineIndex === 0 ? RangeIndex + this.StartRange : RangeIndex), Line : LineIndex + this.StartLine});
}
}
return Ranges;
};
ParaRun.prototype.CompareDrawingsLogicPositions = function(CompareObject)
{
var Drawing1 = CompareObject.Drawing1;
var Drawing2 = CompareObject.Drawing2;
for (var Pos = 0, Count = this.Content.length; Pos < Count; Pos++)
{
var Item = this.Content[Pos];
if (Item === Drawing1)
{
CompareObject.Result = 1;
return;
}
else if (Item === Drawing2)
{
CompareObject.Result = -1;
return;
}
}
};
ParaRun.prototype.Get_ReviewType = function()
{
return this.ReviewType;
};
ParaRun.prototype.Get_ReviewInfo = function()
{
return this.ReviewInfo;
};
ParaRun.prototype.Get_ReviewColor = function()
{
if (this.ReviewInfo)
return this.ReviewInfo.Get_Color();
return REVIEW_COLOR;
};
ParaRun.prototype.Set_ReviewType = function(Value)
{
if (Value !== this.ReviewType)
{
var OldReviewType = this.ReviewType;
var OldReviewInfo = this.ReviewInfo.Copy();
this.ReviewType = Value;
this.ReviewInfo.Update();
History.Add(new CChangesRunReviewType(this,
{
ReviewType : OldReviewType,
ReviewInfo : OldReviewInfo
},
{
ReviewType : this.ReviewType,
ReviewInfo : this.ReviewInfo.Copy()
}));
this.private_UpdateTrackRevisions();
}
};
ParaRun.prototype.Set_ReviewTypeWithInfo = function(ReviewType, ReviewInfo)
{
History.Add(new CChangesRunReviewType(this,
{
ReviewType : this.ReviewType,
ReviewInfo : this.ReviewInfo ? this.ReviewInfo.Copy() : undefined
},
{
ReviewType : ReviewType,
ReviewInfo : ReviewInfo ? ReviewInfo.Copy() : undefined
}));
this.ReviewType = ReviewType;
this.ReviewInfo = ReviewInfo;
this.private_UpdateTrackRevisions();
};
ParaRun.prototype.Get_Parent = function()
{
if (!this.Paragraph)
return null;
var ContentPos = this.Paragraph.Get_PosByElement(this);
if (null == ContentPos || undefined == ContentPos || ContentPos.Get_Depth() < 0)
return null;
ContentPos.Decrease_Depth(1);
return this.Paragraph.Get_ElementByPos(ContentPos);
};
ParaRun.prototype.private_GetPosInParent = function(_Parent)
{
var Parent = (_Parent? _Parent : this.Get_Parent());
if (!Parent)
return -1;
// Ищем данный элемент в родительском классе
var RunPos = -1;
for (var Pos = 0, Count = Parent.Content.length; Pos < Count; Pos++)
{
if (this === Parent.Content[Pos])
{
RunPos = Pos;
break;
}
}
return RunPos;
};
ParaRun.prototype.Make_ThisElementCurrent = function(bUpdateStates)
{
if (this.Is_UseInDocument())
{
var ContentPos = this.Paragraph.Get_PosByElement(this);
ContentPos.Add(this.State.ContentPos);
this.Paragraph.Set_ParaContentPos(ContentPos, true, -1, -1);
this.Paragraph.Document_SetThisElementCurrent(true === bUpdateStates ? true : false);
}
};
ParaRun.prototype.GetAllParagraphs = function(Props, ParaArray)
{
var ContentLen = this.Content.length;
for (var CurPos = 0; CurPos < ContentLen; CurPos++)
{
if (para_Drawing == this.Content[CurPos].Type)
this.Content[CurPos].GetAllParagraphs(Props, ParaArray);
}
};
ParaRun.prototype.Check_RevisionsChanges = function(Checker, ContentPos, Depth)
{
if (this.Is_Empty())
return;
if (true !== Checker.Is_ParaEndRun() && true !== Checker.Is_CheckOnlyTextPr())
{
var ReviewType = this.Get_ReviewType();
if (ReviewType !== Checker.Get_AddRemoveType() || (reviewtype_Common !== ReviewType && this.ReviewInfo.Get_UserId() !== Checker.Get_AddRemoveUserId()))
{
Checker.Flush_AddRemoveChange();
ContentPos.Update(0, Depth);
if (reviewtype_Add === ReviewType || reviewtype_Remove === ReviewType)
Checker.Start_AddRemove(ReviewType, ContentPos);
}
if (reviewtype_Add === ReviewType || reviewtype_Remove === ReviewType)
{
var Text = "";
var ContentLen = this.Content.length;
for (var CurPos = 0; CurPos < ContentLen; CurPos++)
{
var Item = this.Content[CurPos];
var ItemType = Item.Type;
switch (ItemType)
{
case para_Drawing:
{
Checker.Add_Text(Text);
Text = "";
Checker.Add_Drawing(Item);
break;
}
case para_Text :
{
Text += String.fromCharCode(Item.Value);
break;
}
case para_Math_Text:
{
Text += String.fromCharCode(Item.getCodeChr());
break;
}
case para_Space:
case para_Tab :
{
Text += " ";
break;
}
}
}
Checker.Add_Text(Text);
ContentPos.Update(this.Content.length, Depth);
Checker.Set_AddRemoveEndPos(ContentPos);
Checker.Update_AddRemoveReviewInfo(this.ReviewInfo);
}
}
var HavePrChange = this.Have_PrChange();
var DiffPr = this.Get_DiffPrChange();
if (HavePrChange !== Checker.Have_PrChange() || true !== Checker.Compare_PrChange(DiffPr) || this.Pr.ReviewInfo.Get_UserId() !== Checker.Get_PrChangeUserId())
{
Checker.Flush_TextPrChange();
ContentPos.Update(0, Depth);
if (true === HavePrChange)
{
Checker.Start_PrChange(DiffPr, ContentPos);
}
}
if (true === HavePrChange)
{
ContentPos.Update(this.Content.length, Depth);
Checker.Set_PrChangeEndPos(ContentPos);
Checker.Update_PrChangeReviewInfo(this.Pr.ReviewInfo);
}
};
ParaRun.prototype.private_UpdateTrackRevisionOnChangeContent = function(bUpdateInfo)
{
if (reviewtype_Common !== this.Get_ReviewType())
{
this.private_UpdateTrackRevisions();
if (true === bUpdateInfo && this.Paragraph && this.Paragraph.LogicDocument && this.Paragraph.bFromDocument && true === this.Paragraph.LogicDocument.Is_TrackRevisions() && this.ReviewInfo && true === this.ReviewInfo.Is_CurrentUser())
{
var OldReviewInfo = this.ReviewInfo.Copy();
this.ReviewInfo.Update();
History.Add(new CChangesRunContentReviewInfo(this, OldReviewInfo, this.ReviewInfo.Copy()));
}
}
};
ParaRun.prototype.private_UpdateTrackRevisionOnChangeTextPr = function(bUpdateInfo)
{
if (true === this.Have_PrChange())
{
this.private_UpdateTrackRevisions();
if (true === bUpdateInfo && this.Paragraph && this.Paragraph.bFromDocument && this.Paragraph.LogicDocument && true === this.Paragraph.LogicDocument.Is_TrackRevisions())
{
var OldReviewInfo = this.Pr.ReviewInfo.Copy();
this.Pr.ReviewInfo.Update();
History.Add(new CChangesRunPrReviewInfo(this, OldReviewInfo, this.Pr.ReviewInfo.Copy()));
}
}
};
ParaRun.prototype.private_UpdateTrackRevisions = function()
{
if (this.Paragraph && this.Paragraph.bFromDocument && this.Paragraph.LogicDocument && this.Paragraph.LogicDocument.Get_TrackRevisionsManager)
{
var RevisionsManager = this.Paragraph.LogicDocument.Get_TrackRevisionsManager();
RevisionsManager.Check_Paragraph(this.Paragraph);
}
};
ParaRun.prototype.AcceptRevisionChanges = function(Type, bAll)
{
var Parent = this.Get_Parent();
var RunPos = this.private_GetPosInParent();
var ReviewType = this.Get_ReviewType();
var HavePrChange = this.Have_PrChange();
// Нет изменений в данном ране
if (reviewtype_Common === ReviewType && true !== HavePrChange)
return;
if (true === this.Selection.Use || true === bAll)
{
var StartPos = this.Selection.StartPos;
var EndPos = this.Selection.EndPos;
if (StartPos > EndPos)
{
StartPos = this.Selection.EndPos;
EndPos = this.Selection.StartPos;
}
if (true === bAll)
{
StartPos = 0;
EndPos = this.Content.length;
}
var CenterRun = null, CenterRunPos = RunPos;
if (0 === StartPos && this.Content.length === EndPos)
{
CenterRun = this;
}
else if (StartPos > 0 && this.Content.length === EndPos)
{
CenterRun = this.Split2(StartPos, Parent, RunPos);
CenterRunPos = RunPos + 1;
}
else if (0 === StartPos && this.Content.length > EndPos)
{
CenterRun = this;
this.Split2(EndPos, Parent, RunPos);
}
else
{
this.Split2(EndPos, Parent, RunPos);
CenterRun = this.Split2(StartPos, Parent, RunPos);
CenterRunPos = RunPos + 1;
}
if (true === HavePrChange && (undefined === Type || c_oAscRevisionsChangeType.TextPr === Type))
{
CenterRun.Remove_PrChange();
}
if (reviewtype_Add === ReviewType && (undefined === Type || c_oAscRevisionsChangeType.TextAdd === Type))
{
CenterRun.Set_ReviewType(reviewtype_Common);
}
else if (reviewtype_Remove === ReviewType && (undefined === Type || c_oAscRevisionsChangeType.TextRem === Type))
{
Parent.Remove_FromContent(CenterRunPos, 1);
if (Parent.Get_ContentLength() <= 0)
{
Parent.RemoveSelection();
Parent.Add_ToContent(0, new ParaRun());
Parent.MoveCursorToStartPos();
}
}
}
};
ParaRun.prototype.RejectRevisionChanges = function(Type, bAll)
{
var Parent = this.Get_Parent();
var RunPos = this.private_GetPosInParent();
var ReviewType = this.Get_ReviewType();
var HavePrChange = this.Have_PrChange();
// Нет изменений в данном ране
if (reviewtype_Common === ReviewType && true !== HavePrChange)
return;
if (true === this.Selection.Use || true === bAll)
{
var StartPos = this.Selection.StartPos;
var EndPos = this.Selection.EndPos;
if (StartPos > EndPos)
{
StartPos = this.Selection.EndPos;
EndPos = this.Selection.StartPos;
}
if (true === bAll)
{
StartPos = 0;
EndPos = this.Content.length;
}
var CenterRun = null, CenterRunPos = RunPos;
if (0 === StartPos && this.Content.length === EndPos)
{
CenterRun = this;
}
else if (StartPos > 0 && this.Content.length === EndPos)
{
CenterRun = this.Split2(StartPos, Parent, RunPos);
CenterRunPos = RunPos + 1;
}
else if (0 === StartPos && this.Content.length > EndPos)
{
CenterRun = this;
this.Split2(EndPos, Parent, RunPos);
}
else
{
this.Split2(EndPos, Parent, RunPos);
CenterRun = this.Split2(StartPos, Parent, RunPos);
CenterRunPos = RunPos + 1;
}
if (true === HavePrChange && (undefined === Type || c_oAscRevisionsChangeType.TextPr === Type))
{
CenterRun.Set_Pr(CenterRun.Pr.PrChange);
}
if (reviewtype_Add === ReviewType && (undefined === Type || c_oAscRevisionsChangeType.TextAdd === Type))
{
Parent.Remove_FromContent(CenterRunPos, 1);
if (Parent.Get_ContentLength() <= 0)
{
Parent.RemoveSelection();
Parent.Add_ToContent(0, new ParaRun());
Parent.MoveCursorToStartPos();
}
}
else if (reviewtype_Remove === ReviewType && (undefined === Type || c_oAscRevisionsChangeType.TextRem === Type))
{
CenterRun.Set_ReviewType(reviewtype_Common);
}
}
};
ParaRun.prototype.Is_InHyperlink = function()
{
if (!this.Paragraph)
return false;
var ContentPos = this.Paragraph.Get_PosByElement(this);
var Classes = this.Paragraph.Get_ClassesByPos(ContentPos);
var bHyper = false;
var bRun = false;
for (var Index = 0, Count = Classes.length; Index < Count; Index++)
{
var Item = Classes[Index];
if (Item === this)
{
bRun = true;
break;
}
else if (Item instanceof ParaHyperlink)
{
bHyper = true;
}
}
return (bHyper && bRun);
};
ParaRun.prototype.Get_ClassesByPos = function(Classes, ContentPos, Depth)
{
Classes.push(this);
};
ParaRun.prototype.GetDocumentPositionFromObject = function(PosArray)
{
if (!PosArray)
PosArray = [];
if (this.Paragraph)
{
var ParaContentPos = this.Paragraph.Get_PosByElement(this);
if (null !== ParaContentPos)
{
var Depth = ParaContentPos.Get_Depth();
while (Depth > 0)
{
var Pos = ParaContentPos.Get(Depth);
ParaContentPos.Decrease_Depth(1);
var Class = this.Paragraph.Get_ElementByPos(ParaContentPos);
Depth--;
PosArray.splice(0, 0, {Class : Class, Position : Pos});
}
PosArray.splice(0, 0, {Class : this.Paragraph, Position : ParaContentPos.Get(0)});
}
this.Paragraph.GetDocumentPositionFromObject(PosArray);
}
return PosArray;
};
ParaRun.prototype.Is_UseInParagraph = function()
{
if (!this.Paragraph)
return false;
var ContentPos = this.Paragraph.Get_PosByElement(this);
if (!ContentPos)
return false;
return true;
};
ParaRun.prototype.Displace_BreakOperator = function(isForward, bBrkBefore, CountOperators)
{
var bResult = true;
var bFirstItem = this.State.ContentPos == 0 || this.State.ContentPos == 1,
bLastItem = this.State.ContentPos == this.Content.length - 1 || this.State.ContentPos == this.Content.length;
if(true === this.Is_StartForcedBreakOperator() && bFirstItem == true)
{
var AlnAt = this.MathPrp.Get_AlnAt();
var NotIncrease = AlnAt == CountOperators && isForward == true;
if(NotIncrease == false)
{
this.MathPrp.Displace_Break(isForward);
var NewAlnAt = this.MathPrp.Get_AlnAt();
if(AlnAt !== NewAlnAt)
{
History.Add(new CChangesRunMathAlnAt(this, AlnAt, NewAlnAt));
}
}
}
else
{
bResult = (bLastItem && bBrkBefore) || (bFirstItem && !bBrkBefore) ? false : true;
}
return bResult; // применили смещение к данному Run
};
ParaRun.prototype.Math_UpdateLineMetrics = function(PRS, ParaPr)
{
var LineRule = ParaPr.Spacing.LineRule;
// Пересчитаем метрику строки относительно размера данного текста
if ( PRS.LineTextAscent < this.TextAscent )
PRS.LineTextAscent = this.TextAscent;
if ( PRS.LineTextAscent2 < this.TextAscent2 )
PRS.LineTextAscent2 = this.TextAscent2;
if ( PRS.LineTextDescent < this.TextDescent )
PRS.LineTextDescent = this.TextDescent;
if ( Asc.linerule_Exact === LineRule )
{
// Смещение не учитывается в метриках строки, когда расстояние между строк точное
if ( PRS.LineAscent < this.TextAscent )
PRS.LineAscent = this.TextAscent;
if ( PRS.LineDescent < this.TextDescent )
PRS.LineDescent = this.TextDescent;
}
else
{
if ( PRS.LineAscent < this.TextAscent + this.YOffset )
PRS.LineAscent = this.TextAscent + this.YOffset;
if ( PRS.LineDescent < this.TextDescent - this.YOffset )
PRS.LineDescent = this.TextDescent - this.YOffset;
}
};
ParaRun.prototype.Set_CompositeInput = function(oCompositeInput)
{
this.CompositeInput = oCompositeInput;
};
ParaRun.prototype.Get_FootnotesList = function(oEngine)
{
for (var nIndex = 0, nCount = this.Content.length; nIndex < nCount; ++nIndex)
{
var oItem = this.Content[nIndex];
if (para_FootnoteReference === oItem.Type)
{
oEngine.Add(oItem.Get_Footnote(), oItem, this);
}
}
};
ParaRun.prototype.Is_UseInDocument = function()
{
return (this.Paragraph && true === this.Paragraph.Is_UseInDocument() && true === this.Is_UseInParagraph() ? true : false);
};
ParaRun.prototype.GetParaEnd = function()
{
for (var nIndex = 0, nCount = this.Content.length; nIndex < nCount; ++nIndex)
{
if (this.Content[nIndex].Type === para_End)
return this.Content[nIndex];
}
return null;
};
ParaRun.prototype.RemoveElement = function(oElement)
{
for (var nIndex = 0, nCount = this.Content.length; nIndex < nCount; ++nIndex)
{
if (oElement === this.Content[nIndex])
return this.Remove_FromContent(nIndex, 1, true);
}
};
ParaRun.prototype.GotoFootnoteRef = function(isNext, isCurrent, isStepOver)
{
var nPos = 0;
if (true === isCurrent)
{
if (true === this.Selection.Use)
nPos = Math.min(this.Selection.StartPos, this.Selection.EndPos);
else
nPos = this.State.ContentPos;
}
else
{
if (true === isNext)
nPos = 0;
else
nPos = this.Content.length - 1;
}
var nResult = 0;
if (true === isNext)
{
for (var nIndex = nPos, nCount = this.Content.length; nIndex < nCount; ++nIndex)
{
if (para_FootnoteReference === this.Content[nIndex].Type && ((true !== isCurrent && true === isStepOver) || (true === isCurrent && (true === this.Selection.Use || nPos !== nIndex))))
{
if (this.Paragraph && this.Paragraph.bFromDocument && this.Paragraph.LogicDocument)
this.Paragraph.LogicDocument.RemoveSelection();
this.State.ContentPos = nIndex;
this.Make_ThisElementCurrent(true);
return -1;
}
nResult++;
}
}
else
{
for (var nIndex = Math.min(nPos, this.Content.length - 1); nIndex >= 0; --nIndex)
{
if (para_FootnoteReference === this.Content[nIndex].Type && ((true !== isCurrent && true === isStepOver) || (true === isCurrent && (true === this.Selection.Use || nPos !== nIndex))))
{
if (this.Paragraph && this.Paragraph.bFromDocument && this.Paragraph.LogicDocument)
this.Paragraph.LogicDocument.RemoveSelection();
this.State.ContentPos = nIndex;
this.Make_ThisElementCurrent(true);
return -1;
}
nResult++;
}
}
return nResult;
};
ParaRun.prototype.GetFootnoteRefsInRange = function(arrFootnotes, _CurLine, _CurRange)
{
var CurLine = _CurLine - this.StartLine;
var CurRange = (0 === CurLine ? _CurRange - this.StartRange : _CurRange);
var StartPos = this.protected_GetRangeStartPos(CurLine, CurRange);
var EndPos = this.protected_GetRangeEndPos(CurLine, CurRange);
for (var CurPos = StartPos; CurPos < EndPos; CurPos++)
{
if (para_FootnoteReference === this.Content[CurPos].Type)
arrFootnotes.push(this.Content[CurPos]);
}
};
ParaRun.prototype.GetAllContentControls = function(arrContentControls)
{
if (!arrContentControls)
return;
for (var nIndex = 0, nCount = this.Content.length; nIndex < nCount; ++nIndex)
{
var oItem = this.Content[nIndex];
if (para_Drawing === oItem.Type || para_FootnoteReference === oItem.Type)
{
oItem.GetAllContentControls(arrContentControls);
}
}
};
function CParaRunStartState(Run)
{
this.Paragraph = Run.Paragraph;
this.Pr = Run.Pr.Copy();
this.Content = [];
for(var i = 0; i < Run.Content.length; ++i)
{
this.Content.push(Run.Content[i]);
}
}
function CReviewInfo()
{
this.Editor = editor;
this.UserId = "";
this.UserName = "";
this.DateTime = "";
}
CReviewInfo.prototype.Update = function()
{
if (this.Editor && this.Editor.DocInfo)
{
this.UserId = this.Editor.DocInfo.get_UserId();
this.UserName = this.Editor.DocInfo.get_UserName();
this.DateTime = (new Date()).getTime();
}
};
CReviewInfo.prototype.Copy = function()
{
var Info = new CReviewInfo();
Info.UserId = this.UserId;
Info.UserName = this.UserName;
Info.DateTime = this.DateTime;
return Info;
};
CReviewInfo.prototype.Get_UserId = function()
{
return this.UserId;
};
CReviewInfo.prototype.Get_UserName = function()
{
return this.UserName;
};
CReviewInfo.prototype.Get_DateTime = function()
{
return this.DateTime;
};
CReviewInfo.prototype.Write_ToBinary = function(Writer)
{
Writer.WriteString2(this.UserId);
Writer.WriteString2(this.UserName);
Writer.WriteString2(this.DateTime);
};
CReviewInfo.prototype.Read_FromBinary = function(Reader)
{
this.UserId = Reader.GetString2();
this.UserName = Reader.GetString2();
this.DateTime = parseInt(Reader.GetString2());
};
CReviewInfo.prototype.Get_Color = function()
{
if (!this.UserId && !this.UserName)
return REVIEW_COLOR;
return AscCommon.getUserColorById(this.UserId, this.UserName, true, false);
};
CReviewInfo.prototype.Is_CurrentUser = function()
{
if (this.Editor)
{
var UserId = this.Editor.DocInfo.get_UserId();
return (UserId === this.UserId);
}
return true;
};
CReviewInfo.prototype.Get_UserId = function()
{
return this.UserId;
};
function CanUpdatePosition(Para, Run) {
return (Para && true === Para.Is_UseInDocument() && true === Run.Is_UseInParagraph());
}
//--------------------------------------------------------export----------------------------------------------------
window['AscCommonWord'] = window['AscCommonWord'] || {};
window['AscCommonWord'].ParaRun = ParaRun;
window['AscCommonWord'].CanUpdatePosition = CanUpdatePosition;
| fix Bug 21042
| word/Editor/Run.js | fix Bug 21042 | <ide><path>ord/Editor/Run.js
<ide> var ReviewColor = this.Get_ReviewColor();
<ide>
<ide> // Выставляем цвет обводки
<del> if ( true === PDSL.VisitedHyperlink && ( undefined === this.Pr.Color && undefined === this.Pr.Unifill ) )
<del> CurColor = new CDocumentColor( 128, 0, 151 );
<add>
<add> var bPresentation = this.Paragraph && !this.Paragraph.bFromDocument;
<add> if ( true === PDSL.VisitedHyperlink && ( undefined === this.Pr.Color && undefined === this.Pr.Unifill || bPresentation) )
<add> {
<add> AscFormat.G_O_VISITED_HLINK_COLOR.check(Theme, ColorMap);
<add> RGBA = AscFormat.G_O_VISITED_HLINK_COLOR.getRGBAColor();
<add> CurColor = new CDocumentColor( RGBA.R, RGBA.G, RGBA.B, RGBA.A );
<add> }
<ide> else if ( true === CurTextPr.Color.Auto && !CurTextPr.Unifill)
<ide> CurColor = new CDocumentColor( AutoColor.r, AutoColor.g, AutoColor.b );
<ide> else |
|
Java | epl-1.0 | 1e10d27eed39149c4527042856362900e9a643dc | 0 | rrimmana/birt-1,Charling-Huang/birt,Charling-Huang/birt,rrimmana/birt-1,sguan-actuate/birt,rrimmana/birt-1,sguan-actuate/birt,rrimmana/birt-1,sguan-actuate/birt,Charling-Huang/birt,sguan-actuate/birt,Charling-Huang/birt,rrimmana/birt-1,Charling-Huang/birt,sguan-actuate/birt | /*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.data.engine.executor;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.birt.core.data.DataType.AnyType;
import org.eclipse.birt.core.util.IOUtil;
import org.eclipse.birt.data.engine.core.DataException;
import org.eclipse.birt.data.engine.executor.cache.ResultSetUtil;
import org.eclipse.birt.data.engine.i18n.ResourceConstants;
import org.eclipse.birt.data.engine.odi.IResultClass;
/**
* <code>ResultClass</code> contains the metadata about
* the projected columns in the result set.
*/
public class ResultClass implements IResultClass
{
private ResultFieldMetadata[] projectedCols;
private int m_fieldCount;
private HashMap nameToIdMapping;
private String[] fieldNames;
private int[] fieldDriverPositions;
private ResultClassHelper resultClassHelper;
private boolean hasAny;
private List originalAnyTypeField;
public ResultClass( List projectedColumns ) throws DataException
{
assert( projectedColumns != null );
initColumnsInfo( projectedColumns );
}
/**
*
* @param projectedColumns
* @throws DataException
*/
private void validateProjectColumns( ResultFieldMetadata[] projectedColumns ) throws DataException
{
Set columnNameSet = new HashSet();
for( int i = 0; i < projectedColumns.length; i++ )
{
ResultFieldMetadata column = projectedColumns[i];
if ( columnNameSet.contains( column.getName( ) ) )
{
throw new DataException( ResourceConstants.DUPLICATE_COLUMN_NAME,
column.getName( ) );
}
if ( columnNameSet.contains( column.getAlias( ) ) )
{
throw new DataException( ResourceConstants.DUPLICATE_COLUMN_NAME,
column.getAlias( ) );
}
columnNameSet.add( column.getName());
if( column.getAlias()!= null )
columnNameSet.add(column.getAlias());
}
}
/**
* @param projectedColumns
*/
private void initColumnsInfo( List projectedColumns )
{
m_fieldCount = projectedColumns.size( );
projectedCols = new ResultFieldMetadata[m_fieldCount];
nameToIdMapping = new HashMap( );
this.originalAnyTypeField = new ArrayList();
for ( int i = 0, n = projectedColumns.size( ); i < n; i++ )
{
projectedCols[i] = (ResultFieldMetadata) projectedColumns.get( i );
ResultFieldMetadata column = projectedCols[i];
if( isOfAnyType( column ))
{
this.hasAny = true;
this.originalAnyTypeField.add( new Integer( i + 1 ) );
}
String upperCaseName = column.getName( );
//if ( upperCaseName != null )
// upperCaseName = upperCaseName.toUpperCase( );
// need to add 1 to the 0-based array index, so we can put the
// 1-based index into the name-to-id mapping that will be used
// for the rest of the interfaces in this class
Integer index = new Integer( i + 1 );
// If the name is a duplicate of an existing column name or alias,
// this entry is not put into the mapping table. This effectively
// makes this entry inaccessible by name, which is the intended
// behavior
if ( !nameToIdMapping.containsKey( upperCaseName ) )
{
nameToIdMapping.put( upperCaseName, index );
}
String upperCaseAlias = column.getAlias( );
//if ( upperCaseAlias != null )
// upperCaseAlias = upperCaseAlias.toUpperCase( );
if ( upperCaseAlias != null
&& upperCaseAlias.length( ) > 0
&& !nameToIdMapping.containsKey( upperCaseAlias ) )
{
nameToIdMapping.put( upperCaseAlias, index );
}
}
}
/**
*
* @param column
* @return
*/
private boolean isOfAnyType( ResultFieldMetadata column )
{
return column.getDataType( ).getName( ).equals( AnyType.class.getName( ) );
}
/**
* New an instance of ResultClass from input stream.
*
* @param inputStream
* @throws DataException
*/
public ResultClass( InputStream inputStream ) throws DataException
{
assert inputStream != null;
DataInputStream dis = new DataInputStream( inputStream );
try
{
List newProjectedColumns = new ArrayList( );
int size = IOUtil.readInt( dis );
for ( int i = 0; i < size; i++ )
{
int driverPos = IOUtil.readInt( dis );
String name = IOUtil.readString( dis );
String lable = IOUtil.readString( dis );
String alias = IOUtil.readString( dis );
String dtName = IOUtil.readString( dis );
String ntName = IOUtil.readString( dis );
boolean bool = IOUtil.readBool( dis );
String dpdpName = IOUtil.readString( dis );
ResultFieldMetadata metaData = new ResultFieldMetadata( driverPos,
name,
lable,
Class.forName( dtName ),
ntName,
bool );
metaData.setAlias( alias );
if ( dpdpName != null )
metaData.setDriverProvidedDataType( Class.forName( dpdpName ) );
newProjectedColumns.add( metaData );
}
dis.close( );
initColumnsInfo( newProjectedColumns );
}
catch ( ClassNotFoundException e )
{
throw new DataException( ResourceConstants.RD_LOAD_ERROR,
e,
"Result Class" );
}
catch ( IOException e )
{
throw new DataException( ResourceConstants.RD_LOAD_ERROR,
e,
"Result Class" );
}
}
/**
* Serialize instance status into output stream.
*
* @param outputStream
* @throws DataException
*/
public void doSave( OutputStream outputStream, Map requestColumnMap )
throws DataException
{
assert outputStream != null;
DataOutputStream dos = new DataOutputStream( outputStream );
Set resultSetNameSet = ResultSetUtil.getRsColumnRequestMap( requestColumnMap );
// If there are refrences on columnName and columnAlias in
// resultSetNameSet, size--;
int size = resultSetNameSet.size( );
for ( int i = 0; i < projectedCols.length; i++ )
{
String columnName = projectedCols[i].getName( );
String columnAlias = projectedCols[i].getAlias( );
if ( columnName != null &&
!columnName.equals( columnAlias ) &&
resultSetNameSet.contains( columnName ) &&
resultSetNameSet.contains( columnAlias ) )
size--;
}
try
{
IOUtil.writeInt( outputStream, size );
int writeCount = 0;
for ( int i = 0; i < m_fieldCount; i++ )
{
ResultFieldMetadata column = projectedCols[i];
// check if result set contains the column, if exists, remove it
// from the result set for further invalid columns collecting
if (resultSetNameSet.remove(column.getName())
|| resultSetNameSet.remove(column.getAlias()))
{
IOUtil.writeInt( dos, column.getDriverPosition( ) );
IOUtil.writeString( dos, column.getName( ) );
IOUtil.writeString( dos, column.getLabel( ) );
IOUtil.writeString( dos, column.getAlias( ) );
IOUtil.writeString( dos, column.getDataType( ).getName( ) );
IOUtil.writeString( dos, column.getNativeTypeName( ) );
IOUtil.writeBool( dos, column.isCustom( ) );
if ( column.getDriverProvidedDataType( ) == null )
IOUtil.writeString( dos, null );
else
IOUtil.writeString( dos,
column.getDriverProvidedDataType( ).getName( ) );
writeCount++;
}
}
if ( writeCount != size)
{
validateProjectColumns( projectedCols );
StringBuffer buf = new StringBuffer( );
for ( Iterator i = resultSetNameSet.iterator( ); i.hasNext( ); )
{
String colName = (String) i.next( );
buf.append( colName );
buf.append( ',' );
}
buf.deleteCharAt( buf.length( ) - 1 );
throw new DataException( ResourceConstants.RESULT_CLASS_SAVE_ERROR,
buf.toString( ) );
}
dos.close( );
}
catch ( IOException e )
{
throw new DataException( ResourceConstants.RD_SAVE_ERROR,
e,
"Result Class" );
}
}
public int getFieldCount()
{
return m_fieldCount;
}
// returns the field names in the projected order
// or an empty array if no fields were projected
public String[] getFieldNames()
{
return doGetFieldNames();
}
private String[] doGetFieldNames()
{
if( fieldNames == null )
{
int size = m_fieldCount;
fieldNames = new String[ size ];
for( int i = 0; i < size; i++ )
{
fieldNames[i] = projectedCols[i].getName();
}
}
return fieldNames;
}
public int[] getFieldDriverPositions()
{
if( fieldDriverPositions == null )
{
int size = m_fieldCount;
fieldDriverPositions = new int[ size ];
for( int i = 0; i < size; i++ )
{
ResultFieldMetadata column = projectedCols[i];
fieldDriverPositions[i] = column.getDriverPosition();
}
}
return fieldDriverPositions;
}
public String getFieldName( int index ) throws DataException
{
return projectedCols[index - 1].getName();
}
public String getFieldAlias( int index ) throws DataException
{
return projectedCols[index - 1].getAlias();
}
public int getFieldIndex( String fieldName )
{
Integer i =
(Integer) nameToIdMapping.get( fieldName );//.toUpperCase( ) );
return ( i == null ) ? -1 : i.intValue();
}
private int doGetFieldIndex( String fieldName ) throws DataException
{
int index = getFieldIndex( fieldName );
if( index <= 0 )
throw new DataException( ResourceConstants.INVALID_FIELD_NAME, fieldName );
return index;
}
public Class getFieldValueClass( String fieldName ) throws DataException
{
int index = doGetFieldIndex( fieldName );
return getFieldValueClass( index );
}
public Class getFieldValueClass( int index ) throws DataException
{
return projectedCols[index - 1].getDataType();
}
public boolean isCustomField( String fieldName ) throws DataException
{
int index = doGetFieldIndex( fieldName );
return isCustomField( index );
}
public boolean isCustomField( int index ) throws DataException
{
return projectedCols[index - 1].isCustom();
}
public String getFieldLabel( int index ) throws DataException
{
return projectedCols[index - 1].getLabel();
}
public String getFieldNativeTypeName( int index ) throws DataException
{
return projectedCols[index - 1].getNativeTypeName();
}
public ResultFieldMetadata getFieldMetaData( int index )
throws DataException
{
return projectedCols[index - 1];
}
/*
* (non-Javadoc)
* @see org.eclipse.birt.data.engine.odi.IResultClass#existCloborBlob()
*/
public boolean hasClobOrBlob( ) throws DataException
{
return getResultClasstHelper( ).hasClobOrBlob( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.data.engine.odi.IResultClass#getClobIndexArray()
*/
public int[] getClobFieldIndexes( ) throws DataException
{
return getResultClasstHelper( ).getClobIndexArray( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.data.engine.odi.IResultClass#getBlobIndexArray()
*/
public int[] getBlobFieldIndexes( ) throws DataException
{
return getResultClasstHelper( ).getBlobIndexArray( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.data.engine.odi.IResultClass#getResultObjectHelper()
*/
public ResultClassHelper getResultClasstHelper( ) throws DataException
{
if ( resultClassHelper == null )
resultClassHelper = new ResultClassHelper( this );
return resultClassHelper;
}
/*
* (non-Javadoc)
* @see org.eclipse.birt.data.engine.odi.IResultClass#hasAny()
*/
public boolean hasAnyTYpe( ) throws DataException
{
if( this.hasAny )
{
for ( int i = 0; i < projectedCols.length; i++ )
{
if( this.isOfAnyType( projectedCols[i] ) )
return this.hasAny;
}
this.hasAny = false;
}
return this.hasAny;
}
/**
*
* @param name
* @return
* @throws DataException
*/
public boolean wasAnyType( String name ) throws DataException
{
Iterator it = this.originalAnyTypeField.iterator( );
while ( it.hasNext( ) )
{
int index = ((Integer)it.next( )).intValue( );
if ( this.getFieldName( index ).equals( name ) || this.getFieldAlias( index ).equals( name ))
return true;
}
return false;
}
/**
*
* @param index
* @return
*/
public boolean wasAnyType( int index )
{
Iterator it = this.originalAnyTypeField.iterator( );
while ( it.hasNext( ) )
{
if ( index == ((Integer)it.next( )).intValue( ))
return true;
}
return false;
}
}
| data/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/executor/ResultClass.java | /*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.data.engine.executor;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.birt.core.data.DataType.AnyType;
import org.eclipse.birt.core.util.IOUtil;
import org.eclipse.birt.data.engine.core.DataException;
import org.eclipse.birt.data.engine.executor.cache.ResultSetUtil;
import org.eclipse.birt.data.engine.i18n.ResourceConstants;
import org.eclipse.birt.data.engine.odi.IResultClass;
/**
* <code>ResultClass</code> contains the metadata about
* the projected columns in the result set.
*/
public class ResultClass implements IResultClass
{
private ResultFieldMetadata[] projectedCols;
private int m_fieldCount;
private HashMap nameToIdMapping;
private String[] fieldNames;
private int[] fieldDriverPositions;
private ResultClassHelper resultClassHelper;
private boolean hasAny;
private List originalAnyTypeField;
public ResultClass( List projectedColumns ) throws DataException
{
assert( projectedColumns != null );
initColumnsInfo( projectedColumns );
}
/**
*
* @param projectedColumns
* @throws DataException
*/
private void validateProjectColumns( ResultFieldMetadata[] projectedColumns ) throws DataException
{
Set columnNameSet = new HashSet();
for( int i = 0; i < projectedColumns.length; i++ )
{
ResultFieldMetadata column = projectedColumns[i];
if ( columnNameSet.contains( column.getName( ) ) )
{
throw new DataException( ResourceConstants.DUPLICATE_COLUMN_NAME,
column.getName( ) );
}
if ( columnNameSet.contains( column.getAlias( ) ) )
{
throw new DataException( ResourceConstants.DUPLICATE_COLUMN_NAME,
column.getAlias( ) );
}
columnNameSet.add( column.getName());
if( column.getAlias()!= null )
columnNameSet.add(column.getAlias());
}
}
/**
* @param projectedColumns
*/
private void initColumnsInfo( List projectedColumns )
{
m_fieldCount = projectedColumns.size( );
projectedCols = new ResultFieldMetadata[m_fieldCount];
nameToIdMapping = new HashMap( );
this.originalAnyTypeField = new ArrayList();
for ( int i = 0, n = projectedColumns.size( ); i < n; i++ )
{
projectedCols[i] = (ResultFieldMetadata) projectedColumns.get( i );
ResultFieldMetadata column = projectedCols[i];
if( isOfAnyType( column ))
{
this.hasAny = true;
this.originalAnyTypeField.add( new Integer( i + 1 ) );
}
String upperCaseName = column.getName( );
//if ( upperCaseName != null )
// upperCaseName = upperCaseName.toUpperCase( );
// need to add 1 to the 0-based array index, so we can put the
// 1-based index into the name-to-id mapping that will be used
// for the rest of the interfaces in this class
Integer index = new Integer( i + 1 );
// If the name is a duplicate of an existing column name or alias,
// this entry is not put into the mapping table. This effectively
// makes this entry inaccessible by name, which is the intended
// behavior
if ( !nameToIdMapping.containsKey( upperCaseName ) )
{
nameToIdMapping.put( upperCaseName, index );
}
String upperCaseAlias = column.getAlias( );
//if ( upperCaseAlias != null )
// upperCaseAlias = upperCaseAlias.toUpperCase( );
if ( upperCaseAlias != null
&& upperCaseAlias.length( ) > 0
&& !nameToIdMapping.containsKey( upperCaseAlias ) )
{
nameToIdMapping.put( upperCaseAlias, index );
}
}
}
/**
*
* @param column
* @return
*/
private boolean isOfAnyType( ResultFieldMetadata column )
{
return column.getDataType( ).getName( ).equals( AnyType.class.getName( ) );
}
/**
* New an instance of ResultClass from input stream.
*
* @param inputStream
* @throws DataException
*/
public ResultClass( InputStream inputStream ) throws DataException
{
assert inputStream != null;
DataInputStream dis = new DataInputStream( inputStream );
try
{
List newProjectedColumns = new ArrayList( );
int size = IOUtil.readInt( dis );
for ( int i = 0; i < size; i++ )
{
int driverPos = IOUtil.readInt( dis );
String name = IOUtil.readString( dis );
String lable = IOUtil.readString( dis );
String alias = IOUtil.readString( dis );
String dtName = IOUtil.readString( dis );
String ntName = IOUtil.readString( dis );
boolean bool = IOUtil.readBool( dis );
String dpdpName = IOUtil.readString( dis );
ResultFieldMetadata metaData = new ResultFieldMetadata( driverPos,
name,
lable,
Class.forName( dtName ),
ntName,
bool );
metaData.setAlias( alias );
if ( dpdpName != null )
metaData.setDriverProvidedDataType( Class.forName( dpdpName ) );
newProjectedColumns.add( metaData );
}
dis.close( );
initColumnsInfo( newProjectedColumns );
}
catch ( ClassNotFoundException e )
{
throw new DataException( ResourceConstants.RD_LOAD_ERROR,
e,
"Result Class" );
}
catch ( IOException e )
{
throw new DataException( ResourceConstants.RD_LOAD_ERROR,
e,
"Result Class" );
}
}
/**
* Serialize instance status into output stream.
*
* @param outputStream
* @throws DataException
*/
public void doSave( OutputStream outputStream, Map requestColumnMap )
throws DataException
{
assert outputStream != null;
DataOutputStream dos = new DataOutputStream( outputStream );
Set resultSetNameSet = ResultSetUtil.getRsColumnRequestMap( requestColumnMap );
// If there are refrences on columnName and columnAlias in
// resultSetNameSet, size--;
int size = resultSetNameSet.size( );
for ( int i = 0; i < projectedCols.length; i++ )
{
String columnName = projectedCols[i].getName( );
String columnAlias = projectedCols[i].getAlias( );
if ( resultSetNameSet.contains( columnName )
&& resultSetNameSet.contains( columnAlias ) )
size--;
}
try
{
IOUtil.writeInt( outputStream, size );
int writeCount = 0;
for ( int i = 0; i < m_fieldCount; i++ )
{
ResultFieldMetadata column = projectedCols[i];
// check if result set contains the column, if exists, remove it
// from the result set for further invalid columns collecting
if (resultSetNameSet.remove(column.getName())
|| resultSetNameSet.remove(column.getAlias()))
{
IOUtil.writeInt( dos, column.getDriverPosition( ) );
IOUtil.writeString( dos, column.getName( ) );
IOUtil.writeString( dos, column.getLabel( ) );
IOUtil.writeString( dos, column.getAlias( ) );
IOUtil.writeString( dos, column.getDataType( ).getName( ) );
IOUtil.writeString( dos, column.getNativeTypeName( ) );
IOUtil.writeBool( dos, column.isCustom( ) );
if ( column.getDriverProvidedDataType( ) == null )
IOUtil.writeString( dos, null );
else
IOUtil.writeString( dos,
column.getDriverProvidedDataType( ).getName( ) );
writeCount++;
}
}
if ( writeCount != size)
{
validateProjectColumns( projectedCols );
StringBuffer buf = new StringBuffer( );
for ( Iterator i = resultSetNameSet.iterator( ); i.hasNext( ); )
{
String colName = (String) i.next( );
buf.append( colName );
buf.append( ',' );
}
buf.deleteCharAt( buf.length( ) - 1 );
throw new DataException( ResourceConstants.RESULT_CLASS_SAVE_ERROR,
buf.toString( ) );
}
dos.close( );
}
catch ( IOException e )
{
throw new DataException( ResourceConstants.RD_SAVE_ERROR,
e,
"Result Class" );
}
}
public int getFieldCount()
{
return m_fieldCount;
}
// returns the field names in the projected order
// or an empty array if no fields were projected
public String[] getFieldNames()
{
return doGetFieldNames();
}
private String[] doGetFieldNames()
{
if( fieldNames == null )
{
int size = m_fieldCount;
fieldNames = new String[ size ];
for( int i = 0; i < size; i++ )
{
fieldNames[i] = projectedCols[i].getName();
}
}
return fieldNames;
}
public int[] getFieldDriverPositions()
{
if( fieldDriverPositions == null )
{
int size = m_fieldCount;
fieldDriverPositions = new int[ size ];
for( int i = 0; i < size; i++ )
{
ResultFieldMetadata column = projectedCols[i];
fieldDriverPositions[i] = column.getDriverPosition();
}
}
return fieldDriverPositions;
}
public String getFieldName( int index ) throws DataException
{
return projectedCols[index - 1].getName();
}
public String getFieldAlias( int index ) throws DataException
{
return projectedCols[index - 1].getAlias();
}
public int getFieldIndex( String fieldName )
{
Integer i =
(Integer) nameToIdMapping.get( fieldName );//.toUpperCase( ) );
return ( i == null ) ? -1 : i.intValue();
}
private int doGetFieldIndex( String fieldName ) throws DataException
{
int index = getFieldIndex( fieldName );
if( index <= 0 )
throw new DataException( ResourceConstants.INVALID_FIELD_NAME, fieldName );
return index;
}
public Class getFieldValueClass( String fieldName ) throws DataException
{
int index = doGetFieldIndex( fieldName );
return getFieldValueClass( index );
}
public Class getFieldValueClass( int index ) throws DataException
{
return projectedCols[index - 1].getDataType();
}
public boolean isCustomField( String fieldName ) throws DataException
{
int index = doGetFieldIndex( fieldName );
return isCustomField( index );
}
public boolean isCustomField( int index ) throws DataException
{
return projectedCols[index - 1].isCustom();
}
public String getFieldLabel( int index ) throws DataException
{
return projectedCols[index - 1].getLabel();
}
public String getFieldNativeTypeName( int index ) throws DataException
{
return projectedCols[index - 1].getNativeTypeName();
}
public ResultFieldMetadata getFieldMetaData( int index )
throws DataException
{
return projectedCols[index - 1];
}
/*
* (non-Javadoc)
* @see org.eclipse.birt.data.engine.odi.IResultClass#existCloborBlob()
*/
public boolean hasClobOrBlob( ) throws DataException
{
return getResultClasstHelper( ).hasClobOrBlob( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.data.engine.odi.IResultClass#getClobIndexArray()
*/
public int[] getClobFieldIndexes( ) throws DataException
{
return getResultClasstHelper( ).getClobIndexArray( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.data.engine.odi.IResultClass#getBlobIndexArray()
*/
public int[] getBlobFieldIndexes( ) throws DataException
{
return getResultClasstHelper( ).getBlobIndexArray( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.data.engine.odi.IResultClass#getResultObjectHelper()
*/
public ResultClassHelper getResultClasstHelper( ) throws DataException
{
if ( resultClassHelper == null )
resultClassHelper = new ResultClassHelper( this );
return resultClassHelper;
}
/*
* (non-Javadoc)
* @see org.eclipse.birt.data.engine.odi.IResultClass#hasAny()
*/
public boolean hasAnyTYpe( ) throws DataException
{
if( this.hasAny )
{
for ( int i = 0; i < projectedCols.length; i++ )
{
if( this.isOfAnyType( projectedCols[i] ) )
return this.hasAny;
}
this.hasAny = false;
}
return this.hasAny;
}
/**
*
* @param name
* @return
* @throws DataException
*/
public boolean wasAnyType( String name ) throws DataException
{
Iterator it = this.originalAnyTypeField.iterator( );
while ( it.hasNext( ) )
{
int index = ((Integer)it.next( )).intValue( );
if ( this.getFieldName( index ).equals( name ) || this.getFieldAlias( index ).equals( name ))
return true;
}
return false;
}
/**
*
* @param index
* @return
*/
public boolean wasAnyType( int index )
{
Iterator it = this.originalAnyTypeField.iterator( );
while ( it.hasNext( ) )
{
if ( index == ((Integer)it.next( )).intValue( ))
return true;
}
return false;
}
}
| CheckIn:Fix bugzilla bug 187793Scripted DataSource from Library fails
| data/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/executor/ResultClass.java | CheckIn:Fix bugzilla bug 187793Scripted DataSource from Library fails | <ide><path>ata/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/executor/ResultClass.java
<ide> {
<ide> String columnName = projectedCols[i].getName( );
<ide> String columnAlias = projectedCols[i].getAlias( );
<del> if ( resultSetNameSet.contains( columnName )
<del> && resultSetNameSet.contains( columnAlias ) )
<add> if ( columnName != null &&
<add> !columnName.equals( columnAlias ) &&
<add> resultSetNameSet.contains( columnName ) &&
<add> resultSetNameSet.contains( columnAlias ) )
<ide> size--;
<ide> }
<ide> |
|
Java | apache-2.0 | 1037cb819723e3f4ffab35c08e412752f661ceaf | 0 | ProjectPersephone/Orekit,liscju/Orekit,liscju/Orekit,attatrol/Orekit,petrushy/Orekit,CS-SI/Orekit,ProjectPersephone/Orekit,treeform/orekit,Yakushima/Orekit,petrushy/Orekit,Yakushima/Orekit,attatrol/Orekit,CS-SI/Orekit,wardev/orekit | /* Copyright 2002-2010 CS Communication & Systèmes
* Licensed to CS Communication & Systèmes (CS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* CS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.orekit.propagation.numerical;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.apache.commons.math.ode.DerivativeException;
import org.apache.commons.math.ode.FirstOrderDifferentialEquations;
import org.apache.commons.math.ode.FirstOrderIntegrator;
import org.apache.commons.math.ode.IntegratorException;
import org.apache.commons.math.ode.events.EventHandler;
import org.apache.commons.math.ode.sampling.DummyStepHandler;
import org.orekit.attitudes.Attitude;
import org.orekit.attitudes.AttitudeLaw;
import org.orekit.attitudes.InertialLaw;
import org.orekit.errors.OrekitException;
import org.orekit.errors.OrekitMessages;
import org.orekit.errors.PropagationException;
import org.orekit.forces.ForceModel;
import org.orekit.frames.Frame;
import org.orekit.orbits.EquinoctialOrbit;
import org.orekit.propagation.BoundedPropagator;
import org.orekit.propagation.Propagator;
import org.orekit.propagation.SpacecraftState;
import org.orekit.propagation.events.AdaptedEventDetector;
import org.orekit.propagation.events.EventDetector;
import org.orekit.propagation.sampling.AdaptedStepHandler;
import org.orekit.propagation.sampling.OrekitFixedStepHandler;
import org.orekit.propagation.sampling.OrekitStepHandler;
import org.orekit.propagation.sampling.OrekitStepNormalizer;
import org.orekit.time.AbsoluteDate;
import org.orekit.utils.PVCoordinates;
/** This class propagates {@link org.orekit.orbits.Orbit orbits} using
* numerical integration.
* <p>Numerical propagation is much more accurate than analytical propagation
* like for example {@link org.orekit.propagation.analytical.KeplerianPropagator
* keplerian} or {@link org.orekit.propagation.analytical.EcksteinHechlerPropagator
* Eckstein-Hechler}, but requires a few more steps to set up to be used properly.
* Whereas analytical propagators are configured only thanks to their various
* constructors and can be used immediately after construction, numerical propagators
* configuration involve setting several parameters between construction time
* and propagation time.</p>
* <p>The configuration parameters that can be set are:</p>
* <ul>
* <li>the initial spacecraft state ({@link #setInitialState(SpacecraftState)})</li>
* <li>the central attraction coefficient ({@link #setMu(double)})</li>
* <li>the various force models ({@link #addForceModel(ForceModel)},
* {@link #removeForceModels()})</li>
* <li>the discrete events that should be triggered during propagation
* ({@link #addEventDetector(EventDetector)},
* {@link #clearEventsDetectors()})</li>
* <li>the binding logic with the rest of the application ({@link #setSlaveMode()},
* {@link #setMasterMode(double, OrekitFixedStepHandler)}, {@link
* #setMasterMode(OrekitStepHandler)}, {@link #setEphemerisMode()}, {@link
* #getGeneratedEphemeris()})</li>
* </ul>
* <p>From these configuration parameters, only the initial state is mandatory. If the
* central attraction coefficient is not explicitly specified, the one used to define
* the initial orbit will be used. However, specifying only the initial state and
* perhaps the central attraction coefficient would mean the propagator would use only
* keplerian forces. In this case, the simpler {@link
* org.orekit.propagation.analytical.KeplerianPropagator KeplerianPropagator} class would
* perhaps be more effective. The propagator is only in one mode at a time.</p>
* <p>The underlying numerical integrator set up in the constructor may also have its own
* configuration parameters. Typical configuration parameters for adaptive stepsize integrators
* are the min, max and perhaps start step size as well as the absolute and/or relative errors
* thresholds. The state that is seen by the integrator is a simple seven elements double array.
* The six first elements are the {@link EquinoctialOrbit equinoxial orbit parameters} (a, e<sub>x</sub>,
* e<sub>y</sub>, h<sub>x</sub>, h<sub>y</sub>, l<sub>v</sub>) in meters and radians, and
* the last element is the mass in kilograms. The following code snippet shows a typical
* setting for Low Earth Orbit propagation:</p>
* <pre>
* final double minStep = 0.001;
* final double maxStep = 1000;
* final double initStep = 60;
* final double[] absTolerance = {
* 0.001, 1.0e-9, 1.0e-9, 1.0e-6, 1.0e-6, 1.0e-6, 0.001
* };
* final double[] relTolerance = {
* 1.0e-7, 1.0e-4, 1.0e-4, 1.0e-7, 1.0e-7, 1.0e-7, 1.0e-7
* };
* AdaptiveStepsizeIntegrator integrator =
* new DormandPrince853Integrator(minStep, maxStep, absTolerance, relTolerance);
* integrator.setInitialStepSize(initStep);
* propagator = new NumericalPropagator(integrator);
* </pre>
* <p>The same propagator can be reused for several orbit extrapolations, by resetting
* the initial state without modifying the other configuration parameters. However, the
* same instance cannot be used simultaneously by different threads, the class is not
* thread-safe.</p>
* @see SpacecraftState
* @see ForceModel
* @see OrekitStepHandler
* @see OrekitFixedStepHandler
* @see IntegratedEphemeris
* @see TimeDerivativesEquations
*
* @author Mathieu Roméro
* @author Luc Maisonobe
* @author Guylaine Prat
* @author Fabien Maussion
* @author Véronique Pommier-Maurussane
* @version $Revision$ $Date$
*/
public class NumericalPropagator implements Propagator {
/** Serializable UID. */
private static final long serialVersionUID = -2385169798425713766L;
// CHECKSTYLE: stop VisibilityModifierCheck
/** Attitude law. */
protected AttitudeLaw attitudeLaw;
/** Central body gravitational constant. */
protected double mu;
/** Force models used during the extrapolation of the Orbit. */
protected final List<ForceModel> forceModels;
/** Event detectors not related to force models. */
protected final List<EventDetector> detectors;
/** State vector. */
protected final double[] stateVector;
/** Start date. */
protected AbsoluteDate startDate;
/** Initial state to propagate. */
protected SpacecraftState initialState;
/** Current state to propagate. */
protected SpacecraftState currentState;
/** Integrator selected by the user for the orbital extrapolation process. */
protected transient FirstOrderIntegrator integrator;
/** Counter for differential equations calls. */
protected int calls;
/** Gauss equations handler. */
protected TimeDerivativesEquations adder;
/** Propagator mode handler. */
protected ModeHandler modeHandler;
/** Current mode. */
protected int mode;
// CHECKSTYLE: resume VisibilityModifierCheck
/** Create a new instance of NumericalPropagator, based on orbit definition mu.
* After creation, the instance is empty, i.e. the attitude law is set to an
* unspecified default law and there are no perturbing forces at all.
* This means that if {@link #addForceModel addForceModel} is not
* called after creation, the integrated orbit will follow a keplerian
* evolution only.
* @param integrator numerical integrator to use for propagation.
*/
public NumericalPropagator(final FirstOrderIntegrator integrator) {
this.mu = Double.NaN;
this.forceModels = new ArrayList<ForceModel>();
this.detectors = new ArrayList<EventDetector>();
this.startDate = new AbsoluteDate();
this.currentState = null;
this.adder = null;
this.attitudeLaw = InertialLaw.EME2000_ALIGNED;
this.stateVector = new double[7];
setIntegrator(integrator);
setSlaveMode();
}
/** Set the integrator.
* @param integrator numerical integrator to use for propagation.
*/
public void setIntegrator(final FirstOrderIntegrator integrator) {
this.integrator = integrator;
}
/** Set the central attraction coefficient μ.
* @param mu central attraction coefficient (m^3/s^2)
* @see #getMu()
* @see #addForceModel(ForceModel)
*/
public void setMu(final double mu) {
this.mu = mu;
}
/** Get the central attraction coefficient μ.
* @return mu central attraction coefficient (m^3/s^2)
* @see #setMu(double)
*/
public double getMu() {
return mu;
}
/** Set the attitude law.
* @param attitudeLaw attitude law
*/
public void setAttitudeLaw(final AttitudeLaw attitudeLaw) {
this.attitudeLaw = attitudeLaw;
}
/** {@inheritDoc} */
public void addEventDetector(final EventDetector detector) {
detectors.add(detector);
}
/** {@inheritDoc} */
public Collection<EventDetector>getEventsDetectors() {
return Collections.unmodifiableCollection(detectors);
}
/** {@inheritDoc} */
public void clearEventsDetectors() {
detectors.clear();
}
/** Add a force model to the global perturbation model.
* <p>If the force models is associated to discrete events, these
* events will be handled automatically, they must <strong>not</strong>
* be added using the {@link #addEventDetector(EventDetector) addEventDetector}
* method.</p>
* <p>If this method is not called at all, the integrated orbit will follow
* a keplerian evolution only.</p>
* @param model perturbing {@link ForceModel} to add
* @see #removeForceModels()
* @see #setMu(double)
*/
public void addForceModel(final ForceModel model) {
forceModels.add(model);
}
/** Remove all perturbing force models from the global perturbation model.
* <p>Once all perturbing forces have been removed (and as long as no new force
* model is added), the integrated orbit will follow a keplerian evolution
* only.</p>
* @see #addForceModel(ForceModel)
*/
public void removeForceModels() {
forceModels.clear();
}
/** {@inheritDoc} */
public int getMode() {
return mode;
}
/** {@inheritDoc}
* <p>Note that this method has the side effect of replacing the step handlers
* of the underlying integrator set up in the {@link
* #NumericalPropagator(FirstOrderIntegrator) constructor} or the {@link
* #setIntegrator(FirstOrderIntegrator) setIntegrator} method. So if a specific
* step handler is needed, it should be added after this method has been callled.</p>
*/
public void setSlaveMode() {
integrator.clearStepHandlers();
integrator.addStepHandler(DummyStepHandler.getInstance());
modeHandler = null;
mode = SLAVE_MODE;
}
/** {@inheritDoc}
* <p>Note that this method has the side effect of replacing the step handlers
* of the underlying integrator set up in the {@link
* #NumericalPropagator(FirstOrderIntegrator) constructor} or the {@link
* #setIntegrator(FirstOrderIntegrator) setIntegrator} method. So if a specific
* step handler is needed, it should be added after this method has been callled.</p>
*/
public void setMasterMode(final double h, final OrekitFixedStepHandler handler) {
setMasterMode(new OrekitStepNormalizer(h, handler));
}
/** {@inheritDoc}
* <p>Note that this method has the side effect of replacing the step handlers
* of the underlying integrator set up in the {@link
* #NumericalPropagator(FirstOrderIntegrator) constructor} or the {@link
* #setIntegrator(FirstOrderIntegrator) setIntegrator} method. So if a specific
* step handler is needed, it should be added after this method has been callled.</p>
*/
public void setMasterMode(final OrekitStepHandler handler) {
integrator.clearStepHandlers();
final AdaptedStepHandler wrapped = new AdaptedStepHandler(handler);
integrator.addStepHandler(wrapped);
modeHandler = wrapped;
mode = MASTER_MODE;
}
/** {@inheritDoc}
* <p>Note that this method has the side effect of replacing the step handlers
* of the underlying integrator set up in the {@link
* #NumericalPropagator(FirstOrderIntegrator) constructor} or the {@link
* #setIntegrator(FirstOrderIntegrator) setIntegrator} method. So if a specific
* step handler is needed, it should be added after this method has been callled.</p>
*/
public void setEphemerisMode() {
integrator.clearStepHandlers();
final IntegratedEphemeris ephemeris = new IntegratedEphemeris();
integrator.addStepHandler(ephemeris);
modeHandler = ephemeris;
mode = EPHEMERIS_GENERATION_MODE;
}
/** {@inheritDoc} */
public BoundedPropagator getGeneratedEphemeris()
throws IllegalStateException {
if (mode != EPHEMERIS_GENERATION_MODE) {
throw OrekitException.createIllegalStateException(OrekitMessages.PROPAGATOR_NOT_IN_EPHEMERIS_GENERATION_MODE);
}
return (IntegratedEphemeris) modeHandler;
}
/** {@inheritDoc} */
public SpacecraftState getInitialState() {
return initialState;
}
/** Set the initial state.
* @param initialState initial state
* @see #propagate(AbsoluteDate)
*/
public void setInitialState(final SpacecraftState initialState) {
resetInitialState(initialState);
}
/** {@inheritDoc} */
public void resetInitialState(final SpacecraftState state) {
if (Double.isNaN(mu)) {
mu = state.getMu();
}
this.initialState = state;
}
/** {@inheritDoc} */
public SpacecraftState propagate(final AbsoluteDate finalDate)
throws PropagationException {
try {
if (initialState == null) {
throw new PropagationException(OrekitMessages.INITIAL_STATE_NOT_SPECIFIED_FOR_ORBIT_PROPAGATION);
}
if (initialState.getDate().equals(finalDate)) {
// don't extrapolate
return initialState;
}
if (integrator == null) {
throw new PropagationException(OrekitMessages.ODE_INTEGRATOR_NOT_SET_FOR_ORBIT_PROPAGATION);
}
// space dynamics view
startDate = initialState.getDate();
if (modeHandler != null) {
modeHandler.initialize(startDate, initialState.getFrame(), mu, attitudeLaw);
}
final EquinoctialOrbit initialOrbit =
new EquinoctialOrbit(initialState.getOrbit());
currentState =
new SpacecraftState(initialOrbit, initialState.getAttitude(), initialState.getMass());
adder = new TimeDerivativesEquations(initialOrbit);
if (initialState.getMass() <= 0.0) {
throw new IllegalArgumentException("Mass is null or negative");
}
// mathematical view
final double t0 = 0;
final double t1 = finalDate.durationFrom(startDate);
// Map state to array
stateVector[0] = initialOrbit.getA();
stateVector[1] = initialOrbit.getEquinoctialEx();
stateVector[2] = initialOrbit.getEquinoctialEy();
stateVector[3] = initialOrbit.getHx();
stateVector[4] = initialOrbit.getHy();
stateVector[5] = initialOrbit.getLv();
stateVector[6] = initialState.getMass();
integrator.clearEventHandlers();
// set up events related to force models
for (final ForceModel forceModel : forceModels) {
final EventDetector[] modelDetectors = forceModel.getEventsDetectors();
if (modelDetectors != null) {
for (final EventDetector detector : modelDetectors) {
setUpEventDetector(detector);
}
}
}
// set up events added by user
for (final EventDetector detector : detectors) {
setUpEventDetector(detector);
}
// mathematical integration
final double stopTime = integrator.integrate(new DifferentialEquations(), t0, stateVector, t1, stateVector);
// back to space dynamics view
final AbsoluteDate date = startDate.shiftedBy(stopTime);
final EquinoctialOrbit orbit =
new EquinoctialOrbit(stateVector[0], stateVector[1], stateVector[2], stateVector[3],
stateVector[4], stateVector[5], EquinoctialOrbit.TRUE_LATITUDE_ARGUMENT,
initialOrbit.getFrame(), date, mu);
resetInitialState(new SpacecraftState(orbit, attitudeLaw.getAttitude(orbit), stateVector[6]));
return initialState;
} catch (OrekitException oe) {
throw new PropagationException(oe);
} catch (DerivativeException de) {
// recover a possible embedded PropagationException
for (Throwable t = de; t != null; t = t.getCause()) {
if (t instanceof PropagationException) {
throw (PropagationException) t;
}
}
throw new PropagationException(de, de.getLocalizablePattern(), de.getArguments());
} catch (IntegratorException ie) {
// recover a possible embedded PropagationException
for (Throwable t = ie; t != null; t = t.getCause()) {
if (t instanceof PropagationException) {
throw (PropagationException) t;
}
}
throw new PropagationException(ie, ie.getLocalizablePattern(), ie.getArguments());
}
}
/** {@inheritDoc} */
public PVCoordinates getPVCoordinates(final AbsoluteDate date, final Frame frame)
throws OrekitException {
return propagate(date).getPVCoordinates(frame);
}
/** Get the number of calls to the differential equations computation method.
* <p>The number of calls is reset each time the {@link #propagate(AbsoluteDate)}
* method is called.</p>
* @return number of calls to the differential equations computation method
*/
public int getCalls() {
return calls;
}
/** Wrap an Orekit event detector and register it to the integrator.
* @param osf event handler to wrap
*/
protected void setUpEventDetector(final EventDetector osf) {
final EventHandler handler =
new AdaptedEventDetector(osf, startDate, mu,
initialState.getFrame(), attitudeLaw);
integrator.addEventHandler(handler,
osf.getMaxCheckInterval(),
osf.getThreshold(),
osf.getMaxIterationCount());
}
/** Internal class for differential equations representation. */
private class DifferentialEquations implements FirstOrderDifferentialEquations {
/** Serializable UID. */
private static final long serialVersionUID = -1927530118454989452L;
/** Build a new instance. */
public DifferentialEquations() {
calls = 0;
}
/** {@inheritDoc} */
public int getDimension() {
return 7;
}
/** {@inheritDoc} */
public void computeDerivatives(final double t, final double[] y, final double[] yDot)
throws DerivativeException {
try {
// update space dynamics view
currentState = mapState(t, y, startDate, currentState.getFrame());
if (currentState.getMass() <= 0.0) {
throw new PropagationException(OrekitMessages.SPACECRAFT_MASS_BECOMES_NEGATIVE,
currentState.getMass());
}
// initialize derivatives
adder.initDerivatives(yDot, (EquinoctialOrbit) currentState.getOrbit());
// compute the contributions of all perturbing forces
for (final ForceModel forceModel : forceModels) {
forceModel.addContribution(currentState, adder);
}
// finalize derivatives by adding the Kepler contribution
adder.addKeplerContribution();
// increment calls counter
++calls;
} catch (OrekitException oe) {
throw new DerivativeException(oe.getSpecifier(), oe.getParts());
}
}
/** Convert state array to space dynamics objects (AbsoluteDate and OrbitalParameters).
* @param t integration time (s)
* @param y state as a flat array
* @param referenceDate reference date from which t is counted
* @param frame frame in which integration is performed
* @return state corresponding to the flat array as a space dynamics object
* @exception OrekitException if the attitude state cannot be determined
* by the attitude law
*/
private SpacecraftState mapState(final double t, final double [] y,
final AbsoluteDate referenceDate, final Frame frame)
throws OrekitException {
// convert raw mathematical data to space dynamics objects
final AbsoluteDate date = referenceDate.shiftedBy(t);
final EquinoctialOrbit orbit =
new EquinoctialOrbit(y[0], y[1], y[2], y[3], y[4], y[5],
EquinoctialOrbit.TRUE_LATITUDE_ARGUMENT,
frame, date, mu);
final Attitude attitude = attitudeLaw.getAttitude(orbit);
return new SpacecraftState(orbit, attitude, y[6]);
}
}
}
| src/main/java/org/orekit/propagation/numerical/NumericalPropagator.java | /* Copyright 2002-2010 CS Communication & Systèmes
* Licensed to CS Communication & Systèmes (CS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* CS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.orekit.propagation.numerical;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.apache.commons.math.ode.DerivativeException;
import org.apache.commons.math.ode.FirstOrderDifferentialEquations;
import org.apache.commons.math.ode.FirstOrderIntegrator;
import org.apache.commons.math.ode.IntegratorException;
import org.apache.commons.math.ode.events.EventHandler;
import org.apache.commons.math.ode.sampling.DummyStepHandler;
import org.orekit.attitudes.Attitude;
import org.orekit.attitudes.AttitudeLaw;
import org.orekit.attitudes.InertialLaw;
import org.orekit.errors.OrekitException;
import org.orekit.errors.OrekitMessages;
import org.orekit.errors.PropagationException;
import org.orekit.forces.ForceModel;
import org.orekit.frames.Frame;
import org.orekit.orbits.EquinoctialOrbit;
import org.orekit.propagation.BoundedPropagator;
import org.orekit.propagation.Propagator;
import org.orekit.propagation.SpacecraftState;
import org.orekit.propagation.events.AdaptedEventDetector;
import org.orekit.propagation.events.EventDetector;
import org.orekit.propagation.sampling.AdaptedStepHandler;
import org.orekit.propagation.sampling.OrekitFixedStepHandler;
import org.orekit.propagation.sampling.OrekitStepHandler;
import org.orekit.propagation.sampling.OrekitStepNormalizer;
import org.orekit.time.AbsoluteDate;
import org.orekit.utils.PVCoordinates;
/** This class propagates {@link org.orekit.orbits.Orbit orbits} using
* numerical integration.
* <p>Numerical propagation is much more accurate than analytical propagation
* like for example {@link org.orekit.propagation.analytical.KeplerianPropagator
* keplerian} or {@link org.orekit.propagation.analytical.EcksteinHechlerPropagator
* Eckstein-Hechler}, but requires a few more steps to set up to be used properly.
* Whereas analytical propagators are configured only thanks to their various
* constructors and can be used immediately after construction, numerical propagators
* configuration involve setting several parameters between construction time
* and propagation time.</p>
* <p>The configuration parameters that can be set are:</p>
* <ul>
* <li>the initial spacecraft state ({@link #setInitialState(SpacecraftState)})</li>
* <li>the central attraction coefficient ({@link #setMu(double)})</li>
* <li>the various force models ({@link #addForceModel(ForceModel)},
* {@link #removeForceModels()})</li>
* <li>the discrete events that should be triggered during propagation
* ({@link #addEventDetector(EventDetector)},
* {@link #clearEventsDetectors()})</li>
* <li>the binding logic with the rest of the application ({@link #setSlaveMode()},
* {@link #setMasterMode(double, OrekitFixedStepHandler)}, {@link
* #setMasterMode(OrekitStepHandler)}, {@link #setEphemerisMode()}, {@link
* #getGeneratedEphemeris()})</li>
* </ul>
* <p>From these configuration parameters, only the initial state is mandatory. If the
* central attraction coefficient is not explicitly specified, the one used to define
* the initial orbit will be used. However, specifying only the initial state and
* perhaps the central attraction coefficient would mean the propagator would use only
* keplerian forces. In this case, the simpler {@link
* org.orekit.propagation.analytical.KeplerianPropagator KeplerianPropagator} class would
* perhaps be more effective. The propagator is only in one mode at a time.</p>
* <p>The underlying numerical integrator set up in the constructor may also have its own
* configuration parameters. Typical configuration parameters for adaptive stepsize integrators
* are the min, max and perhaps start step size as well as the absolute and/or relative errors
* thresholds. The state that is seen by the integrator is a simple seven elements double array.
* The six first elements are the {@link EquinoctialOrbit equinoxial orbit parameters} (a, e<sub>x</sub>,
* e<sub>y</sub>, h<sub>x</sub>, h<sub>y</sub>, l<sub>v</sub>) in meters and radians, and
* the last element is the mass in kilograms. The following code snippet shows a typical
* setting for Low Earth Orbit propagation:</p>
* <pre>
* final double minStep = 0.001;
* final double maxStep = 1000;
* final double initStep = 60;
* final double[] absTolerance = {
* 0.001, 1.0e-9, 1.0e-9, 1.0e-6, 1.0e-6, 1.0e-6, 0.001
* };
* final double[] relTolerance = {
* 1.0e-7, 1.0e-4, 1.0e-4, 1.0e-7, 1.0e-7, 1.0e-7, 1.0e-7
* };
* AdaptiveStepsizeIntegrator integrator =
* new DormandPrince853Integrator(minStep, maxStep, absTolerance, relTolerance);
* integrator.setInitialStepSize(initStep);
* propagator = new NumericalPropagator(integrator);
* </pre>
* <p>The same propagator can be reused for several orbit extrapolations, by resetting
* the initial state without modifying the other configuration parameters. However, the
* same instance cannot be used simultaneously by different threads, the class is not
* thread-safe.</p>
* @see SpacecraftState
* @see ForceModel
* @see OrekitStepHandler
* @see OrekitFixedStepHandler
* @see IntegratedEphemeris
* @see TimeDerivativesEquations
*
* @author Mathieu Roméro
* @author Luc Maisonobe
* @author Guylaine Prat
* @author Fabien Maussion
* @author Véronique Pommier-Maurussane
* @version $Revision$ $Date$
*/
public class NumericalPropagator implements Propagator {
/** Serializable UID. */
private static final long serialVersionUID = -2385169798425713766L;
// CHECKSTYLE: stop VisibilityModifierCheck
/** Attitude law. */
protected AttitudeLaw attitudeLaw;
/** Central body gravitational constant. */
protected double mu;
/** Force models used during the extrapolation of the Orbit. */
protected final List<ForceModel> forceModels;
/** Event detectors not related to force models. */
protected final List<EventDetector> detectors;
/** State vector. */
protected final double[] stateVector;
/** Start date. */
protected AbsoluteDate startDate;
/** Initial state to propagate. */
protected SpacecraftState initialState;
/** Current state to propagate. */
protected SpacecraftState currentState;
/** Integrator selected by the user for the orbital extrapolation process. */
protected transient FirstOrderIntegrator integrator;
/** Counter for differential equations calls. */
protected int calls;
/** Gauss equations handler. */
protected TimeDerivativesEquations adder;
/** Propagator mode handler. */
protected ModeHandler modeHandler;
/** Current mode. */
protected int mode;
// CHECKSTYLE: resume VisibilityModifierCheck
/** Create a new instance of NumericalPropagator, based on orbit definition mu.
* After creation, the instance is empty, i.e. the attitude law is set to an
* unspecified default law and there are no perturbing forces at all.
* This means that if {@link #addForceModel addForceModel} is not
* called after creation, the integrated orbit will follow a keplerian
* evolution only.
* @param integrator numerical integrator to use for propagation.
*/
public NumericalPropagator(final FirstOrderIntegrator integrator) {
this.mu = Double.NaN;
this.forceModels = new ArrayList<ForceModel>();
this.detectors = new ArrayList<EventDetector>();
this.startDate = new AbsoluteDate();
this.currentState = null;
this.adder = null;
this.attitudeLaw = InertialLaw.EME2000_ALIGNED;
this.stateVector = new double[7];
setIntegrator(integrator);
setSlaveMode();
}
/** Set the integrator.
* @param integrator numerical integrator to use for propagation.
*/
public void setIntegrator(final FirstOrderIntegrator integrator) {
this.integrator = integrator;
}
/** Set the central attraction coefficient μ.
* @param mu central attraction coefficient (m^3/s^2)
* @see #getMu()
* @see #addForceModel(ForceModel)
*/
public void setMu(final double mu) {
this.mu = mu;
}
/** Get the central attraction coefficient μ.
* @return mu central attraction coefficient (m^3/s^2)
* @see #setMu(double)
*/
public double getMu() {
return mu;
}
/** Set the attitude law.
* @param attitudeLaw attitude law
*/
public void setAttitudeLaw(final AttitudeLaw attitudeLaw) {
this.attitudeLaw = attitudeLaw;
}
/** {@inheritDoc} */
public void addEventDetector(final EventDetector detector) {
detectors.add(detector);
}
/** {@inheritDoc} */
public Collection<EventDetector>getEventsDetectors() {
return Collections.unmodifiableCollection(detectors);
}
/** {@inheritDoc} */
public void clearEventsDetectors() {
detectors.clear();
}
/** Add a force model to the global perturbation model.
* <p>If the force models is associated to discrete events, these
* events will be handled automatically, they must <strong>not</strong>
* be added using the {@link #addEventDetector(EventDetector) addEventDetector}
* method.</p>
* <p>If this method is not called at all, the integrated orbit will follow
* a keplerian evolution only.</p>
* @param model perturbing {@link ForceModel} to add
* @see #removeForceModels()
* @see #setMu(double)
*/
public void addForceModel(final ForceModel model) {
forceModels.add(model);
}
/** Remove all perturbing force models from the global perturbation model.
* <p>Once all perturbing forces have been removed (and as long as no new force
* model is added), the integrated orbit will follow a keplerian evolution
* only.</p>
* @see #addForceModel(ForceModel)
*/
public void removeForceModels() {
forceModels.clear();
}
/** {@inheritDoc} */
public int getMode() {
return mode;
}
/** {@inheritDoc}
* <p>Note that this method has the side effect of replacing the step handlers
* of the underlying integrator set up in the {@link
* #NumericalPropagator(FirstOrderIntegrator) constructor} or the {@link
* #setIntegrator(FirstOrderIntegrator) setIntegrator} method. So if a specific
* step handler is needed, it should be added after this method has been callled.</p>
*/
public void setSlaveMode() {
integrator.clearEventHandlers();
integrator.addStepHandler(DummyStepHandler.getInstance());
modeHandler = null;
mode = SLAVE_MODE;
}
/** {@inheritDoc}
* <p>Note that this method has the side effect of replacing the step handlers
* of the underlying integrator set up in the {@link
* #NumericalPropagator(FirstOrderIntegrator) constructor} or the {@link
* #setIntegrator(FirstOrderIntegrator) setIntegrator} method. So if a specific
* step handler is needed, it should be added after this method has been callled.</p>
*/
public void setMasterMode(final double h, final OrekitFixedStepHandler handler) {
setMasterMode(new OrekitStepNormalizer(h, handler));
}
/** {@inheritDoc}
* <p>Note that this method has the side effect of replacing the step handlers
* of the underlying integrator set up in the {@link
* #NumericalPropagator(FirstOrderIntegrator) constructor} or the {@link
* #setIntegrator(FirstOrderIntegrator) setIntegrator} method. So if a specific
* step handler is needed, it should be added after this method has been callled.</p>
*/
public void setMasterMode(final OrekitStepHandler handler) {
integrator.clearEventHandlers();
final AdaptedStepHandler wrapped = new AdaptedStepHandler(handler);
integrator.addStepHandler(wrapped);
modeHandler = wrapped;
mode = MASTER_MODE;
}
/** {@inheritDoc}
* <p>Note that this method has the side effect of replacing the step handlers
* of the underlying integrator set up in the {@link
* #NumericalPropagator(FirstOrderIntegrator) constructor} or the {@link
* #setIntegrator(FirstOrderIntegrator) setIntegrator} method. So if a specific
* step handler is needed, it should be added after this method has been callled.</p>
*/
public void setEphemerisMode() {
integrator.clearEventHandlers();
final IntegratedEphemeris ephemeris = new IntegratedEphemeris();
integrator.addStepHandler(ephemeris);
modeHandler = ephemeris;
mode = EPHEMERIS_GENERATION_MODE;
}
/** {@inheritDoc} */
public BoundedPropagator getGeneratedEphemeris()
throws IllegalStateException {
if (mode != EPHEMERIS_GENERATION_MODE) {
throw OrekitException.createIllegalStateException(OrekitMessages.PROPAGATOR_NOT_IN_EPHEMERIS_GENERATION_MODE);
}
return (IntegratedEphemeris) modeHandler;
}
/** {@inheritDoc} */
public SpacecraftState getInitialState() {
return initialState;
}
/** Set the initial state.
* @param initialState initial state
* @see #propagate(AbsoluteDate)
*/
public void setInitialState(final SpacecraftState initialState) {
resetInitialState(initialState);
}
/** {@inheritDoc} */
public void resetInitialState(final SpacecraftState state) {
if (Double.isNaN(mu)) {
mu = state.getMu();
}
this.initialState = state;
}
/** {@inheritDoc} */
public SpacecraftState propagate(final AbsoluteDate finalDate)
throws PropagationException {
try {
if (initialState == null) {
throw new PropagationException(OrekitMessages.INITIAL_STATE_NOT_SPECIFIED_FOR_ORBIT_PROPAGATION);
}
if (initialState.getDate().equals(finalDate)) {
// don't extrapolate
return initialState;
}
if (integrator == null) {
throw new PropagationException(OrekitMessages.ODE_INTEGRATOR_NOT_SET_FOR_ORBIT_PROPAGATION);
}
// space dynamics view
startDate = initialState.getDate();
if (modeHandler != null) {
modeHandler.initialize(startDate, initialState.getFrame(), mu, attitudeLaw);
}
final EquinoctialOrbit initialOrbit =
new EquinoctialOrbit(initialState.getOrbit());
currentState =
new SpacecraftState(initialOrbit, initialState.getAttitude(), initialState.getMass());
adder = new TimeDerivativesEquations(initialOrbit);
if (initialState.getMass() <= 0.0) {
throw new IllegalArgumentException("Mass is null or negative");
}
// mathematical view
final double t0 = 0;
final double t1 = finalDate.durationFrom(startDate);
// Map state to array
stateVector[0] = initialOrbit.getA();
stateVector[1] = initialOrbit.getEquinoctialEx();
stateVector[2] = initialOrbit.getEquinoctialEy();
stateVector[3] = initialOrbit.getHx();
stateVector[4] = initialOrbit.getHy();
stateVector[5] = initialOrbit.getLv();
stateVector[6] = initialState.getMass();
integrator.clearEventHandlers();
// set up events related to force models
for (final ForceModel forceModel : forceModels) {
final EventDetector[] modelDetectors = forceModel.getEventsDetectors();
if (modelDetectors != null) {
for (final EventDetector detector : modelDetectors) {
setUpEventDetector(detector);
}
}
}
// set up events added by user
for (final EventDetector detector : detectors) {
setUpEventDetector(detector);
}
// mathematical integration
final double stopTime = integrator.integrate(new DifferentialEquations(), t0, stateVector, t1, stateVector);
// back to space dynamics view
final AbsoluteDate date = startDate.shiftedBy(stopTime);
final EquinoctialOrbit orbit =
new EquinoctialOrbit(stateVector[0], stateVector[1], stateVector[2], stateVector[3],
stateVector[4], stateVector[5], EquinoctialOrbit.TRUE_LATITUDE_ARGUMENT,
initialOrbit.getFrame(), date, mu);
resetInitialState(new SpacecraftState(orbit, attitudeLaw.getAttitude(orbit), stateVector[6]));
return initialState;
} catch (OrekitException oe) {
throw new PropagationException(oe);
} catch (DerivativeException de) {
// recover a possible embedded PropagationException
for (Throwable t = de; t != null; t = t.getCause()) {
if (t instanceof PropagationException) {
throw (PropagationException) t;
}
}
throw new PropagationException(de, de.getLocalizablePattern(), de.getArguments());
} catch (IntegratorException ie) {
// recover a possible embedded PropagationException
for (Throwable t = ie; t != null; t = t.getCause()) {
if (t instanceof PropagationException) {
throw (PropagationException) t;
}
}
throw new PropagationException(ie, ie.getLocalizablePattern(), ie.getArguments());
}
}
/** {@inheritDoc} */
public PVCoordinates getPVCoordinates(final AbsoluteDate date, final Frame frame)
throws OrekitException {
return propagate(date).getPVCoordinates(frame);
}
/** Get the number of calls to the differential equations computation method.
* <p>The number of calls is reset each time the {@link #propagate(AbsoluteDate)}
* method is called.</p>
* @return number of calls to the differential equations computation method
*/
public int getCalls() {
return calls;
}
/** Wrap an Orekit event detector and register it to the integrator.
* @param osf event handler to wrap
*/
protected void setUpEventDetector(final EventDetector osf) {
final EventHandler handler =
new AdaptedEventDetector(osf, startDate, mu,
initialState.getFrame(), attitudeLaw);
integrator.addEventHandler(handler,
osf.getMaxCheckInterval(),
osf.getThreshold(),
osf.getMaxIterationCount());
}
/** Internal class for differential equations representation. */
private class DifferentialEquations implements FirstOrderDifferentialEquations {
/** Serializable UID. */
private static final long serialVersionUID = -1927530118454989452L;
/** Build a new instance. */
public DifferentialEquations() {
calls = 0;
}
/** {@inheritDoc} */
public int getDimension() {
return 7;
}
/** {@inheritDoc} */
public void computeDerivatives(final double t, final double[] y, final double[] yDot)
throws DerivativeException {
try {
// update space dynamics view
currentState = mapState(t, y, startDate, currentState.getFrame());
if (currentState.getMass() <= 0.0) {
throw new PropagationException(OrekitMessages.SPACECRAFT_MASS_BECOMES_NEGATIVE,
currentState.getMass());
}
// initialize derivatives
adder.initDerivatives(yDot, (EquinoctialOrbit) currentState.getOrbit());
// compute the contributions of all perturbing forces
for (final ForceModel forceModel : forceModels) {
forceModel.addContribution(currentState, adder);
}
// finalize derivatives by adding the Kepler contribution
adder.addKeplerContribution();
// increment calls counter
++calls;
} catch (OrekitException oe) {
throw new DerivativeException(oe.getSpecifier(), oe.getParts());
}
}
/** Convert state array to space dynamics objects (AbsoluteDate and OrbitalParameters).
* @param t integration time (s)
* @param y state as a flat array
* @param referenceDate reference date from which t is counted
* @param frame frame in which integration is performed
* @return state corresponding to the flat array as a space dynamics object
* @exception OrekitException if the attitude state cannot be determined
* by the attitude law
*/
private SpacecraftState mapState(final double t, final double [] y,
final AbsoluteDate referenceDate, final Frame frame)
throws OrekitException {
// convert raw mathematical data to space dynamics objects
final AbsoluteDate date = referenceDate.shiftedBy(t);
final EquinoctialOrbit orbit =
new EquinoctialOrbit(y[0], y[1], y[2], y[3], y[4], y[5],
EquinoctialOrbit.TRUE_LATITUDE_ARGUMENT,
frame, date, mu);
final Attitude attitude = attitudeLaw.getAttitude(orbit);
return new SpacecraftState(orbit, attitude, y[6]);
}
}
}
| fixed step handler clearing at mode switch
| src/main/java/org/orekit/propagation/numerical/NumericalPropagator.java | fixed step handler clearing at mode switch | <ide><path>rc/main/java/org/orekit/propagation/numerical/NumericalPropagator.java
<ide> * step handler is needed, it should be added after this method has been callled.</p>
<ide> */
<ide> public void setSlaveMode() {
<del> integrator.clearEventHandlers();
<add> integrator.clearStepHandlers();
<ide> integrator.addStepHandler(DummyStepHandler.getInstance());
<ide> modeHandler = null;
<ide> mode = SLAVE_MODE;
<ide> * step handler is needed, it should be added after this method has been callled.</p>
<ide> */
<ide> public void setMasterMode(final OrekitStepHandler handler) {
<del> integrator.clearEventHandlers();
<add> integrator.clearStepHandlers();
<ide> final AdaptedStepHandler wrapped = new AdaptedStepHandler(handler);
<ide> integrator.addStepHandler(wrapped);
<ide> modeHandler = wrapped;
<ide> * step handler is needed, it should be added after this method has been callled.</p>
<ide> */
<ide> public void setEphemerisMode() {
<del> integrator.clearEventHandlers();
<add> integrator.clearStepHandlers();
<ide> final IntegratedEphemeris ephemeris = new IntegratedEphemeris();
<ide> integrator.addStepHandler(ephemeris);
<ide> modeHandler = ephemeris; |
|
Java | mit | 566e8f0300f2eae2382d9a26530e3213a0ed3543 | 0 | jarvis-app/jarvis-android | package com.jarvis.jarvis;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private TextView textInput;
private final String TAG = "MainActivity";
private ImageButton speakBtn;
ProgressDialog waitDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.speakBtn = (ImageButton) findViewById(R.id.speakBtn);
speakBtn.setOnClickListener(this);
this.textInput = (TextView) findViewById(R.id.textInput);
waitDialog = new ProgressDialog(this);
waitDialog.setTitle("Processing...");
if (!HttpUtils.isNetworkAvailable(this)) {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
Intent intent = getIntent();
finish();
startActivity(intent);
break;
case DialogInterface.BUTTON_NEGATIVE:
finish();
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
AlertDialog dialog = builder.setMessage(getResources().getString(R.string.InternetNotAvailableMsg)).setPositiveButton(getResources().getString(R.string.Yes), dialogClickListener)
.setNegativeButton(getResources().getString(R.string.No), dialogClickListener).create();
dialog.setTitle(getResources().getString(R.string.NoInternetTitle));
dialog.setCanceledOnTouchOutside(false);
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
finish();
}
});
dialog.show();
}else {
// Init utils
TextSpeechUtils.init(this);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
showSettingsDlg();
return true;
}
return super.onOptionsItemSelected(item);
}
public void queryJarvisServer(String input)
{
showWaitDialog();
try {
JarvisServerUtils.getQueryResult(input, new HttpUtils.Callback() {
@Override
public void onResult(String responseStr) {
hideWaitDialog();
speakBtn.setImageDrawable(getResources().getDrawable(R.drawable.ic_microphone));
if(responseStr == null || responseStr.isEmpty())
showErrorResponse();
else {
try {
HttpUtils.Callback translatorCallback = new HttpUtils.Callback() {
@Override
public void onResult(String translatedStr) {
textInput.setText(translatedStr);
translatedStr = translatedStr.replace(",", "");
TextSpeechUtils.speakText(translatedStr);
}
};
if(PrefManager.langEnglish(MainActivity.this.getApplicationContext()))
TranslatorUtils.translateToEnglish(responseStr, translatorCallback);
else
TranslatorUtils.translateToHindi(responseStr, translatorCallback);
}catch (Exception e)
{
hideWaitDialog();
showErrorResponse();
}
}
}
});
}catch (Exception e)
{
hideWaitDialog();
showErrorResponse();
}
}
@Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.speakBtn:
TextSpeechUtils.getVoiceInput(new TextSpeechUtils.TextSpeechUtilsCallback() {
@Override
public void onSpeechStart() {
}
@Override
public void onPartialSpeech(String input) {
textInput.setText(input);
}
@Override
public void onSpeechInputComplete(String input) {
try {
textInput.setText(input);
HttpUtils.Callback translatorCallback = new HttpUtils.Callback() {
@Override
public void onResult(String translatedText) {
queryJarvisServer(translatedText);
}
};
TranslatorUtils.translateToEnglish(input, translatorCallback);
}catch (Exception e)
{
textInput.setText(e.getMessage());
showErrorResponse();
}
}
});
speakBtn.setImageDrawable(getResources().getDrawable(R.drawable.ic_microphone_active));
break;
}
}
public void showWaitDialog()
{
if(this.waitDialog == null )
{
waitDialog = new ProgressDialog(this);
waitDialog.setTitle("Processing...");
}
this.waitDialog.show();
}
public void hideWaitDialog()
{
if(this.waitDialog !=null && this.waitDialog.isShowing()) {
this.waitDialog.hide();
}
}
public void showErrorResponse()
{
String msg = "Some error has occurred while processing your request";
if(PrefManager.langEnglish(getApplicationContext()))
TextSpeechUtils.speakText(msg);
else
{
try {
TranslatorUtils.translateToHindi(msg, new HttpUtils.Callback() {
@Override
public void onResult(String translatedMsg) {
TextSpeechUtils.speakText(translatedMsg);
}
});
}catch (Exception e)
{
}
}
}
public void showSettingsDlg()
{
Intent intent = new Intent(this, PreferenceActivity.class);
startActivity(intent);
}
}
| app/src/main/java/com/jarvis/jarvis/MainActivity.java | package com.jarvis.jarvis;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private TextView textInput;
private final String TAG = "MainActivity";
private ImageButton speakBtn;
ProgressDialog waitDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.speakBtn = (ImageButton) findViewById(R.id.speakBtn);
speakBtn.setOnClickListener(this);
this.textInput = (TextView) findViewById(R.id.textInput);
waitDialog = new ProgressDialog(this);
waitDialog.setTitle("Processing...");
if (!HttpUtils.isNetworkAvailable(this)) {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
Intent intent = getIntent();
finish();
startActivity(intent);
break;
case DialogInterface.BUTTON_NEGATIVE:
finish();
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
AlertDialog dialog = builder.setMessage(getResources().getString(R.string.InternetNotAvailableMsg)).setPositiveButton(getResources().getString(R.string.Yes), dialogClickListener)
.setNegativeButton(getResources().getString(R.string.No), dialogClickListener).create();
dialog.setTitle(getResources().getString(R.string.NoInternetTitle));
dialog.setCanceledOnTouchOutside(false);
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
finish();
}
});
dialog.show();
}else {
// Init utils
TextSpeechUtils.init(this);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
showSettingsDlg();
return true;
}
return super.onOptionsItemSelected(item);
}
public void queryJarvisServer(String input)
{
showWaitDialog();
try {
JarvisServerUtils.getQueryResult(input, new HttpUtils.Callback() {
@Override
public void onResult(String responseStr) {
hideWaitDialog();
speakBtn.setImageDrawable(getResources().getDrawable(R.drawable.ic_microphone));
if(responseStr == null || responseStr.isEmpty())
showErrorResponse();
else {
try {
HttpUtils.Callback translatorCallback = new HttpUtils.Callback() {
@Override
public void onResult(String translatedStr) {
textInput.setText(translatedStr);
translatedStr = translatedStr.replace(",", "");
TextSpeechUtils.speakText(translatedStr);
}
};
if(PrefManager.langEnglish(MainActivity.this.getApplicationContext()))
TranslatorUtils.translateToEnglish(responseStr, translatorCallback);
else
TranslatorUtils.translateToHindi(responseStr, translatorCallback);
}catch (Exception e)
{
hideWaitDialog();
showErrorResponse();
}
}
}
});
}catch (Exception e)
{
hideWaitDialog();
showErrorResponse();
}
}
@Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.speakBtn:
TextSpeechUtils.getVoiceInput(new TextSpeechUtils.TextSpeechUtilsCallback() {
@Override
public void onSpeechStart() {
}
@Override
public void onPartialSpeech(String input) {
textInput.setText(input);
}
@Override
public void onSpeechInputComplete(String input) {
try {
textInput.setText(input);
HttpUtils.Callback translatorCallback = new HttpUtils.Callback() {
@Override
public void onResult(String translatedText) {
queryJarvisServer(translatedText);
}
};
TranslatorUtils.translateToEnglish(input, translatorCallback);
}catch (Exception e)
{
textInput.setText(e.getMessage());
showErrorResponse();
}
}
});
speakBtn.setImageDrawable(getResources().getDrawable(R.drawable.ic_microphone_active));
break;
}
}
public void showWaitDialog()
{
if(this.waitDialog == null )
{
waitDialog = new ProgressDialog(this);
waitDialog.setTitle("Processing...");
}
this.waitDialog.show();
}
public void hideWaitDialog()
{
if(this.waitDialog !=null && this.waitDialog.isShowing()) {
this.waitDialog.hide();
}
}
public void showErrorResponse()
{
TextSpeechUtils.speakText("Some error has occurred while processing your request");
}
public void showSettingsDlg()
{
Intent intent = new Intent(this, PreferenceActivity.class);
startActivity(intent);
}
}
| Adding Language aware failure msg
| app/src/main/java/com/jarvis/jarvis/MainActivity.java | Adding Language aware failure msg | <ide><path>pp/src/main/java/com/jarvis/jarvis/MainActivity.java
<ide>
<ide> public void showErrorResponse()
<ide> {
<del> TextSpeechUtils.speakText("Some error has occurred while processing your request");
<add> String msg = "Some error has occurred while processing your request";
<add> if(PrefManager.langEnglish(getApplicationContext()))
<add> TextSpeechUtils.speakText(msg);
<add> else
<add> {
<add> try {
<add> TranslatorUtils.translateToHindi(msg, new HttpUtils.Callback() {
<add> @Override
<add> public void onResult(String translatedMsg) {
<add> TextSpeechUtils.speakText(translatedMsg);
<add> }
<add> });
<add> }catch (Exception e)
<add> {
<add>
<add> }
<add>
<add> }
<ide> }
<ide>
<ide> public void showSettingsDlg() |
|
Java | apache-2.0 | ba5456b466d73ca6360fdef2b90dc84de7210ef1 | 0 | orcoliver/traccar,jssenyange/traccar,orcoliver/traccar,orcoliver/traccar,jssenyange/traccar,jssenyange/traccar | /*
* Copyright 2015 - 2020 Anton Tananaev ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.traccar.protocol;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import org.traccar.BaseProtocolDecoder;
import org.traccar.DeviceSession;
import org.traccar.NetworkMessage;
import org.traccar.Protocol;
import org.traccar.helper.BcdUtil;
import org.traccar.helper.BitUtil;
import org.traccar.helper.Checksum;
import org.traccar.helper.DateBuilder;
import org.traccar.helper.UnitsConverter;
import org.traccar.model.CellTower;
import org.traccar.model.Network;
import org.traccar.model.Position;
import java.net.SocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.LinkedList;
import java.util.List;
public class HuabaoProtocolDecoder extends BaseProtocolDecoder {
public HuabaoProtocolDecoder(Protocol protocol) {
super(protocol);
}
public static final int MSG_GENERAL_RESPONSE = 0x8001;
public static final int MSG_GENERAL_RESPONSE_2 = 0x4401;
public static final int MSG_TERMINAL_REGISTER = 0x0100;
public static final int MSG_TERMINAL_REGISTER_RESPONSE = 0x8100;
public static final int MSG_TERMINAL_CONTROL = 0x8105;
public static final int MSG_TERMINAL_AUTH = 0x0102;
public static final int MSG_LOCATION_REPORT = 0x0200;
public static final int MSG_LOCATION_REPORT_2 = 0x5501;
public static final int MSG_LOCATION_REPORT_BLIND = 0x5502;
public static final int MSG_LOCATION_BATCH = 0x0704;
public static final int MSG_OIL_CONTROL = 0XA006;
public static final int RESULT_SUCCESS = 0;
public static ByteBuf formatMessage(int type, ByteBuf id, boolean shortIndex, ByteBuf data) {
ByteBuf buf = Unpooled.buffer();
buf.writeByte(0x7e);
buf.writeShort(type);
buf.writeShort(data.readableBytes());
buf.writeBytes(id);
if (shortIndex) {
buf.writeByte(1);
} else {
buf.writeShort(1);
}
buf.writeBytes(data);
data.release();
buf.writeByte(Checksum.xor(buf.nioBuffer(1, buf.readableBytes() - 1)));
buf.writeByte(0x7e);
return buf;
}
private void sendGeneralResponse(
Channel channel, SocketAddress remoteAddress, ByteBuf id, int type, int index) {
if (channel != null) {
ByteBuf response = Unpooled.buffer();
response.writeShort(index);
response.writeShort(type);
response.writeByte(RESULT_SUCCESS);
channel.writeAndFlush(new NetworkMessage(
formatMessage(MSG_GENERAL_RESPONSE, id, false, response), remoteAddress));
}
}
private void sendGeneralResponse2(
Channel channel, SocketAddress remoteAddress, ByteBuf id, int type) {
if (channel != null) {
ByteBuf response = Unpooled.buffer();
response.writeShort(type);
response.writeByte(RESULT_SUCCESS);
channel.writeAndFlush(new NetworkMessage(
formatMessage(MSG_GENERAL_RESPONSE_2, id, true, response), remoteAddress));
}
}
private String decodeAlarm(long value) {
if (BitUtil.check(value, 0)) {
return Position.ALARM_SOS;
}
if (BitUtil.check(value, 1)) {
return Position.ALARM_OVERSPEED;
}
if (BitUtil.check(value, 5)) {
return Position.ALARM_GPS_ANTENNA_CUT;
}
if (BitUtil.check(value, 4) || BitUtil.check(value, 9)
|| BitUtil.check(value, 10) || BitUtil.check(value, 11)) {
return Position.ALARM_FAULT;
}
if (BitUtil.check(value, 8)) {
return Position.ALARM_POWER_OFF;
}
if (BitUtil.check(value, 20)) {
return Position.ALARM_GEOFENCE;
}
if (BitUtil.check(value, 28)) {
return Position.ALARM_MOVEMENT;
}
if (BitUtil.check(value, 29)) {
return Position.ALARM_ACCIDENT;
}
return null;
}
@Override
protected Object decode(
Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {
ByteBuf buf = (ByteBuf) msg;
if (buf.getByte(buf.readerIndex()) == '(') {
return decodeResult(channel, remoteAddress, buf.toString(StandardCharsets.US_ASCII));
}
buf.readUnsignedByte(); // start marker
int type = buf.readUnsignedShort();
int attribute = buf.readUnsignedShort();
ByteBuf id = buf.readSlice(6); // phone number
int index;
if (type == MSG_LOCATION_REPORT_2 || type == MSG_LOCATION_REPORT_BLIND) {
index = buf.readUnsignedByte();
} else {
index = buf.readUnsignedShort();
}
DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, ByteBufUtil.hexDump(id));
if (deviceSession == null) {
return null;
}
if (deviceSession.getTimeZone() == null) {
deviceSession.setTimeZone(getTimeZone(deviceSession.getDeviceId(), "GMT+8"));
}
if (type == MSG_TERMINAL_REGISTER) {
if (channel != null) {
ByteBuf response = Unpooled.buffer();
response.writeShort(index);
response.writeByte(RESULT_SUCCESS);
response.writeBytes(ByteBufUtil.hexDump(id).getBytes(StandardCharsets.US_ASCII));
channel.writeAndFlush(new NetworkMessage(
formatMessage(MSG_TERMINAL_REGISTER_RESPONSE, id, false, response), remoteAddress));
}
} else if (type == MSG_TERMINAL_AUTH) {
sendGeneralResponse(channel, remoteAddress, id, type, index);
} else if (type == MSG_LOCATION_REPORT) {
sendGeneralResponse(channel, remoteAddress, id, type, index);
return decodeLocation(deviceSession, buf);
} else if (type == MSG_LOCATION_REPORT_2 || type == MSG_LOCATION_REPORT_BLIND) {
if (BitUtil.check(attribute, 15)) {
sendGeneralResponse2(channel, remoteAddress, id, type);
}
return decodeLocation2(deviceSession, buf, type);
} else if (type == MSG_LOCATION_BATCH) {
return decodeLocationBatch(deviceSession, buf);
}
return null;
}
private Position decodeResult(Channel channel, SocketAddress remoteAddress, String sentence) {
DeviceSession deviceSession = getDeviceSession(channel, remoteAddress);
if (deviceSession != null) {
Position position = new Position(getProtocolName());
position.setDeviceId(deviceSession.getDeviceId());
getLastLocation(position, null);
position.set(Position.KEY_RESULT, sentence);
return position;
}
return null;
}
private Position decodeLocation(DeviceSession deviceSession, ByteBuf buf) {
Position position = new Position(getProtocolName());
position.setDeviceId(deviceSession.getDeviceId());
position.set(Position.KEY_ALARM, decodeAlarm(buf.readUnsignedInt()));
int status = buf.readInt();
position.set(Position.KEY_IGNITION, BitUtil.check(status, 0));
position.set(Position.KEY_BLOCKED, BitUtil.check(status, 10));
position.setValid(BitUtil.check(status, 1));
double lat = buf.readUnsignedInt() * 0.000001;
double lon = buf.readUnsignedInt() * 0.000001;
if (BitUtil.check(status, 2)) {
position.setLatitude(-lat);
} else {
position.setLatitude(lat);
}
if (BitUtil.check(status, 3)) {
position.setLongitude(-lon);
} else {
position.setLongitude(lon);
}
position.setAltitude(buf.readShort());
position.setSpeed(UnitsConverter.knotsFromKph(buf.readUnsignedShort() * 0.1));
position.setCourse(buf.readUnsignedShort());
DateBuilder dateBuilder = new DateBuilder(deviceSession.getTimeZone())
.setYear(BcdUtil.readInteger(buf, 2))
.setMonth(BcdUtil.readInteger(buf, 2))
.setDay(BcdUtil.readInteger(buf, 2))
.setHour(BcdUtil.readInteger(buf, 2))
.setMinute(BcdUtil.readInteger(buf, 2))
.setSecond(BcdUtil.readInteger(buf, 2));
position.setTime(dateBuilder.getDate());
while (buf.readableBytes() > 2) {
int subtype = buf.readUnsignedByte();
int length = buf.readUnsignedByte();
int endIndex = buf.readerIndex() + length;
switch (subtype) {
case 0x01:
position.set(Position.KEY_ODOMETER, buf.readUnsignedInt() * 100);
break;
case 0x02:
position.set(Position.KEY_FUEL_LEVEL, buf.readUnsignedShort() * 0.1);
break;
case 0x30:
position.set(Position.KEY_RSSI, buf.readUnsignedByte());
break;
case 0x31:
position.set(Position.KEY_SATELLITES, buf.readUnsignedByte());
break;
case 0x33:
String sentence = buf.readCharSequence(length, StandardCharsets.US_ASCII).toString();
if (sentence.startsWith("*M00")) {
String lockStatus = sentence.substring(8, 8 + 7);
position.set(Position.KEY_BATTERY, Integer.parseInt(lockStatus.substring(2, 5)) * 0.01);
}
break;
case 0x91:
position.set(Position.KEY_BATTERY, buf.readUnsignedShort() * 0.1);
position.set(Position.KEY_RPM, buf.readUnsignedShort());
position.set(Position.KEY_OBD_SPEED, buf.readUnsignedByte());
position.set(Position.KEY_THROTTLE, buf.readUnsignedByte() * 100 / 255);
position.set(Position.KEY_ENGINE_LOAD, buf.readUnsignedByte() * 100 / 255);
position.set(Position.KEY_COOLANT_TEMP, buf.readUnsignedByte() - 40);
buf.readUnsignedShort();
position.set(Position.KEY_FUEL_CONSUMPTION, buf.readUnsignedShort() * 0.01);
buf.readUnsignedShort();
buf.readUnsignedInt();
buf.readUnsignedShort();
position.set(Position.KEY_FUEL_USED, buf.readUnsignedShort() * 0.01);
break;
case 0x94:
if (length > 0) {
position.set(
Position.KEY_VIN, buf.readCharSequence(length, StandardCharsets.US_ASCII).toString());
}
break;
case 0xD0:
long userStatus = buf.readUnsignedInt();
if (BitUtil.check(userStatus, 3)) {
position.set(Position.KEY_ALARM, Position.ALARM_VIBRATION);
}
break;
case 0xD3:
position.set(Position.KEY_POWER, buf.readUnsignedShort() * 0.1);
break;
case 0xD4:
position.set(Position.KEY_BATTERY_LEVEL, buf.readUnsignedByte());
break;
case 0xD5:
position.set(Position.KEY_BATTERY, buf.readUnsignedShort() * 0.01);
break;
case 0xDA:
buf.readUnsignedShort();
int deviceStatus = buf.readUnsignedByte();
position.set("cover", BitUtil.check(deviceStatus, 3));
break;
case 0xEB:
while (buf.readerIndex() < endIndex) {
int extendedLength = buf.readUnsignedShort();
int extendedType = buf.readUnsignedShort();
switch (extendedType) {
case 0x0001:
position.set("fuel1", buf.readUnsignedShort() * 0.1);
buf.readUnsignedByte(); // unused
break;
case 0x0023:
position.set("fuel2", Double.parseDouble(
buf.readCharSequence(6, StandardCharsets.US_ASCII).toString()));
break;
case 0x00CE:
position.set(Position.KEY_POWER, buf.readUnsignedShort() * 0.01);
break;
default:
buf.skipBytes(extendedLength - 2);
break;
}
}
break;
default:
break;
}
buf.readerIndex(endIndex);
}
return position;
}
private Position decodeLocation2(DeviceSession deviceSession, ByteBuf buf, int type) {
Position position = new Position(getProtocolName());
position.setDeviceId(deviceSession.getDeviceId());
Jt600ProtocolDecoder.decodeBinaryLocation(buf, position);
position.setValid(type != MSG_LOCATION_REPORT_BLIND);
position.set(Position.KEY_RSSI, buf.readUnsignedByte());
position.set(Position.KEY_SATELLITES, buf.readUnsignedByte());
position.set(Position.KEY_ODOMETER, buf.readUnsignedInt() * 1000L);
int battery = buf.readUnsignedByte();
if (battery <= 100) {
position.set(Position.KEY_BATTERY_LEVEL, battery);
} else if (battery == 0xAA) {
position.set(Position.KEY_CHARGE, true);
}
position.setNetwork(new Network(CellTower.fromCidLac(buf.readUnsignedInt(), buf.readUnsignedShort())));
int product = buf.readUnsignedByte();
int status = buf.readUnsignedShort();
int alarm = buf.readUnsignedShort();
if (product == 1 || product == 2) {
if (BitUtil.check(alarm, 0)) {
position.set(Position.KEY_ALARM, Position.ALARM_LOW_POWER);
}
} else if (product == 3) {
position.set(Position.KEY_BLOCKED, BitUtil.check(status, 5));
if (BitUtil.check(alarm, 1)) {
position.set(Position.KEY_ALARM, Position.ALARM_LOW_POWER);
}
if (BitUtil.check(alarm, 2)) {
position.set(Position.KEY_ALARM, Position.ALARM_VIBRATION);
}
if (BitUtil.check(alarm, 3)) {
position.set(Position.KEY_ALARM, Position.ALARM_LOW_BATTERY);
}
}
position.set(Position.KEY_STATUS, status);
return position;
}
private List<Position> decodeLocationBatch(DeviceSession deviceSession, ByteBuf buf) {
List<Position> positions = new LinkedList<>();
int count = buf.readUnsignedShort();
buf.readUnsignedByte(); // location type
for (int i = 0; i < count; i++) {
int endIndex = buf.readUnsignedShort() + buf.readerIndex();
positions.add(decodeLocation(deviceSession, buf));
buf.readerIndex(endIndex);
}
return positions;
}
}
| src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java | /*
* Copyright 2015 - 2020 Anton Tananaev ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.traccar.protocol;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import org.traccar.BaseProtocolDecoder;
import org.traccar.DeviceSession;
import org.traccar.NetworkMessage;
import org.traccar.Protocol;
import org.traccar.helper.BcdUtil;
import org.traccar.helper.BitUtil;
import org.traccar.helper.Checksum;
import org.traccar.helper.DateBuilder;
import org.traccar.helper.UnitsConverter;
import org.traccar.model.CellTower;
import org.traccar.model.Network;
import org.traccar.model.Position;
import java.net.SocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.LinkedList;
import java.util.List;
public class HuabaoProtocolDecoder extends BaseProtocolDecoder {
public HuabaoProtocolDecoder(Protocol protocol) {
super(protocol);
}
public static final int MSG_GENERAL_RESPONSE = 0x8001;
public static final int MSG_GENERAL_RESPONSE_2 = 0x4401;
public static final int MSG_TERMINAL_REGISTER = 0x0100;
public static final int MSG_TERMINAL_REGISTER_RESPONSE = 0x8100;
public static final int MSG_TERMINAL_CONTROL = 0x8105;
public static final int MSG_TERMINAL_AUTH = 0x0102;
public static final int MSG_LOCATION_REPORT = 0x0200;
public static final int MSG_LOCATION_REPORT_2 = 0x5501;
public static final int MSG_LOCATION_REPORT_BLIND = 0x5502;
public static final int MSG_LOCATION_BATCH = 0x0704;
public static final int MSG_OIL_CONTROL = 0XA006;
public static final int RESULT_SUCCESS = 0;
public static ByteBuf formatMessage(int type, ByteBuf id, boolean shortIndex, ByteBuf data) {
ByteBuf buf = Unpooled.buffer();
buf.writeByte(0x7e);
buf.writeShort(type);
buf.writeShort(data.readableBytes());
buf.writeBytes(id);
if (shortIndex) {
buf.writeByte(1);
} else {
buf.writeShort(1);
}
buf.writeBytes(data);
data.release();
buf.writeByte(Checksum.xor(buf.nioBuffer(1, buf.readableBytes() - 1)));
buf.writeByte(0x7e);
return buf;
}
private void sendGeneralResponse(
Channel channel, SocketAddress remoteAddress, ByteBuf id, int type, int index) {
if (channel != null) {
ByteBuf response = Unpooled.buffer();
response.writeShort(index);
response.writeShort(type);
response.writeByte(RESULT_SUCCESS);
channel.writeAndFlush(new NetworkMessage(
formatMessage(MSG_GENERAL_RESPONSE, id, false, response), remoteAddress));
}
}
private void sendGeneralResponse2(
Channel channel, SocketAddress remoteAddress, ByteBuf id, int type) {
if (channel != null) {
ByteBuf response = Unpooled.buffer();
response.writeShort(type);
response.writeByte(RESULT_SUCCESS);
channel.writeAndFlush(new NetworkMessage(
formatMessage(MSG_GENERAL_RESPONSE_2, id, true, response), remoteAddress));
}
}
private String decodeAlarm(long value) {
if (BitUtil.check(value, 0)) {
return Position.ALARM_SOS;
}
if (BitUtil.check(value, 1)) {
return Position.ALARM_OVERSPEED;
}
if (BitUtil.check(value, 5)) {
return Position.ALARM_GPS_ANTENNA_CUT;
}
if (BitUtil.check(value, 4) || BitUtil.check(value, 9)
|| BitUtil.check(value, 10) || BitUtil.check(value, 11)) {
return Position.ALARM_FAULT;
}
if (BitUtil.check(value, 8)) {
return Position.ALARM_POWER_OFF;
}
if (BitUtil.check(value, 20)) {
return Position.ALARM_GEOFENCE;
}
if (BitUtil.check(value, 28)) {
return Position.ALARM_MOVEMENT;
}
if (BitUtil.check(value, 29)) {
return Position.ALARM_ACCIDENT;
}
return null;
}
@Override
protected Object decode(
Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {
ByteBuf buf = (ByteBuf) msg;
if (buf.getByte(buf.readerIndex()) == '(') {
return decodeResult(channel, remoteAddress, buf.toString(StandardCharsets.US_ASCII));
}
buf.readUnsignedByte(); // start marker
int type = buf.readUnsignedShort();
int attribute = buf.readUnsignedShort();
ByteBuf id = buf.readSlice(6); // phone number
int index;
if (type == MSG_LOCATION_REPORT_2 || type == MSG_LOCATION_REPORT_BLIND) {
index = buf.readUnsignedByte();
} else {
index = buf.readUnsignedShort();
}
DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, ByteBufUtil.hexDump(id));
if (deviceSession == null) {
return null;
}
if (deviceSession.getTimeZone() == null) {
deviceSession.setTimeZone(getTimeZone(deviceSession.getDeviceId(), "GMT+8"));
}
if (type == MSG_TERMINAL_REGISTER) {
if (channel != null) {
ByteBuf response = Unpooled.buffer();
response.writeShort(index);
response.writeByte(RESULT_SUCCESS);
response.writeBytes(ByteBufUtil.hexDump(id).getBytes(StandardCharsets.US_ASCII));
channel.writeAndFlush(new NetworkMessage(
formatMessage(MSG_TERMINAL_REGISTER_RESPONSE, id, false, response), remoteAddress));
}
} else if (type == MSG_TERMINAL_AUTH) {
sendGeneralResponse(channel, remoteAddress, id, type, index);
} else if (type == MSG_LOCATION_REPORT) {
return decodeLocation(deviceSession, buf);
} else if (type == MSG_LOCATION_REPORT_2 || type == MSG_LOCATION_REPORT_BLIND) {
if (BitUtil.check(attribute, 15)) {
sendGeneralResponse2(channel, remoteAddress, id, type);
}
return decodeLocation2(deviceSession, buf, type);
} else if (type == MSG_LOCATION_BATCH) {
return decodeLocationBatch(deviceSession, buf);
}
return null;
}
private Position decodeResult(Channel channel, SocketAddress remoteAddress, String sentence) {
DeviceSession deviceSession = getDeviceSession(channel, remoteAddress);
if (deviceSession != null) {
Position position = new Position(getProtocolName());
position.setDeviceId(deviceSession.getDeviceId());
getLastLocation(position, null);
position.set(Position.KEY_RESULT, sentence);
return position;
}
return null;
}
private Position decodeLocation(DeviceSession deviceSession, ByteBuf buf) {
Position position = new Position(getProtocolName());
position.setDeviceId(deviceSession.getDeviceId());
position.set(Position.KEY_ALARM, decodeAlarm(buf.readUnsignedInt()));
int status = buf.readInt();
position.set(Position.KEY_IGNITION, BitUtil.check(status, 0));
position.set(Position.KEY_BLOCKED, BitUtil.check(status, 10));
position.setValid(BitUtil.check(status, 1));
double lat = buf.readUnsignedInt() * 0.000001;
double lon = buf.readUnsignedInt() * 0.000001;
if (BitUtil.check(status, 2)) {
position.setLatitude(-lat);
} else {
position.setLatitude(lat);
}
if (BitUtil.check(status, 3)) {
position.setLongitude(-lon);
} else {
position.setLongitude(lon);
}
position.setAltitude(buf.readShort());
position.setSpeed(UnitsConverter.knotsFromKph(buf.readUnsignedShort() * 0.1));
position.setCourse(buf.readUnsignedShort());
DateBuilder dateBuilder = new DateBuilder(deviceSession.getTimeZone())
.setYear(BcdUtil.readInteger(buf, 2))
.setMonth(BcdUtil.readInteger(buf, 2))
.setDay(BcdUtil.readInteger(buf, 2))
.setHour(BcdUtil.readInteger(buf, 2))
.setMinute(BcdUtil.readInteger(buf, 2))
.setSecond(BcdUtil.readInteger(buf, 2));
position.setTime(dateBuilder.getDate());
while (buf.readableBytes() > 2) {
int subtype = buf.readUnsignedByte();
int length = buf.readUnsignedByte();
int endIndex = buf.readerIndex() + length;
switch (subtype) {
case 0x01:
position.set(Position.KEY_ODOMETER, buf.readUnsignedInt() * 100);
break;
case 0x02:
position.set(Position.KEY_FUEL_LEVEL, buf.readUnsignedShort() * 0.1);
break;
case 0x30:
position.set(Position.KEY_RSSI, buf.readUnsignedByte());
break;
case 0x31:
position.set(Position.KEY_SATELLITES, buf.readUnsignedByte());
break;
case 0x33:
String sentence = buf.readCharSequence(length, StandardCharsets.US_ASCII).toString();
if (sentence.startsWith("*M00")) {
String lockStatus = sentence.substring(8, 8 + 7);
position.set(Position.KEY_BATTERY, Integer.parseInt(lockStatus.substring(2, 5)) * 0.01);
}
break;
case 0x91:
position.set(Position.KEY_BATTERY, buf.readUnsignedShort() * 0.1);
position.set(Position.KEY_RPM, buf.readUnsignedShort());
position.set(Position.KEY_OBD_SPEED, buf.readUnsignedByte());
position.set(Position.KEY_THROTTLE, buf.readUnsignedByte() * 100 / 255);
position.set(Position.KEY_ENGINE_LOAD, buf.readUnsignedByte() * 100 / 255);
position.set(Position.KEY_COOLANT_TEMP, buf.readUnsignedByte() - 40);
buf.readUnsignedShort();
position.set(Position.KEY_FUEL_CONSUMPTION, buf.readUnsignedShort() * 0.01);
buf.readUnsignedShort();
buf.readUnsignedInt();
buf.readUnsignedShort();
position.set(Position.KEY_FUEL_USED, buf.readUnsignedShort() * 0.01);
break;
case 0x94:
if (length > 0) {
position.set(
Position.KEY_VIN, buf.readCharSequence(length, StandardCharsets.US_ASCII).toString());
}
break;
case 0xD0:
long userStatus = buf.readUnsignedInt();
if (BitUtil.check(userStatus, 3)) {
position.set(Position.KEY_ALARM, Position.ALARM_VIBRATION);
}
break;
case 0xD3:
position.set(Position.KEY_POWER, buf.readUnsignedShort() * 0.1);
break;
case 0xEB:
while (buf.readerIndex() < endIndex) {
int extendedLength = buf.readUnsignedShort();
int extendedType = buf.readUnsignedShort();
switch (extendedType) {
case 0x0001:
position.set("fuel1", buf.readUnsignedShort() * 0.1);
buf.readUnsignedByte(); // unused
break;
case 0x0023:
position.set("fuel2", Double.parseDouble(
buf.readCharSequence(6, StandardCharsets.US_ASCII).toString()));
break;
case 0x00CE:
position.set(Position.KEY_POWER, buf.readUnsignedShort() * 0.01);
break;
default:
buf.skipBytes(extendedLength - 2);
break;
}
}
break;
default:
break;
}
buf.readerIndex(endIndex);
}
return position;
}
private Position decodeLocation2(DeviceSession deviceSession, ByteBuf buf, int type) {
Position position = new Position(getProtocolName());
position.setDeviceId(deviceSession.getDeviceId());
Jt600ProtocolDecoder.decodeBinaryLocation(buf, position);
position.setValid(type != MSG_LOCATION_REPORT_BLIND);
position.set(Position.KEY_RSSI, buf.readUnsignedByte());
position.set(Position.KEY_SATELLITES, buf.readUnsignedByte());
position.set(Position.KEY_ODOMETER, buf.readUnsignedInt() * 1000L);
int battery = buf.readUnsignedByte();
if (battery <= 100) {
position.set(Position.KEY_BATTERY_LEVEL, battery);
} else if (battery == 0xAA) {
position.set(Position.KEY_CHARGE, true);
}
position.setNetwork(new Network(CellTower.fromCidLac(buf.readUnsignedInt(), buf.readUnsignedShort())));
int product = buf.readUnsignedByte();
int status = buf.readUnsignedShort();
int alarm = buf.readUnsignedShort();
if (product == 1 || product == 2) {
if (BitUtil.check(alarm, 0)) {
position.set(Position.KEY_ALARM, Position.ALARM_LOW_POWER);
}
} else if (product == 3) {
position.set(Position.KEY_BLOCKED, BitUtil.check(status, 5));
if (BitUtil.check(alarm, 1)) {
position.set(Position.KEY_ALARM, Position.ALARM_LOW_POWER);
}
if (BitUtil.check(alarm, 2)) {
position.set(Position.KEY_ALARM, Position.ALARM_VIBRATION);
}
if (BitUtil.check(alarm, 3)) {
position.set(Position.KEY_ALARM, Position.ALARM_LOW_BATTERY);
}
}
position.set(Position.KEY_STATUS, status);
return position;
}
private List<Position> decodeLocationBatch(DeviceSession deviceSession, ByteBuf buf) {
List<Position> positions = new LinkedList<>();
int count = buf.readUnsignedShort();
buf.readUnsignedByte(); // location type
for (int i = 0; i < count; i++) {
int endIndex = buf.readUnsignedShort() + buf.readerIndex();
positions.add(decodeLocation(deviceSession, buf));
buf.readerIndex(endIndex);
}
return positions;
}
}
| Update Huabao decoder
| src/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java | Update Huabao decoder | <ide><path>rc/main/java/org/traccar/protocol/HuabaoProtocolDecoder.java
<ide>
<ide> } else if (type == MSG_LOCATION_REPORT) {
<ide>
<add> sendGeneralResponse(channel, remoteAddress, id, type, index);
<add>
<ide> return decodeLocation(deviceSession, buf);
<ide>
<ide> } else if (type == MSG_LOCATION_REPORT_2 || type == MSG_LOCATION_REPORT_BLIND) {
<ide> break;
<ide> case 0xD3:
<ide> position.set(Position.KEY_POWER, buf.readUnsignedShort() * 0.1);
<add> break;
<add> case 0xD4:
<add> position.set(Position.KEY_BATTERY_LEVEL, buf.readUnsignedByte());
<add> break;
<add> case 0xD5:
<add> position.set(Position.KEY_BATTERY, buf.readUnsignedShort() * 0.01);
<add> break;
<add> case 0xDA:
<add> buf.readUnsignedShort();
<add> int deviceStatus = buf.readUnsignedByte();
<add> position.set("cover", BitUtil.check(deviceStatus, 3));
<ide> break;
<ide> case 0xEB:
<ide> while (buf.readerIndex() < endIndex) { |
|
JavaScript | mit | dfd021f921251589b31c2510f9e5235e11cae6ed | 0 | IsaacLean/adam-engine | var body = document.querySelector('body');
var canvasId = 'adam-engine';
//var ctx = canvas.getContext('2d');
/* Animation test */
// var assets = [
// '/img/robowalk/robowalk00.png',
// '/img/robowalk/robowalk01.png',
// '/img/robowalk/robowalk02.png',
// '/img/robowalk/robowalk03.png',
// '/img/robowalk/robowalk04.png',
// '/img/robowalk/robowalk05.png',
// '/img/robowalk/robowalk06.png',
// '/img/robowalk/robowalk07.png',
// '/img/robowalk/robowalk08.png',
// '/img/robowalk/robowalk09.png',
// '/img/robowalk/robowalk10.png',
// '/img/robowalk/robowalk11.png',
// '/img/robowalk/robowalk12.png',
// '/img/robowalk/robowalk13.png',
// '/img/robowalk/robowalk14.png',
// '/img/robowalk/robowalk15.png',
// '/img/robowalk/robowalk16.png',
// '/img/robowalk/robowalk17.png',
// '/img/robowalk/robowalk18.png'
// ];
// var frames = [];
// var currFrame = 0;
// for(var i=0; i < assets.length; ++i) {
// var newImg = new Image();
// newImg.onload = function() {
// console.log('image loaded');
// };
// newImg.src = assets[i];
// frames[i] = newImg;
// }
// var animate = function() {
// ctx.clearRect(0, 0, canvas.width, canvas.height);
// ctx.drawImage(frames[currFrame], 100, 100);
// currFrame = (currFrame + 1) % frames.length;
// requestAnimationFrame(animate);
// }
// requestAnimationFrame(animate);
/* Atlas test */
// function parseAtlasDefinition(atlasJSON) {
// var parsed = JSON.parse(atlasJSON);
// /*for(var key in parsed.frames) {
// var sprite = parsed.frames[key];
// // define center of sprite as offset
// var cx = -sprite.frame.w * 0.5;
// var cy = -sprite.frame.h * 0.5;
// // define the sprite for this sheet
// //this.defSprite(key, sprite.frame.x, sprite.frame.y, sprite.frame.w, sprite.frame.h, cx, cy);
// }*/
// }
// function main() {
// function onClick(e) {
// var canvasOffset = canvas.getBoundingClientRect();
// console.log((e.clientX - canvasOffset.left) + ', ' + (e.clientY - canvasOffset.top));
// }
// var atlasJson = null;
// var image = new Image();
// image.src = 'img/atlas.png';
// image.onload = function() {
// // attempt dl of atlas JSON
// var xhrAtlasJson = new XMLHttpRequest();
// xhrAtlasJson.responseType = 'json';
// xhrAtlasJson.open('GET', '/img/atlas.json', true);
// xhrAtlasJson.responseType = 'json';
// xhrAtlasJson.onload = function() {
// // store atlas JSON
// atlasJson = this.response;
// ctx.drawImage(
// image,
// atlasJson.frames['BHQ2.png'].frame.x,
// atlasJson.frames['BHQ2.png'].frame.y,
// atlasJson.frames['BHQ2.png'].sourceSize.w,
// atlasJson.frames['BHQ2.png'].sourceSize.h,
// 10, 10, 70, 70
// );
// ctx.drawImage(
// image,
// atlasJson.frames['FAM2.png'].frame.x,
// atlasJson.frames['FAM2.png'].frame.y,
// atlasJson.frames['FAM2.png'].sourceSize.w,
// atlasJson.frames['FAM2.png'].sourceSize.h,
// 100, 100, 70, 70
// );
// // console.log(canvas);
// // console.log(onClick);
// canvas.addEventListener('click', onClick);
// };
// xhrAtlasJson.send();
// };
// }
// main();
// AdamEngine class
var AdamEngine = function(canvasId) {
/*** GENERAL ***/
/* GENERAL: PRIVATE PROPERTIES */
var canvas = document.getElementById(canvasId);
var canvasData = canvas.getBoundingClientRect();
var ctx = canvas.getContext('2d');
var focus = false; // determines if canvas is in focus or not
/*** GAME OBJECTS ***/
/* GAME OBJECTS: CLASSES */
// GameObj class
var GameObj = function(typeName) {
// private properties
var type = typeName;
// public properties
this.state = {};
// private methods
function getType() {
return type;
}
// privileged methods
this.getType = function() {
return getType();
};
};
// GameObj public methods
GameObj.prototype.setup = function() {};
GameObj.prototype.update = function() {};
// WorldObj class
function WorldObj() {
GameObj.call(this, 'world-obj'); // inherit from GameObj
// set default state
this.state.worldObjType = null;
this.state.pos = {x: 0, y: 0};
this.state.size = {w: 0, h: 0};
this.state.image = null;
this.state.color = null;
this.state.stroke = null;
this.state.zIndex = 0;
}
// WorldObj public methods
WorldObj.prototype = Object.create(GameObj.prototype);
WorldObj.prototype.constructor = WorldObj;
/* GAME OBJECTS: PRIVATE PROPERTIES */
var worldObjs = {};
var storeObjs = {};
var renderPipe = []; // determines rendering order of world objs
/* GAME OBJECTS: PRIVATE METHODS */
function createWorldObj(worldObjName) {
if(worldObjs[worldObjName]) {
console.error('A world object with the name "' + worldObjName + '" already exists!');
} else {
worldObjs[worldObjName] = new WorldObj();
return worldObjs[worldObjName];
}
}
function deleteWorldObj(worldObjName) {
delete worldObjs[worldObjName];
}
/* GAME OBJECTS: PRIVILEGED METHODS */
this.createWorldObj = function(worldObjName) {
return createWorldObj(worldObjName);
}
this.deleteWorldObj = function(worldObjName) {
return deleteWorldObj(worldObjName);
}
/*** INPUT MANAGER ***/
// InputManager class
function InputManager() {
// private properties
var inputMap = {
keys: {},
mbs: {}
};
var inputState = {
keys: {},
mbs: {}
};
// private methods
function getKeyState(keyName) {
return inputState.keys[keyName];
}
function getMBState(mbName) {
return inputState.mbs[mbName];
}
// privileged methods
this.setup = function() {
document.addEventListener('keydown', function(e) {
if(focus) {
e.preventDefault();
var keyName = inputMap.keys[e.keyCode];
if(keyName) {
inputState.keys[keyName] = true;
// console.log(keyName, inputState.keys[keyName]);
}
}
}.bind(this));
document.addEventListener('keyup', function(e) {
if(focus) {
var keyName = inputMap.keys[e.keyCode];
if(keyName) {
inputState.keys[keyName] = false;
// console.log(keyName, inputState.keys[keyName]);
}
}
}.bind(this));
document.addEventListener('mousedown', function(e) {
if(e.target === canvas) {
focus = true;
} else {
focus = false;
}
var mbName = inputMap.mbs[e.button];
if((mbName) && (e.target === canvas)) {
inputState.mbs[mbName].isActive = true;
inputState.mbs[mbName].pos.x = e.clientX - canvasData.left;
inputState.mbs[mbName].pos.y = e.clientY - canvasData.top;
// console.log(mbName, inputState.mbs[mbName]);
}
}.bind(this));
document.addEventListener('mouseup', function(e) {
var mbName = inputMap.mbs[e.button];
if(mbName && (e.target === canvas)) {
inputState.mbs[mbName].isActive = false;
// console.log(mbName, inputState.mbs[mbName]);
}
}.bind(this));
// TODO: add listener for mousemove
};
this.addKeyInput = function(keyCode, keyName) {
inputMap.keys[keyCode] = keyName;
inputState.keys[keyName] = false;
};
this.resetKeyState = function() {
for(var i in inputState.keys) {
inputState.keys[i] = false;
}
};
this.addMBInput = function(button, mbName) {
inputMap.mbs[button] = mbName;
inputState.mbs[mbName] = {
isActive: false,
pos: {
x: null,
y: null
}
};
};
// TODO: add method to remove inputs
this.getKeyState = function(keyName) {
return getKeyState(keyName);
};
this.getMBState = function(mbName) {
return getMBState(mbName);
};
}
/* INPUT MANAGER: PUBLIC PROPERTIES */
this.inputMan = new InputManager();
/*** GAME LOOP ***/
/* GAME LOOP: PRIVATE METHODS */
function setupWorldObjs() {
renderPipe = []; // recreate renderPipe
for(var worldObjName in worldObjs) {
worldObjs[worldObjName].setup();
renderPipe.push(worldObjs[worldObjName]);
}
renderPipe.sort(function(a, b) {
console.log(a, b);
//debugger;
if(a.state.zIndex > b.state.zIndex) {
return 1;
}
if(a.state.zIndex < b.state.zIndex) {
return -1;
}
return 0;
});
}
function update() {
for(var worldObjName in worldObjs) {
worldObjs[worldObjName].update();
}
}
function render() {
ctx.clearRect(0, 0, canvasData.width, canvasData.height);
// render all pos x & y of all world objs
for(var i in renderPipe) {
var worldObj = renderPipe[i];
if(worldObj.getType() === 'world-obj') {
if(worldObj.state.worldObjType === 'rect') {
ctx.fillStyle = worldObj.state.color;
ctx.fillRect(worldObj.state.pos.x, worldObj.state.pos.y, worldObj.state.size.w, worldObj.state.size.h);
if(worldObj.state.stroke !== null) {
ctx.strokeStyle = worldObj.state.stroke.color;
ctx.strokeRect(worldObj.state.stroke.pos.x, worldObj.state.stroke.pos.y, worldObj.state.stroke.size.w, worldObj.state.stroke.size.h);
}
}
}
}
}
function gameLoop() {
update();
render();
requestAnimationFrame(gameLoop);
}
/* GAME LOOP: PRIVILEGED METHODS */
this.start = function() {
setupWorldObjs(); // run setup for all world objs
requestAnimationFrame(gameLoop); // start game loop
};
};
var AE = new AdamEngine(canvasId);
AE.inputMan.addKeyInput(37, 'LEFT');
AE.inputMan.addKeyInput(38, 'UP');
AE.inputMan.addKeyInput(39, 'RIGHT');
AE.inputMan.addKeyInput(40, 'DOWN');
AE.inputMan.addMBInput(0, 'LEFTCLICK');
AE.inputMan.setup();
var test = AE.createWorldObj('test');
test.setup = function() {
this.state.pos = {
x: 10,
y: 10
};
this.state.size = {
w: 10,
h: 10
};
this.state.worldObjType = 'rect';
this.state.color = '#0000FF';
};
test.update = function() {
this.state.pos.x += 1;
this.state.pos.y += 1;
};
var test2 = AE.createWorldObj('test2');
test2.setup = function() {
this.state.pos = {
x: 5,
y: 5
};
this.state.size = {
w: 20,
h: 20
};
this.state.worldObjType = 'rect';
this.state.color = '#FF0000';
this.state.zIndex = 200;
};
test2.update = function() {
this.state.pos.y += 2;
}
var zone = AE.createWorldObj('zone');
zone.setup = function() {
this.state.pos = {
x: 50,
y: 50
};
this.state.size = {
w: 30,
h: 30
};
this.state.worldObjType = 'rect';
this.state.color = '#000';
this.state.zIndex = 9001;
}
var player = AE.createWorldObj('player');
player.setup = function() {
this.state.pos = {
x: 10,
y: 10
};
this.state.size = {
w: 10,
h: 10
};
this.state.worldObjType = 'rect';
this.state.color = '#00FF00';
this.state.stroke = {
pos: this.state.pos,
size: this.state.size,
color: '#FFF'
};
this.state.zone = zone;
this.state.zIndex = 200;
};
var zone2 = AE.createWorldObj('zone2');
zone2.setup = function() {
this.state.pos = {
x: 100,
y: 50
};
this.state.size = {
w: 40,
h: 40
};
this.state.worldObjType = 'rect';
this.state.color = '#000';
this.state.zIndex = 100;
};
player.update = function() {
if(AE.inputMan.getKeyState('LEFT')) {
this.state.pos.x -= 1;
} else if(AE.inputMan.getKeyState('RIGHT')) {
this.state.pos.x += 1;
}
if(AE.inputMan.getKeyState('UP')) {
this.state.pos.y -= 1;
} else if(AE.inputMan.getKeyState('DOWN')) {
this.state.pos.y += 1;
}
if(AE.inputMan.getMBState('LEFTCLICK').isActive) {
console.log('teehee~');
}
if(
(this.state.pos.x < (this.state.zone.state.pos.x + this.state.zone.state.size.w)) &&
((this.state.pos.x + this.state.size.w) > this.state.zone.state.pos.x) &&
(this.state.pos.y < (this.state.zone.state.pos.y + this.state.zone.state.size.h)) &&
((this.state.pos.y + this.state.size.h) > this.state.zone.state.pos.y)
) {
console.log('player collision with zone');
}
};
AE.start();
| src/engine-refactor/adamengine/adamengine-dev.js | var body = document.querySelector('body');
var canvasId = 'adam-engine';
//var ctx = canvas.getContext('2d');
/* Animation test */
// var assets = [
// '/img/robowalk/robowalk00.png',
// '/img/robowalk/robowalk01.png',
// '/img/robowalk/robowalk02.png',
// '/img/robowalk/robowalk03.png',
// '/img/robowalk/robowalk04.png',
// '/img/robowalk/robowalk05.png',
// '/img/robowalk/robowalk06.png',
// '/img/robowalk/robowalk07.png',
// '/img/robowalk/robowalk08.png',
// '/img/robowalk/robowalk09.png',
// '/img/robowalk/robowalk10.png',
// '/img/robowalk/robowalk11.png',
// '/img/robowalk/robowalk12.png',
// '/img/robowalk/robowalk13.png',
// '/img/robowalk/robowalk14.png',
// '/img/robowalk/robowalk15.png',
// '/img/robowalk/robowalk16.png',
// '/img/robowalk/robowalk17.png',
// '/img/robowalk/robowalk18.png'
// ];
// var frames = [];
// var currFrame = 0;
// for(var i=0; i < assets.length; ++i) {
// var newImg = new Image();
// newImg.onload = function() {
// console.log('image loaded');
// };
// newImg.src = assets[i];
// frames[i] = newImg;
// }
// var animate = function() {
// ctx.clearRect(0, 0, canvas.width, canvas.height);
// ctx.drawImage(frames[currFrame], 100, 100);
// currFrame = (currFrame + 1) % frames.length;
// requestAnimationFrame(animate);
// }
// requestAnimationFrame(animate);
/* Atlas test */
// function parseAtlasDefinition(atlasJSON) {
// var parsed = JSON.parse(atlasJSON);
// /*for(var key in parsed.frames) {
// var sprite = parsed.frames[key];
// // define center of sprite as offset
// var cx = -sprite.frame.w * 0.5;
// var cy = -sprite.frame.h * 0.5;
// // define the sprite for this sheet
// //this.defSprite(key, sprite.frame.x, sprite.frame.y, sprite.frame.w, sprite.frame.h, cx, cy);
// }*/
// }
// function main() {
// function onClick(e) {
// var canvasOffset = canvas.getBoundingClientRect();
// console.log((e.clientX - canvasOffset.left) + ', ' + (e.clientY - canvasOffset.top));
// }
// var atlasJson = null;
// var image = new Image();
// image.src = 'img/atlas.png';
// image.onload = function() {
// // attempt dl of atlas JSON
// var xhrAtlasJson = new XMLHttpRequest();
// xhrAtlasJson.responseType = 'json';
// xhrAtlasJson.open('GET', '/img/atlas.json', true);
// xhrAtlasJson.responseType = 'json';
// xhrAtlasJson.onload = function() {
// // store atlas JSON
// atlasJson = this.response;
// ctx.drawImage(
// image,
// atlasJson.frames['BHQ2.png'].frame.x,
// atlasJson.frames['BHQ2.png'].frame.y,
// atlasJson.frames['BHQ2.png'].sourceSize.w,
// atlasJson.frames['BHQ2.png'].sourceSize.h,
// 10, 10, 70, 70
// );
// ctx.drawImage(
// image,
// atlasJson.frames['FAM2.png'].frame.x,
// atlasJson.frames['FAM2.png'].frame.y,
// atlasJson.frames['FAM2.png'].sourceSize.w,
// atlasJson.frames['FAM2.png'].sourceSize.h,
// 100, 100, 70, 70
// );
// // console.log(canvas);
// // console.log(onClick);
// canvas.addEventListener('click', onClick);
// };
// xhrAtlasJson.send();
// };
// }
// main();
// AdamEngine class
var AdamEngine = function(canvasId) {
/*** GENERAL ***/
/* GENERAL: PRIVATE PROPERTIES */
var canvas = document.getElementById(canvasId);
var canvasData = canvas.getBoundingClientRect();
var ctx = canvas.getContext('2d');
var focus = false;
/*** GAME OBJECTS ***/
/* GAME OBJECTS: CLASSES */
// GameObj class
var GameObj = function(typeName) {
// private properties
var type = typeName;
// public properties
this.state = {};
// private methods
function getType() {
return type;
}
// privileged methods
this.getType = function() {
return getType();
};
};
// GameObj public methods
GameObj.prototype.setup = function() {};
GameObj.prototype.update = function() {};
// WorldObj class
function WorldObj() {
GameObj.call(this, 'world-obj'); // inherit from GameObj
// set default state
this.state.worldObjType = null;
this.state.pos = {x: 0, y: 0};
this.state.size = {w: 0, h: 0};
this.state.image = null;
this.state.color = null;
this.state.stroke = null;
}
// WorldObj public methods
WorldObj.prototype = Object.create(GameObj.prototype);
WorldObj.prototype.constructor = WorldObj;
/* GAME OBJECTS: PRIVATE PROPERTIES */
var worldObjs = {};
var storeObjs = {};
/* GAME OBJECTS: PRIVATE METHODS */
function createWorldObj(worldObjName) {
worldObjs[worldObjName] = new WorldObj();
return worldObjs[worldObjName];
}
function deleteWorldObj(worldObjName) {
delete worldObjs[worldObjName];
}
/* GAME OBJECTS: PRIVILEGED METHODS */
this.createWorldObj = function(worldObjName) {
return createWorldObj(worldObjName);
}
this.deleteWorldObj = function(worldObjName) {
return deleteWorldObj(worldObjName);
}
/*** INPUT MANAGER ***/
// InputManager class
function InputManager() {
// private properties
var inputMap = {
keys: {},
mbs: {}
};
var inputState = {
keys: {},
mbs: {}
};
// private methods
function getKeyState(keyName) {
return inputState.keys[keyName];
}
function getMBState(mbName) {
return inputState.mbs[mbName];
}
// privileged methods
this.setup = function() {
document.addEventListener('keydown', function(e) {
if(focus) {
e.preventDefault();
var keyName = inputMap.keys[e.keyCode];
if(keyName) {
inputState.keys[keyName] = true;
// console.log(keyName, inputState.keys[keyName]);
}
}
}.bind(this));
document.addEventListener('keyup', function(e) {
if(focus) {
var keyName = inputMap.keys[e.keyCode];
if(keyName) {
inputState.keys[keyName] = false;
// console.log(keyName, inputState.keys[keyName]);
}
}
}.bind(this));
document.addEventListener('mousedown', function(e) {
if(e.target === canvas) {
focus = true;
} else {
focus = false;
}
var mbName = inputMap.mbs[e.button];
if((mbName) && (e.target === canvas)) {
inputState.mbs[mbName].isActive = true;
inputState.mbs[mbName].pos.x = e.clientX - canvasData.left;
inputState.mbs[mbName].pos.y = e.clientY - canvasData.top;
// console.log(mbName, inputState.mbs[mbName]);
}
}.bind(this));
document.addEventListener('mouseup', function(e) {
var mbName = inputMap.mbs[e.button];
if(mbName && (e.target === canvas)) {
inputState.mbs[mbName].isActive = false;
// console.log(mbName, inputState.mbs[mbName]);
}
}.bind(this));
// TODO: add listener for mousemove
};
this.addKeyInput = function(keyCode, keyName) {
inputMap.keys[keyCode] = keyName;
inputState.keys[keyName] = false;
};
this.resetKeyState = function() {
for(var i in inputState.keys) {
inputState.keys[i] = false;
}
};
this.addMBInput = function(button, mbName) {
inputMap.mbs[button] = mbName;
inputState.mbs[mbName] = {
isActive: false,
pos: {
x: null,
y: null
}
};
};
// TODO: add method to remove inputs
this.getKeyState = function(keyName) {
return getKeyState(keyName);
};
this.getMBState = function(mbName) {
return getMBState(mbName);
};
}
this.inputMan = new InputManager();
/*** GAME LOOP ***/
/* GAME LOOP: PRIVATE METHODS */
function setupWorldObjs() {
for(var worldObjName in worldObjs) {
worldObjs[worldObjName].setup();
}
}
function update() {
for(var worldObjName in worldObjs) {
worldObjs[worldObjName].update();
}
}
function render() {
ctx.clearRect(0, 0, canvasData.width, canvasData.height);
// render all pos x & y of all world objs
for(var worldObjName in worldObjs) {
var worldObj = worldObjs[worldObjName];
if(worldObj.getType() === 'world-obj') {
if(worldObj.state.worldObjType === 'rect') {
ctx.fillStyle = worldObj.state.color;
ctx.fillRect(worldObj.state.pos.x, worldObj.state.pos.y, worldObj.state.size.w, worldObj.state.size.h);
if(worldObj.state.stroke !== null) {
ctx.strokeStyle = worldObj.state.stroke.color;
ctx.strokeRect(worldObj.state.stroke.pos.x, worldObj.state.stroke.pos.y, worldObj.state.stroke.size.w, worldObj.state.stroke.size.h);
}
}
}
}
}
function gameLoop() {
update();
render();
requestAnimationFrame(gameLoop);
}
/* GAME LOOP: PRIVILEGED METHODS */
this.start = function() {
setupWorldObjs(); // run setup for all world objs
requestAnimationFrame(gameLoop); // start game loop
};
};
var AE = new AdamEngine(canvasId);
AE.inputMan.addKeyInput(37, 'LEFT');
AE.inputMan.addKeyInput(38, 'UP');
AE.inputMan.addKeyInput(39, 'RIGHT');
AE.inputMan.addKeyInput(40, 'DOWN');
AE.inputMan.addMBInput(0, 'LEFTCLICK');
AE.inputMan.setup();
var test = AE.createWorldObj('test');
test.setup = function() {
this.state.pos = {
x: 10,
y: 10
};
this.state.size = {
w: 10,
h: 10
};
this.state.worldObjType = 'rect';
this.state.color = '#0000FF';
};
test.update = function() {
this.state.pos.x += 1;
this.state.pos.y += 1;
};
var test2 = AE.createWorldObj('test2');
test2.setup = function() {
this.state.pos = {
x: 5,
y: 5
};
this.state.size = {
w: 20,
h: 20
};
this.state.worldObjType = 'rect';
this.state.color = '#FF0000';
};
test2.update = function() {
this.state.pos.y += 2;
}
var zone = AE.createWorldObj('zone');
zone.setup = function() {
this.state.pos = {
x: 50,
y: 50
};
this.state.size = {
w: 30,
h: 30
};
this.state.worldObjType = 'rect';
this.state.color = '#000';
}
var player = AE.createWorldObj('player');
player.setup = function() {
this.state.pos = {
x: 10,
y: 10
};
this.state.size = {
w: 10,
h: 10
};
this.state.worldObjType = 'rect';
this.state.color = '#00FF00';
this.state.stroke = {
pos: this.state.pos,
size: this.state.size,
color: '#FFF'
};
this.state.zone = zone;
};
player.update = function() {
if(AE.inputMan.getKeyState('LEFT')) {
this.state.pos.x -= 1;
} else if(AE.inputMan.getKeyState('RIGHT')) {
this.state.pos.x += 1;
}
if(AE.inputMan.getKeyState('UP')) {
this.state.pos.y -= 1;
} else if(AE.inputMan.getKeyState('DOWN')) {
this.state.pos.y += 1;
}
if(AE.inputMan.getMBState('LEFTCLICK').isActive) {
console.log('teehee~');
}
if(
(this.state.pos.x < (this.state.zone.state.pos.x + this.state.zone.state.size.w)) &&
((this.state.pos.x + this.state.size.w) > this.state.zone.state.pos.x) &&
(this.state.pos.y < (this.state.zone.state.pos.y + this.state.zone.state.size.h)) &&
((this.state.pos.y + this.state.size.h) > this.state.zone.state.pos.y)
) {
console.log('player collision with zone');
}
};
AE.start();
| Implement z-index
| src/engine-refactor/adamengine/adamengine-dev.js | Implement z-index | <ide><path>rc/engine-refactor/adamengine/adamengine-dev.js
<ide> var canvas = document.getElementById(canvasId);
<ide> var canvasData = canvas.getBoundingClientRect();
<ide> var ctx = canvas.getContext('2d');
<del> var focus = false;
<add> var focus = false; // determines if canvas is in focus or not
<ide>
<ide>
<ide>
<ide> this.state.image = null;
<ide> this.state.color = null;
<ide> this.state.stroke = null;
<add> this.state.zIndex = 0;
<ide> }
<ide>
<ide> // WorldObj public methods
<ide> /* GAME OBJECTS: PRIVATE PROPERTIES */
<ide> var worldObjs = {};
<ide> var storeObjs = {};
<add> var renderPipe = []; // determines rendering order of world objs
<ide>
<ide>
<ide> /* GAME OBJECTS: PRIVATE METHODS */
<ide> function createWorldObj(worldObjName) {
<del> worldObjs[worldObjName] = new WorldObj();
<del> return worldObjs[worldObjName];
<add> if(worldObjs[worldObjName]) {
<add> console.error('A world object with the name "' + worldObjName + '" already exists!');
<add> } else {
<add> worldObjs[worldObjName] = new WorldObj();
<add> return worldObjs[worldObjName];
<add> }
<ide> }
<ide>
<ide> function deleteWorldObj(worldObjName) {
<ide> };
<ide> }
<ide>
<add> /* INPUT MANAGER: PUBLIC PROPERTIES */
<ide> this.inputMan = new InputManager();
<ide>
<ide>
<ide> /*** GAME LOOP ***/
<ide> /* GAME LOOP: PRIVATE METHODS */
<ide> function setupWorldObjs() {
<add> renderPipe = []; // recreate renderPipe
<ide> for(var worldObjName in worldObjs) {
<ide> worldObjs[worldObjName].setup();
<del> }
<add> renderPipe.push(worldObjs[worldObjName]);
<add> }
<add>
<add> renderPipe.sort(function(a, b) {
<add> console.log(a, b);
<add> //debugger;
<add> if(a.state.zIndex > b.state.zIndex) {
<add> return 1;
<add> }
<add> if(a.state.zIndex < b.state.zIndex) {
<add> return -1;
<add> }
<add> return 0;
<add> });
<ide> }
<ide>
<ide> function update() {
<ide> ctx.clearRect(0, 0, canvasData.width, canvasData.height);
<ide>
<ide> // render all pos x & y of all world objs
<del> for(var worldObjName in worldObjs) {
<del> var worldObj = worldObjs[worldObjName];
<add> for(var i in renderPipe) {
<add> var worldObj = renderPipe[i];
<ide> if(worldObj.getType() === 'world-obj') {
<ide> if(worldObj.state.worldObjType === 'rect') {
<ide> ctx.fillStyle = worldObj.state.color;
<ide>
<ide> this.state.worldObjType = 'rect';
<ide> this.state.color = '#FF0000';
<add> this.state.zIndex = 200;
<ide> };
<ide>
<ide> test2.update = function() {
<ide>
<ide> this.state.worldObjType = 'rect';
<ide> this.state.color = '#000';
<add> this.state.zIndex = 9001;
<ide> }
<ide>
<ide> var player = AE.createWorldObj('player');
<ide> color: '#FFF'
<ide> };
<ide> this.state.zone = zone;
<add> this.state.zIndex = 200;
<add>};
<add>
<add>var zone2 = AE.createWorldObj('zone2');
<add>zone2.setup = function() {
<add> this.state.pos = {
<add> x: 100,
<add> y: 50
<add> };
<add>
<add> this.state.size = {
<add> w: 40,
<add> h: 40
<add> };
<add>
<add> this.state.worldObjType = 'rect';
<add> this.state.color = '#000';
<add> this.state.zIndex = 100;
<ide> };
<ide>
<ide> player.update = function() { |
|
Java | mit | 2d6dccef7ea477e43e1c3fc079060692c5d742fe | 0 | socrata/datasync,socrata/datasync | package com.socrata.datasync.model;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Vector;
import javax.swing.table.AbstractTableModel;
import au.com.bytecode.opencsv.CSVReader;
import com.socrata.datasync.config.controlfile.ControlFile;
/**
* The CSV Model is used primarily to drive the previews in the mapping panel, as well as for validation
* of key failure points (e.g. date formatting). As discussed in the DatasetModel class, the actual column names
* are for display purposes only. The DatasetModel maintains a separate list of invariant columns that it manages
* independent of the values in the CSV.
*/
public class CSVModel extends AbstractTableModel{
private String[] columnNames;
final int rowsToSample = 100;
private Vector data = new Vector();
public CSVModel(ControlFile file) throws IOException
{
updateTable(file);
}
public void updateTable(ControlFile file) throws IOException {
data.removeAllElements();
updateColumnNames(file);
addSamples(file);
}
//Return rows added
private int addSamples(ControlFile controlFile) throws IOException{
CSVReader reader = getCSVReader(controlFile, controlFile.getFileTypeControl().skip);
String [] row = reader.readNext();
int rowsAdded = 0;
while (row != null && rowsAdded < rowsToSample){
// The consumers of this class assume a table with an equal number of columns in every row.
// If the row is blank, we'll need to get a placeholder with as many columns as the others to allow the
// control file editor the ability to load.
if (isBlankRow(row)){
insertData(getBlankPlaceholderRow(getColumnCount()));
}
else {
insertData(row);
}
rowsAdded++;
row = reader.readNext();
}
return rowsAdded;
}
private boolean isBlankRow(String[] row){
return row.length == 1 && row[0].isEmpty();
}
// This method will create a dummy row with as many columns as exist in the rest of the dataset.
// This will allow the control file editor to load, and the customer to skip the first couple of rows
// by setting the "skip" option under "advanced options"
private String[] getBlankPlaceholderRow(int columns){
String[] placeholder = new String[columns];
return placeholder;
}
private CSVReader getCSVReader(ControlFile controlFile, int skip) throws IOException{
String path = controlFile.getFileTypeControl().filePath;
String encoding = controlFile.getFileTypeControl().encoding;
char sep = controlFile.getFileTypeControl().separator.charAt(0);
char quote = controlFile.getFileTypeControl().quote.charAt(0);
char escape = '\u0000';
InputStreamReader inputReader = new InputStreamReader(new FileInputStream(controlFile.getFileTypeControl().filePath), controlFile.getFileTypeControl().encoding);
if (controlFile.getFileTypeControl().escape != null ){
if (controlFile.getFileTypeControl().escape.equals(""))
escape = '\u0000';
else
escape = controlFile.getFileTypeControl().escape.charAt(0);
}
CSVReader reader = new CSVReader(inputReader,
sep,
quote,
escape,
skip);
return reader;
}
private void updateColumnNames(ControlFile file) throws IOException {
boolean hasHeaderRow = file.getFileTypeControl().hasHeaderRow;
CSVReader headerReader = getCSVReader(file, 0);
String[] row = headerReader.readNext();
if (hasHeaderRow) {
columnNames = row;
}
else{
columnNames = generatePlaceholderNames(row.length);
}
fireTableStructureChanged();
}
private String[] generatePlaceholderNames(int columnCount){
String[] placeholders = new String[columnCount];
for (int i = 0; i < columnCount; i++){
placeholders[i] = ModelUtils.generatePlaceholderName(i);
}
return placeholders;
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public int getRowCount() {
return data.size();
}
public int getRowSize(int row){
return ((Vector) data.get(row)).size();
}
@Override
public Object getValueAt(int row, int col) {
return ((Vector) data.get(row)).get(col);
}
public String getColumnName(int col){
return columnNames[col];
}
public Class getColumnClass(int c){
return getValueAt(0,c).getClass();
}
public void setValueAt(Object value, int row, int col){
((Vector) data.get(row)).setElementAt(value, col);
fireTableCellUpdated(row,col);
}
public String getColumnPreview(int columnIndex, int itemsToPreview){
StringBuffer buf = new StringBuffer();
for (int i = 0; i < Math.min(itemsToPreview,getRowCount()); i++){
Object value = "N/A";
try
{
value = getValueAt(i,columnIndex);
}
catch (ArrayIndexOutOfBoundsException e){
System.out.println("Row contains different number of columns than expected. Rows with missing data will be displayed as \"N/A\" in the map fields dialog");
}
buf.append(value);
if (i+1 < Math.min(itemsToPreview,getRowCount()))
buf.append(", ");
}
return buf.toString();
}
public boolean isCellEditable(int row, int col){
return false;
}
private void insertData(Object[] values){
data.add(new Vector());
for(int i =0; i<values.length; i++){
((Vector) data.get(data.size()-1)).add(values[i]);
}
fireTableDataChanged();
}
}
| src/main/java/com/socrata/datasync/model/CSVModel.java | package com.socrata.datasync.model;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Vector;
import javax.swing.table.AbstractTableModel;
import au.com.bytecode.opencsv.CSVReader;
import com.socrata.datasync.config.controlfile.ControlFile;
/**
* The CSV Model is used primarily to drive the previews in the mapping panel, as well as for validation
* of key failure points (e.g. date formatting). As discussed in the DatasetModel class, the actual column names
* are for display purposes only. The DatasetModel maintains a separate list of invariant columns that it manages
* independent of the values in the CSV.
*/
public class CSVModel extends AbstractTableModel{
private String[] columnNames;
final int rowsToSample = 100;
private Vector data = new Vector();
public CSVModel(ControlFile file) throws IOException
{
updateTable(file);
}
public void updateTable(ControlFile file) throws IOException {
data.removeAllElements();
updateColumnNames(file);
addSamples(file);
}
//Return rows added
private int addSamples(ControlFile controlFile) throws IOException{
CSVReader reader = getCSVReader(controlFile, controlFile.getFileTypeControl().skip);
String [] row = reader.readNext();
int rowsAdded = 0;
while (row != null && rowsAdded < rowsToSample){
// The consumers of this class assume a table with an equal number of columns in every row.
// If the row is blank, we'll need to get a placeholder with as many columns as the others to allow the
// control file editor the ability to load.
if (isBlankRow(row)){
insertData(getBlankPlaceholderRow(getColumnCount()));
}
else {
insertData(row);
}
rowsAdded++;
row = reader.readNext();
}
return rowsAdded;
}
private boolean isBlankRow(String[] row){
return row.length == 1 && row[0].isEmpty();
}
// This method will create a dummy row with as many columns as exist in the rest of the dataset.
// This will allow the control file editor to load, and the customer to skip the first couple of rows
// by setting the "skip" option under "advanced options"
private String[] getBlankPlaceholderRow(int columns){
String[] placeholder = new String[columns];
return placeholder;
}
private CSVReader getCSVReader(ControlFile controlFile, int skip) throws IOException{
String path = controlFile.getFileTypeControl().filePath;
String encoding = controlFile.getFileTypeControl().encoding;
char sep = controlFile.getFileTypeControl().separator.charAt(0);
char quote = controlFile.getFileTypeControl().quote.charAt(0);
char escape = '\u0000';
InputStreamReader inputReader = new InputStreamReader(new FileInputStream(controlFile.getFileTypeControl().filePath), controlFile.getFileTypeControl().encoding);
if (controlFile.getFileTypeControl().escape != null ){
if (controlFile.getFileTypeControl().escape.equals(""))
escape = '\u0000';
else
escape = controlFile.getFileTypeControl().escape.charAt(0);
}
CSVReader reader = new CSVReader(inputReader,
sep,
quote,
escape,
skip);
return reader;
}
private void updateColumnNames(ControlFile file) throws IOException {
boolean hasHeaderRow = file.getFileTypeControl().hasHeaderRow;
CSVReader headerReader = getCSVReader(file, 0);
String[] row = headerReader.readNext();
if (hasHeaderRow) {
columnNames = row;
}
else{
columnNames = generatePlaceholderNames(row.length);
}
fireTableStructureChanged();
}
private String[] generatePlaceholderNames(int columnCount){
String[] placeholders = new String[columnCount];
for (int i = 0; i < columnCount; i++){
placeholders[i] = ModelUtils.generatePlaceholderName(i);
}
return placeholders;
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public int getRowCount() {
return data.size();
}
public int getRowSize(int row){
return ((Vector) data.get(row)).size();
}
@Override
public Object getValueAt(int row, int col) {
return ((Vector) data.get(row)).get(col);
}
public String getColumnName(int col){
return columnNames[col];
}
public Class getColumnClass(int c){
return getValueAt(0,c).getClass();
}
public void setValueAt(Object value, int row, int col){
((Vector) data.get(row)).setElementAt(value, col);
fireTableCellUpdated(row,col);
}
public String getColumnPreview(int columnIndex, int itemsToPreview){
StringBuffer buf = new StringBuffer();
for (int i = 0; i < Math.min(itemsToPreview,getRowCount()); i++){
buf.append(getValueAt(i,columnIndex));
if (i+1 < Math.min(itemsToPreview,getRowCount()))
buf.append(", ");
}
return buf.toString();
}
public boolean isCellEditable(int row, int col){
return false;
}
private void insertData(Object[] values){
data.add(new Vector());
for(int i =0; i<values.length; i++){
((Vector) data.get(data.size()-1)).add(values[i]);
}
fireTableDataChanged();
}
}
| Bug: Preview pipe delimited fields in the map fields dialog
If the file contained a delimiter that wasn't the default ',' but one of the fields
contained a comma (e.g. 12345|foo,bar) then we would detect a different
number of columns in each row, causing the dialog to fail to render.
This fix simply substitutes "n/a" in the preview (but not the data)
to allow the dialog to render and the customer to fix the delimiter.
Reviewed-by: TBD
QA: Verified with recent NYC upload
| src/main/java/com/socrata/datasync/model/CSVModel.java | Bug: Preview pipe delimited fields in the map fields dialog | <ide><path>rc/main/java/com/socrata/datasync/model/CSVModel.java
<ide> public String getColumnPreview(int columnIndex, int itemsToPreview){
<ide> StringBuffer buf = new StringBuffer();
<ide> for (int i = 0; i < Math.min(itemsToPreview,getRowCount()); i++){
<del> buf.append(getValueAt(i,columnIndex));
<add> Object value = "N/A";
<add> try
<add> {
<add> value = getValueAt(i,columnIndex);
<add> }
<add> catch (ArrayIndexOutOfBoundsException e){
<add> System.out.println("Row contains different number of columns than expected. Rows with missing data will be displayed as \"N/A\" in the map fields dialog");
<add> }
<add> buf.append(value);
<ide> if (i+1 < Math.min(itemsToPreview,getRowCount()))
<ide> buf.append(", ");
<ide> } |
|
JavaScript | mit | 4141a067990e8c095e5d266df2f3c598b21ef9a1 | 0 | necroscope/angular-js-bootstrap-datetimepicker,forestjohnsonilm/angular-js-bootstrap-datetimepicker,zhaber/angular-js-bootstrap-datetimepicker,forestjohnsonilm/angular-js-bootstrap-datetimepicker,zhaber/datetimepicker,transGLUKator/angular-js-bootstrap-datetimepicker,zhaber/angular-js-bootstrap-datetimepicker,transGLUKator/angular-js-bootstrap-datetimepicker,necroscope/angular-js-bootstrap-datetimepicker,xdimedrolx/angular-js-bootstrap-datetimepicker,zhaber/datetimepicker,xdimedrolx/angular-js-bootstrap-datetimepicker | angular.module('ui.bootstrap.datetimepicker',
["ui.bootstrap.dateparser", "ui.bootstrap.datepicker", "ui.bootstrap.timepicker"]
)
.directive('datepickerPopup', function (){
return {
restrict: 'EAC',
require: 'ngModel',
link: function(scope, element, attr, controller) {
//remove the default formatter from the input directive to prevent conflict
controller.$formatters.shift();
}
}
})
.directive('datetimepicker', [
function() {
if (angular.version.full < '1.1.4') {
return {
restrict: 'EA',
template: "<div class=\"alert alert-danger\">Angular 1.1.4 or above is required for datetimepicker to work correctly</div>"
};
}
return {
restrict: 'EA',
require: 'ngModel',
scope: {
ngModel: '=',
dayFormat: "=",
monthFormat: "=",
yearFormat: "=",
dayHeaderFormat: "=",
dayTitleFormat: "=",
monthTitleFormat: "=",
showWeeks: "=",
startingDay: "=",
yearRange: "=",
dateFormat: "=",
minDate: "=",
maxDate: "=",
dateOptions: "=",
dateDisabled: "&",
hourStep: "=",
minuteStep: "=",
showMeridian: "=",
meredians: "=",
mousewheel: "=",
placeholder: "=",
readonlyTime: "@",
ngDisabled: "="
},
template: function(elem, attrs) {
function dashCase(name, separator) {
return name.replace(/[A-Z]/g, function(letter, pos) {
return (pos ? '-' : '') + letter.toLowerCase();
});
}
function createAttr(innerAttr, dateTimeAttrOpt) {
var dateTimeAttr = angular.isDefined(dateTimeAttrOpt) ? dateTimeAttrOpt : innerAttr;
if (attrs[dateTimeAttr]) {
return dashCase(innerAttr) + "=\"" + dateTimeAttr + "\" ";
} else {
return '';
}
}
function createFuncAttr(innerAttr, funcArgs, dateTimeAttrOpt) {
var dateTimeAttr = angular.isDefined(dateTimeAttrOpt) ? dateTimeAttrOpt : innerAttr;
if (attrs[dateTimeAttr]) {
return dashCase(innerAttr) + "=\"" + dateTimeAttr + "({" + funcArgs + "})\" ";
} else {
return '';
}
}
function createEvalAttr(innerAttr, dateTimeAttrOpt) {
var dateTimeAttr = angular.isDefined(dateTimeAttrOpt) ? dateTimeAttrOpt : innerAttr;
if (attrs[dateTimeAttr]) {
return dashCase(innerAttr) + "=\"" + attrs[dateTimeAttr] + "\" ";
} else {
return dashCase(innerAttr);
}
}
function createAttrConcat(previousAttrs, attr) {
return previousAttrs + createAttr.apply(null, attr)
}
var tmpl = "<div class=\"datetimepicker-wrapper\">" +
"<input class=\"form-control\" type=\"text\" " +
"ng-click=\"open($event)\" " +
"ng-change=\"date_change($event)\" " +
"is-open=\"opened\" " +
"ng-model=\"ngModel\" " + [
["minDate"],
["maxDate"],
["dayFormat"],
["monthFormat"],
["yearFormat"],
["dayHeaderFormat"],
["dayTitleFormat"],
["monthTitleFormat"],
["startingDay"],
["yearRange"],
["datepickerOptions", "dateOptions"],
["ngDisabled"]
].reduce(createAttrConcat, '') +
createFuncAttr("dateDisabled", "date: date, mode: mode") +
createEvalAttr("datepickerPopup", "dateFormat") +
createEvalAttr("placeholder", "placeholder") +
"/>\n" +
"</div>\n" +
"<div class=\"datetimepicker-wrapper\" ng-model=\"time\" ng-change=\"time_change()\" style=\"display:inline-block\">\n" +
"<timepicker " + [
["hourStep"],
["minuteStep"],
["showMeridian"],
["meredians"],
["mousewheel"]
].reduce(createAttrConcat, '') +
createEvalAttr("readonlyInput", "readonlyTime") +
"></timepicker>\n" +
"</div>";
return tmpl;
},
controller: ['$scope',
function($scope) {
$scope.date_change = function() {
// If we changed the date only, set the time (h,m) on it.
// This is important in case the previous date was null.
// This solves the issue when the user set a date and time, cleared the date, and chose another date,
// and then, the time was cleared too - which is unexpected
var time = $scope.time;
if ($scope.ngModel) { // if this is null, that's because the user cleared the date field
$scope.ngModel.setHours(time.getHours(), time.getMinutes(), 0, 0);
}
};
$scope.time_change = function() {
if ($scope.ngModel && $scope.time) {
// convert from ISO format to Date
if (!($scope.ngModel instanceof Date)) $scope.ngModel = new Date($scope.ngModel);
$scope.ngModel.setHours($scope.time.getHours(), $scope.time.getMinutes(), 0, 0);
}
};
$scope.open = function($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened = true;
};
}
],
link: function(scope, element) {
var firstTimeAssign = true;
scope.$watch(function() {
return scope.ngModel;
}, function(newTime) {
// if a time element is focused, updating its model will cause hours/minutes to be formatted by padding with leading zeros
if (!element.children()[1].contains(document.activeElement)) {
if (newTime == null || newTime === '') { // if the newTime is not defined
if (firstTimeAssign) { // if it's the first time we assign the time value
// create a new default time where the hours, minutes, seconds and milliseconds are set to 0.
newTime = new Date();
newTime.setHours(0, 0, 0, 0);
} else { // just leave the time unchanged
return;
}
}
// Update timepicker (watch on ng-model in timepicker does not use object equality),
// also if the ngModel was not a Date, convert it to date
newTime = new Date(newTime);
scope.time = newTime; // change the time
if (firstTimeAssign) {
firstTimeAssign = false;
}
}
}, true);
}
}
}
]);
| datetimepicker.js | angular.module('ui.bootstrap.datetimepicker',
["ui.bootstrap.dateparser", "ui.bootstrap.datepicker", "ui.bootstrap.timepicker"]
)
.directive('datepickerPopup', function (){
return {
restrict: 'EAC',
require: 'ngModel',
link: function(scope, element, attr, controller) {
//remove the default formatter from the input directive to prevent conflict
controller.$formatters.shift();
}
}
})
.directive('datetimepicker', [
function() {
if (angular.version.full < '1.1.4') {
return {
restrict: 'EA',
template: "<div class=\"alert alert-danger\">Angular 1.1.4 or above is required for datetimepicker to work correctly</div>"
};
}
return {
restrict: 'EA',
require: 'ngModel',
scope: {
ngModel: '=',
dayFormat: "=",
monthFormat: "=",
yearFormat: "=",
dayHeaderFormat: "=",
dayTitleFormat: "=",
monthTitleFormat: "=",
showWeeks: "=",
startingDay: "=",
yearRange: "=",
dateFormat: "=",
minDate: "=",
maxDate: "=",
dateOptions: "=",
dateDisabled: "&",
hourStep: "=",
minuteStep: "=",
showMeridian: "=",
meredians: "=",
mousewheel: "=",
placeholder: "=",
readonlyTime: "@",
ngDisabled: "="
},
template: function(elem, attrs) {
function dashCase(name, separator) {
return name.replace(/[A-Z]/g, function(letter, pos) {
return (pos ? '-' : '') + letter.toLowerCase();
});
}
function createAttr(innerAttr, dateTimeAttrOpt) {
var dateTimeAttr = angular.isDefined(dateTimeAttrOpt) ? dateTimeAttrOpt : innerAttr;
if (attrs[dateTimeAttr]) {
return dashCase(innerAttr) + "=\"" + dateTimeAttr + "\" ";
} else {
return '';
}
}
function createFuncAttr(innerAttr, funcArgs, dateTimeAttrOpt) {
var dateTimeAttr = angular.isDefined(dateTimeAttrOpt) ? dateTimeAttrOpt : innerAttr;
if (attrs[dateTimeAttr]) {
return dashCase(innerAttr) + "=\"" + dateTimeAttr + "({" + funcArgs + "})\" ";
} else {
return '';
}
}
function createEvalAttr(innerAttr, dateTimeAttrOpt) {
var dateTimeAttr = angular.isDefined(dateTimeAttrOpt) ? dateTimeAttrOpt : innerAttr;
if (attrs[dateTimeAttr]) {
return dashCase(innerAttr) + "=\"" + attrs[dateTimeAttr] + "\" ";
} else {
return dashCase(innerAttr);
}
}
function createAttrConcat(previousAttrs, attr) {
return previousAttrs + createAttr.apply(null, attr)
}
var tmpl = "<div class=\"datetimepicker-wrapper\">" +
"<input class=\"form-control\" type=\"text\" " +
"ng-click=\"open($event)\" " +
"ng-change=\"date_change($event)\" " +
"is-open=\"opened\" " +
"ng-model=\"ngModel\" " + [
["minDate"],
["maxDate"],
["dayFormat"],
["monthFormat"],
["yearFormat"],
["dayHeaderFormat"],
["dayTitleFormat"],
["monthTitleFormat"],
["startingDay"],
["yearRange"],
["datepickerOptions", "dateOptions"],
["ngDisabled"]
].reduce(createAttrConcat, '') +
createFuncAttr("dateDisabled", "date: date, mode: mode") +
createEvalAttr("datepickerPopup", "dateFormat") +
createEvalAttr("placeholder", "placeholder") +
"/>\n" +
"</div>\n" +
"<div class=\"datetimepicker-wrapper\" ng-model=\"time\" ng-change=\"time_change()\" style=\"display:inline-block\">\n" +
"<timepicker " + [
["hourStep"],
["minuteStep"],
["showMeridian"],
["meredians"],
["mousewheel"]
].reduce(createAttrConcat, '') +
createEvalAttr("readonlyInput", "readonlyTime") +
"></timepicker>\n" +
"</div>";
return tmpl;
},
controller: ['$scope',
function($scope) {
$scope.date_change = function() {
// If we changed the date only, set the time (h,m) on it.
// This is important in case the previous date was null.
// This solves the issue when the user set a date and time, cleared the date, and chose another date,
// and then, the time was cleared too - which is unexpected
var time = $scope.time;
if ($scope.ngModel) { // if this is null, that's because the user cleared the date field
$scope.ngModel.setHours(time.getHours(), time.getMinutes(), 0, 0);
}
};
$scope.time_change = function() {
if ($scope.ngModel && $scope.time) {
// convert from ISO format to Date
if (typeof $scope.ngModel === "string" || typeof $scope.ngModel == "number") $scope.ngModel = new Date($scope.ngModel);
$scope.ngModel.setHours($scope.time.getHours(), $scope.time.getMinutes(), 0, 0);
}
};
$scope.open = function($event) {
$event.preventDefault();
$event.stopPropagation();
$scope.opened = true;
};
}
],
link: function(scope, element) {
var firstTimeAssign = true;
scope.$watch(function() {
return scope.ngModel;
}, function(newTime) {
// if a time element is focused, updating its model will cause hours/minutes to be formatted by padding with leading zeros
if (!element.children()[1].contains(document.activeElement)) {
if (newTime == null || newTime === '') { // if the newTime is not defined
if (firstTimeAssign) { // if it's the first time we assign the time value
// create a new default time where the hours, minutes, seconds and milliseconds are set to 0.
newTime = new Date();
newTime.setHours(0, 0, 0, 0);
} else { // just leave the time unchanged
return;
}
}
if (!(newTime instanceof Date)) { // if the ngModel was not a Date, convert it
newTime = new Date(newTime);
}
scope.time = newTime; // change the time
if (firstTimeAssign) {
firstTimeAssign = false;
}
}
}, true);
}
}
}
]);
| Updating timepicker on time change
| datetimepicker.js | Updating timepicker on time change | <ide><path>atetimepicker.js
<ide> $scope.time_change = function() {
<ide> if ($scope.ngModel && $scope.time) {
<ide> // convert from ISO format to Date
<del> if (typeof $scope.ngModel === "string" || typeof $scope.ngModel == "number") $scope.ngModel = new Date($scope.ngModel);
<add> if (!($scope.ngModel instanceof Date)) $scope.ngModel = new Date($scope.ngModel);
<ide> $scope.ngModel.setHours($scope.time.getHours(), $scope.time.getMinutes(), 0, 0);
<ide> }
<ide> };
<ide> }
<ide> }
<ide>
<del> if (!(newTime instanceof Date)) { // if the ngModel was not a Date, convert it
<del> newTime = new Date(newTime);
<del> }
<add> // Update timepicker (watch on ng-model in timepicker does not use object equality),
<add> // also if the ngModel was not a Date, convert it to date
<add> newTime = new Date(newTime);
<ide>
<ide> scope.time = newTime; // change the time
<ide> if (firstTimeAssign) { |
|
JavaScript | mit | 4d06965e918cb82b395dca53cd3220c940b9c713 | 0 | agconti/github-issues-to-markdown | const Rx = require('rx')
const request = Rx.Observable.fromNodeCallback(require('request'))
const oauthToken = process.argv[2]
const owner = process.argv[3]
const repository = process.argv[4]
const url = `https://api.github.com/repos/${owner}/${repository}/issues`
const headers = {
'Authorization': `token ${oauthToken}`
, 'User-Agent': owner
}
request({url, headers})
.map(res => JSON.parse(res[0].body))
.flatMap(issues => issues.map(issue => issue))
.filter(issue => issue.state == 'open')
.map(issue => `- [ ] ${issue.title} [#${issue.number}](${issue.url})`)
.subscribe( result => console.log(result)
, err => console.error(err))
| index.js | const Rx = require('rx')
const marked = require('marked')
const request = Rx.Observable.fromNodeCallback(require('request'))
const oauthToken = process.argv[2]
const owner = process.argv[3]
const repository = process.argv[4]
const url = `https://api.github.com/repos/${owner}/${repository}/issues`
const headers = {
'Authorization': `token ${oauthToken}`
, 'User-Agent': owner
}
request({url, headers})
.map(res => JSON.parse(res[0].body))
.flatMap(issues => issues.map(issue => issue))
.filter(issue => issue.state == 'open')
.map(issue => `- [ ] ${issue.title} [#${issue.number}](${issue.url})`)
.subscribe( result => console.log(result)
, err => console.error(err))
| fix(index): removed marked dependency
| index.js | fix(index): removed marked dependency | <ide><path>ndex.js
<ide> const Rx = require('rx')
<del>const marked = require('marked')
<ide> const request = Rx.Observable.fromNodeCallback(require('request'))
<ide>
<ide> const oauthToken = process.argv[2] |
|
Java | apache-2.0 | 6ff07b96de3ba39d4219f2aad9482887210b051b | 0 | SpineEventEngine/core-java,SpineEventEngine/core-java,SpineEventEngine/core-java | /*
* Copyright 2019, TeamDev. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.server.model;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import com.google.errorprone.annotations.Immutable;
import com.google.protobuf.Empty;
import com.google.protobuf.Message;
import io.spine.base.EventMessage;
import io.spine.base.Field;
import io.spine.base.FieldPath;
import io.spine.core.ByField;
import io.spine.core.Subscribe;
import io.spine.core.Where;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Objects;
import java.util.function.Predicate;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static io.spine.server.model.AbstractHandlerMethod.firstParamType;
import static io.spine.string.Stringifiers.fromString;
import static io.spine.util.Exceptions.newIllegalStateException;
/**
* Allows to filter messages passed by a handler method by a value of the message field.
*/
@Immutable
public final class ArgumentFilter implements Predicate<EventMessage> {
private final @Nullable Field field;
@SuppressWarnings("Immutable") // Values are primitives.
private final @Nullable Object expectedValue;
/**
* Creates a new filter which accepts only the passed value of the specified field.
*/
public static ArgumentFilter acceptingOnly(FieldPath field, Object fieldValue) {
checkNotNull(field);
checkNotNull(fieldValue);
return new ArgumentFilter(field, fieldValue);
}
private static ArgumentFilter acceptingAll() {
return new ArgumentFilter(FieldPath.getDefaultInstance(), Empty.getDefaultInstance());
}
/**
* Creates a new filter by the passed method.
*
* <p>If the method is not annotated for filtering, the returned instance
* {@linkplain ArgumentFilter#acceptsAll() accepts all} arguments.
*/
@SuppressWarnings("deprecation") // still need to support `ByField` when building older models.
public static ArgumentFilter createFilter(Method method) {
Subscribe annotation = method.getAnnotation(Subscribe.class);
checkAnnotated(method, annotation);
@Nullable Where where = filterAnnotationOf(method);
@Nullable ByField byField = annotation.filter();
boolean byFieldEmpty = byField.path().isEmpty();
String fieldPath;
String value;
if (where != null) {
fieldPath = where.field();
value = where.equals();
checkState(
byFieldEmpty,
"The subscriber method `%s()` has `@%s` and `@%s`" +
" annotations at the same time." +
" Please use only one, preferring `%s` because `%s` is deprecated.",
method.getName(), ByField.class.getName(), Where.class.getName(),
Where.class.getName(), ByField.class.getName()
);
} else {
if (byFieldEmpty) {
return acceptingAll();
}
fieldPath = byField.path();
value = byField.value();
}
Class<Message> paramType = firstParamType(method);
Field field = Field.parse(fieldPath);
Class<?> fieldType = field.findType(paramType).orElseThrow(
() -> newIllegalStateException(
"The message with the type `%s` does not have the field `%s`.",
paramType.getName(), field)
);
Object expectedValue = fromString(value, fieldType);
return acceptingOnly(field.path(), expectedValue);
}
private static @Nullable Where filterAnnotationOf(Method method) {
Parameter firstParam = firstParameterOf(method);
return firstParam.getAnnotation(Where.class);
}
private static Parameter firstParameterOf(Method method) {
Parameter[] parameters = method.getParameters();
checkArgument(parameters.length >= 1,
"The method `%s.%s()` does not have parameters.",
method.getDeclaringClass().getName(), method.getName());
return parameters[0];
}
private static void checkAnnotated(Method method, @Nullable Subscribe annotation) {
checkArgument(annotation != null,
"The method `%s.%s()` must be annotated with `@%s`.",
method.getDeclaringClass().getName(),
method.getName(),
Subscribe.class.getName()
);
}
@VisibleForTesting
@Nullable Object expectedValue() {
return expectedValue;
}
/**
* Tells if the passed filter works on the same field as this one.
*/
boolean sameField(ArgumentFilter another) {
return Objects.equals(field, another.field);
}
/** Obtains the depth of the filtered field. */
public int pathLength() {
if (field == null) {
return 0;
}
return field.path().getFieldNameCount();
}
private ArgumentFilter(FieldPath path, Object expectedValue) {
this.field = path.getFieldNameCount() > 0
? Field.withPath(path)
: null;
this.expectedValue = field != null
? expectedValue
: null;
}
/** Tells if this filter accepts all the events. */
public boolean acceptsAll() {
return field == null;
}
/**
* Accepts the passed event message if this filter {@linkplain #acceptingAll() accepts all}
* events, or if the field of the message matches the configured value.
*/
@Override
public boolean test(EventMessage event) {
if (acceptsAll()) {
return true;
}
Object eventField = field.valueIn(event);
boolean result = eventField.equals(expectedValue);
return result;
}
@Override
public String toString() {
MoreObjects.ToStringHelper helper = MoreObjects.toStringHelper(this);
if (acceptsAll()) {
helper.add("acceptsAll", true);
} else {
helper.add("field", field)
.add("expectedValue", expectedValue);
}
return helper.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ArgumentFilter filter = (ArgumentFilter) o;
return Objects.equals(field, filter.field) &&
Objects.equals(expectedValue, filter.expectedValue);
}
@Override
public int hashCode() {
return Objects.hash(field, expectedValue);
}
}
| server/src/main/java/io/spine/server/model/ArgumentFilter.java | /*
* Copyright 2019, TeamDev. All rights reserved.
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.server.model;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import com.google.errorprone.annotations.Immutable;
import com.google.protobuf.Empty;
import com.google.protobuf.Message;
import io.spine.base.EventMessage;
import io.spine.base.Field;
import io.spine.base.FieldPath;
import io.spine.core.ByField;
import io.spine.core.Subscribe;
import io.spine.core.Where;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Objects;
import java.util.function.Predicate;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static io.spine.server.model.AbstractHandlerMethod.firstParamType;
import static io.spine.string.Stringifiers.fromString;
import static io.spine.util.Exceptions.newIllegalStateException;
/**
* Allows to filter messages passed by a handler method by a value of the message field.
*/
@Immutable
public final class ArgumentFilter implements Predicate<EventMessage> {
private final @Nullable Field field;
@SuppressWarnings("Immutable") // Values are primitives.
private final @Nullable Object expectedValue;
/**
* Creates a new filter which accepts only the passed value of the specified field.
*/
public static ArgumentFilter acceptingOnly(FieldPath field, Object fieldValue) {
checkNotNull(field);
checkNotNull(fieldValue);
return new ArgumentFilter(field, fieldValue);
}
private static ArgumentFilter acceptingAll() {
return new ArgumentFilter(FieldPath.getDefaultInstance(), Empty.getDefaultInstance());
}
/**
* Creates a new filter by the passed method.
*
* <p>If the method is not annotated for filtering, the returned instance
* {@linkplain ArgumentFilter#acceptsAll() accepts all} arguments.
*/
@SuppressWarnings("deprecation") // still need to support `ByField` when building older models.
public static ArgumentFilter createFilter(Method method) {
Subscribe annotation = method.getAnnotation(Subscribe.class);
checkAnnotated(method, annotation);
@Nullable Where where = filterAnnotationOf(method);
@Nullable ByField byField = annotation.filter();
boolean byFieldEmpty = byField.path().isEmpty();
String fieldPath;
String value;
if (where != null) {
fieldPath = where.field();
value = where.equals();
checkState(
byFieldEmpty,
"The subscriber method `%s()` has `@%s` and `@%s`" +
" annotations at the same time." +
" Please use only one, preferring `%s` because `%s` is deprecated.",
method.getName(), ByField.class.getName(), Where.class.getName(),
Where.class.getName(), ByField.class.getName()
);
} else {
if (byFieldEmpty) {
return acceptingAll();
}
fieldPath = byField.path();
value = byField.value();
}
Class<Message> paramType = firstParamType(method);
Field field = Field.parse(fieldPath);
Class<?> fieldType = field.findType(paramType).orElseThrow(
() -> newIllegalStateException(
"The message with the type `%s` does not have the field `%s`.",
paramType.getName(), field)
);
Object expectedValue = fromString(value, fieldType);
return acceptingOnly(field.path(), expectedValue);
}
private static @Nullable Where filterAnnotationOf(Method method) {
Parameter firstParam = firstParameterOf(method);
return firstParam.getAnnotation(Where.class);
}
private static Parameter firstParameterOf(Method method) {
Parameter[] parameters = method.getParameters();
checkArgument(parameters.length >= 1,
"The method `%s.%s()` does not have parameters.",
method.getDeclaringClass().getName(), method.getName());
return parameters[0];
}
private static void checkAnnotated(Method method, @Nullable Subscribe annotation) {
checkArgument(annotation != null,
"The method `%s.%s()` must be annotated with `@%s`.",
method.getDeclaringClass().getName(),
method.getName(),
Subscribe.class.getName()
);
}
@VisibleForTesting
@Nullable Object expectedValue() {
return expectedValue;
}
/**
* Tells if the passed filter works on the same field as this one.
*/
boolean sameField(ArgumentFilter another) {
if (field == null) {
return another.field == null;
}
boolean result = field.equals(another.field);
return result;
}
/** Obtains the depth of the filtered field. */
public int pathLength() {
if (field == null) {
return 0;
}
return field.path().getFieldNameCount();
}
private ArgumentFilter(FieldPath path, Object expectedValue) {
this.field = path.getFieldNameCount() > 0
? Field.withPath(path)
: null;
this.expectedValue = field != null
? expectedValue
: null;
}
/** Tells if this filter accepts all the events. */
public boolean acceptsAll() {
return field == null;
}
/**
* Accepts the passed event message if this filter {@linkplain #acceptingAll() accepts all}
* events, or if the field of the message matches the configured value.
*/
@Override
public boolean test(EventMessage event) {
if (acceptsAll()) {
return true;
}
Object eventField = field.valueIn(event);
boolean result = eventField.equals(expectedValue);
return result;
}
@Override
public String toString() {
MoreObjects.ToStringHelper helper = MoreObjects.toStringHelper(this);
if (acceptsAll()) {
helper.add("acceptsAll", true);
} else {
helper.add("field", field)
.add("expectedValue", expectedValue);
}
return helper.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ArgumentFilter filter = (ArgumentFilter) o;
return Objects.equals(field, filter.field) &&
Objects.equals(expectedValue, filter.expectedValue);
}
@Override
public int hashCode() {
return Objects.hash(field, expectedValue);
}
}
| Simplify equality check
| server/src/main/java/io/spine/server/model/ArgumentFilter.java | Simplify equality check | <ide><path>erver/src/main/java/io/spine/server/model/ArgumentFilter.java
<ide> * Tells if the passed filter works on the same field as this one.
<ide> */
<ide> boolean sameField(ArgumentFilter another) {
<del> if (field == null) {
<del> return another.field == null;
<del> }
<del> boolean result = field.equals(another.field);
<del> return result;
<add> return Objects.equals(field, another.field);
<ide> }
<ide>
<ide> /** Obtains the depth of the filtered field. */ |
|
JavaScript | apache-2.0 | 7e25246bfe544da8b8d808cef66821710402a0ac | 0 | driebit/ginger,driebit/ginger,driebit/ginger |
(function ($) {
'use strict';
$.widget("ui.ginger_search", {
_init: function() {
this.init();
},
init: function() {
var self = this,
element = self.element,
timer = null,
prevVal = null,
paramResults = element.data('param-results'),
paramContainer = element.data('param-container'),
paramWire = element.data('param-wire'),
resultsElement = $("#" + paramResults),
windowHeight = $(window).height();
resultsElement.css('visibility', 'hidden');
function doSearch() {
var val = self.element.val();
if (!val.length) {
resultsElement.css('visibility', 'hidden');
return;
}
if (prevVal && val == prevVal || !val.length) {
return;
}
prevVal = val;
z_event(paramWire, {value: val});
resultsElement.removeClass('is-scrolable');
setTimeout(function(){
//TODO: This should happen in the complete of the wire
if ((resultsElement.outerHeight() + 65) > windowHeight) {
resultsElement.addClass('is-scrolable');
resultsElement.css('visibility', 'visible');
} else {
resultsElement.css('visibility', 'visible');
}
}, 300);
}
self.element.on('keyup', function() {
if (timer) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(doSearch, 500);
});
$(document).mouseup(function (e) {
var container = $("#" + paramContainer),
closest = $(e.target).closest(container);
if (!container.is(e.target) // if the target of the click isn't the container...
&& closest.size() == 0)
{
$('.ginger-search').removeClass('is-visible');
resultsElement.css('visibility', 'hidden');
}
});
}
});
})(jQuery);
| lib/js/ginger-search.js |
(function ($) {
'use strict';
$.widget("ui.ginger_search", {
_init: function() {
this.init();
},
init: function() {
var self = this,
element = self.element,
timer = null,
prevVal = null,
paramResults = element.data('param-results'),
paramContainer = element.data('param-container'),
paramWire = element.data('param-wire'),
resultsElement = $("#" + paramResults),
windowHeight = $(window).height();
resultsElement.hide();
resultsElement.removeClass('is-scrolable');
function doSearch() {
var val = self.element.val();
if (!val.length) {
resultsElement.hide();
return;
}
if (prevVal && val == prevVal || !val.length) {
return;
}
prevVal = val;
z_event(paramWire, {value: val});
resultsElement.removeClass('is-scrolable');
resultsElement.show(function(){
if ((resultsElement.outerHeight() + 65) > windowHeight) {
resultsElement.addClass('is-scrolable');
}
});
}
self.element.on('keyup', function() {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(doSearch, 300);
});
$(document).mouseup(function (e) {
var container = $("#" + paramContainer),
closest = $(e.target).closest(container);
if (!container.is(e.target) // if the target of the click isn't the container...
&& closest.size() == 0)
{
$('.ginger-search').removeClass('is-visible');
resultsElement.hide();
}
});
}
});
})(jQuery);
| [search] minst lelijke oplossing
| lib/js/ginger-search.js | [search] minst lelijke oplossing | <ide><path>ib/js/ginger-search.js
<ide> resultsElement = $("#" + paramResults),
<ide> windowHeight = $(window).height();
<ide>
<del> resultsElement.hide();
<del> resultsElement.removeClass('is-scrolable');
<add> resultsElement.css('visibility', 'hidden');
<ide>
<ide> function doSearch() {
<ide>
<ide> var val = self.element.val();
<ide>
<ide> if (!val.length) {
<del> resultsElement.hide();
<add> resultsElement.css('visibility', 'hidden');
<ide> return;
<ide> }
<ide>
<ide>
<ide> resultsElement.removeClass('is-scrolable');
<ide>
<del> resultsElement.show(function(){
<add> setTimeout(function(){
<add> //TODO: This should happen in the complete of the wire
<add>
<ide> if ((resultsElement.outerHeight() + 65) > windowHeight) {
<ide> resultsElement.addClass('is-scrolable');
<add> resultsElement.css('visibility', 'visible');
<add> } else {
<add> resultsElement.css('visibility', 'visible');
<ide> }
<del> });
<add> }, 300);
<ide> }
<ide>
<ide> self.element.on('keyup', function() {
<ide> if (timer) {
<ide> clearTimeout(timer);
<add> timer = null;
<ide> }
<ide>
<del> timer = setTimeout(doSearch, 300);
<add> timer = setTimeout(doSearch, 500);
<ide> });
<ide>
<ide> $(document).mouseup(function (e) {
<ide> {
<ide> $('.ginger-search').removeClass('is-visible');
<ide>
<del> resultsElement.hide();
<add> resultsElement.css('visibility', 'hidden');
<ide> }
<ide> });
<ide> } |
|
JavaScript | mit | 2aba01dada5a690425ed15d3a543f057227846e5 | 0 | jaredpalmer/razzle,jaredpalmer/razzle | const yargs = require('yargs');
const execa = require('execa');
const fs = require('fs-extra');
const path = require('path');
const rootDir = path.resolve(__dirname, '..');
const defaultExample = 'packages/create-razzle-app/templates/default';
let argv = yargs
.usage('$0 [<example>...] [-s|--stage=<stage>] [-c|--copy-only] [-a|--all]')
.command({
command: '*',
builder: yargs => {
return yargs
.option('c', {
alias: 'copy-only',
describe: 'only copy',
type: 'boolean',
default: false,
})
.option('a', {
alias: 'all',
describe: 'bootstrap all',
type: 'boolean',
default: false,
})
.option('s', {
alias: 'stage',
describe: 'stage directory',
default: false,
type: 'string'
})
.option('d', {
alias: 'default',
describe: 'bootstrap default example',
type: 'boolean',
default: false,
});
},
handler: async argv => {
const packageJsonData = JSON.parse(
await fs.readFile(path.join(rootDir, 'package.json'))
);
const packageMetaData = JSON.parse(
await fs.readFile(path.join(rootDir, 'package.meta.json'))
);
const examples = (
await fs.readdir(path.join(rootDir, 'examples'), {
withFileTypes: true,
})
)
.filter(item => item.isDirectory())
.map(item => item.name);
const exampleNamesMap = (argv.all
? [defaultExample].concat(examples)
: argv._).map(example => {
return [example, example.includes('/') ? example : `examples/${example}`];
});
const exampleDirs = exampleNamesMap.map(example =>example[1]);
let extraWorkspaceDirs = [];
if (exampleDirs) {
const missing = exampleDirs
.map(example => {
const examplePackageJson = path.join(rootDir, example, 'package.json');
if (!fs.existsSync(examplePackageJson)) {
return example;
}
let examplePackageJsonData = {};
try {
examplePackageJsonData = JSON.parse(fs.readFileSync(examplePackageJson));
} catch {
console.log(`failed to read json ${examplePackageJson}`);
process.exit(1);
}
extraWorkspaceDirs = extraWorkspaceDirs
.concat([example])
.concat((examplePackageJsonData.razzle || {}).extraWorkspacedirs || []);
return false;
})
.filter(x => Boolean(x));
if (missing.length) {
console.log(`${missing.join(', ')} not found in ${rootDir}`);
process.exit(1);
}
}
packageJsonData.workspaces = packageJsonData.workspaces.concat(extraWorkspaceDirs);
const jsonString = JSON.stringify(packageJsonData, null, ' ') + '\n';
if (jsonString) {
try {
fs.writeFileSync(path.join(rootDir, 'package.json'), jsonString);
} catch {
console.log(`failed to write json ${item}`);
}
} else {
console.log(`not writing empty json ${item}`);
}
await execa("yarn install --no-lockfile", { shell: true, stdio: 'inherit' });
exampleDirs
.map(example => {
fs.writeFileSync(path.join(rootDir, example, 'node_modules', '.bin', 'restrap'), `#!/usr/bin/env node
'use strict';
const execa = require('execa');
execa("cd ${rootDir} && yarn bootstrap-examples ${example}", { shell: true, stdio: 'inherit' });`);
fs.chmodSync(path.join(rootDir, example, 'node_modules', '.bin', 'restrap'), 0o775)
})
packageJsonData.workspaces = packageMetaData.workspaces;
const resetJsonString = JSON.stringify(packageJsonData, null, ' ') + '\n';
if (resetJsonString) {
try {
fs.writeFileSync(path.join(rootDir, 'package.json'), resetJsonString);
} catch {
console.log(`failed to write json ${item}`);
}
} else {
console.log(`not writing empty json ${item}`);
}
},
})
.help().argv;
| scripts/bootstrap-examples.js | const yargs = require('yargs');
const execa = require('execa');
const fs = require('fs-extra');
const path = require('path');
const rootDir = path.resolve(__dirname, '..');
const defaultExample = 'packages/create-razzle-app/templates/default';
let argv = yargs
.usage('$0 [<example>...] [-s|--stage=<stage>] [-c|--copy-only] [-a|--all]')
.command({
command: '*',
builder: yargs => {
return yargs
.option('c', {
alias: 'copy-only',
describe: 'only copy',
type: 'boolean',
default: false,
})
.option('a', {
alias: 'all',
describe: 'bootstrap all',
type: 'boolean',
default: false,
})
.option('s', {
alias: 'stage',
describe: 'stage directory',
default: false,
type: 'string'
})
.option('d', {
alias: 'default',
describe: 'bootstrap default example',
type: 'boolean',
default: false,
});
},
handler: async argv => {
const packageJsonData = JSON.parse(
await fs.readFile(path.join(rootDir, 'package.json'))
);
const packageMetaData = JSON.parse(
await fs.readFile(path.join(rootDir, 'package.meta.json'))
);
const examples = (
await fs.readdir(path.join(rootDir, 'examples'), {
withFileTypes: true,
})
)
.filter(item => item.isDirectory())
.map(item => item.name);
const exampleNamesMap = (argv.all
? [defaultExample].concat(examples)
: argv._).map(example => {
return [example, example.includes('/') ? example : `examples/${example}`];
});
const exampleDirs = exampleNamesMap.map(example =>example[1]);
if (exampleDirs) {
const missing = exampleDirs
.map(example => {
if (!fs.existsSync(path.join(rootDir, example, 'package.json'))) {
return example;
}
return false;
})
.filter(x => Boolean(x));
if (missing.length) {
console.log(`${missing.join(', ')} not found in ${rootDir}`);
process.exit(1);
}
}
packageJsonData.workspaces = packageJsonData.workspaces.concat(exampleDirs);
const jsonString = JSON.stringify(packageJsonData, null, ' ') + '\n';
if (jsonString) {
try {
fs.writeFileSync(path.join(rootDir, 'package.json'), jsonString);
} catch {
console.log(`failed to write json ${item}`);
}
} else {
console.log(`not writing empty json ${item}`);
}
await execa("yarn install --no-lockfile", { shell: true, stdio: 'inherit' });
exampleDirs
.map(example => {
fs.writeFileSync(path.join(rootDir, example, 'node_modules', '.bin', 'restrap'), `#!/usr/bin/env node
'use strict';
const execa = require('execa');
execa("cd ${rootDir} && yarn bootstrap-examples ${example}", { shell: true, stdio: 'inherit' });`);
fs.chmodSync(path.join(rootDir, example, 'node_modules', '.bin', 'restrap'), 0o775)
})
packageJsonData.workspaces = packageMetaData.workspaces;
const resetJsonString = JSON.stringify(packageJsonData, null, ' ') + '\n';
if (resetJsonString) {
try {
fs.writeFileSync(path.join(rootDir, 'package.json'), resetJsonString);
} catch {
console.log(`failed to write json ${item}`);
}
} else {
console.log(`not writing empty json ${item}`);
}
},
})
.help().argv;
| dev-infra: add more example bootstrap features
| scripts/bootstrap-examples.js | dev-infra: add more example bootstrap features | <ide><path>cripts/bootstrap-examples.js
<ide>
<ide> const exampleDirs = exampleNamesMap.map(example =>example[1]);
<ide>
<add> let extraWorkspaceDirs = [];
<add>
<ide> if (exampleDirs) {
<ide> const missing = exampleDirs
<ide> .map(example => {
<del>
<del> if (!fs.existsSync(path.join(rootDir, example, 'package.json'))) {
<add> const examplePackageJson = path.join(rootDir, example, 'package.json');
<add> if (!fs.existsSync(examplePackageJson)) {
<ide> return example;
<ide> }
<add> let examplePackageJsonData = {};
<add> try {
<add> examplePackageJsonData = JSON.parse(fs.readFileSync(examplePackageJson));
<add> } catch {
<add> console.log(`failed to read json ${examplePackageJson}`);
<add> process.exit(1);
<add> }
<add> extraWorkspaceDirs = extraWorkspaceDirs
<add> .concat([example])
<add> .concat((examplePackageJsonData.razzle || {}).extraWorkspacedirs || []);
<ide> return false;
<ide> })
<ide> .filter(x => Boolean(x));
<ide> process.exit(1);
<ide> }
<ide> }
<del> packageJsonData.workspaces = packageJsonData.workspaces.concat(exampleDirs);
<add> packageJsonData.workspaces = packageJsonData.workspaces.concat(extraWorkspaceDirs);
<ide> const jsonString = JSON.stringify(packageJsonData, null, ' ') + '\n';
<ide> if (jsonString) {
<ide> try { |
|
Java | bsd-3-clause | 16d1959c99399961ae603e1f81e900539253dfc5 | 0 | all-of-us/workbench,all-of-us/workbench,all-of-us/workbench,all-of-us/workbench,all-of-us/workbench,all-of-us/workbench,all-of-us/workbench,all-of-us/workbench,all-of-us/workbench | package org.pmiops.workbench;
import com.blockscore.models.PaginatedResult;
import com.blockscore.models.Person;
import com.blockscore.net.BlockscoreApiClient;
import javax.inject.Provider;
import org.pmiops.workbench.google.CloudStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class BlockscoreServiceImpl implements BlockscoreService {
private final Provider<CloudStorageService> cloudStorageServiceProvider;
private String apiKey = null;
@Autowired
public BlockscoreServiceImpl(Provider<CloudStorageService> cloudStorageServiceProvider) {
this.cloudStorageServiceProvider = cloudStorageServiceProvider;
}
public PaginatedResult<Person> listPeople() {
if (apiKey == null) {
apiKey = cloudStorageServiceProvider.get().readBlockscoreApiKey();
}
BlockscoreApiClient client = new BlockscoreApiClient(apiKey);
return client.listPeople();
}
}
| api/src/main/java/org/pmiops/workbench/BlockscoreServiceImpl.java | package org.pmiops.workbench;
import com.blockscore.models.PaginatedResult;
import com.blockscore.models.Person;
import com.blockscore.net.BlockscoreApiClient;
import javax.inject.Provider;
import org.pmiops.workbench.google.CloudStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class BlockscoreServiceImpl implements BlockscoreService {
private final CloudStorageService cloudStorageService;
private String apiKey = null;
@Autowired
public BlockscoreServiceImpl(CloudStorageService cloudStorageService) {
this.cloudStorageService = cloudStorageService;
apiKey = cloudStorageService.readBlockscoreApiKey();
}
public PaginatedResult<Person> listPeople() {
BlockscoreApiClient client = new BlockscoreApiClient(apiKey);
return client.listPeople();
}
}
| Move Blockscore API key fetch until later to fix dev (#317)
| api/src/main/java/org/pmiops/workbench/BlockscoreServiceImpl.java | Move Blockscore API key fetch until later to fix dev (#317) | <ide><path>pi/src/main/java/org/pmiops/workbench/BlockscoreServiceImpl.java
<ide> @Service
<ide> public class BlockscoreServiceImpl implements BlockscoreService {
<ide>
<del> private final CloudStorageService cloudStorageService;
<add> private final Provider<CloudStorageService> cloudStorageServiceProvider;
<ide> private String apiKey = null;
<ide>
<ide> @Autowired
<del> public BlockscoreServiceImpl(CloudStorageService cloudStorageService) {
<del> this.cloudStorageService = cloudStorageService;
<del> apiKey = cloudStorageService.readBlockscoreApiKey();
<add> public BlockscoreServiceImpl(Provider<CloudStorageService> cloudStorageServiceProvider) {
<add> this.cloudStorageServiceProvider = cloudStorageServiceProvider;
<ide> }
<ide>
<ide> public PaginatedResult<Person> listPeople() {
<add> if (apiKey == null) {
<add> apiKey = cloudStorageServiceProvider.get().readBlockscoreApiKey();
<add> }
<ide> BlockscoreApiClient client = new BlockscoreApiClient(apiKey);
<ide> return client.listPeople();
<ide> } |
|
Java | mit | eb2fe6f4756bb7a1eb9a0b1afd0e9d12bc24ad74 | 0 | ugent-cros/cros-core,ugent-cros/cros-core,ugent-cros/cros-core | package controllers;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.ExpressionList;
import com.fasterxml.jackson.annotation.JsonRootName;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import models.User;
import play.data.Form;
import play.libs.Json;
import play.mvc.Result;
import utilities.ControllerHelper;
import utilities.JsonHelper;
import utilities.QueryHelper;
import utilities.annotations.Authentication;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static play.mvc.Controller.request;
import static play.mvc.Results.*;
/**
* Created by yasser on 4/03/15.
*/
public class UserController {
private static ObjectMapper jsonMapper = new ObjectMapper();
public static final ControllerHelper.Link allUsersLink = new ControllerHelper.Link("users", controllers.routes.UserController.getAll().url());
private static Form<User> form = Form.form(User.class);
private static final String PASSWORD_FIELD_KEY = "password";
@Authentication({User.Role.ADMIN, User.Role.READONLY_ADMIN})
public static Result getAll() {
ExpressionList<User> exp = QueryHelper.buildQuery(User.class, User.FIND.where());
List<JsonHelper.Tuple> tuples = exp.findList().stream().map(user -> new JsonHelper.Tuple(user, new ControllerHelper.Link("self",
controllers.routes.UserController.get(user.getId()).url()))).collect(Collectors.toList());
// TODO: add links when available
List<ControllerHelper.Link> links = new ArrayList<>();
links.add(new ControllerHelper.Link("self", controllers.routes.UserController.getAll().url()));
links.add(new ControllerHelper.Link("total", controllers.routes.UserController.getTotal().url()));
links.add(new ControllerHelper.Link("me", controllers.routes.UserController.currentUser().url()));
try {
JsonNode result = JsonHelper.createJsonNode(tuples, links, User.class);
String[] totalQuery = request().queryString().get("total");
if (totalQuery != null && totalQuery.length == 1 && totalQuery[0].equals("true")) {
ExpressionList<User> countExpression = QueryHelper.buildQuery(User.class, User.FIND.where(), true);
String root = User.class.getAnnotation(JsonRootName.class).value();
((ObjectNode) result.get(root)).put("total",countExpression.findRowCount());
}
return ok(result);
} catch(JsonProcessingException ex) {
play.Logger.error(ex.getMessage(), ex);
return internalServerError();
}
}
@Authentication({User.Role.ADMIN, User.Role.READONLY_ADMIN})
public static Result getTotal() {
return ok(JsonHelper.addRootElement(Json.newObject().put("total", User.FIND.findRowCount()), User.class));
}
@Authentication({User.Role.ADMIN, User.Role.READONLY_ADMIN, User.Role.USER})
public static Result get(Long id) {
// Check if user has correct privileges
User client = SecurityController.getUser();
if(User.Role.USER.equals(client.getRole()) && client.getId() != id)
return unauthorized();
User user = User.FIND.byId(id);
if(user == null)
return notFound();
return ok(JsonHelper.createJsonNode(user, getAllLinks(id), User.class));
}
@Authentication({User.Role.ADMIN})
public static Result create() {
JsonNode body = request().body().asJson();
JsonNode strippedBody;
try {
strippedBody = JsonHelper.removeRootElement(body, User.class, false);
} catch(JsonHelper.InvalidJSONException ex) {
play.Logger.debug(ex.getMessage(), ex);
return badRequest(ex.getMessage());
}
Form<User> filledForm = form.bind(strippedBody);
// Check password
Form.Field passwordField = filledForm.field(PASSWORD_FIELD_KEY);
String passwordError = User.validatePassword(passwordField.value());
if(passwordError != null) {
filledForm.reject(PASSWORD_FIELD_KEY, passwordError);
}
if(filledForm.hasErrors()) {
// maybe create info about what's wrong
return badRequest(filledForm.errorsAsJson());
}
User newUser = filledForm.get();
// Check if a user with this email address already exists
if(User.findByEmail(newUser.getEmail()) != null) {
return badRequest("Email address is already in use.");
}
// Create new user
newUser.save();
return created(JsonHelper.createJsonNode(newUser, getAllLinks(newUser.getId()), User.class));
}
@Authentication({User.Role.ADMIN, User.Role.READONLY_ADMIN, User.Role.USER})
public static Result update(Long id) {
// Check if user has correct privileges
User client = SecurityController.getUser();
if(!User.Role.ADMIN.equals(client.getRole()) && client.getId() != id)
return unauthorized();
// Check if user exists
User user = User.FIND.byId(id);
if(user == null)
return notFound();
// Check input
JsonNode body = request().body().asJson();
JsonNode strippedBody;
try {
strippedBody = JsonHelper.removeRootElement(body, User.class, false);
} catch(JsonHelper.InvalidJSONException ex) {
play.Logger.debug(ex.getMessage(), ex);
return badRequest(ex.getMessage());
}
Form<User> filledForm = form.bind(strippedBody);
// Check if password is long enough in filled form
String password = filledForm.field(PASSWORD_FIELD_KEY).value();
if(password != null) {
String error = User.validatePassword(password);
if(error != null) {
filledForm.reject(PASSWORD_FIELD_KEY, error);
}
}
// Check rest of input
if(filledForm.hasErrors()) {
return badRequest(filledForm.errorsAsJson());
}
// Update the user
User updatedUser = filledForm.get();
updatedUser.setId(id);
Set<String> updatedFields = filledForm.data().keySet();
if (updatedFields.contains("password")) {
updatedFields.remove("password");
updatedFields.add("shaPassword");
}
Ebean.update(updatedUser, updatedFields);
return ok(JsonHelper.createJsonNode(updatedUser, getAllLinks(id), User.class));
}
// no check needed
public static Result currentUser() {
User client = SecurityController.getUser();
if(client == null) {
return unauthorized();
}
return get(client.getId());
}
@Authentication({User.Role.ADMIN})
public static Result deleteAll() {
User client = SecurityController.getUser();
User.FIND.where().ne("id", client.getId()).findList().forEach(u -> u.delete());
return getAll();
}
@Authentication({User.Role.ADMIN})
public static Result delete(Long id) {
// Check if user exists
User userToDelete = User.FIND.byId(id);
if(userToDelete == null) {
return notFound();
}
// Delete the user
userToDelete.delete();
// Add links to result
ObjectNode root = jsonMapper.createObjectNode();
List<ControllerHelper.Link> links = new ArrayList<>();
links.add(Application.homeLink);
links.add(allUsersLink);
root.put("links", (JsonNode) jsonMapper.valueToTree(links));
return ok(root);
}
@Authentication({User.Role.ADMIN, User.Role.READONLY_ADMIN, User.Role.USER})
public static Result getUserAuthToken(Long id) {
// Check if user has correct privileges
User client = SecurityController.getUser();
if(client.getId() != id) {
return unauthorized();
}
// Return auth token to the client
String authToken = client.getAuthToken();
ObjectNode authTokenJson = Json.newObject();
authTokenJson.put(SecurityController.AUTH_TOKEN, authToken);
return ok(authTokenJson);
}
@Authentication({User.Role.ADMIN, User.Role.USER})
public static Result invalidateAuthToken(Long userId) {
// Check if user has correct privileges
User client = SecurityController.getUser();
if(!User.Role.ADMIN.equals(client.getRole())
&& client.getId() != userId) {
return unauthorized();
}
User user = User.FIND.byId(userId);
if(user == null) {
// Return possible links
ObjectNode root = jsonMapper.createObjectNode();
List<ControllerHelper.Link> links = new ArrayList<>();
links.add(Application.homeLink);
links.add(allUsersLink);
root.put("links", (JsonNode) jsonMapper.valueToTree(links));
return notFound();
}
user.invalidateAuthToken();
user.save();
return ok();
}
private static List<ControllerHelper.Link> getAllLinks(long id) {
List<ControllerHelper.Link> links = new ArrayList<>();
links.add(new ControllerHelper.Link("self", controllers.routes.UserController.get(id).url()));
links.add(new ControllerHelper.Link("getAuthToken", controllers.routes.UserController.getUserAuthToken(id).url()));
links.add(new ControllerHelper.Link("invalidateAuthToken", controllers.routes.UserController.invalidateAuthToken(id).url()));
return links;
}
}
| app/controllers/UserController.java | package controllers;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.ExpressionList;
import com.fasterxml.jackson.annotation.JsonRootName;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import models.User;
import play.data.Form;
import play.libs.Json;
import play.mvc.Result;
import utilities.ControllerHelper;
import utilities.JsonHelper;
import utilities.QueryHelper;
import utilities.annotations.Authentication;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static play.mvc.Controller.request;
import static play.mvc.Results.*;
/**
* Created by yasser on 4/03/15.
*/
public class UserController {
private static ObjectMapper jsonMapper = new ObjectMapper();
public static final ControllerHelper.Link allUsersLink = new ControllerHelper.Link("users", controllers.routes.UserController.getAll().url());
private static Form<User> form = Form.form(User.class);
private static final String PASSWORD_FIELD_KEY = "password";
@Authentication({User.Role.ADMIN, User.Role.READONLY_ADMIN})
public static Result getAll() {
ExpressionList<User> exp = QueryHelper.buildQuery(User.class, User.FIND.where());
List<JsonHelper.Tuple> tuples = exp.findList().stream().map(user -> new JsonHelper.Tuple(user, new ControllerHelper.Link("self",
controllers.routes.UserController.get(user.getId()).url()))).collect(Collectors.toList());
// TODO: add links when available
List<ControllerHelper.Link> links = new ArrayList<>();
links.add(new ControllerHelper.Link("self", controllers.routes.UserController.getAll().url()));
links.add(new ControllerHelper.Link("total", controllers.routes.UserController.getTotal().url()));
links.add(new ControllerHelper.Link("me", controllers.routes.UserController.currentUser().url()));
try {
JsonNode result = JsonHelper.createJsonNode(tuples, links, User.class);
String[] totalQuery = request().queryString().get("total");
if (totalQuery != null && totalQuery.length == 1 && totalQuery[0].equals("true")) {
ExpressionList<User> countExpression = QueryHelper.buildQuery(User.class, User.FIND.where(), true);
String root = User.class.getAnnotation(JsonRootName.class).value();
((ObjectNode) result.get(root)).put("total",countExpression.findRowCount());
}
return ok(result);
} catch(JsonProcessingException ex) {
play.Logger.error(ex.getMessage(), ex);
return internalServerError();
}
}
@Authentication({User.Role.ADMIN, User.Role.READONLY_ADMIN})
public static Result getTotal() {
return ok(JsonHelper.addRootElement(Json.newObject().put("total", User.FIND.findRowCount()), User.class));
}
@Authentication({User.Role.ADMIN, User.Role.READONLY_ADMIN, User.Role.USER})
public static Result get(Long id) {
// Check if user has correct privileges
User client = SecurityController.getUser();
if(User.Role.USER.equals(client.getRole()) && client.getId() != id)
return unauthorized();
User user = User.FIND.byId(id);
if(user == null)
return notFound();
return ok(JsonHelper.createJsonNode(user, getAllLinks(id), User.class));
}
@Authentication({User.Role.ADMIN})
public static Result create() {
JsonNode body = request().body().asJson();
JsonNode strippedBody;
try {
strippedBody = JsonHelper.removeRootElement(body, User.class, false);
} catch(JsonHelper.InvalidJSONException ex) {
play.Logger.debug(ex.getMessage(), ex);
return badRequest(ex.getMessage());
}
Form<User> filledForm = form.bind(strippedBody);
// Check password
Form.Field passwordField = filledForm.field(PASSWORD_FIELD_KEY);
String passwordError = User.validatePassword(passwordField.value());
if(passwordError != null) {
filledForm.reject(PASSWORD_FIELD_KEY, passwordError);
}
if(filledForm.hasErrors()) {
// maybe create info about what's wrong
return badRequest(filledForm.errorsAsJson());
}
User newUser = filledForm.get();
// Check if a user with this email address already exists
if(User.findByEmail(newUser.getEmail()) != null) {
return badRequest("Email address is already in use.");
}
// Create new user
newUser.save();
return created(JsonHelper.createJsonNode(newUser, getAllLinks(newUser.getId()), User.class));
}
@Authentication({User.Role.ADMIN, User.Role.READONLY_ADMIN, User.Role.USER})
public static Result update(Long id) {
// Check if user has correct privileges
User client = SecurityController.getUser();
if(!User.Role.ADMIN.equals(client.getRole()) && client.getId() != id)
return unauthorized();
// Check if user exists
User user = User.FIND.byId(id);
if(user == null)
return notFound();
// Check input
JsonNode body = request().body().asJson();
JsonNode strippedBody;
try {
strippedBody = JsonHelper.removeRootElement(body, User.class, false);
} catch(JsonHelper.InvalidJSONException ex) {
play.Logger.debug(ex.getMessage(), ex);
return badRequest(ex.getMessage());
}
Form<User> filledForm = form.bind(strippedBody);
// Check if password is long enough in filled form
String password = filledForm.field(PASSWORD_FIELD_KEY).value();
if(password != null) {
String error = User.validatePassword(password);
if(error != null) {
filledForm.reject(PASSWORD_FIELD_KEY, error);
}
}
// Check rest of input
if(filledForm.hasErrors()) {
return badRequest(filledForm.errorsAsJson());
}
// Update the user
User updatedUser = filledForm.get();
updatedUser.setId(id);
Set<String> updatedFields = filledForm.data().keySet();
Ebean.update(updatedUser, updatedFields);
return ok(JsonHelper.createJsonNode(updatedUser, getAllLinks(id), User.class));
}
// no check needed
public static Result currentUser() {
User client = SecurityController.getUser();
if(client == null) {
return unauthorized();
}
return get(client.getId());
}
@Authentication({User.Role.ADMIN})
public static Result deleteAll() {
User client = SecurityController.getUser();
User.FIND.where().ne("id", client.getId()).findList().forEach(u -> u.delete());
return getAll();
}
@Authentication({User.Role.ADMIN})
public static Result delete(Long id) {
// Check if user exists
User userToDelete = User.FIND.byId(id);
if(userToDelete == null) {
return notFound();
}
// Delete the user
userToDelete.delete();
// Add links to result
ObjectNode root = jsonMapper.createObjectNode();
List<ControllerHelper.Link> links = new ArrayList<>();
links.add(Application.homeLink);
links.add(allUsersLink);
root.put("links", (JsonNode) jsonMapper.valueToTree(links));
return ok(root);
}
@Authentication({User.Role.ADMIN, User.Role.READONLY_ADMIN, User.Role.USER})
public static Result getUserAuthToken(Long id) {
// Check if user has correct privileges
User client = SecurityController.getUser();
if(client.getId() != id) {
return unauthorized();
}
// Return auth token to the client
String authToken = client.getAuthToken();
ObjectNode authTokenJson = Json.newObject();
authTokenJson.put(SecurityController.AUTH_TOKEN, authToken);
return ok(authTokenJson);
}
@Authentication({User.Role.ADMIN, User.Role.USER})
public static Result invalidateAuthToken(Long userId) {
// Check if user has correct privileges
User client = SecurityController.getUser();
if(!User.Role.ADMIN.equals(client.getRole())
&& client.getId() != userId) {
return unauthorized();
}
User user = User.FIND.byId(userId);
if(user == null) {
// Return possible links
ObjectNode root = jsonMapper.createObjectNode();
List<ControllerHelper.Link> links = new ArrayList<>();
links.add(Application.homeLink);
links.add(allUsersLink);
root.put("links", (JsonNode) jsonMapper.valueToTree(links));
return notFound();
}
user.invalidateAuthToken();
user.save();
return ok();
}
private static List<ControllerHelper.Link> getAllLinks(long id) {
List<ControllerHelper.Link> links = new ArrayList<>();
links.add(new ControllerHelper.Link("self", controllers.routes.UserController.get(id).url()));
links.add(new ControllerHelper.Link("getAuthToken", controllers.routes.UserController.getUserAuthToken(id).url()));
links.add(new ControllerHelper.Link("invalidateAuthToken", controllers.routes.UserController.invalidateAuthToken(id).url()));
return links;
}
}
| Dirty hack to get password updated too
| app/controllers/UserController.java | Dirty hack to get password updated too | <ide><path>pp/controllers/UserController.java
<ide> User updatedUser = filledForm.get();
<ide> updatedUser.setId(id);
<ide> Set<String> updatedFields = filledForm.data().keySet();
<add> if (updatedFields.contains("password")) {
<add> updatedFields.remove("password");
<add> updatedFields.add("shaPassword");
<add> }
<ide> Ebean.update(updatedUser, updatedFields);
<ide>
<ide> return ok(JsonHelper.createJsonNode(updatedUser, getAllLinks(id), User.class)); |
|
Java | mit | 5ec8945cb671ea54a7466b442c7ca820825f9938 | 0 | mezz/JustEnoughItems,Adaptivity/JustEnoughItems,mezz/JustEnoughItems,Adaptivity/JustEnoughItems | package mezz.jei.gui.overlay;
import com.google.common.collect.ImmutableList;
import mezz.jei.Internal;
import mezz.jei.api.IIngredientListOverlay;
import mezz.jei.api.IItemListOverlay;
import mezz.jei.api.gui.IAdvancedGuiHandler;
import mezz.jei.api.gui.IGuiProperties;
import mezz.jei.config.Config;
import mezz.jei.config.KeyBindings;
import mezz.jei.config.SessionData;
import mezz.jei.gui.ghost.GhostIngredientDragManager;
import mezz.jei.gui.PageNavigation;
import mezz.jei.gui.ingredients.IIngredientListElement;
import mezz.jei.gui.recipes.RecipesGui;
import mezz.jei.ingredients.IngredientFilter;
import mezz.jei.input.GuiTextFieldFilter;
import mezz.jei.input.IClickedIngredient;
import mezz.jei.input.IMouseHandler;
import mezz.jei.input.IPaged;
import mezz.jei.input.IShowsRecipeFocuses;
import mezz.jei.input.MouseHelper;
import mezz.jei.runtime.JeiRuntime;
import mezz.jei.util.CommandUtil;
import mezz.jei.util.ErrorUtil;
import mezz.jei.util.Log;
import mezz.jei.util.MathUtil;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.settings.GameSettings;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import javax.annotation.Nullable;
import java.awt.Rectangle;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class IngredientListOverlay implements IItemListOverlay, IIngredientListOverlay, IPaged, IMouseHandler, IShowsRecipeFocuses {
private static final int BORDER_PADDING = 2;
private static final int BUTTON_SIZE = 20;
private static final int NAVIGATION_HEIGHT = 20;
private static final int SEARCH_HEIGHT = 16;
/**
* @return true if this can be displayed next to the gui with the given guiProperties
*/
private static boolean hasRoom(IGuiProperties guiProperties) {
Rectangle displayArea = getDisplayArea(guiProperties);
final int availableColumns = displayArea.width / IngredientGrid.INGREDIENT_WIDTH;
return availableColumns >= Config.smallestNumColumns;
}
private static boolean isSearchBarCentered(IGuiProperties guiProperties) {
return Config.isCenterSearchBarEnabled() &&
guiProperties.getGuiTop() + guiProperties.getGuiYSize() + SEARCH_HEIGHT < guiProperties.getScreenHeight();
}
private final IngredientFilter ingredientFilter;
private final NonNullList<ItemStack> highlightedStacks = NonNullList.create();
private final ConfigButton configButton;
private final PageNavigation navigation;
private final IngredientGrid contents;
private final GuiTextFieldFilter searchField;
private final GhostIngredientDragManager ghostIngredientDragManager;
private Set<Rectangle> guiExclusionAreas = Collections.emptySet();
private Rectangle displayArea = new Rectangle();
// properties of the gui we're beside
@Nullable
private IGuiProperties guiProperties;
public IngredientListOverlay(IngredientFilter ingredientFilter) {
this.ingredientFilter = ingredientFilter;
this.contents = new IngredientGridAll(ingredientFilter);
this.searchField = new GuiTextFieldFilter(0, ingredientFilter);
this.navigation = new PageNavigation(this, false);
this.configButton = new ConfigButton(this);
this.ghostIngredientDragManager = new GhostIngredientDragManager(this.contents);
this.setKeyboardFocus(false);
}
public void rebuildItemFilter() {
Log.get().info("Updating ingredient filter...");
long start_time = System.currentTimeMillis();
this.ingredientFilter.modesChanged();
Log.get().info("Updated ingredient filter in {} ms", System.currentTimeMillis() - start_time);
SessionData.setFirstItemIndex(0);
updateLayout();
}
@Override
public String getFilterText() {
return Config.getFilterText();
}
@Override
public ImmutableList<ItemStack> getFilteredStacks() {
List<IIngredientListElement> elements = ingredientFilter.getIngredientList();
ImmutableList.Builder<ItemStack> builder = ImmutableList.builder();
for (IIngredientListElement element : elements) {
Object ingredient = element.getIngredient();
if (ingredient instanceof ItemStack) {
builder.add((ItemStack) ingredient);
}
}
return builder.build();
}
@Override
public void highlightStacks(Collection<ItemStack> stacks) {
highlightedStacks.clear();
highlightedStacks.addAll(stacks);
}
public boolean isEnabled() {
return this.guiProperties != null;
}
public boolean isListDisplayed() {
return Config.isOverlayEnabled() && this.guiProperties != null && hasRoom(this.guiProperties);
}
private static boolean areGuiPropertiesEqual(IGuiProperties guiProperties1, IGuiProperties guiProperties2) {
return guiProperties1.getGuiClass().equals(guiProperties2.getGuiClass()) &&
guiProperties1.getGuiLeft() == guiProperties2.getGuiLeft() &&
guiProperties1.getGuiXSize() == guiProperties2.getGuiXSize() &&
guiProperties1.getScreenWidth() == guiProperties2.getScreenWidth() &&
guiProperties1.getScreenHeight() == guiProperties2.getScreenHeight();
}
private static Rectangle getDisplayArea(IGuiProperties guiProperties) {
final int x = guiProperties.getGuiLeft() + guiProperties.getGuiXSize() + BORDER_PADDING;
final int y = BORDER_PADDING;
final int width = guiProperties.getScreenWidth() - x - (2 * BORDER_PADDING);
final int height = guiProperties.getScreenHeight() - y - (2 * BORDER_PADDING);
return new Rectangle(x, y, width, height);
}
public void updateScreen(@Nullable GuiScreen guiScreen) {
JeiRuntime runtime = Internal.getRuntime();
if (runtime == null) {
return;
}
IGuiProperties guiProperties = runtime.getGuiProperties(guiScreen);
if (guiProperties == null) {
this.guiProperties = null;
setKeyboardFocus(false);
} else if (this.guiProperties == null || !areGuiPropertiesEqual(this.guiProperties, guiProperties)) {
this.guiProperties = guiProperties;
this.displayArea = getDisplayArea(guiProperties);
final boolean searchBarCentered = isSearchBarCentered(guiProperties);
final int searchHeight = searchBarCentered ? 0 : SEARCH_HEIGHT + 4;
Rectangle contentsArea = new Rectangle(displayArea.x, displayArea.y + NAVIGATION_HEIGHT + 2, displayArea.width, displayArea.height - NAVIGATION_HEIGHT - searchHeight);
this.contents.updateBounds(contentsArea, this.guiExclusionAreas);
// update area to match contents size
contentsArea = this.contents.getArea();
displayArea.x = contentsArea.x;
displayArea.width = contentsArea.width;
Rectangle navigationArea = new Rectangle(displayArea.x, displayArea.y, displayArea.width, NAVIGATION_HEIGHT);
this.navigation.updateBounds(navigationArea);
if (searchBarCentered) {
Rectangle searchArea = new Rectangle(guiProperties.getGuiLeft() + 2, guiProperties.getScreenHeight() - 4 - SEARCH_HEIGHT, guiProperties.getGuiXSize() - 3 - BUTTON_SIZE, SEARCH_HEIGHT);
this.searchField.updateBounds(searchArea);
} else {
Rectangle searchArea = new Rectangle(displayArea.x + 2, displayArea.y + displayArea.height - SEARCH_HEIGHT, displayArea.width - 3 - BUTTON_SIZE, SEARCH_HEIGHT);
this.searchField.updateBounds(searchArea);
}
int configButtonX = this.searchField.x + this.searchField.width + 1;
int configButtonY = this.searchField.y - BORDER_PADDING;
this.configButton.updateBounds(new Rectangle(configButtonX, configButtonY, BUTTON_SIZE, BUTTON_SIZE));
updateLayout();
}
}
private void updateLayout() {
this.contents.updateLayout(this.guiExclusionAreas);
int pageNum = this.contents.getPageNum();
int pageCount = this.contents.getPageCount();
this.navigation.updatePageState(pageNum, pageCount);
this.searchField.update();
}
public void drawScreen(Minecraft minecraft, int mouseX, int mouseY, float partialTicks) {
if (this.updateGuiExclusionAreas()) {
updateLayout();
}
GlStateManager.disableLighting();
if (isListDisplayed()) {
this.navigation.draw(minecraft, mouseX, mouseY, partialTicks);
this.searchField.drawTextBox();
this.contents.draw(minecraft, mouseX, mouseY);
}
this.configButton.draw(minecraft, mouseX, mouseY, partialTicks);
}
public boolean updateGuiExclusionAreas() {
final Set<Rectangle> guiAreas = getGuiAreas();
if (!guiAreas.equals(this.guiExclusionAreas)) {
this.guiExclusionAreas = guiAreas;
return true;
}
return false;
}
public void drawTooltips(Minecraft minecraft, int mouseX, int mouseY) {
if (this.guiProperties != null) {
boolean hasRoom = hasRoom(this.guiProperties);
this.configButton.drawTooltips(minecraft, mouseX, mouseY, hasRoom);
this.ghostIngredientDragManager.drawTooltips(minecraft, mouseX, mouseY);
if (Config.isOverlayEnabled() && hasRoom) {
this.contents.drawTooltips(minecraft, mouseX, mouseY);
}
}
}
public void drawOnForeground(Minecraft minecraft, int mouseX, int mouseY) {
this.ghostIngredientDragManager.drawOnForeground(minecraft, mouseX, mouseY);
}
public void handleTick() {
this.searchField.updateCursorCounter();
}
@Override
public boolean nextPage() {
if (this.contents.nextPage()) {
updateLayout();
return true;
}
return false;
}
@Override
public boolean previousPage() {
if (this.contents.previousPage()) {
updateLayout();
return true;
}
return false;
}
@Override
public boolean hasNext() {
return this.contents.hasNext();
}
@Override
public boolean hasPrevious() {
return this.contents.hasPrevious();
}
@Override
public boolean isMouseOver(int mouseX, int mouseY) {
if (displayArea.contains(mouseX, mouseY) || searchField.isMouseOver(mouseX, mouseY) || configButton.isMouseOver(mouseX, mouseY)) {
return !MathUtil.contains(guiExclusionAreas, mouseX, mouseY);
}
return false;
}
@Override
@Nullable
public IClickedIngredient<?> getIngredientUnderMouse(int mouseX, int mouseY) {
if (isListDisplayed()) {
IClickedIngredient<?> clicked = this.contents.getIngredientUnderMouse(mouseX, mouseY);
if (clicked != null) {
clicked.setOnClickHandler(() -> setKeyboardFocus(false));
return clicked;
}
}
return null;
}
@Override
public boolean canSetFocusWithMouse() {
return this.isListDisplayed() && this.contents.canSetFocusWithMouse();
}
@Override
public boolean handleMouseClicked(int mouseX, int mouseY, int mouseButton) {
if (this.ghostIngredientDragManager.handleMouseClicked(mouseX, mouseY)) {
return true;
} // if the ghost ingredient drag failed, fall through to let the click be handled by something else
if (this.configButton.handleMouseClick(Minecraft.getMinecraft(), mouseX, mouseY)) {
return true;
}
if (isListDisplayed()) {
if (!isMouseOver(mouseX, mouseY)) {
setKeyboardFocus(false);
return false;
}
if (this.contents.handleMouseClicked(mouseX, mouseY)) {
setKeyboardFocus(false);
return true;
}
if (this.navigation.handleMouseClickedButtons(mouseX, mouseY)) {
setKeyboardFocus(false);
return true;
}
boolean searchClicked = this.searchField.isMouseOver(mouseX, mouseY);
setKeyboardFocus(searchClicked);
if (searchClicked) {
final boolean updated = this.searchField.handleMouseClicked(mouseX, mouseY, mouseButton);
if (updated) {
updateLayout();
}
return true;
}
Minecraft minecraft = Minecraft.getMinecraft();
GuiScreen currentScreen = minecraft.currentScreen;
if (currentScreen != null && !(currentScreen instanceof RecipesGui) &&
(mouseButton == 0 || mouseButton == 1 || minecraft.gameSettings.keyBindPickBlock.isActiveAndMatches(mouseButton - 100))) {
IClickedIngredient<?> clicked = getIngredientUnderMouse(mouseX, mouseY);
if (clicked != null) {
if (Config.isCheatItemsEnabled()) {
ItemStack itemStack = clicked.getCheatItemStack();
if (!itemStack.isEmpty()) {
CommandUtil.giveStack(itemStack, mouseButton);
}
clicked.onClickHandled();
return true;
}
ItemStack mouseItem = minecraft.player.inventory.getItemStack();
if (mouseItem.isEmpty() && this.ghostIngredientDragManager.handleClickGhostIngredient(currentScreen, clicked)) {
return true;
}
}
}
}
return false;
}
@Override
public boolean handleMouseScrolled(int mouseX, int mouseY, int scrollDelta) {
if (isListDisplayed() && isMouseOver(mouseX, mouseY)) {
if (scrollDelta < 0) {
nextPage();
return true;
} else if (scrollDelta > 0) {
previousPage();
return true;
}
}
return false;
}
@Override
public boolean hasKeyboardFocus() {
return this.searchField.isFocused();
}
public void setKeyboardFocus(boolean keyboardFocus) {
this.searchField.setFocused(keyboardFocus);
}
public boolean onKeyPressed(char typedChar, int keyCode) {
if (!isListDisplayed()) {
return false;
}
if (hasKeyboardFocus() &&
searchField.textboxKeyTyped(typedChar, keyCode)) {
boolean changed = Config.setFilterText(searchField.getText());
if (changed) {
SessionData.setFirstItemIndex(0);
updateLayout();
}
return true;
} else if (KeyBindings.nextPage.isActiveAndMatches(keyCode)) {
nextPage();
return true;
} else if (KeyBindings.previousPage.isActiveAndMatches(keyCode)) {
previousPage();
return true;
}
return checkHotbarKeys(keyCode);
}
/**
* Modeled after {@link GuiContainer#checkHotbarKeys(int)}
* Sets the stack in a hotbar slot to the one that's hovered over.
*/
protected boolean checkHotbarKeys(int keyCode) {
GuiScreen guiScreen = Minecraft.getMinecraft().currentScreen;
if (Config.isCheatItemsEnabled() && guiScreen != null && !(guiScreen instanceof RecipesGui)) {
final int mouseX = MouseHelper.getX();
final int mouseY = MouseHelper.getY();
if (isMouseOver(mouseX, mouseY)) {
GameSettings gameSettings = Minecraft.getMinecraft().gameSettings;
for (int hotbarSlot = 0; hotbarSlot < 9; ++hotbarSlot) {
if (gameSettings.keyBindsHotbar[hotbarSlot].isActiveAndMatches(keyCode)) {
IClickedIngredient<?> ingredientUnderMouse = getIngredientUnderMouse(mouseX, mouseY);
if (ingredientUnderMouse != null) {
ItemStack itemStack = ingredientUnderMouse.getCheatItemStack();
if (!itemStack.isEmpty()) {
CommandUtil.setHotbarStack(itemStack, hotbarSlot);
}
ingredientUnderMouse.onClickHandled();
}
return true;
}
}
}
}
return false;
}
@Override
@Nullable
public ItemStack getStackUnderMouse() {
Object ingredient = getIngredientUnderMouse();
if (ingredient instanceof ItemStack) {
return (ItemStack) ingredient;
}
return null;
}
@Nullable
@Override
public Object getIngredientUnderMouse() {
IIngredientListElement elementUnderMouse = this.contents.getElementUnderMouse();
if (elementUnderMouse != null) {
return elementUnderMouse.getIngredient();
}
return null;
}
@Override
public void setFilterText(String filterText) {
ErrorUtil.checkNotNull(filterText, "filterText");
if (Config.setFilterText(filterText)) {
onSetFilterText(filterText);
}
}
public void onSetFilterText(String filterText) {
this.searchField.setText(filterText);
SessionData.setFirstItemIndex(0);
updateLayout();
}
@Override
public ImmutableList<ItemStack> getVisibleStacks() {
ImmutableList.Builder<ItemStack> visibleStacks = ImmutableList.builder();
List<IIngredientListElement> visibleElements = this.contents.getVisibleElements();
for (IIngredientListElement element : visibleElements) {
Object ingredient = element.getIngredient();
if (ingredient instanceof ItemStack) {
visibleStacks.add((ItemStack) ingredient);
}
}
return visibleStacks.build();
}
@Override
public ImmutableList<Object> getVisibleIngredients() {
ImmutableList.Builder<Object> visibleIngredients = ImmutableList.builder();
List<IIngredientListElement> visibleElements = this.contents.getVisibleElements();
for (IIngredientListElement element : visibleElements) {
Object ingredient = element.getIngredient();
visibleIngredients.add(ingredient);
}
return visibleIngredients.build();
}
private static Set<Rectangle> getGuiAreas() {
final GuiScreen currentScreen = Minecraft.getMinecraft().currentScreen;
if (currentScreen instanceof GuiContainer) {
final GuiContainer guiContainer = (GuiContainer) currentScreen;
final JeiRuntime jeiRuntime = Internal.getRuntime();
if (jeiRuntime != null) {
final Set<Rectangle> allGuiExtraAreas = new HashSet<>();
final List<IAdvancedGuiHandler<GuiContainer>> activeAdvancedGuiHandlers = jeiRuntime.getActiveAdvancedGuiHandlers(guiContainer);
for (IAdvancedGuiHandler<GuiContainer> advancedGuiHandler : activeAdvancedGuiHandlers) {
final List<Rectangle> guiExtraAreas = advancedGuiHandler.getGuiExtraAreas(guiContainer);
if (guiExtraAreas != null) {
allGuiExtraAreas.addAll(guiExtraAreas);
}
}
return allGuiExtraAreas;
}
}
return Collections.emptySet();
}
}
| src/main/java/mezz/jei/gui/overlay/IngredientListOverlay.java | package mezz.jei.gui.overlay;
import com.google.common.collect.ImmutableList;
import mezz.jei.Internal;
import mezz.jei.api.IIngredientListOverlay;
import mezz.jei.api.IItemListOverlay;
import mezz.jei.api.gui.IAdvancedGuiHandler;
import mezz.jei.api.gui.IGuiProperties;
import mezz.jei.config.Config;
import mezz.jei.config.KeyBindings;
import mezz.jei.config.SessionData;
import mezz.jei.gui.ghost.GhostIngredientDragManager;
import mezz.jei.gui.PageNavigation;
import mezz.jei.gui.ingredients.IIngredientListElement;
import mezz.jei.gui.recipes.RecipesGui;
import mezz.jei.ingredients.IngredientFilter;
import mezz.jei.input.GuiTextFieldFilter;
import mezz.jei.input.IClickedIngredient;
import mezz.jei.input.IMouseHandler;
import mezz.jei.input.IPaged;
import mezz.jei.input.IShowsRecipeFocuses;
import mezz.jei.input.MouseHelper;
import mezz.jei.runtime.JeiRuntime;
import mezz.jei.util.CommandUtil;
import mezz.jei.util.ErrorUtil;
import mezz.jei.util.Log;
import mezz.jei.util.MathUtil;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.settings.GameSettings;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import javax.annotation.Nullable;
import java.awt.Rectangle;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class IngredientListOverlay implements IItemListOverlay, IIngredientListOverlay, IPaged, IMouseHandler, IShowsRecipeFocuses {
private static final int BORDER_PADDING = 2;
private static final int BUTTON_SIZE = 20;
private static final int NAVIGATION_HEIGHT = 20;
private static final int SEARCH_HEIGHT = 16;
/**
* @return true if this can be displayed next to the gui with the given guiProperties
*/
private static boolean hasRoom(IGuiProperties guiProperties) {
Rectangle displayArea = getDisplayArea(guiProperties);
final int availableColumns = displayArea.width / IngredientGrid.INGREDIENT_WIDTH;
return availableColumns >= Config.smallestNumColumns;
}
private static boolean isSearchBarCentered(IGuiProperties guiProperties) {
return Config.isCenterSearchBarEnabled() &&
guiProperties.getGuiTop() + guiProperties.getGuiYSize() + SEARCH_HEIGHT < guiProperties.getScreenHeight();
}
private final IngredientFilter ingredientFilter;
private final NonNullList<ItemStack> highlightedStacks = NonNullList.create();
private final ConfigButton configButton;
private final PageNavigation navigation;
private final IngredientGrid contents;
private final GuiTextFieldFilter searchField;
private final GhostIngredientDragManager ghostIngredientDragManager;
private Set<Rectangle> guiExclusionAreas = Collections.emptySet();
private Rectangle displayArea = new Rectangle();
// properties of the gui we're beside
@Nullable
private IGuiProperties guiProperties;
public IngredientListOverlay(IngredientFilter ingredientFilter) {
this.ingredientFilter = ingredientFilter;
this.contents = new IngredientGridAll(ingredientFilter);
this.searchField = new GuiTextFieldFilter(0, ingredientFilter);
this.navigation = new PageNavigation(this, false);
this.configButton = new ConfigButton(this);
this.ghostIngredientDragManager = new GhostIngredientDragManager(this.contents);
this.setKeyboardFocus(false);
}
public void rebuildItemFilter() {
Log.get().info("Updating ingredient filter...");
long start_time = System.currentTimeMillis();
this.ingredientFilter.modesChanged();
Log.get().info("Updated ingredient filter in {} ms", System.currentTimeMillis() - start_time);
SessionData.setFirstItemIndex(0);
updateLayout();
}
@Override
public String getFilterText() {
return Config.getFilterText();
}
@Override
public ImmutableList<ItemStack> getFilteredStacks() {
List<IIngredientListElement> elements = ingredientFilter.getIngredientList();
ImmutableList.Builder<ItemStack> builder = ImmutableList.builder();
for (IIngredientListElement element : elements) {
Object ingredient = element.getIngredient();
if (ingredient instanceof ItemStack) {
builder.add((ItemStack) ingredient);
}
}
return builder.build();
}
@Override
public void highlightStacks(Collection<ItemStack> stacks) {
highlightedStacks.clear();
highlightedStacks.addAll(stacks);
}
public boolean isEnabled() {
return this.guiProperties != null;
}
public boolean isListDisplayed() {
return Config.isOverlayEnabled() && this.guiProperties != null && hasRoom(this.guiProperties);
}
private static boolean areGuiPropertiesEqual(IGuiProperties guiProperties1, IGuiProperties guiProperties2) {
return guiProperties1.getGuiClass().equals(guiProperties2.getGuiClass()) &&
guiProperties1.getGuiLeft() == guiProperties2.getGuiLeft() &&
guiProperties1.getGuiXSize() == guiProperties2.getGuiXSize() &&
guiProperties1.getScreenWidth() == guiProperties2.getScreenWidth() &&
guiProperties1.getScreenHeight() == guiProperties2.getScreenHeight();
}
private static Rectangle getDisplayArea(IGuiProperties guiProperties) {
final int x = guiProperties.getGuiLeft() + guiProperties.getGuiXSize() + BORDER_PADDING;
final int y = BORDER_PADDING;
final int width = guiProperties.getScreenWidth() - x - (2 * BORDER_PADDING);
final int height = guiProperties.getScreenHeight() - y - (2 * BORDER_PADDING);
return new Rectangle(x, y, width, height);
}
public void updateScreen(@Nullable GuiScreen guiScreen) {
JeiRuntime runtime = Internal.getRuntime();
if (runtime == null) {
return;
}
IGuiProperties guiProperties = runtime.getGuiProperties(guiScreen);
if (guiProperties == null) {
this.guiProperties = null;
setKeyboardFocus(false);
} else if (this.guiProperties == null || !areGuiPropertiesEqual(this.guiProperties, guiProperties)) {
this.guiProperties = guiProperties;
this.displayArea = getDisplayArea(guiProperties);
final boolean searchBarCentered = isSearchBarCentered(guiProperties);
final int searchHeight = searchBarCentered ? 0 : SEARCH_HEIGHT + 4;
Rectangle contentsArea = new Rectangle(displayArea.x, displayArea.y + NAVIGATION_HEIGHT + 2, displayArea.width, displayArea.height - NAVIGATION_HEIGHT - searchHeight);
this.contents.updateBounds(contentsArea, this.guiExclusionAreas);
// update area to match contents size
contentsArea = this.contents.getArea();
displayArea.x = contentsArea.x;
displayArea.width = contentsArea.width;
Rectangle navigationArea = new Rectangle(displayArea.x, displayArea.y, displayArea.width, NAVIGATION_HEIGHT);
this.navigation.updateBounds(navigationArea);
if (searchBarCentered) {
Rectangle searchArea = new Rectangle(guiProperties.getGuiLeft() + 2, guiProperties.getScreenHeight() - 4 - SEARCH_HEIGHT, guiProperties.getGuiXSize() - 3 - BUTTON_SIZE, SEARCH_HEIGHT);
this.searchField.updateBounds(searchArea);
} else {
Rectangle searchArea = new Rectangle(displayArea.x + 2, displayArea.y + displayArea.height - SEARCH_HEIGHT, displayArea.width - 3 - BUTTON_SIZE, SEARCH_HEIGHT);
this.searchField.updateBounds(searchArea);
}
int configButtonX = this.searchField.x + this.searchField.width + 1;
int configButtonY = this.searchField.y - BORDER_PADDING;
this.configButton.updateBounds(new Rectangle(configButtonX, configButtonY, BUTTON_SIZE, BUTTON_SIZE));
updateLayout();
}
}
private void updateLayout() {
this.contents.updateLayout(this.guiExclusionAreas);
int pageNum = this.contents.getPageNum();
int pageCount = this.contents.getPageCount();
this.navigation.updatePageState(pageNum, pageCount);
this.searchField.update();
}
public void drawScreen(Minecraft minecraft, int mouseX, int mouseY, float partialTicks) {
if (this.updateGuiExclusionAreas()) {
updateLayout();
}
GlStateManager.disableLighting();
if (isListDisplayed()) {
this.navigation.draw(minecraft, mouseX, mouseY, partialTicks);
this.searchField.drawTextBox();
this.contents.draw(minecraft, mouseX, mouseY);
}
this.configButton.draw(minecraft, mouseX, mouseY, partialTicks);
}
public boolean updateGuiExclusionAreas() {
final Set<Rectangle> guiAreas = getGuiAreas();
if (!guiAreas.equals(this.guiExclusionAreas)) {
this.guiExclusionAreas = guiAreas;
return true;
}
return false;
}
public void drawTooltips(Minecraft minecraft, int mouseX, int mouseY) {
if (this.guiProperties != null) {
boolean hasRoom = hasRoom(this.guiProperties);
this.configButton.drawTooltips(minecraft, mouseX, mouseY, hasRoom);
this.ghostIngredientDragManager.drawTooltips(minecraft, mouseX, mouseY);
if (Config.isOverlayEnabled() && hasRoom) {
this.contents.drawTooltips(minecraft, mouseX, mouseY);
}
}
}
public void drawOnForeground(Minecraft minecraft, int mouseX, int mouseY) {
this.ghostIngredientDragManager.drawOnForeground(minecraft, mouseX, mouseY);
}
public void handleTick() {
this.searchField.updateCursorCounter();
}
@Override
public boolean nextPage() {
if (this.contents.nextPage()) {
updateLayout();
return true;
}
return false;
}
@Override
public boolean previousPage() {
if (this.contents.previousPage()) {
updateLayout();
return true;
}
return false;
}
@Override
public boolean hasNext() {
return this.contents.hasNext();
}
@Override
public boolean hasPrevious() {
return this.contents.hasPrevious();
}
@Override
public boolean isMouseOver(int mouseX, int mouseY) {
if (displayArea.contains(mouseX, mouseY) || searchField.isMouseOver(mouseX, mouseY) || configButton.isMouseOver(mouseX, mouseY)) {
return !MathUtil.contains(guiExclusionAreas, mouseX, mouseY);
}
return false;
}
@Override
@Nullable
public IClickedIngredient<?> getIngredientUnderMouse(int mouseX, int mouseY) {
if (isListDisplayed()) {
IClickedIngredient<?> clicked = this.contents.getIngredientUnderMouse(mouseX, mouseY);
if (clicked != null) {
clicked.setOnClickHandler(() -> setKeyboardFocus(false));
return clicked;
}
}
return null;
}
@Override
public boolean canSetFocusWithMouse() {
return this.isListDisplayed() && this.contents.canSetFocusWithMouse();
}
@Override
public boolean handleMouseClicked(int mouseX, int mouseY, int mouseButton) {
if (this.ghostIngredientDragManager.handleMouseClicked(mouseX, mouseY)) {
return true;
} // if the ghost ingredient drag failed, fall through to let the click be handled by something else
if (this.configButton.handleMouseClick(Minecraft.getMinecraft(), mouseX, mouseY)) {
return true;
}
if (isListDisplayed()) {
if (!isMouseOver(mouseX, mouseY)) {
setKeyboardFocus(false);
return false;
}
if (this.contents.handleMouseClicked(mouseX, mouseY)) {
setKeyboardFocus(false);
return true;
}
if (this.navigation.handleMouseClickedButtons(mouseX, mouseY)) {
setKeyboardFocus(false);
return true;
}
boolean searchClicked = this.searchField.isMouseOver(mouseX, mouseY);
setKeyboardFocus(searchClicked);
if (searchClicked) {
final boolean updated = this.searchField.handleMouseClicked(mouseX, mouseY, mouseButton);
if (updated) {
updateLayout();
}
return true;
}
Minecraft minecraft = Minecraft.getMinecraft();
GuiScreen currentScreen = minecraft.currentScreen;
if (currentScreen != null && !(currentScreen instanceof RecipesGui) &&
(mouseButton == 0 || mouseButton == 1 || minecraft.gameSettings.keyBindPickBlock.isActiveAndMatches(mouseButton - 100))) {
IClickedIngredient<?> clicked = getIngredientUnderMouse(mouseX, mouseY);
if (clicked != null) {
if (Config.isCheatItemsEnabled()) {
ItemStack itemStack = clicked.getCheatItemStack();
if (!itemStack.isEmpty()) {
CommandUtil.giveStack(itemStack, mouseButton);
}
clicked.onClickHandled();
return true;
}
if (this.ghostIngredientDragManager.handleClickGhostIngredient(currentScreen, clicked)) {
return true;
}
}
}
}
return false;
}
@Override
public boolean handleMouseScrolled(int mouseX, int mouseY, int scrollDelta) {
if (isListDisplayed() && isMouseOver(mouseX, mouseY)) {
if (scrollDelta < 0) {
nextPage();
return true;
} else if (scrollDelta > 0) {
previousPage();
return true;
}
}
return false;
}
@Override
public boolean hasKeyboardFocus() {
return this.searchField.isFocused();
}
public void setKeyboardFocus(boolean keyboardFocus) {
this.searchField.setFocused(keyboardFocus);
}
public boolean onKeyPressed(char typedChar, int keyCode) {
if (!isListDisplayed()) {
return false;
}
if (hasKeyboardFocus() &&
searchField.textboxKeyTyped(typedChar, keyCode)) {
boolean changed = Config.setFilterText(searchField.getText());
if (changed) {
SessionData.setFirstItemIndex(0);
updateLayout();
}
return true;
} else if (KeyBindings.nextPage.isActiveAndMatches(keyCode)) {
nextPage();
return true;
} else if (KeyBindings.previousPage.isActiveAndMatches(keyCode)) {
previousPage();
return true;
}
return checkHotbarKeys(keyCode);
}
/**
* Modeled after {@link GuiContainer#checkHotbarKeys(int)}
* Sets the stack in a hotbar slot to the one that's hovered over.
*/
protected boolean checkHotbarKeys(int keyCode) {
GuiScreen guiScreen = Minecraft.getMinecraft().currentScreen;
if (Config.isCheatItemsEnabled() && guiScreen != null && !(guiScreen instanceof RecipesGui)) {
final int mouseX = MouseHelper.getX();
final int mouseY = MouseHelper.getY();
if (isMouseOver(mouseX, mouseY)) {
GameSettings gameSettings = Minecraft.getMinecraft().gameSettings;
for (int hotbarSlot = 0; hotbarSlot < 9; ++hotbarSlot) {
if (gameSettings.keyBindsHotbar[hotbarSlot].isActiveAndMatches(keyCode)) {
IClickedIngredient<?> ingredientUnderMouse = getIngredientUnderMouse(mouseX, mouseY);
if (ingredientUnderMouse != null) {
ItemStack itemStack = ingredientUnderMouse.getCheatItemStack();
if (!itemStack.isEmpty()) {
CommandUtil.setHotbarStack(itemStack, hotbarSlot);
}
ingredientUnderMouse.onClickHandled();
}
return true;
}
}
}
}
return false;
}
@Override
@Nullable
public ItemStack getStackUnderMouse() {
Object ingredient = getIngredientUnderMouse();
if (ingredient instanceof ItemStack) {
return (ItemStack) ingredient;
}
return null;
}
@Nullable
@Override
public Object getIngredientUnderMouse() {
IIngredientListElement elementUnderMouse = this.contents.getElementUnderMouse();
if (elementUnderMouse != null) {
return elementUnderMouse.getIngredient();
}
return null;
}
@Override
public void setFilterText(String filterText) {
ErrorUtil.checkNotNull(filterText, "filterText");
if (Config.setFilterText(filterText)) {
onSetFilterText(filterText);
}
}
public void onSetFilterText(String filterText) {
this.searchField.setText(filterText);
SessionData.setFirstItemIndex(0);
updateLayout();
}
@Override
public ImmutableList<ItemStack> getVisibleStacks() {
ImmutableList.Builder<ItemStack> visibleStacks = ImmutableList.builder();
List<IIngredientListElement> visibleElements = this.contents.getVisibleElements();
for (IIngredientListElement element : visibleElements) {
Object ingredient = element.getIngredient();
if (ingredient instanceof ItemStack) {
visibleStacks.add((ItemStack) ingredient);
}
}
return visibleStacks.build();
}
@Override
public ImmutableList<Object> getVisibleIngredients() {
ImmutableList.Builder<Object> visibleIngredients = ImmutableList.builder();
List<IIngredientListElement> visibleElements = this.contents.getVisibleElements();
for (IIngredientListElement element : visibleElements) {
Object ingredient = element.getIngredient();
visibleIngredients.add(ingredient);
}
return visibleIngredients.build();
}
private static Set<Rectangle> getGuiAreas() {
final GuiScreen currentScreen = Minecraft.getMinecraft().currentScreen;
if (currentScreen instanceof GuiContainer) {
final GuiContainer guiContainer = (GuiContainer) currentScreen;
final JeiRuntime jeiRuntime = Internal.getRuntime();
if (jeiRuntime != null) {
final Set<Rectangle> allGuiExtraAreas = new HashSet<>();
final List<IAdvancedGuiHandler<GuiContainer>> activeAdvancedGuiHandlers = jeiRuntime.getActiveAdvancedGuiHandlers(guiContainer);
for (IAdvancedGuiHandler<GuiContainer> advancedGuiHandler : activeAdvancedGuiHandlers) {
final List<Rectangle> guiExtraAreas = advancedGuiHandler.getGuiExtraAreas(guiContainer);
if (guiExtraAreas != null) {
allGuiExtraAreas.addAll(guiExtraAreas);
}
}
return allGuiExtraAreas;
}
}
return Collections.emptySet();
}
}
| Fix #1186 Ghost items from JEI overlap items held on the player cursor
| src/main/java/mezz/jei/gui/overlay/IngredientListOverlay.java | Fix #1186 Ghost items from JEI overlap items held on the player cursor | <ide><path>rc/main/java/mezz/jei/gui/overlay/IngredientListOverlay.java
<ide> clicked.onClickHandled();
<ide> return true;
<ide> }
<del> if (this.ghostIngredientDragManager.handleClickGhostIngredient(currentScreen, clicked)) {
<add> ItemStack mouseItem = minecraft.player.inventory.getItemStack();
<add> if (mouseItem.isEmpty() && this.ghostIngredientDragManager.handleClickGhostIngredient(currentScreen, clicked)) {
<ide> return true;
<ide> }
<ide> } |
|
Java | apache-2.0 | 75396a71c9ead0c64f015e1d5844fd30ceb38fca | 0 | OpenTOSCA/container,OpenTOSCA/container | package org.opentosca.planbuilder.type.plugin.mosquittoconnectsto;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.io.FileUtils;
import org.eclipse.core.runtime.FileLocator;
import org.opentosca.planbuilder.model.tosca.AbstractNodeTemplate;
import org.opentosca.planbuilder.model.tosca.AbstractRelationshipTemplate;
import org.opentosca.planbuilder.plugins.commons.Interfaces;
import org.opentosca.planbuilder.plugins.commons.Properties;
import org.opentosca.planbuilder.plugins.context.TemplatePlanContext;
import org.opentosca.planbuilder.plugins.context.TemplatePlanContext.Variable;
import org.opentosca.planbuilder.provphase.plugin.invoker.Plugin;
import org.opentosca.planbuilder.utils.Utils;
import org.osgi.framework.FrameworkUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* Copyright 2016 IAAS University of Stuttgart <br>
* <br>
*
* @author Kalman Kepes - [email protected]
*
*/
public class Handler {
private Plugin invokerPlugin = new Plugin();
private final static Logger LOG = LoggerFactory.getLogger(Handler.class);
private DocumentBuilderFactory docFactory;
private DocumentBuilder docBuilder;
/**
* Constructor
*
* @throws ParserConfigurationException
* is thrown when initializing the DOM Parsers fails
*/
public Handler() throws ParserConfigurationException {
this.docFactory = DocumentBuilderFactory.newInstance();
this.docFactory.setNamespaceAware(true);
this.docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
}
public boolean handle(TemplatePlanContext templateContext) {
AbstractRelationshipTemplate relationTemplate = templateContext.getRelationshipTemplate();
// fetch topic
Variable topicName = templateContext.getPropertyVariable(relationTemplate.getTarget(), "Name");
/* fetch ip of mosquitto */
Variable mosquittoVmIp = null;
// find infrastructure nodes of mosquitto
List<AbstractNodeTemplate> infrastructureNodes = new ArrayList<AbstractNodeTemplate>();
Utils.getInfrastructureNodes(relationTemplate.getTarget(), infrastructureNodes);
for (AbstractNodeTemplate infraNode : infrastructureNodes) {
// fetch mosquitto ip
if (templateContext.getPropertyVariable(infraNode,
Properties.OPENTOSCA_DECLARATIVE_PROPERTYNAME_VMIP) != null) {
mosquittoVmIp = templateContext.getPropertyVariable(infraNode,
Properties.OPENTOSCA_DECLARATIVE_PROPERTYNAME_VMIP);
}
}
/* fetch user, key, ip and ubuntuTemplateId of client stack */
Variable clientVmIp = null;
Variable clientVmUser = null;
Variable clientVmPass = null;
String ubuntuTemplateId = null;
infrastructureNodes = new ArrayList<AbstractNodeTemplate>();
Utils.getInfrastructureNodes(relationTemplate.getSource(), infrastructureNodes);
for (AbstractNodeTemplate infraNode : infrastructureNodes) {
if (templateContext.getPropertyVariable(infraNode,
Properties.OPENTOSCA_DECLARATIVE_PROPERTYNAME_VMIP) != null) {
clientVmIp = templateContext.getPropertyVariable(infraNode,
Properties.OPENTOSCA_DECLARATIVE_PROPERTYNAME_VMIP);
}
if (templateContext.getPropertyVariable(infraNode,
Properties.OPENTOSCA_DECLARATIVE_PROPERTYNAME_VMLOGINNAME) != null) {
ubuntuTemplateId = infraNode.getId();
clientVmUser = templateContext.getPropertyVariable(infraNode,
Properties.OPENTOSCA_DECLARATIVE_PROPERTYNAME_VMLOGINNAME);
}
if (templateContext.getPropertyVariable(infraNode,
Properties.OPENTOSCA_DECLARATIVE_PROPERTYNAME_VMLOGINPASSWORD) != null) {
ubuntuTemplateId = infraNode.getId();
clientVmPass = templateContext.getPropertyVariable(infraNode,
Properties.OPENTOSCA_DECLARATIVE_PROPERTYNAME_VMLOGINPASSWORD);
}
}
/* create skript */
// the script itself
String bashCommand = "echo \"topicName = hostName\" > $(find ~ -maxdepth 1 -path \"*.csar\")/mosquitto_connections.txt;";
// add it as a var to the plan
Variable bashCommandVariable = templateContext.createGlobalStringVariable("addMosquittoConnection",
bashCommand);
// create bpel query which replaces topicName and hostName with real
// values
String xpathQuery = "replace(replace($" + bashCommandVariable.getName() + ",'topicName',$" + topicName.getName()
+ "),'hostName',$" + mosquittoVmIp.getName() + ")";
// create bpel assign with created query
try {
// create assign and append
Node assignNode = this.loadAssignXpathQueryToStringVarFragmentAsNode(
"assignValuesToAddConnection" + System.currentTimeMillis(), xpathQuery,
bashCommandVariable.getName());
assignNode = templateContext.importNode(assignNode);
templateContext.getProvisioningPhaseElement().appendChild(assignNode);
} catch (IOException e) {
LOG.error("Couldn't load fragment from file", e);
return false;
} catch (SAXException e) {
LOG.error("Couldn't parse fragment to DOM", e);
return false;
}
/* add logic to execute script on client machine */
Map<String, Variable> runScriptRequestInputParams = new HashMap<String, Variable>();
runScriptRequestInputParams.put("IP", clientVmIp);
// these two are requested from the input message if they are not set
if (!Utils.isVariableValueEmpty(clientVmUser, templateContext)) {
runScriptRequestInputParams.put("User", clientVmUser);
} else {
runScriptRequestInputParams.put("User", null);
}
if (!Utils.isVariableValueEmpty(clientVmPass, templateContext)) {
runScriptRequestInputParams.put("Password", clientVmPass);
} else {
runScriptRequestInputParams.put("Password", null);
}
runScriptRequestInputParams.put("Script", bashCommandVariable);
this.invokerPlugin.handle(templateContext, ubuntuTemplateId, true, "runScript",
Interfaces.OPENTOSCA_DECLARATIVE_INTERFACE_OPERATINGSYSTEM, "planCallbackAddress_invoker",
runScriptRequestInputParams, new HashMap<String, Variable>(), false);
return true;
}
/**
* Loads a BPEL Assign fragment which queries the csarEntrypath from the
* input message into String variable.
*
* @param assignName
* the name of the BPEL assign
* @param xpath2Query
* the csarEntryPoint XPath query
* @param stringVarName
* the variable to load the queries results into
* @return a String containing a BPEL Assign element
* @throws IOException
* is thrown when reading the BPEL fragment form the resources
* fails
*/
public String loadAssignXpathQueryToStringVarFragmentAsString(String assignName, String xpath2Query,
String stringVarName) throws IOException {
// <!-- {AssignName},{xpath2query}, {stringVarName} -->
URL url = FrameworkUtil.getBundle(this.getClass()).getBundleContext().getBundle()
.getResource("assignStringVarWithXpath2Query.xml");
File bpelFragmentFile = new File(FileLocator.toFileURL(url).getPath());
String template = FileUtils.readFileToString(bpelFragmentFile);
template = template.replace("{AssignName}", assignName);
template = template.replace("{xpath2query}", xpath2Query);
template = template.replace("{stringVarName}", stringVarName);
return template;
}
/**
* Loads a BPEL Assign fragment which queries the csarEntrypath from the
* input message into String variable.
*
* @param assignName
* the name of the BPEL assign
* @param csarEntryXpathQuery
* the csarEntryPoint XPath query
* @param stringVarName
* the variable to load the queries results into
* @return a DOM Node representing a BPEL assign element
* @throws IOException
* is thrown when loading internal bpel fragments fails
* @throws SAXException
* is thrown when parsing internal format into DOM fails
*/
public Node loadAssignXpathQueryToStringVarFragmentAsNode(String assignName, String xpath2Query,
String stringVarName) throws IOException, SAXException {
String templateString = this.loadAssignXpathQueryToStringVarFragmentAsString(assignName, xpath2Query,
stringVarName);
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(templateString));
Document doc = this.docBuilder.parse(is);
return doc.getFirstChild();
}
}
| org.opentosca.planbuilder.type.plugin.mosquittoconnectsto/src/org/opentosca/planbuilder/type/plugin/mosquittoconnectsto/Handler.java | package org.opentosca.planbuilder.type.plugin.mosquittoconnectsto;
import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.io.FileUtils;
import org.eclipse.core.runtime.FileLocator;
import org.opentosca.planbuilder.model.tosca.AbstractNodeTemplate;
import org.opentosca.planbuilder.model.tosca.AbstractRelationshipTemplate;
import org.opentosca.planbuilder.plugins.commons.Interfaces;
import org.opentosca.planbuilder.plugins.commons.Properties;
import org.opentosca.planbuilder.plugins.context.TemplatePlanContext;
import org.opentosca.planbuilder.plugins.context.TemplatePlanContext.Variable;
import org.opentosca.planbuilder.provphase.plugin.invoker.Plugin;
import org.opentosca.planbuilder.utils.Utils;
import org.osgi.framework.FrameworkUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
* Copyright 2016 IAAS University of Stuttgart <br>
* <br>
*
* @author Kalman Kepes - [email protected]
*
*/
public class Handler {
private Plugin invokerPlugin = new Plugin();
private final static Logger LOG = LoggerFactory.getLogger(Handler.class);
private DocumentBuilderFactory docFactory;
private DocumentBuilder docBuilder;
/**
* Constructor
*
* @throws ParserConfigurationException
* is thrown when initializing the DOM Parsers fails
*/
public Handler() throws ParserConfigurationException {
this.docFactory = DocumentBuilderFactory.newInstance();
this.docFactory.setNamespaceAware(true);
this.docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
}
public boolean handle(TemplatePlanContext templateContext) {
AbstractRelationshipTemplate relationTemplate = templateContext.getRelationshipTemplate();
// fetch topic
Variable topicName = templateContext.getPropertyVariable(relationTemplate.getTarget(), "Name");
/* fetch ip of mosquitto */
Variable mosquittoVmIp = null;
// find infrastructure nodes of mosquitto
List<AbstractNodeTemplate> infrastructureNodes = new ArrayList<AbstractNodeTemplate>();
Utils.getInfrastructureNodes(relationTemplate.getTarget(), infrastructureNodes);
for (AbstractNodeTemplate infraNode : infrastructureNodes) {
// fetch mosquitto ip
if (templateContext.getPropertyVariable(infraNode,
Properties.OPENTOSCA_DECLARATIVE_PROPERTYNAME_VMIP) != null) {
mosquittoVmIp = templateContext.getPropertyVariable(infraNode,
Properties.OPENTOSCA_DECLARATIVE_PROPERTYNAME_VMIP);
}
}
/* fetch user, key, ip and ubuntuTemplateId of client stack */
Variable clientVmIp = null;
Variable clientVmUser = null;
Variable clientVmPass = null;
String ubuntuTemplateId = null;
infrastructureNodes = new ArrayList<AbstractNodeTemplate>();
Utils.getInfrastructureNodes(relationTemplate.getSource(), infrastructureNodes);
for (AbstractNodeTemplate infraNode : infrastructureNodes) {
if (templateContext.getPropertyVariable(infraNode,
Properties.OPENTOSCA_DECLARATIVE_PROPERTYNAME_VMIP) != null) {
clientVmIp = templateContext.getPropertyVariable(infraNode,
Properties.OPENTOSCA_DECLARATIVE_PROPERTYNAME_VMIP);
}
if (templateContext.getPropertyVariable(infraNode,
Properties.OPENTOSCA_DECLARATIVE_PROPERTYNAME_VMLOGINNAME) != null) {
ubuntuTemplateId = infraNode.getId();
clientVmUser = templateContext.getPropertyVariable(infraNode,
Properties.OPENTOSCA_DECLARATIVE_PROPERTYNAME_VMLOGINNAME);
}
if (templateContext.getPropertyVariable(infraNode,
Properties.OPENTOSCA_DECLARATIVE_PROPERTYNAME_VMLOGINPASSWORD) != null) {
ubuntuTemplateId = infraNode.getId();
clientVmPass = templateContext.getPropertyVariable(infraNode,
Properties.OPENTOSCA_DECLARATIVE_PROPERTYNAME_VMLOGINPASSWORD);
}
}
/* create skript */
// the script itself
String bashCommand = "echo \"topicName = hostName\" >> $(find ~ -maxdepth 1 -path \"*.csar\")/mosquitto_connections.txt;";
// add it as a var to the plan
Variable bashCommandVariable = templateContext.createGlobalStringVariable("addMosquittoConnection",
bashCommand);
// create bpel query which replaces topicName and hostName with real
// values
String xpathQuery = "replace(replace($" + bashCommandVariable.getName() + ",'topicName',$" + topicName.getName()
+ "),'hostName',$" + mosquittoVmIp.getName() + ")";
// create bpel assign with created query
try {
// create assign and append
Node assignNode = this.loadAssignXpathQueryToStringVarFragmentAsNode(
"assignValuesToAddConnection" + System.currentTimeMillis(), xpathQuery,
bashCommandVariable.getName());
assignNode = templateContext.importNode(assignNode);
templateContext.getProvisioningPhaseElement().appendChild(assignNode);
} catch (IOException e) {
LOG.error("Couldn't load fragment from file", e);
return false;
} catch (SAXException e) {
LOG.error("Couldn't parse fragment to DOM", e);
return false;
}
/* add logic to execute script on client machine */
Map<String, Variable> runScriptRequestInputParams = new HashMap<String, Variable>();
runScriptRequestInputParams.put("IP", clientVmIp);
// these two are requested from the input message if they are not set
if (!Utils.isVariableValueEmpty(clientVmUser, templateContext)) {
runScriptRequestInputParams.put("User", clientVmUser);
} else {
runScriptRequestInputParams.put("User", null);
}
if (!Utils.isVariableValueEmpty(clientVmPass, templateContext)) {
runScriptRequestInputParams.put("Password", clientVmPass);
} else {
runScriptRequestInputParams.put("Password", null);
}
runScriptRequestInputParams.put("Script", bashCommandVariable);
this.invokerPlugin.handle(templateContext, ubuntuTemplateId, true, "runScript",
Interfaces.OPENTOSCA_DECLARATIVE_INTERFACE_OPERATINGSYSTEM, "planCallbackAddress_invoker",
runScriptRequestInputParams, new HashMap<String, Variable>(), false);
return true;
}
/**
* Loads a BPEL Assign fragment which queries the csarEntrypath from the
* input message into String variable.
*
* @param assignName
* the name of the BPEL assign
* @param xpath2Query
* the csarEntryPoint XPath query
* @param stringVarName
* the variable to load the queries results into
* @return a String containing a BPEL Assign element
* @throws IOException
* is thrown when reading the BPEL fragment form the resources
* fails
*/
public String loadAssignXpathQueryToStringVarFragmentAsString(String assignName, String xpath2Query,
String stringVarName) throws IOException {
// <!-- {AssignName},{xpath2query}, {stringVarName} -->
URL url = FrameworkUtil.getBundle(this.getClass()).getBundleContext().getBundle()
.getResource("assignStringVarWithXpath2Query.xml");
File bpelFragmentFile = new File(FileLocator.toFileURL(url).getPath());
String template = FileUtils.readFileToString(bpelFragmentFile);
template = template.replace("{AssignName}", assignName);
template = template.replace("{xpath2query}", xpath2Query);
template = template.replace("{stringVarName}", stringVarName);
return template;
}
/**
* Loads a BPEL Assign fragment which queries the csarEntrypath from the
* input message into String variable.
*
* @param assignName
* the name of the BPEL assign
* @param csarEntryXpathQuery
* the csarEntryPoint XPath query
* @param stringVarName
* the variable to load the queries results into
* @return a DOM Node representing a BPEL assign element
* @throws IOException
* is thrown when loading internal bpel fragments fails
* @throws SAXException
* is thrown when parsing internal format into DOM fails
*/
public Node loadAssignXpathQueryToStringVarFragmentAsNode(String assignName, String xpath2Query,
String stringVarName) throws IOException, SAXException {
String templateString = this.loadAssignXpathQueryToStringVarFragmentAsString(assignName, xpath2Query,
stringVarName);
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(templateString));
Document doc = this.docBuilder.parse(is);
return doc.getFirstChild();
}
}
| fixes issue in mosquitto connection script
| org.opentosca.planbuilder.type.plugin.mosquittoconnectsto/src/org/opentosca/planbuilder/type/plugin/mosquittoconnectsto/Handler.java | fixes issue in mosquitto connection script | <ide><path>rg.opentosca.planbuilder.type.plugin.mosquittoconnectsto/src/org/opentosca/planbuilder/type/plugin/mosquittoconnectsto/Handler.java
<ide>
<ide> /* create skript */
<ide> // the script itself
<del> String bashCommand = "echo \"topicName = hostName\" >> $(find ~ -maxdepth 1 -path \"*.csar\")/mosquitto_connections.txt;";
<add> String bashCommand = "echo \"topicName = hostName\" > $(find ~ -maxdepth 1 -path \"*.csar\")/mosquitto_connections.txt;";
<ide>
<ide> // add it as a var to the plan
<ide> Variable bashCommandVariable = templateContext.createGlobalStringVariable("addMosquittoConnection", |
|
Java | apache-2.0 | e82fecfa33505ac037c77dadea1e52b68bd1c735 | 0 | ppavlidis/baseCode,ppavlidis/baseCode | /*
* The baseCode project
*
* Copyright (c) 2006 University of British Columbia
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package ubic.basecode.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.zip.GZIPInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* @author keshav
* @author Pavlidis
* @author Will Braynen
* @version $Id$
*/
public class FileTools {
private static Log log = LogFactory.getLog( FileTools.class.getName() );
protected final static String PNG_EXTENSION = ".png";
protected final static String GIF_EXTENSION = ".gif";
protected final static String TXT_EXTENSION = ".txt";
protected final static String[] XML_EXTENSIONS = { ".XML", ".RDF-XML", ".rdf-xml.gz", ".rdf-xml.zip", ".xml.zip",
".xml.gz" };
protected final static String[] IMAGE_EXTENSIONS = { PNG_EXTENSION, GIF_EXTENSION, "PNG", "GIF", "JPEG", "JPG" };
protected final static String[] DATA_EXTENSIONS = { TXT_EXTENSION, ".TXT", "txt.gz", "txt.zip", "txt.gzip" };
// default values
public final static String DEFAULT_DATA_EXTENSION = TXT_EXTENSION;
public final static String DEFAULT_IMAGE_EXTENSION = PNG_EXTENSION;
public final static String DEFAULT_XML_EXTENSION = ".xml";
/**
* @param file
* @throws IOException
*/
public static void checkPathIsReadableFile( String file ) throws IOException {
File infile = new File( file );
if ( !infile.exists() || !infile.canRead() ) {
throw new IOException( "Could not find file: " + file );
}
}
/**
* Returns the extension of a file.
*
* @param filename
* @return
* @return
*/
public static String getExtension( String filename ) {
String extension = null;
int i = filename.lastIndexOf( '.' );
if ( i > 0 && i < filename.length() - 1 ) {
extension = filename.substring( i + 1 ).toLowerCase();
}
return extension;
} // end getExtension
/**
* @param filename
* @return
*/
public static String chompExtension( String filename ) {
int j = filename.lastIndexOf( '.' );
if ( j > 1 ) {
return filename.substring( 0, filename.lastIndexOf( '.' ) );
}
return filename;
}
/**
* @param filename
* @param newExtension
* @return the new filename with the changed extension, but does not modify the <code>filename</code> parameter.
*/
public static String changeExtension( String filename, String newExtension ) {
String filenameWithoutExtension = chompExtension( filename );
return ( filenameWithoutExtension + "." + newExtension );
} // end getWithChangedExtension
/**
* @param filename
* @return
*/
public static boolean hasImageExtension( String filename ) {
for ( int i = 0; i < FileTools.IMAGE_EXTENSIONS.length; i++ ) {
if ( filename.toUpperCase().endsWith( FileTools.IMAGE_EXTENSIONS[i].toUpperCase() ) ) {
return true;
}
}
return false;
} // end hasImageExtension
/**
* @param filename
* @return
*/
public static boolean hasXMLExtension( String filename ) {
for ( int i = 0; i < FileTools.XML_EXTENSIONS.length; i++ ) {
if ( filename.toUpperCase().endsWith( FileTools.XML_EXTENSIONS[i].toUpperCase() ) ) {
return true;
}
}
return false;
}
/**
* @param filename
* @return the new filename with the added extension, but does not modify the <code>filename</code> parameter.
*/
public static String addImageExtension( String filename ) {
return ( filename + ( FileTools.DEFAULT_IMAGE_EXTENSION.startsWith( "." ) ? "" : "." ) + FileTools.DEFAULT_IMAGE_EXTENSION );
}
/**
* @param filename
* @return the new filename with the added extension, but does not modify the <code>filename</code> parameter.
*/
public static String addDataExtension( String filename ) {
return ( filename + ( FileTools.DEFAULT_DATA_EXTENSION.startsWith( "." ) ? "" : "." ) + FileTools.DEFAULT_DATA_EXTENSION );
}
/**
* @param dirname directory name
* @return
*/
public static boolean testDir( String dirname ) {
if ( dirname != null && dirname.length() > 0 ) {
File f = new File( dirname );
if ( f.isDirectory() && f.canRead() ) {
return true;
}
}
return false;
}
/**
* @param filename
* @return
*/
public static boolean testFile( String filename ) {
if ( filename != null && filename.length() > 0 ) {
File f = new File( filename );
if ( f.isFile() && f.canRead() ) {
return true;
}
}
return false;
}
/**
* @param resourcePath
* @return
* @throws URISyntaxException
*/
public static String resourceToPath( String resourcePath ) throws URISyntaxException {
if ( StringUtils.isBlank( resourcePath ) ) throw new IllegalArgumentException();
URL resource = FileTools.class.getResource( resourcePath );
if ( resource == null ) throw new IllegalArgumentException( "Could not get URL for resource=" + resourcePath );
return new File( resource.toURI() ).getAbsolutePath();
}
/**
* Test whether a File is writeable.
*
* @param file
* @return
*/
public static boolean testFile( File file ) {
if ( file != null ) {
if ( file.isFile() && file.canRead() ) {
return true;
}
}
return false;
}
/**
* @param filename
* @return
*/
public static boolean isZipped( String filename ) {
String capfileName = filename.toUpperCase();
if ( capfileName.endsWith( ".ZIP" ) ) {
return true;
}
return false;
}
/**
* @param fileName
* @return
*/
public static boolean isGZipped( String fileName ) {
String capfileName = fileName.toUpperCase();
if ( capfileName.endsWith( ".GZ" ) || capfileName.endsWith( ".GZIP" ) ) {
return true;
}
return false;
}
/**
* Given the path to a gzipped-file, unzips it into the same directory. If the file already exists it will be
* overwritten.
*
* @param seekFile
* @throws IOException
* @return path to the unzipped file.
*/
public static String unGzipFile( final String seekFile ) throws IOException {
if ( !isGZipped( seekFile ) ) {
throw new IllegalArgumentException();
}
checkPathIsReadableFile( seekFile );
String outputFilePath = chompExtension( seekFile );
File outputFile = copyPlainOrCompressedFile( seekFile, outputFilePath );
return outputFile.getAbsolutePath();
}
/**
* @param seekFile
* @return Collection of File objects
* @throws IOException
*/
public static Collection<File> unZipFiles( final String seekFile ) throws IOException {
if ( !isZipped( seekFile ) ) {
throw new IllegalArgumentException();
}
checkPathIsReadableFile( seekFile );
String outputFilePath = chompExtension( seekFile );
Collection<File> result = new HashSet<File>();
try {
ZipFile f = new ZipFile( seekFile );
for ( Enumeration<? extends ZipEntry> entries = f.entries(); entries.hasMoreElements(); ) {
ZipEntry entry = entries.nextElement();
String outputFileTitle = entry.getName();
InputStream is = f.getInputStream( entry );
File out = new File( outputFilePath + outputFileTitle );
OutputStream os = new FileOutputStream( out );
copy( is, os );
result.add( out );
log.debug( outputFileTitle );
}
} catch ( IOException e ) {
throw new RuntimeException( e );
}
return result;
}
/**
* @param sourcePath
* @param outputFilePath
* @return
* @throws FileNotFoundException
* @throws IOException
*/
public static File copyPlainOrCompressedFile( final String sourcePath, String outputFilePath )
throws FileNotFoundException, IOException {
File sourceFile = new File( sourcePath );
if ( !sourceFile.exists() ) {
throw new IllegalArgumentException( "Source file (" + sourcePath + ") does not exist" );
}
if ( sourceFile.exists() && sourceFile.isDirectory() ) {
throw new UnsupportedOperationException( "Don't know how to copy directories (" + sourceFile + ")" );
}
File outputFile = new File( outputFilePath );
if ( outputFile.exists() && outputFile.isDirectory() ) {
throw new UnsupportedOperationException( "Don't know how to copy to directories (" + outputFile + ")" );
}
OutputStream out = new FileOutputStream( outputFile );
InputStream is = FileTools.getInputStreamFromPlainOrCompressedFile( sourcePath );
copy( is, out );
return outputFile;
}
/**
* On completion streams are closed.
*
* @param input
* @param output
* @throws IOException
*/
public static void copy( InputStream input, OutputStream output ) throws IOException {
if ( input.available() == 0 ) return;
byte[] buf = new byte[1024];
int len;
while ( ( len = input.read( buf ) ) > 0 ) {
output.write( buf, 0, len );
}
input.close();
output.close();
}
/**
* Open a non-compresed, zipped, or gzipped file. Uses the file name pattern to figure this out.
*
* @param fileName. If Zipped, only the first file in the archive is used.
* @return
* @throws IOException
* @throws FileNotFoundException
*/
public static InputStream getInputStreamFromPlainOrCompressedFile( String fileName ) throws IOException,
FileNotFoundException {
if ( !FileTools.testFile( fileName ) ) {
throw new IOException( "Could not read from " + fileName );
}
InputStream i;
if ( FileTools.isZipped( fileName ) ) {
log.debug( "Reading from zipped file" );
ZipFile f = new ZipFile( fileName );
ZipEntry entry = f.entries().nextElement();
if ( entry == null ) throw new IOException( "No zip entries" );
if ( f.entries().hasMoreElements() ) {
log.debug( "ZIP archive has more then one file, reading the first one." );
}
i = f.getInputStream( entry );
} else if ( FileTools.isGZipped( fileName ) ) {
log.debug( "Reading from gzipped file" );
i = new GZIPInputStream( new FileInputStream( fileName ) );
} else {
log.debug( "Reading from uncompressed file" );
i = new FileInputStream( fileName );
}
return i;
}
/**
* Given a File object representing a directory, return a collection of File objects representing the files
* contained in that directory.
*
* @param directory
* @return
*/
public static Collection<File> listDirectoryFiles( File directory ) {
if ( !directory.isDirectory() ) throw new IllegalArgumentException( "Must be a directory" );
File[] files = directory.listFiles();
FileFilter fileFilter = new FileFilter() {
@Override
public boolean accept( File file ) {
return file.isFile();
}
};
files = directory.listFiles( fileFilter );
return Arrays.asList( files );
}
/**
* Given a File object representing a directory, return a collection of File objects representing the directories
* contained in that directory.
*
* @param directory
* @return
*/
public static Collection<File> listSubDirectories( File directory ) {
if ( !directory.isDirectory() ) throw new IllegalArgumentException( "Must be a directory" );
File[] files = directory.listFiles();
FileFilter fileFilter = new FileFilter() {
@Override
public boolean accept( File file ) {
return file.isDirectory();
}
};
files = directory.listFiles( fileFilter );
return Arrays.asList( files );
}
/**
* Creates the directory if it does not exist.
*
* @param directory
* @return
*/
public static File createDir( String directory ) {
File dirPath = new File( directory );
if ( !dirPath.exists() ) {
dirPath.mkdirs();
}
return dirPath;
}
/**
* Deletes the specified <link>Collection<link> of files.
*
* @param files
* @return int The number of files deleted.
* @see java.io.File#delete()
*/
public static int deleteFiles( Collection<File> files ) {
int numDeleted = 0;
Iterator<File> iter = files.iterator();
while ( iter.hasNext() ) {
File file = iter.next();
if ( file.isDirectory() ) {
log.warn( "Cannot delete a directory." );
continue;
}
if ( log.isDebugEnabled() ) log.debug( "Deleting file " + file.getAbsolutePath() + "." );
file.getAbsoluteFile().delete();
numDeleted++;
}
log.info( "Deleted " + numDeleted + " files." );
return numDeleted;
}
/**
* Deletes the directory and subdirectories if empty.
*
* @param directory
* @return int The number of directories deleted.
* @see java.io.File#delete()
*/
public static int deleteDir( File directory ) {
int numDeleted = 0;
Collection<File> directories = listSubDirectories( directory );
Iterator<File> iter = directories.iterator();
while ( iter.hasNext() ) {
File dir = iter.next();
if ( dir.listFiles().length == 0 ) {
dir.getAbsoluteFile().delete();
numDeleted++;
} else {
log.info( "Directory not empty. Skipping deletion of " + dir.getAbsolutePath() + "." );
}
}
/* The top level directory */
if ( directory.listFiles().length == 0 ) {
log.warn( "Deleting top level directory." );
directory.getAbsoluteFile().delete();
numDeleted++;
}
else {
log.info( "Top level directory " + directory.getAbsolutePath() + " not empty. Will not delete." );
}
log.info( "Deleted " + numDeleted + " directories." );
return numDeleted;
}
// Leon added the below methods
/**
* Outputs a string to a file.
*/
public static void stringToFile( String s, File f ) throws Exception {
stringToFile( s, f, false );
}
/**
* Outputs a many strings to a file, one line at a time.
*/
public static void stringsToFile( Collection<String> lines, String f ) throws Exception {
stringsToFile( lines, new File( f ) );
}
/**
* Outputs a many strings to a file, one line at a time.
*/
public static void stringsToFile( Collection<String> lines, File f ) throws Exception {
stringsToFile( lines, f, false );
}
/**
* Outputs many strings to a file, one line at a time.
*
* @param lines - input lines
* @param f - file that wrote to
* @param append - add to end of file or overwrite
* @throws Exception
*/
public static void stringsToFile( Collection<String> lines, File f, boolean append ) throws Exception {
PrintWriter fout = new PrintWriter( new FileWriter( f, append ) );
for ( String line : lines ) {
fout.println( line );
}
fout.close();
}
/**
* Outputs a string to a file, one line at a time.
*
* @param s - input line/string
* @param f - file that wrote to
* @param append - add to end of file or overwrite
* @throws Exception
*/
public static void stringToFile( String s, File f, boolean append ) throws Exception {
FileWriter fout = new FileWriter( f, append );
fout.write( s );
fout.close();
}
/**
* opens a file and returns its contents as a list of lines.
*
* @return - List of strings representing the lines, first line is first in list
* @throws IOException
*/
public static List<String> getLines( String filename ) throws IOException {
return getLines( new File( filename ) );
}
// is this code duplicated? I can't find any if so
/**
* opens a file and returns its contents as a list of lines.
*
* @return - List of strings representing the lines, first line is first in list
* @throws IOException
*/
public static List<String> getLines( File file ) throws IOException {
List<String> lines = new LinkedList<String>();
BufferedReader in = new BufferedReader( new FileReader( file ) );
String line;
while ( ( line = in.readLine() ) != null ) {
lines.add( line );
}
in.close();
return lines;
}
/**
* Used for reading output generated by Collection.toString(). For example [a,b,c] stored in a file would be
* converted to a new List containing "a", "b" and "c".
*
* @param f - input file, with only one line for the toString output.
* @return - list created from the strings in the file
* @throws Exception
*/
public static List<String> getStringListFromFile( File f ) throws Exception {
List<String> result = new LinkedList<String>();
List<String> lines = FileTools.getLines( f );
if ( lines.size() != 1 ) {
throw new RuntimeException( "Too many lines in file" );
}
String line = lines.get( 0 );
line = line.substring( 1, line.length() - 1 );
StringTokenizer toke = new StringTokenizer( line, "," );
while ( toke.hasMoreTokens() ) {
result.add( toke.nextToken().trim() );
}
return result;
}
} | src/ubic/basecode/util/FileTools.java | /*
* The baseCode project
*
* Copyright (c) 2006 University of British Columbia
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package ubic.basecode.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.zip.GZIPInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* @author keshav
* @author Pavlidis
* @author Will Braynen
* @version $Id$
*/
public class FileTools {
private static Log log = LogFactory.getLog( FileTools.class.getName() );
protected final static String PNG_EXTENSION = ".png";
protected final static String GIF_EXTENSION = ".gif";
protected final static String TXT_EXTENSION = ".txt";
protected final static String[] XML_EXTENSIONS = { ".XML", ".RDF-XML", ".rdf-xml.gz", ".rdf-xml.zip", ".xml.zip",
".xml.gz" };
protected final static String[] IMAGE_EXTENSIONS = { PNG_EXTENSION, GIF_EXTENSION, "PNG", "GIF", "JPEG", "JPG" };
protected final static String[] DATA_EXTENSIONS = { TXT_EXTENSION, ".TXT", "txt.gz", "txt.zip", "txt.gzip" };
// default values
public final static String DEFAULT_DATA_EXTENSION = TXT_EXTENSION;
public final static String DEFAULT_IMAGE_EXTENSION = PNG_EXTENSION;
public final static String DEFAULT_XML_EXTENSION = ".xml";
/**
* @param file
* @throws IOException
*/
public static void checkPathIsReadableFile( String file ) throws IOException {
File infile = new File( file );
if ( !infile.exists() || !infile.canRead() ) {
throw new IOException( "Could not find file: " + file );
}
}
/**
* Returns the extension of a file.
*
* @param filename
* @return
* @return
*/
public static String getExtension( String filename ) {
String extension = null;
int i = filename.lastIndexOf( '.' );
if ( i > 0 && i < filename.length() - 1 ) {
extension = filename.substring( i + 1 ).toLowerCase();
}
return extension;
} // end getExtension
/**
* @param filename
* @return
*/
public static String chompExtension( String filename ) {
int j = filename.lastIndexOf( '.' );
if ( j > 1 ) {
return filename.substring( 0, filename.lastIndexOf( '.' ) );
}
return filename;
}
/**
* @param filename
* @param newExtension
* @return the new filename with the changed extension, but does not modify the <code>filename</code> parameter.
*/
public static String changeExtension( String filename, String newExtension ) {
String filenameWithoutExtension = chompExtension( filename );
return ( filenameWithoutExtension + "." + newExtension );
} // end getWithChangedExtension
/**
* @param filename
* @return
*/
public static boolean hasImageExtension( String filename ) {
for ( int i = 0; i < FileTools.IMAGE_EXTENSIONS.length; i++ ) {
if ( filename.toUpperCase().endsWith( FileTools.IMAGE_EXTENSIONS[i].toUpperCase() ) ) {
return true;
}
}
return false;
} // end hasImageExtension
/**
* @param filename
* @return
*/
public static boolean hasXMLExtension( String filename ) {
for ( int i = 0; i < FileTools.XML_EXTENSIONS.length; i++ ) {
if ( filename.toUpperCase().endsWith( FileTools.XML_EXTENSIONS[i].toUpperCase() ) ) {
return true;
}
}
return false;
}
/**
* @param filename
* @return the new filename with the added extension, but does not modify the <code>filename</code> parameter.
*/
public static String addImageExtension( String filename ) {
return ( filename + ( FileTools.DEFAULT_IMAGE_EXTENSION.startsWith( "." ) ? "" : "." ) + FileTools.DEFAULT_IMAGE_EXTENSION );
}
/**
* @param filename
* @return the new filename with the added extension, but does not modify the <code>filename</code> parameter.
*/
public static String addDataExtension( String filename ) {
return ( filename + ( FileTools.DEFAULT_DATA_EXTENSION.startsWith( "." ) ? "" : "." ) + FileTools.DEFAULT_DATA_EXTENSION );
}
/**
* @param dirname directory name
* @return
*/
public static boolean testDir( String dirname ) {
if ( dirname != null && dirname.length() > 0 ) {
File f = new File( dirname );
if ( f.isDirectory() && f.canRead() ) {
return true;
}
}
return false;
}
/**
* @param filename
* @return
*/
public static boolean testFile( String filename ) {
if ( filename != null && filename.length() > 0 ) {
File f = new File( filename );
if ( f.isFile() && f.canRead() ) {
return true;
}
}
return false;
}
/**
* Test whether a File is writeable.
*
* @param file
* @return
*/
public static boolean testFile( File file ) {
if ( file != null ) {
if ( file.isFile() && file.canRead() ) {
return true;
}
}
return false;
}
/**
* @param filename
* @return
*/
public static boolean isZipped( String filename ) {
String capfileName = filename.toUpperCase();
if ( capfileName.endsWith( ".ZIP" ) ) {
return true;
}
return false;
}
/**
* @param fileName
* @return
*/
public static boolean isGZipped( String fileName ) {
String capfileName = fileName.toUpperCase();
if ( capfileName.endsWith( ".GZ" ) || capfileName.endsWith( ".GZIP" ) ) {
return true;
}
return false;
}
/**
* Given the path to a gzipped-file, unzips it into the same directory. If the file already exists it will be
* overwritten.
*
* @param seekFile
* @throws IOException
* @return path to the unzipped file.
*/
public static String unGzipFile( final String seekFile ) throws IOException {
if ( !isGZipped( seekFile ) ) {
throw new IllegalArgumentException();
}
checkPathIsReadableFile( seekFile );
String outputFilePath = chompExtension( seekFile );
File outputFile = copyPlainOrCompressedFile( seekFile, outputFilePath );
return outputFile.getAbsolutePath();
}
/**
* @param seekFile
* @return Collection of File objects
* @throws IOException
*/
public static Collection<File> unZipFiles( final String seekFile ) throws IOException {
if ( !isZipped( seekFile ) ) {
throw new IllegalArgumentException();
}
checkPathIsReadableFile( seekFile );
String outputFilePath = chompExtension( seekFile );
Collection<File> result = new HashSet<File>();
try {
ZipFile f = new ZipFile( seekFile );
for ( Enumeration<? extends ZipEntry> entries = f.entries(); entries.hasMoreElements(); ) {
ZipEntry entry = entries.nextElement();
String outputFileTitle = entry.getName();
InputStream is = f.getInputStream( entry );
File out = new File( outputFilePath + outputFileTitle );
OutputStream os = new FileOutputStream( out );
copy( is, os );
result.add( out );
log.debug( outputFileTitle );
}
} catch ( IOException e ) {
throw new RuntimeException( e );
}
return result;
}
/**
* @param sourcePath
* @param outputFilePath
* @return
* @throws FileNotFoundException
* @throws IOException
*/
public static File copyPlainOrCompressedFile( final String sourcePath, String outputFilePath )
throws FileNotFoundException, IOException {
File sourceFile = new File( sourcePath );
if ( !sourceFile.exists() ) {
throw new IllegalArgumentException( "Source file (" + sourcePath + ") does not exist" );
}
if ( sourceFile.exists() && sourceFile.isDirectory() ) {
throw new UnsupportedOperationException( "Don't know how to copy directories (" + sourceFile + ")" );
}
File outputFile = new File( outputFilePath );
if ( outputFile.exists() && outputFile.isDirectory() ) {
throw new UnsupportedOperationException( "Don't know how to copy to directories (" + outputFile + ")" );
}
OutputStream out = new FileOutputStream( outputFile );
InputStream is = FileTools.getInputStreamFromPlainOrCompressedFile( sourcePath );
copy( is, out );
return outputFile;
}
/**
* On completion streams are closed.
*
* @param input
* @param output
* @throws IOException
*/
public static void copy( InputStream input, OutputStream output ) throws IOException {
if ( input.available() == 0 ) return;
byte[] buf = new byte[1024];
int len;
while ( ( len = input.read( buf ) ) > 0 ) {
output.write( buf, 0, len );
}
input.close();
output.close();
}
/**
* Open a non-compresed, zipped, or gzipped file. Uses the file name pattern to figure this out.
*
* @param fileName. If Zipped, only the first file in the archive is used.
* @return
* @throws IOException
* @throws FileNotFoundException
*/
public static InputStream getInputStreamFromPlainOrCompressedFile( String fileName ) throws IOException,
FileNotFoundException {
if ( !FileTools.testFile( fileName ) ) {
throw new IOException( "Could not read from " + fileName );
}
InputStream i;
if ( FileTools.isZipped( fileName ) ) {
log.debug( "Reading from zipped file" );
ZipFile f = new ZipFile( fileName );
ZipEntry entry = f.entries().nextElement();
if ( entry == null ) throw new IOException( "No zip entries" );
if ( f.entries().hasMoreElements() ) {
log.debug( "ZIP archive has more then one file, reading the first one." );
}
i = f.getInputStream( entry );
} else if ( FileTools.isGZipped( fileName ) ) {
log.debug( "Reading from gzipped file" );
i = new GZIPInputStream( new FileInputStream( fileName ) );
} else {
log.debug( "Reading from uncompressed file" );
i = new FileInputStream( fileName );
}
return i;
}
/**
* Given a File object representing a directory, return a collection of File objects representing the files
* contained in that directory.
*
* @param directory
* @return
*/
public static Collection<File> listDirectoryFiles( File directory ) {
if ( !directory.isDirectory() ) throw new IllegalArgumentException( "Must be a directory" );
File[] files = directory.listFiles();
FileFilter fileFilter = new FileFilter() {
@Override
public boolean accept( File file ) {
return file.isFile();
}
};
files = directory.listFiles( fileFilter );
return Arrays.asList( files );
}
/**
* Given a File object representing a directory, return a collection of File objects representing the directories
* contained in that directory.
*
* @param directory
* @return
*/
public static Collection<File> listSubDirectories( File directory ) {
if ( !directory.isDirectory() ) throw new IllegalArgumentException( "Must be a directory" );
File[] files = directory.listFiles();
FileFilter fileFilter = new FileFilter() {
@Override
public boolean accept( File file ) {
return file.isDirectory();
}
};
files = directory.listFiles( fileFilter );
return Arrays.asList( files );
}
/**
* Creates the directory if it does not exist.
*
* @param directory
* @return
*/
public static File createDir( String directory ) {
File dirPath = new File( directory );
if ( !dirPath.exists() ) {
dirPath.mkdirs();
}
return dirPath;
}
/**
* Deletes the specified <link>Collection<link> of files.
*
* @param files
* @return int The number of files deleted.
* @see java.io.File#delete()
*/
public static int deleteFiles( Collection<File> files ) {
int numDeleted = 0;
Iterator<File> iter = files.iterator();
while ( iter.hasNext() ) {
File file = iter.next();
if ( file.isDirectory() ) {
log.warn( "Cannot delete a directory." );
continue;
}
if ( log.isDebugEnabled() ) log.debug( "Deleting file " + file.getAbsolutePath() + "." );
file.getAbsoluteFile().delete();
numDeleted++;
}
log.info( "Deleted " + numDeleted + " files." );
return numDeleted;
}
/**
* Deletes the directory and subdirectories if empty.
*
* @param directory
* @return int The number of directories deleted.
* @see java.io.File#delete()
*/
public static int deleteDir( File directory ) {
int numDeleted = 0;
Collection<File> directories = listSubDirectories( directory );
Iterator<File> iter = directories.iterator();
while ( iter.hasNext() ) {
File dir = iter.next();
if ( dir.listFiles().length == 0 ) {
dir.getAbsoluteFile().delete();
numDeleted++;
} else {
log.info( "Directory not empty. Skipping deletion of " + dir.getAbsolutePath() + "." );
}
}
/* The top level directory */
if ( directory.listFiles().length == 0 ) {
log.warn( "Deleting top level directory." );
directory.getAbsoluteFile().delete();
numDeleted++;
}
else {
log.info( "Top level directory " + directory.getAbsolutePath() + " not empty. Will not delete." );
}
log.info( "Deleted " + numDeleted + " directories." );
return numDeleted;
}
// Leon added the below methods
/**
* Outputs a string to a file.
*/
public static void stringToFile( String s, File f ) throws Exception {
stringToFile( s, f, false );
}
/**
* Outputs a many strings to a file, one line at a time.
*/
public static void stringsToFile( Collection<String> lines, String f ) throws Exception {
stringsToFile( lines, new File( f ) );
}
/**
* Outputs a many strings to a file, one line at a time.
*/
public static void stringsToFile( Collection<String> lines, File f ) throws Exception {
stringsToFile( lines, f, false );
}
/**
* Outputs many strings to a file, one line at a time.
*
* @param lines - input lines
* @param f - file that wrote to
* @param append - add to end of file or overwrite
* @throws Exception
*/
public static void stringsToFile( Collection<String> lines, File f, boolean append ) throws Exception {
PrintWriter fout = new PrintWriter( new FileWriter( f, append ) );
for ( String line : lines ) {
fout.println( line );
}
fout.close();
}
/**
* Outputs a string to a file, one line at a time.
*
* @param s - input line/string
* @param f - file that wrote to
* @param append - add to end of file or overwrite
* @throws Exception
*/
public static void stringToFile( String s, File f, boolean append ) throws Exception {
FileWriter fout = new FileWriter( f, append );
fout.write( s );
fout.close();
}
/**
* opens a file and returns its contents as a list of lines.
*
* @return - List of strings representing the lines, first line is first in list
* @throws IOException
*/
public static List<String> getLines( String filename ) throws IOException {
return getLines( new File( filename ) );
}
// is this code duplicated? I can't find any if so
/**
* opens a file and returns its contents as a list of lines.
*
* @return - List of strings representing the lines, first line is first in list
* @throws IOException
*/
public static List<String> getLines( File file ) throws IOException {
List<String> lines = new LinkedList<String>();
BufferedReader in = new BufferedReader( new FileReader( file ) );
String line;
while ( ( line = in.readLine() ) != null ) {
lines.add( line );
}
in.close();
return lines;
}
/**
* Used for reading output generated by Collection.toString(). For example [a,b,c] stored in a file would be
* converted to a new List containing "a", "b" and "c".
*
* @param f - input file, with only one line for the toString output.
* @return - list created from the strings in the file
* @throws Exception
*/
public static List<String> getStringListFromFile( File f ) throws Exception {
List<String> result = new LinkedList<String>();
List<String> lines = FileTools.getLines( f );
if ( lines.size() != 1 ) {
throw new RuntimeException( "Too many lines in file" );
}
String line = lines.get( 0 );
line = line.substring( 1, line.length() - 1 );
StringTokenizer toke = new StringTokenizer( line, "," );
while ( toke.hasMoreTokens() ) {
result.add( toke.nextToken().trim() );
}
return result;
}
} | utility method
| src/ubic/basecode/util/FileTools.java | utility method | <ide><path>rc/ubic/basecode/util/FileTools.java
<ide> import java.io.InputStream;
<ide> import java.io.OutputStream;
<ide> import java.io.PrintWriter;
<add>import java.net.URISyntaxException;
<add>import java.net.URL;
<ide> import java.util.Arrays;
<ide> import java.util.Collection;
<ide> import java.util.Enumeration;
<ide> import java.util.zip.ZipEntry;
<ide> import java.util.zip.ZipFile;
<ide>
<add>import org.apache.commons.lang.StringUtils;
<ide> import org.apache.commons.logging.Log;
<ide> import org.apache.commons.logging.LogFactory;
<ide>
<ide> }
<ide> }
<ide> return false;
<add>
<add> }
<add>
<add> /**
<add> * @param resourcePath
<add> * @return
<add> * @throws URISyntaxException
<add> */
<add> public static String resourceToPath( String resourcePath ) throws URISyntaxException {
<add> if ( StringUtils.isBlank( resourcePath ) ) throw new IllegalArgumentException();
<add> URL resource = FileTools.class.getResource( resourcePath );
<add> if ( resource == null ) throw new IllegalArgumentException( "Could not get URL for resource=" + resourcePath );
<add> return new File( resource.toURI() ).getAbsolutePath();
<ide> }
<ide>
<ide> /** |
|
Java | lgpl-2.1 | 103be236f2ca9f98ec0650bccbaeb95152074e05 | 0 | zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform | /*
* Copyright 2013, Red Hat, Inc. and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.zanata.webtrans.client.presenter;
import net.customware.gwt.presenter.client.EventBus;
import net.customware.gwt.presenter.client.widget.WidgetPresenter;
import org.zanata.webtrans.client.view.AttentionKeyShortcutDisplay;
import com.google.inject.Inject;
/**
* Responsible for getting the necessary model data to show when attention mode is
* active in response to relevant events.
*
* @author David Mason, <a href="mailto:[email protected]">[email protected]</a>
*
*/
public class AttentionKeyShortcutPresenter extends WidgetPresenter<AttentionKeyShortcutDisplay>
{
@Inject
public AttentionKeyShortcutPresenter(AttentionKeyShortcutDisplay display, EventBus eventBus)
{
super(display, eventBus);
}
@Override
protected void onBind()
{
}
@Override
protected void onUnbind()
{
// TODO Auto-generated method stub
}
@Override
protected void onRevealDisplay()
{
// TODO Auto-generated method stub
}
}
| zanata-war/src/main/java/org/zanata/webtrans/client/presenter/AttentionKeyShortcutPresenter.java | /*
* Copyright 2013, Red Hat, Inc. and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.zanata.webtrans.client.presenter;
import java.util.Map;
import java.util.Set;
import org.zanata.webtrans.client.keys.EventWrapper;
import org.zanata.webtrans.client.keys.KeyShortcut;
import org.zanata.webtrans.client.keys.Keys;
import org.zanata.webtrans.client.view.AttentionKeyShortcutDisplay;
import com.google.gwt.dom.client.NativeEvent;
import com.google.inject.Inject;
import net.customware.gwt.presenter.client.EventBus;
import net.customware.gwt.presenter.client.widget.WidgetPresenter;
/**
*
* @author David Mason, <a href="mailto:[email protected]">[email protected]</a>
*
*/
public class AttentionKeyShortcutPresenter extends WidgetPresenter<AttentionKeyShortcutDisplay>
{
private final EventWrapper event;
// hold a map of shortcuts similar to KeyShortcutPresenter, accessible by KeyShortcutPresenter
private Map<Keys, Set<KeyShortcut>> shortcutMap;
// hold awareness of the current shortcut key (KeyShortcutPresenter can look it up from here)
// (Note: this will come from user config, this is just the definitive place that looks it up from there)
// rely on KeyShortcutPresenter to invoke event handling at an appropriate time
@Inject
public AttentionKeyShortcutPresenter(AttentionKeyShortcutDisplay display,
EventBus eventBus,
final EventWrapper event)
{
super(display, eventBus);
this.event = event;
}
@Override
protected void onBind()
{
// TODO look up attention key setting from user settings
// TODO register attention shortcut
// Note: keep the registration handle so it can be unregistered if the user changes the setting.
}
@Override
protected void onUnbind()
{
// TODO Auto-generated method stub
}
@Override
protected void onRevealDisplay()
{
// TODO Auto-generated method stub
}
public boolean isAttentionMode()
{
// TODO Auto-generated method stub
return false;
}
public void processKeyEvent(NativeEvent evt)
{
// TODO Auto-generated method stub
Keys pressedKeys = event.createKeys(evt);
}
}
| rhbz961564 gut attention key presenter pending change of behaviour
| zanata-war/src/main/java/org/zanata/webtrans/client/presenter/AttentionKeyShortcutPresenter.java | rhbz961564 gut attention key presenter pending change of behaviour | <ide><path>anata-war/src/main/java/org/zanata/webtrans/client/presenter/AttentionKeyShortcutPresenter.java
<ide> */
<ide> package org.zanata.webtrans.client.presenter;
<ide>
<del>import java.util.Map;
<del>import java.util.Set;
<del>
<del>import org.zanata.webtrans.client.keys.EventWrapper;
<del>import org.zanata.webtrans.client.keys.KeyShortcut;
<del>import org.zanata.webtrans.client.keys.Keys;
<del>import org.zanata.webtrans.client.view.AttentionKeyShortcutDisplay;
<del>
<del>import com.google.gwt.dom.client.NativeEvent;
<del>import com.google.inject.Inject;
<del>
<ide> import net.customware.gwt.presenter.client.EventBus;
<ide> import net.customware.gwt.presenter.client.widget.WidgetPresenter;
<ide>
<add>import org.zanata.webtrans.client.view.AttentionKeyShortcutDisplay;
<add>
<add>import com.google.inject.Inject;
<add>
<ide> /**
<add> * Responsible for getting the necessary model data to show when attention mode is
<add> * active in response to relevant events.
<ide> *
<ide> * @author David Mason, <a href="mailto:[email protected]">[email protected]</a>
<ide> *
<ide> public class AttentionKeyShortcutPresenter extends WidgetPresenter<AttentionKeyShortcutDisplay>
<ide> {
<ide>
<del> private final EventWrapper event;
<del>
<del> // hold a map of shortcuts similar to KeyShortcutPresenter, accessible by KeyShortcutPresenter
<del> private Map<Keys, Set<KeyShortcut>> shortcutMap;
<del>
<del>
<del> // hold awareness of the current shortcut key (KeyShortcutPresenter can look it up from here)
<del> // (Note: this will come from user config, this is just the definitive place that looks it up from there)
<del>
<del> // rely on KeyShortcutPresenter to invoke event handling at an appropriate time
<ide>
<ide> @Inject
<del> public AttentionKeyShortcutPresenter(AttentionKeyShortcutDisplay display,
<del> EventBus eventBus,
<del> final EventWrapper event)
<add> public AttentionKeyShortcutPresenter(AttentionKeyShortcutDisplay display, EventBus eventBus)
<ide> {
<ide> super(display, eventBus);
<del> this.event = event;
<ide> }
<ide>
<ide> @Override
<ide> protected void onBind()
<ide> {
<del>
<del> // TODO look up attention key setting from user settings
<del>
<del> // TODO register attention shortcut
<del> // Note: keep the registration handle so it can be unregistered if the user changes the setting.
<ide> }
<ide>
<ide> @Override
<ide>
<ide> }
<ide>
<del> public boolean isAttentionMode()
<del> {
<del> // TODO Auto-generated method stub
<del> return false;
<del> }
<del>
<del> public void processKeyEvent(NativeEvent evt)
<del> {
<del> // TODO Auto-generated method stub
<del>
<del> Keys pressedKeys = event.createKeys(evt);
<del> }
<del>
<ide> } |
|
Java | mit | 31e7c76ecf305862d284be8934c9ebb15e5cd3ed | 0 | GreenfieldTech/irked | package tech.greenfield.vertx.irked.example;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.http.HttpServerOptions;
import tech.greenfield.vertx.irked.Controller;
import tech.greenfield.vertx.irked.Irked;
import tech.greenfield.vertx.irked.Request;
import tech.greenfield.vertx.irked.annotations.Endpoint;
import tech.greenfield.vertx.irked.annotations.OnFail;
import tech.greenfield.vertx.irked.helpers.Redirect;
public class App extends AbstractVerticle {
@Override
public void start(Promise<Void> startFuture) throws Exception {
System.out.println("Starting Irked example app listening on port " + config().getInteger("port", 8000));
vertx.createHttpServer(new HttpServerOptions())
.requestHandler(Irked.irked(vertx).router()
.configure(new ExampleAPIv1(), "/v1")
.configure(new ExampleAPIv2(), "/v2")
.configure(new Controller() {
@Endpoint("/")
WebHandler latest = r -> {
throw new Redirect("/v2" + r.request().uri()).unchecked();
};
@OnFail
@Endpoint("/*")
WebHandler failureHandler = Request.failureHandler();
}))
.listen(config().getInteger("port", 8000))
.onSuccess(v -> startFuture.complete())
.onFailure(t -> startFuture.fail(t));
}
}
| src/example/java/tech/greenfield/vertx/irked/example/App.java | package tech.greenfield.vertx.irked.example;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.http.HttpServerOptions;
import tech.greenfield.vertx.irked.Controller;
import tech.greenfield.vertx.irked.Irked;
import tech.greenfield.vertx.irked.annotations.Endpoint;
import tech.greenfield.vertx.irked.helpers.Redirect;
public class App extends AbstractVerticle {
@Override
public void start(Promise<Void> startFuture) throws Exception {
vertx.createHttpServer(new HttpServerOptions())
.requestHandler(Irked.irked(vertx).router()
.configure(new ExampleAPIv1(), "/v1")
.configure(new ExampleAPIv2(), "/v2")
.configure(new Controller() {
@Endpoint("/")
WebHandler latest = r -> {
throw new Redirect("/v2" + r.request().uri()).unchecked();
};
}))
.listen(config().getInteger("port", 8080))
.onSuccess(v -> startFuture.complete())
.onFailure(t -> startFuture.fail(t));
}
}
| add a failure handle so that redirect works | src/example/java/tech/greenfield/vertx/irked/example/App.java | add a failure handle so that redirect works | <ide><path>rc/example/java/tech/greenfield/vertx/irked/example/App.java
<ide> import io.vertx.core.http.HttpServerOptions;
<ide> import tech.greenfield.vertx.irked.Controller;
<ide> import tech.greenfield.vertx.irked.Irked;
<add>import tech.greenfield.vertx.irked.Request;
<ide> import tech.greenfield.vertx.irked.annotations.Endpoint;
<add>import tech.greenfield.vertx.irked.annotations.OnFail;
<ide> import tech.greenfield.vertx.irked.helpers.Redirect;
<ide>
<ide> public class App extends AbstractVerticle {
<ide>
<ide> @Override
<ide> public void start(Promise<Void> startFuture) throws Exception {
<add> System.out.println("Starting Irked example app listening on port " + config().getInteger("port", 8000));
<ide> vertx.createHttpServer(new HttpServerOptions())
<ide> .requestHandler(Irked.irked(vertx).router()
<ide> .configure(new ExampleAPIv1(), "/v1")
<ide> WebHandler latest = r -> {
<ide> throw new Redirect("/v2" + r.request().uri()).unchecked();
<ide> };
<add> @OnFail
<add> @Endpoint("/*")
<add> WebHandler failureHandler = Request.failureHandler();
<ide> }))
<del> .listen(config().getInteger("port", 8080))
<add> .listen(config().getInteger("port", 8000))
<ide> .onSuccess(v -> startFuture.complete())
<ide> .onFailure(t -> startFuture.fail(t));
<ide> } |
|
Java | apache-2.0 | c4beb4ad85bc407304ce557aa8f118a73876557d | 0 | shidh/CSSA,shidh/CSSA,shidh/CSSA,shidh/CSSA | package controllers;
import play.*;
import play.mvc.*;
import java.util.*;
import models.*;
public class Application extends Controller {
public static void index() {
render();
}
public static void register(String email, String password1, String password2) {
boolean register = true;
boolean flag_register = false;
boolean flag_twice = false;
if (password1.equals(password2)) {
if (User.find("byEmail", email).first() == null) {
flag_register = true;
new User(email, password1).save();
render("Application/index.html", flag_register, register);
} else {
render("Application/index.html", flag_register, register);
}
} else {
flag_twice = true;
render("Application/index.html", flag_twice, register);
}
}
} | app/controllers/Application.java | package controllers;
import play.*;
import play.mvc.*;
import java.util.*;
import models.*;
public class Application extends Controller {
public static void index() {
render();
}
public static void register(String email, String password1, String password2) {
boolean register = true;
boolean flag_register = false;
boolean flag_twice = false;
if (password1.equals(password2)) {
if (User.find("byEmail", email).first() == null) {
flag_register = true;
new User(email, password1).save();
render("Application/index.html", flag_register, register);
} else {
render("Application/index.html", flag_register, register);
}
} else {
flag_twice = true;
render("Application/index.html", flag_twice, register);
}
}
} | test commit
| app/controllers/Application.java | test commit | <ide><path>pp/controllers/Application.java
<ide> new User(email, password1).save();
<ide> render("Application/index.html", flag_register, register);
<ide> } else {
<add>
<ide> render("Application/index.html", flag_register, register);
<ide> }
<ide> } else { |
|
Java | apache-2.0 | 967a939038526b9c54a1c30270ec886b3c1740ed | 0 | b2ihealthcare/snow-owl,IHTSDO/snow-owl,IHTSDO/snow-owl,IHTSDO/snow-owl,IHTSDO/snow-owl,b2ihealthcare/snow-owl,b2ihealthcare/snow-owl,b2ihealthcare/snow-owl | /*
* Copyright 2017-2018 B2i Healthcare Pte Ltd, http://b2i.sg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.b2international.index.es.admin;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.Maps.newHashMap;
import static com.google.common.collect.Maps.newHashMapWithExpectedSize;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Pattern;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest.Level;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
import org.elasticsearch.action.admin.indices.refresh.RefreshRequest;
import org.elasticsearch.action.admin.indices.refresh.RefreshResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.RestStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.b2international.commons.CompareUtils;
import com.b2international.commons.ReflectionUtils;
import com.b2international.index.Analyzers;
import com.b2international.index.IndexClientFactory;
import com.b2international.index.IndexException;
import com.b2international.index.Keyword;
import com.b2international.index.Text;
import com.b2international.index.admin.IndexAdmin;
import com.b2international.index.es.EsClient;
import com.b2international.index.mapping.DocumentMapping;
import com.b2international.index.mapping.Mappings;
import com.b2international.index.util.NumericClassUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
import com.google.common.primitives.Primitives;
/**
* @since 5.10
*/
public final class EsIndexAdmin implements IndexAdmin {
private final EsClient client;
private final String name;
private final Mappings mappings;
private final Map<String, Object> settings;
private final ObjectMapper mapper;
private final Logger log;
private final String prefix;
public EsIndexAdmin(EsClient client, String clientUri, String name, Mappings mappings, Map<String, Object> settings, ObjectMapper mapper) {
this.client = client;
this.name = name.toLowerCase();
this.mappings = mappings;
this.settings = newHashMap(settings);
this.mapper = mapper;
this.log = LoggerFactory.getLogger(String.format("index.%s", this.name));
this.settings.putIfAbsent(IndexClientFactory.COMMIT_CONCURRENCY_LEVEL, IndexClientFactory.DEFAULT_COMMIT_CONCURRENCY_LEVEL);
this.settings.putIfAbsent(IndexClientFactory.RESULT_WINDOW_KEY, ""+IndexClientFactory.DEFAULT_RESULT_WINDOW);
this.settings.putIfAbsent(IndexClientFactory.TRANSLOG_SYNC_INTERVAL_KEY, IndexClientFactory.DEFAULT_TRANSLOG_SYNC_INTERVAL);
final String prefix = (String) settings.getOrDefault(IndexClientFactory.INDEX_PREFIX, IndexClientFactory.DEFAULT_INDEX_PREFIX);
this.prefix = prefix.isEmpty() ? "" : prefix + ".";
}
@Override
public Logger log() {
return log;
}
@Override
public boolean exists() {
final String[] indices = getAllIndexes();
final GetIndexRequest getIndexRequest = new GetIndexRequest().indices(indices);
try {
return client().indices().exists(getIndexRequest, RequestOptions.DEFAULT);
} catch (IOException e) {
throw new IndexException("Couldn't check the existence of all ES indices.", e);
}
}
private boolean exists(DocumentMapping mapping) {
final String index = getTypeIndex(mapping);
final GetIndexRequest getIndexRequest = new GetIndexRequest().indices(index);
try {
return client().indices().exists(getIndexRequest, RequestOptions.DEFAULT);
} catch (IOException e) {
throw new IndexException("Couldn't check the existence of ES index '" + index + "'.", e);
}
}
@Override
public void create() {
log.info("Preparing '{}' indexes...", name);
if (!exists()) {
// create number of indexes based on number of types
for (DocumentMapping mapping : mappings.getMappings()) {
if (exists(mapping)) {
continue;
}
final String index = getTypeIndex(mapping);
final String type = mapping.typeAsString();
final Map<String, Object> typeMapping = ImmutableMap.of(type,
ImmutableMap.builder()
.put("date_detection", "false")
.put("numeric_detection", "false")
.putAll(toProperties(mapping))
.build());
final Map<String, Object> indexSettings;
try {
indexSettings = createIndexSettings();
log.info("Configuring '{}' index with settings: {}", index, indexSettings);
} catch (IOException e) {
throw new IndexException("Couldn't prepare settings for index " + index, e);
}
final CreateIndexRequest createIndexRequest = new CreateIndexRequest(index);
createIndexRequest.mapping(type, typeMapping);
createIndexRequest.settings(indexSettings);
try {
final CreateIndexResponse response = client.indices()
.create(createIndexRequest, RequestOptions.DEFAULT);
checkState(response.isAcknowledged(), "Failed to create index '%s' for type '%s'", name, mapping.typeAsString());
} catch (IOException e) {
throw new IndexException(String.format("Failed to create index '%s' for type '%s'", name, mapping.typeAsString()), e);
}
}
}
// wait until the cluster processes each index create request
waitForYellowHealth(getAllIndexes());
log.info("'{}' indexes are ready.", name);
}
private String[] getAllIndexes() {
return mappings.getMappings()
.stream()
.map(this::getTypeIndex)
.distinct()
.toArray(String[]::new);
}
private Map<String, Object> createIndexSettings() throws IOException {
InputStream analysisStream = getClass().getResourceAsStream("analysis.json");
Settings analysisSettings = Settings.builder()
.loadFromStream("analysis.json", analysisStream, true)
.build();
// FIXME: Is XContent a good alternative to a Map? getAsStructureMap is now private
Map<String, Object> analysisMap = ReflectionUtils.callMethod(Settings.class, analysisSettings, "getAsStructuredMap");
return ImmutableMap.<String, Object>builder()
.put("analysis", analysisMap)
.put("number_of_shards", String.valueOf(settings().getOrDefault(IndexClientFactory.NUMBER_OF_SHARDS, "1")))
.put("number_of_replicas", "0")
// disable es refresh, we will do it manually on each commit
.put("refresh_interval", "-1")
.put(IndexClientFactory.RESULT_WINDOW_KEY, settings().get(IndexClientFactory.RESULT_WINDOW_KEY))
.put(IndexClientFactory.TRANSLOG_SYNC_INTERVAL_KEY, settings().get(IndexClientFactory.TRANSLOG_SYNC_INTERVAL_KEY))
.put("translog.durability", "async")
.build();
}
private void waitForYellowHealth(String... indices) {
if (!CompareUtils.isEmpty(indices)) {
/*
* See https://www.elastic.co/guide/en/elasticsearch/reference/6.3/cluster-health.html
* for the low-level structure of the cluster health request.
*/
final Object clusterTimeoutSetting = settings.getOrDefault(IndexClientFactory.CLUSTER_HEALTH_TIMEOUT, IndexClientFactory.DEFAULT_CLUSTER_HEALTH_TIMEOUT);
final Object socketTimeoutSetting = settings.getOrDefault(IndexClientFactory.SOCKET_TIMEOUT, IndexClientFactory.DEFAULT_SOCKET_TIMEOUT);
final int clusterTimeout = clusterTimeoutSetting instanceof Integer ? (int) clusterTimeoutSetting : Integer.parseInt((String) clusterTimeoutSetting);
final int socketTimeout = socketTimeoutSetting instanceof Integer ? (int) socketTimeoutSetting : Integer.parseInt((String) socketTimeoutSetting);
final int pollTimeout = socketTimeout / 2;
final ClusterHealthRequest req = new ClusterHealthRequest(indices)
.waitForYellowStatus() // Wait until yellow status is reached
.timeout(String.format("%sms", pollTimeout)); // Poll interval is half the socket timeout
req.level(Level.INDICES); // Detail level should be concerned with the indices in the path
final long startTime = System.currentTimeMillis();
final long endTime = startTime + clusterTimeout; // Polling finishes when the cluster timeout is reached
long currentTime = startTime;
ClusterHealthResponse response = null;
do {
try {
response = client().cluster().health(req, RequestOptions.DEFAULT);
if (!response.isTimedOut()) {
currentTime = System.currentTimeMillis();
break;
}
} catch (IOException e) {
throw new IndexException("Couldn't retrieve cluster health for index " + name, e);
}
currentTime = System.currentTimeMillis();
} while (currentTime < endTime);
if (response == null || response.isTimedOut()) {
throw new IndexException(String.format("Cluster health did not reach yellow status for '%s' indexes after %s ms.", name, currentTime - startTime), null);
} else {
log.info("Cluster health for '{}' indexes reported as '{}' after {} ms.", name, response.getStatus(), currentTime - startTime);
}
}
}
private Map<String, Object> toProperties(DocumentMapping mapping) {
Map<String, Object> properties = newHashMap();
for (Field field : mapping.getFields()) {
final String property = field.getName();
if (DocumentMapping._ID.equals(property)) continue;
final Class<?> fieldType = NumericClassUtils.unwrapCollectionType(field);
if (Map.class.isAssignableFrom(fieldType)) {
// allow dynamic mappings for dynamic objects like field using Map
final Map<String, Object> prop = newHashMap();
prop.put("type", "object");
prop.put("dynamic", "true");
properties.put(property, prop);
continue;
} else if (mapping.isNestedMapping(fieldType)) {
// this is a nested document type create a nested mapping
final Map<String, Object> prop = newHashMap();
prop.put("type", "nested");
prop.putAll(toProperties(mapping.getNestedMapping(fieldType)));
properties.put(property, prop);
} else {
final Map<String, Object> prop = newHashMap();
if (!mapping.isText(property) && !mapping.isKeyword(property)) {
addFieldProperties(prop, fieldType);
properties.put(property, prop);
} else {
checkState(String.class.isAssignableFrom(fieldType), "Only String fields can have Text and Keyword annotation. Found them on '%s'", property);
final Map<String, Text> textFields = mapping.getTextFields(property);
final Map<String, Keyword> keywordFields = mapping.getKeywordFields(property);
final Text textMapping = textFields.get(property);
final Keyword keywordMapping = keywordFields.get(property);
checkState(textMapping == null || keywordMapping == null, "Cannot declare both Text and Keyword annotation on same field '%s'", property);
if (textMapping != null) {
prop.put("type", "text");
prop.put("analyzer", EsTextAnalysis.getAnalyzer(textMapping.analyzer()));
if (textMapping.searchAnalyzer() != Analyzers.INDEX) {
prop.put("search_analyzer", EsTextAnalysis.getAnalyzer(textMapping.searchAnalyzer()));
}
}
if (keywordMapping != null) {
prop.put("type", "keyword");
String normalizer = EsTextAnalysis.getNormalizer(keywordMapping.normalizer());
if (!Strings.isNullOrEmpty(normalizer)) {
prop.put("normalizer", normalizer);
}
prop.put("index", keywordMapping.index());
prop.put("doc_values", keywordMapping.index());
}
// put extra text fields into fields object
final Map<String, Object> fields = newHashMapWithExpectedSize(textFields.size() + keywordFields.size());
for (Entry<String, Text> analyzer : textFields.entrySet()) {
final String extraField = analyzer.getKey();
final String[] extraFieldParts = extraField.split(Pattern.quote(DocumentMapping.DELIMITER));
if (extraFieldParts.length > 1) {
final Text analyzed = analyzer.getValue();
final Map<String, Object> fieldProps = newHashMap();
fieldProps.put("type", "text");
fieldProps.put("analyzer", EsTextAnalysis.getAnalyzer(analyzed.analyzer()));
if (analyzed.searchAnalyzer() != Analyzers.INDEX) {
fieldProps.put("search_analyzer", EsTextAnalysis.getAnalyzer(analyzed.searchAnalyzer()));
}
fields.put(extraFieldParts[1], fieldProps);
}
}
// put extra keyword fields into fields object
for (Entry<String, Keyword> analyzer : keywordFields.entrySet()) {
final String extraField = analyzer.getKey();
final String[] extraFieldParts = extraField.split(Pattern.quote(DocumentMapping.DELIMITER));
if (extraFieldParts.length > 1) {
final Keyword analyzed = analyzer.getValue();
final Map<String, Object> fieldProps = newHashMap();
fieldProps.put("type", "keyword");
String normalizer = EsTextAnalysis.getNormalizer(analyzed.normalizer());
if (!Strings.isNullOrEmpty(normalizer)) {
fieldProps.put("normalizer", normalizer);
}
fieldProps.put("index", analyzed.index());
fields.put(extraFieldParts[1], fieldProps);
}
}
if (!fields.isEmpty()) {
prop.put("fields", fields);
}
properties.put(property, prop);
}
}
}
// Add system field "_hash", if there is at least a single field to hash
if (!mapping.getHashedFields().isEmpty()) {
final Map<String, Object> prop = newHashMap();
prop.put("type", "keyword");
prop.put("index", false);
properties.put(DocumentMapping._HASH, prop);
}
return ImmutableMap.of("properties", properties);
}
private void addFieldProperties(Map<String, Object> fieldProperties, Class<?> fieldType) {
if (Enum.class.isAssignableFrom(fieldType) || NumericClassUtils.isBigDecimal(fieldType) || String.class.isAssignableFrom(fieldType)) {
fieldProperties.put("type", "keyword");
} else if (NumericClassUtils.isFloat(fieldType)) {
fieldProperties.put("type", "float");
} else if (NumericClassUtils.isInt(fieldType)) {
fieldProperties.put("type", "integer");
} else if (NumericClassUtils.isShort(fieldType)) {
fieldProperties.put("type", "short");
} else if (NumericClassUtils.isDate(fieldType) || NumericClassUtils.isLong(fieldType)) {
fieldProperties.put("type", "long");
} else if (Boolean.class.isAssignableFrom(Primitives.wrap(fieldType))) {
fieldProperties.put("type", "boolean");
} else {
// Any other type will result in a sub-object that only appears in _source
fieldProperties.put("type", "object");
fieldProperties.put("enabled", false);
}
}
@Override
public void delete() {
if (exists()) {
final DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(name + "*");
try {
final DeleteIndexResponse deleteIndexResponse = client()
.indices()
.delete(deleteIndexRequest, RequestOptions.DEFAULT);
checkState(deleteIndexResponse.isAcknowledged(), "Failed to delete all ES indices for '%s'.", name);
} catch (IOException e) {
throw new IndexException(String.format("Failed to delete all ES indices for '%s'.", name), e);
}
}
}
@Override
public <T> void clear(Class<T> type) {
// TODO remove all documents matching the given type, based on mappings
}
@Override
public Map<String, Object> settings() {
return settings;
}
@Override
public Mappings mappings() {
return mappings;
}
@Override
public String name() {
return name;
}
@Override
public void close() {}
@Override
public void optimize(int maxSegments) {
// client().admin().indices().prepareForceMerge(name).setMaxNumSegments(maxSegments).get();
// waitForYellowHealth();
}
public String getTypeIndex(DocumentMapping mapping) {
if (mapping.getParent() != null) {
return String.format("%s%s-%s", prefix, name, mapping.getParent().typeAsString());
} else {
return String.format("%s%s-%s", prefix, name, mapping.typeAsString());
}
}
public EsClient client() {
return client;
}
public void refresh(Set<DocumentMapping> typesToRefresh) {
if (!CompareUtils.isEmpty(typesToRefresh)) {
final String[] indicesToRefresh;
synchronized (typesToRefresh) {
indicesToRefresh = typesToRefresh.stream()
.map(this::getTypeIndex)
.distinct()
.toArray(String[]::new);
}
if (log.isTraceEnabled()) {
log.trace("Refreshing indexes '{}'", Arrays.toString(indicesToRefresh));
}
try {
final RefreshRequest refreshRequest = new RefreshRequest(indicesToRefresh);
final RefreshResponse refreshResponse = client()
.indices()
.refresh(refreshRequest, RequestOptions.DEFAULT);
if (RestStatus.OK != refreshResponse.getStatus() && log.isErrorEnabled()) {
log.error("Index refresh request of '{}' returned with status {}", Joiner.on(", ").join(indicesToRefresh), refreshResponse.getStatus());
}
} catch (IOException e) {
throw new IndexException(String.format("Failed to refresh ES indexes '%s'.", Arrays.toString(indicesToRefresh)), e);
}
}
}
}
| commons/com.b2international.index/src/com/b2international/index/es/admin/EsIndexAdmin.java | /*
* Copyright 2017-2018 B2i Healthcare Pte Ltd, http://b2i.sg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.b2international.index.es.admin;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.Maps.newHashMap;
import static com.google.common.collect.Maps.newHashMapWithExpectedSize;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Pattern;
import org.apache.http.client.methods.HttpGet;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
import org.elasticsearch.action.admin.indices.refresh.RefreshRequest;
import org.elasticsearch.action.admin.indices.refresh.RefreshResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.Response;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.RestStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.b2international.commons.CompareUtils;
import com.b2international.commons.ReflectionUtils;
import com.b2international.index.Analyzers;
import com.b2international.index.IndexClientFactory;
import com.b2international.index.IndexException;
import com.b2international.index.Keyword;
import com.b2international.index.Text;
import com.b2international.index.admin.IndexAdmin;
import com.b2international.index.es.EsClient;
import com.b2international.index.mapping.DocumentMapping;
import com.b2international.index.mapping.Mappings;
import com.b2international.index.util.NumericClassUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
import com.google.common.primitives.Primitives;
/**
* @since 5.10
*/
public final class EsIndexAdmin implements IndexAdmin {
private final EsClient client;
private final String name;
private final Mappings mappings;
private final Map<String, Object> settings;
private final ObjectMapper mapper;
private final Logger log;
private final String prefix;
public EsIndexAdmin(EsClient client, String clientUri, String name, Mappings mappings, Map<String, Object> settings, ObjectMapper mapper) {
this.client = client;
this.name = name.toLowerCase();
this.mappings = mappings;
this.settings = newHashMap(settings);
this.mapper = mapper;
this.log = LoggerFactory.getLogger(String.format("index.%s", this.name));
this.settings.putIfAbsent(IndexClientFactory.COMMIT_CONCURRENCY_LEVEL, IndexClientFactory.DEFAULT_COMMIT_CONCURRENCY_LEVEL);
this.settings.putIfAbsent(IndexClientFactory.RESULT_WINDOW_KEY, ""+IndexClientFactory.DEFAULT_RESULT_WINDOW);
this.settings.putIfAbsent(IndexClientFactory.TRANSLOG_SYNC_INTERVAL_KEY, IndexClientFactory.DEFAULT_TRANSLOG_SYNC_INTERVAL);
final String prefix = (String) settings.getOrDefault(IndexClientFactory.INDEX_PREFIX, IndexClientFactory.DEFAULT_INDEX_PREFIX);
this.prefix = prefix.isEmpty() ? "" : prefix + ".";
}
@Override
public Logger log() {
return log;
}
@Override
public boolean exists() {
final String[] indices = getAllIndexes();
final GetIndexRequest getIndexRequest = new GetIndexRequest().indices(indices);
try {
return client().indices().exists(getIndexRequest, RequestOptions.DEFAULT);
} catch (IOException e) {
throw new IndexException("Couldn't check the existence of all ES indices.", e);
}
}
private boolean exists(DocumentMapping mapping) {
final String index = getTypeIndex(mapping);
final GetIndexRequest getIndexRequest = new GetIndexRequest().indices(index);
try {
return client().indices().exists(getIndexRequest, RequestOptions.DEFAULT);
} catch (IOException e) {
throw new IndexException("Couldn't check the existence of ES index '" + index + "'.", e);
}
}
@Override
public void create() {
log.info("Preparing '{}' indexes...", name);
if (!exists()) {
// create number of indexes based on number of types
for (DocumentMapping mapping : mappings.getMappings()) {
if (exists(mapping)) {
continue;
}
final String index = getTypeIndex(mapping);
final String type = mapping.typeAsString();
final Map<String, Object> typeMapping = ImmutableMap.of(type,
ImmutableMap.builder()
.put("date_detection", "false")
.put("numeric_detection", "false")
.putAll(toProperties(mapping))
.build());
final Map<String, Object> indexSettings;
try {
indexSettings = createIndexSettings();
log.info("Configuring '{}' index with settings: {}", index, indexSettings);
} catch (IOException e) {
throw new IndexException("Couldn't prepare settings for index " + index, e);
}
final CreateIndexRequest createIndexRequest = new CreateIndexRequest(index);
createIndexRequest.mapping(type, typeMapping);
createIndexRequest.settings(indexSettings);
try {
final CreateIndexResponse response = client.indices()
.create(createIndexRequest, RequestOptions.DEFAULT);
checkState(response.isAcknowledged(), "Failed to create index '%s' for type '%s'", name, mapping.typeAsString());
} catch (IOException e) {
throw new IndexException(String.format("Failed to create index '%s' for type '%s'", name, mapping.typeAsString()), e);
}
}
}
// wait until the cluster processes each index create request
waitForYellowHealth(getAllIndexes());
log.info("'{}' indexes are ready.", name);
}
private String[] getAllIndexes() {
return mappings.getMappings()
.stream()
.map(this::getTypeIndex)
.distinct()
.toArray(String[]::new);
}
private Map<String, Object> createIndexSettings() throws IOException {
InputStream analysisStream = getClass().getResourceAsStream("analysis.json");
Settings analysisSettings = Settings.builder()
.loadFromStream("analysis.json", analysisStream, true)
.build();
// FIXME: Is XContent a good alternative to a Map? getAsStructureMap is now private
Map<String, Object> analysisMap = ReflectionUtils.callMethod(Settings.class, analysisSettings, "getAsStructuredMap");
return ImmutableMap.<String, Object>builder()
.put("analysis", analysisMap)
.put("number_of_shards", String.valueOf(settings().getOrDefault(IndexClientFactory.NUMBER_OF_SHARDS, "1")))
.put("number_of_replicas", "0")
// disable es refresh, we will do it manually on each commit
.put("refresh_interval", "-1")
.put(IndexClientFactory.RESULT_WINDOW_KEY, settings().get(IndexClientFactory.RESULT_WINDOW_KEY))
.put(IndexClientFactory.TRANSLOG_SYNC_INTERVAL_KEY, settings().get(IndexClientFactory.TRANSLOG_SYNC_INTERVAL_KEY))
.put("translog.durability", "async")
.build();
}
private void waitForYellowHealth(String... indices) {
if (!CompareUtils.isEmpty(indices)) {
/*
* See https://www.elastic.co/guide/en/elasticsearch/reference/6.3/cluster-health.html
* for the low-level structure of the cluster health request.
*/
final Object clusterTimeoutSetting = settings.getOrDefault(IndexClientFactory.CLUSTER_HEALTH_TIMEOUT, IndexClientFactory.DEFAULT_CLUSTER_HEALTH_TIMEOUT);
final Object socketTimeoutSetting = settings.getOrDefault(IndexClientFactory.SOCKET_TIMEOUT, IndexClientFactory.DEFAULT_SOCKET_TIMEOUT);
final int clusterTimeout = clusterTimeoutSetting instanceof Integer ? (int) clusterTimeoutSetting : Integer.parseInt((String) clusterTimeoutSetting);
final int socketTimeout = socketTimeoutSetting instanceof Integer ? (int) socketTimeoutSetting : Integer.parseInt((String) socketTimeoutSetting);
final int pollTimeout = socketTimeout / 2;
// GET /_cluster/health/test1,test2
final String endpoint = new EsClient.EndpointBuilder()
.addPathPartAsIs("_cluster")
.addPathPartAsIs("health")
.addCommaSeparatedPathParts(indices)
.build();
// https://www.elastic.co/guide/en/elasticsearch/reference/6.3/cluster-health.html#request-params
final Map<String, String> parameters = ImmutableMap.<String, String>builder()
.put("level", "indices") // Detail level should be concerned with the indices in the path
.put("wait_for_status", "yellow") // Wait until yellow status is reached
.put("timeout", String.format("%sms", pollTimeout)) // Poll interval is half the socket timeout
.put("ignore", "408") // This parameter is not sent to ES; it makes server 408 responses not throw an exception
.build();
final long startTime = System.currentTimeMillis();
final long endTime = startTime + clusterTimeout; // Polling finishes when the cluster timeout is reached
long currentTime = startTime;
JsonNode responseNode = null;
do {
try {
final Response clusterHealthResponse = client().getLowLevelClient()
.performRequest(HttpGet.METHOD_NAME, endpoint, parameters);
final InputStream responseStream = clusterHealthResponse.getEntity()
.getContent();
responseNode = mapper.readTree(responseStream);
if (!responseNode.get("timed_out").asBoolean()) {
currentTime = System.currentTimeMillis();
break;
}
} catch (IOException e) {
throw new IndexException("Couldn't retrieve cluster health for index " + name, e);
}
currentTime = System.currentTimeMillis();
} while (currentTime < endTime);
if (responseNode == null || responseNode.get("timed_out").asBoolean()) {
throw new IndexException(String.format("Cluster health did not reach yellow status for '%s' indexes after %s ms.", name, currentTime - startTime), null);
} else {
log.info("Cluster health for '{}' indexes reported as '{}' after {} ms.", name, responseNode.get("status").asText(), currentTime - startTime);
}
}
}
private Map<String, Object> toProperties(DocumentMapping mapping) {
Map<String, Object> properties = newHashMap();
for (Field field : mapping.getFields()) {
final String property = field.getName();
if (DocumentMapping._ID.equals(property)) continue;
final Class<?> fieldType = NumericClassUtils.unwrapCollectionType(field);
if (Map.class.isAssignableFrom(fieldType)) {
// allow dynamic mappings for dynamic objects like field using Map
final Map<String, Object> prop = newHashMap();
prop.put("type", "object");
prop.put("dynamic", "true");
properties.put(property, prop);
continue;
} else if (mapping.isNestedMapping(fieldType)) {
// this is a nested document type create a nested mapping
final Map<String, Object> prop = newHashMap();
prop.put("type", "nested");
prop.putAll(toProperties(mapping.getNestedMapping(fieldType)));
properties.put(property, prop);
} else {
final Map<String, Object> prop = newHashMap();
if (!mapping.isText(property) && !mapping.isKeyword(property)) {
addFieldProperties(prop, fieldType);
properties.put(property, prop);
} else {
checkState(String.class.isAssignableFrom(fieldType), "Only String fields can have Text and Keyword annotation. Found them on '%s'", property);
final Map<String, Text> textFields = mapping.getTextFields(property);
final Map<String, Keyword> keywordFields = mapping.getKeywordFields(property);
final Text textMapping = textFields.get(property);
final Keyword keywordMapping = keywordFields.get(property);
checkState(textMapping == null || keywordMapping == null, "Cannot declare both Text and Keyword annotation on same field '%s'", property);
if (textMapping != null) {
prop.put("type", "text");
prop.put("analyzer", EsTextAnalysis.getAnalyzer(textMapping.analyzer()));
if (textMapping.searchAnalyzer() != Analyzers.INDEX) {
prop.put("search_analyzer", EsTextAnalysis.getAnalyzer(textMapping.searchAnalyzer()));
}
}
if (keywordMapping != null) {
prop.put("type", "keyword");
String normalizer = EsTextAnalysis.getNormalizer(keywordMapping.normalizer());
if (!Strings.isNullOrEmpty(normalizer)) {
prop.put("normalizer", normalizer);
}
prop.put("index", keywordMapping.index());
prop.put("doc_values", keywordMapping.index());
}
// put extra text fields into fields object
final Map<String, Object> fields = newHashMapWithExpectedSize(textFields.size() + keywordFields.size());
for (Entry<String, Text> analyzer : textFields.entrySet()) {
final String extraField = analyzer.getKey();
final String[] extraFieldParts = extraField.split(Pattern.quote(DocumentMapping.DELIMITER));
if (extraFieldParts.length > 1) {
final Text analyzed = analyzer.getValue();
final Map<String, Object> fieldProps = newHashMap();
fieldProps.put("type", "text");
fieldProps.put("analyzer", EsTextAnalysis.getAnalyzer(analyzed.analyzer()));
if (analyzed.searchAnalyzer() != Analyzers.INDEX) {
fieldProps.put("search_analyzer", EsTextAnalysis.getAnalyzer(analyzed.searchAnalyzer()));
}
fields.put(extraFieldParts[1], fieldProps);
}
}
// put extra keyword fields into fields object
for (Entry<String, Keyword> analyzer : keywordFields.entrySet()) {
final String extraField = analyzer.getKey();
final String[] extraFieldParts = extraField.split(Pattern.quote(DocumentMapping.DELIMITER));
if (extraFieldParts.length > 1) {
final Keyword analyzed = analyzer.getValue();
final Map<String, Object> fieldProps = newHashMap();
fieldProps.put("type", "keyword");
String normalizer = EsTextAnalysis.getNormalizer(analyzed.normalizer());
if (!Strings.isNullOrEmpty(normalizer)) {
fieldProps.put("normalizer", normalizer);
}
fieldProps.put("index", analyzed.index());
fields.put(extraFieldParts[1], fieldProps);
}
}
if (!fields.isEmpty()) {
prop.put("fields", fields);
}
properties.put(property, prop);
}
}
}
// Add system field "_hash", if there is at least a single field to hash
if (!mapping.getHashedFields().isEmpty()) {
final Map<String, Object> prop = newHashMap();
prop.put("type", "keyword");
prop.put("index", false);
properties.put(DocumentMapping._HASH, prop);
}
return ImmutableMap.of("properties", properties);
}
private void addFieldProperties(Map<String, Object> fieldProperties, Class<?> fieldType) {
if (Enum.class.isAssignableFrom(fieldType) || NumericClassUtils.isBigDecimal(fieldType) || String.class.isAssignableFrom(fieldType)) {
fieldProperties.put("type", "keyword");
} else if (NumericClassUtils.isFloat(fieldType)) {
fieldProperties.put("type", "float");
} else if (NumericClassUtils.isInt(fieldType)) {
fieldProperties.put("type", "integer");
} else if (NumericClassUtils.isShort(fieldType)) {
fieldProperties.put("type", "short");
} else if (NumericClassUtils.isDate(fieldType) || NumericClassUtils.isLong(fieldType)) {
fieldProperties.put("type", "long");
} else if (Boolean.class.isAssignableFrom(Primitives.wrap(fieldType))) {
fieldProperties.put("type", "boolean");
} else {
// Any other type will result in a sub-object that only appears in _source
fieldProperties.put("type", "object");
fieldProperties.put("enabled", false);
}
}
@Override
public void delete() {
if (exists()) {
final DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(name + "*");
try {
final DeleteIndexResponse deleteIndexResponse = client()
.indices()
.delete(deleteIndexRequest, RequestOptions.DEFAULT);
checkState(deleteIndexResponse.isAcknowledged(), "Failed to delete all ES indices for '%s'.", name);
} catch (IOException e) {
throw new IndexException(String.format("Failed to delete all ES indices for '%s'.", name), e);
}
}
}
@Override
public <T> void clear(Class<T> type) {
// TODO remove all documents matching the given type, based on mappings
}
@Override
public Map<String, Object> settings() {
return settings;
}
@Override
public Mappings mappings() {
return mappings;
}
@Override
public String name() {
return name;
}
@Override
public void close() {}
@Override
public void optimize(int maxSegments) {
// client().admin().indices().prepareForceMerge(name).setMaxNumSegments(maxSegments).get();
// waitForYellowHealth();
}
public String getTypeIndex(DocumentMapping mapping) {
if (mapping.getParent() != null) {
return String.format("%s%s-%s", prefix, name, mapping.getParent().typeAsString());
} else {
return String.format("%s%s-%s", prefix, name, mapping.typeAsString());
}
}
public EsClient client() {
return client;
}
public void refresh(Set<DocumentMapping> typesToRefresh) {
if (!CompareUtils.isEmpty(typesToRefresh)) {
final String[] indicesToRefresh;
synchronized (typesToRefresh) {
indicesToRefresh = typesToRefresh.stream()
.map(this::getTypeIndex)
.distinct()
.toArray(String[]::new);
}
if (log.isTraceEnabled()) {
log.trace("Refreshing indexes '{}'", Arrays.toString(indicesToRefresh));
}
try {
final RefreshRequest refreshRequest = new RefreshRequest(indicesToRefresh);
final RefreshResponse refreshResponse = client()
.indices()
.refresh(refreshRequest, RequestOptions.DEFAULT);
if (RestStatus.OK != refreshResponse.getStatus() && log.isErrorEnabled()) {
log.error("Index refresh request of '{}' returned with status {}", Joiner.on(", ").join(indicesToRefresh), refreshResponse.getStatus());
}
} catch (IOException e) {
throw new IndexException(String.format("Failed to refresh ES indexes '%s'.", Arrays.toString(indicesToRefresh)), e);
}
}
}
}
| [index] use Cluster Health API classes in...
...EsIndexAdmin.waitForYellowHealth(String...indices) | commons/com.b2international.index/src/com/b2international/index/es/admin/EsIndexAdmin.java | [index] use Cluster Health API classes in... | <ide><path>ommons/com.b2international.index/src/com/b2international/index/es/admin/EsIndexAdmin.java
<ide> import java.util.Set;
<ide> import java.util.regex.Pattern;
<ide>
<del>import org.apache.http.client.methods.HttpGet;
<add>import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest;
<add>import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest.Level;
<add>import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
<ide> import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
<ide> import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
<ide> import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
<ide> import org.elasticsearch.action.admin.indices.refresh.RefreshRequest;
<ide> import org.elasticsearch.action.admin.indices.refresh.RefreshResponse;
<ide> import org.elasticsearch.client.RequestOptions;
<del>import org.elasticsearch.client.Response;
<ide> import org.elasticsearch.common.Strings;
<ide> import org.elasticsearch.common.settings.Settings;
<ide> import org.elasticsearch.rest.RestStatus;
<ide> import com.b2international.index.mapping.DocumentMapping;
<ide> import com.b2international.index.mapping.Mappings;
<ide> import com.b2international.index.util.NumericClassUtils;
<del>import com.fasterxml.jackson.databind.JsonNode;
<ide> import com.fasterxml.jackson.databind.ObjectMapper;
<ide> import com.google.common.base.Joiner;
<ide> import com.google.common.collect.ImmutableMap;
<ide> final int socketTimeout = socketTimeoutSetting instanceof Integer ? (int) socketTimeoutSetting : Integer.parseInt((String) socketTimeoutSetting);
<ide> final int pollTimeout = socketTimeout / 2;
<ide>
<del> // GET /_cluster/health/test1,test2
<del> final String endpoint = new EsClient.EndpointBuilder()
<del> .addPathPartAsIs("_cluster")
<del> .addPathPartAsIs("health")
<del> .addCommaSeparatedPathParts(indices)
<del> .build();
<del>
<del> // https://www.elastic.co/guide/en/elasticsearch/reference/6.3/cluster-health.html#request-params
<del> final Map<String, String> parameters = ImmutableMap.<String, String>builder()
<del> .put("level", "indices") // Detail level should be concerned with the indices in the path
<del> .put("wait_for_status", "yellow") // Wait until yellow status is reached
<del> .put("timeout", String.format("%sms", pollTimeout)) // Poll interval is half the socket timeout
<del> .put("ignore", "408") // This parameter is not sent to ES; it makes server 408 responses not throw an exception
<del> .build();
<del>
<add> final ClusterHealthRequest req = new ClusterHealthRequest(indices)
<add> .waitForYellowStatus() // Wait until yellow status is reached
<add> .timeout(String.format("%sms", pollTimeout)); // Poll interval is half the socket timeout
<add> req.level(Level.INDICES); // Detail level should be concerned with the indices in the path
<add>
<ide> final long startTime = System.currentTimeMillis();
<ide> final long endTime = startTime + clusterTimeout; // Polling finishes when the cluster timeout is reached
<del> long currentTime = startTime;
<del> JsonNode responseNode = null;
<add> long currentTime = startTime;
<add>
<add> ClusterHealthResponse response = null;
<ide>
<ide> do {
<ide>
<ide> try {
<ide>
<del> final Response clusterHealthResponse = client().getLowLevelClient()
<del> .performRequest(HttpGet.METHOD_NAME, endpoint, parameters);
<del> final InputStream responseStream = clusterHealthResponse.getEntity()
<del> .getContent();
<del> responseNode = mapper.readTree(responseStream);
<del>
<del> if (!responseNode.get("timed_out").asBoolean()) {
<add> response = client().cluster().health(req, RequestOptions.DEFAULT);
<add>
<add> if (!response.isTimedOut()) {
<ide> currentTime = System.currentTimeMillis();
<ide> break;
<ide> }
<ide>
<ide> } while (currentTime < endTime);
<ide>
<del> if (responseNode == null || responseNode.get("timed_out").asBoolean()) {
<add> if (response == null || response.isTimedOut()) {
<ide> throw new IndexException(String.format("Cluster health did not reach yellow status for '%s' indexes after %s ms.", name, currentTime - startTime), null);
<ide> } else {
<del> log.info("Cluster health for '{}' indexes reported as '{}' after {} ms.", name, responseNode.get("status").asText(), currentTime - startTime);
<add> log.info("Cluster health for '{}' indexes reported as '{}' after {} ms.", name, response.getStatus(), currentTime - startTime);
<ide> }
<ide> }
<ide> } |
|
JavaScript | mit | 4170b69f030e3b6d96c0a782041d242a0d0a102b | 0 | hpchud/vccjs,hpchud/vccjs | var logger = require("./log.js");
var fs = require('fs');
var path = require('path');
var yaml = require('yamljs');
var promise = require("deferred");
var notify = require('systemd-notify');
exports.systemdNotify = function (status, ready) {
var deferred = promise();
var config = exports.getConfig();
if (config.systemd) {
notify({
ready: ready,
status: status
},
function(err) {
if (err) {
deferred.reject(err);
} else {
deferred.resolve();
}
}
);
}
return deferred.promise;
}
exports.getRunDir = function () {
// the run dir where we can find init.yml is in env VCC_RUN_DIR
var run_dir = process.env['VCC_RUN_DIR'];
if (!run_dir) {
logger.warn('No environment variable VCC_RUN_DIR.... assuming /run');
run_dir = '/run';
}
return run_dir;
}
exports.getConfig = function (full, run_dir) {
if (!run_dir) {
var run_dir = exports.getRunDir();
}
return yaml.load(path.join(run_dir, 'cluster.yml'));
}
exports.writeConfig = function (newconfig) {
var deferred = promise();
var run_dir = exports.getRunDir();
fs.writeFile(path.join(run_dir, 'cluster.yml'), yaml.stringify(newconfig), function (err) {
if (err) {
deferred.reject(err);
}
deferred.resolve();
});
return deferred.promise;
}
| vccutil.js | var logger = require("./log.js");
var fs = require('fs');
var path = require('path');
var yaml = require('yamljs');
var promise = require("deferred");
var notify = require('systemd-notify');
exports.systemdNotify = function (status, ready) {
var deferred = promise();
var config = exports.getConfig();
if (config.systemd) {
notify({
ready: ready,
status: status,
pid: process.pid
},
function(err) {
if (err) {
deferred.reject(err);
} else {
deferred.resolve();
}
}
);
}
return deferred.promise;
}
exports.getRunDir = function () {
// the run dir where we can find init.yml is in env VCC_RUN_DIR
var run_dir = process.env['VCC_RUN_DIR'];
if (!run_dir) {
logger.warn('No environment variable VCC_RUN_DIR.... assuming /run');
run_dir = '/run';
}
return run_dir;
}
exports.getConfig = function (full, run_dir) {
if (!run_dir) {
var run_dir = exports.getRunDir();
}
return yaml.load(path.join(run_dir, 'cluster.yml'));
}
exports.writeConfig = function (newconfig) {
var deferred = promise();
var run_dir = exports.getRunDir();
fs.writeFile(path.join(run_dir, 'cluster.yml'), yaml.stringify(newconfig), function (err) {
if (err) {
deferred.reject(err);
}
deferred.resolve();
});
return deferred.promise;
} | dont send pid with status notification, systemd will work it out #7
| vccutil.js | dont send pid with status notification, systemd will work it out #7 | <ide><path>ccutil.js
<ide> if (config.systemd) {
<ide> notify({
<ide> ready: ready,
<del> status: status,
<del> pid: process.pid
<add> status: status
<ide> },
<ide> function(err) {
<ide> if (err) { |
|
Java | mit | 63886be9f75c6f538b9401d9cb445b701b1f017c | 0 | patbos/jenkins,protazy/jenkins,oleg-nenashev/jenkins,SebastienGllmt/jenkins,vjuranek/jenkins,DanielWeber/jenkins,damianszczepanik/jenkins,batmat/jenkins,patbos/jenkins,rlugojr/jenkins,SebastienGllmt/jenkins,ErikVerheul/jenkins,jenkinsci/jenkins,amuniz/jenkins,rsandell/jenkins,recena/jenkins,dennisjlee/jenkins,sathiya-mit/jenkins,pjanouse/jenkins,tfennelly/jenkins,christ66/jenkins,bkmeneguello/jenkins,hplatou/jenkins,vjuranek/jenkins,ydubreuil/jenkins,NehemiahMi/jenkins,daniel-beck/jenkins,ikedam/jenkins,patbos/jenkins,samatdav/jenkins,alvarolobato/jenkins,Ykus/jenkins,escoem/jenkins,ajshastri/jenkins,olivergondza/jenkins,jenkinsci/jenkins,Ykus/jenkins,amuniz/jenkins,MichaelPranovich/jenkins_sc,Jochen-A-Fuerbacher/jenkins,tangkun75/jenkins,rlugojr/jenkins,ajshastri/jenkins,kohsuke/hudson,Ykus/jenkins,protazy/jenkins,stephenc/jenkins,rlugojr/jenkins,daniel-beck/jenkins,jenkinsci/jenkins,pjanouse/jenkins,daniel-beck/jenkins,lilyJi/jenkins,andresrc/jenkins,gitaccountforprashant/gittest,varmenise/jenkins,dariver/jenkins,tfennelly/jenkins,ikedam/jenkins,damianszczepanik/jenkins,ikedam/jenkins,MichaelPranovich/jenkins_sc,rsandell/jenkins,ErikVerheul/jenkins,tfennelly/jenkins,FarmGeek4Life/jenkins,andresrc/jenkins,alvarolobato/jenkins,escoem/jenkins,christ66/jenkins,dariver/jenkins,ndeloof/jenkins,daniel-beck/jenkins,oleg-nenashev/jenkins,pjanouse/jenkins,pjanouse/jenkins,MarkEWaite/jenkins,hplatou/jenkins,bpzhang/jenkins,bkmeneguello/jenkins,gitaccountforprashant/gittest,NehemiahMi/jenkins,ErikVerheul/jenkins,stephenc/jenkins,sathiya-mit/jenkins,godfath3r/jenkins,olivergondza/jenkins,rsandell/jenkins,Vlatombe/jenkins,vjuranek/jenkins,jenkinsci/jenkins,FarmGeek4Life/jenkins,gitaccountforprashant/gittest,batmat/jenkins,bpzhang/jenkins,Vlatombe/jenkins,v1v/jenkins,christ66/jenkins,pjanouse/jenkins,gitaccountforprashant/gittest,sathiya-mit/jenkins,DanielWeber/jenkins,dariver/jenkins,NehemiahMi/jenkins,ikedam/jenkins,viqueen/jenkins,varmenise/jenkins,dennisjlee/jenkins,christ66/jenkins,varmenise/jenkins,daniel-beck/jenkins,varmenise/jenkins,olivergondza/jenkins,jpbriend/jenkins,azweb76/jenkins,Jimilian/jenkins,damianszczepanik/jenkins,samatdav/jenkins,andresrc/jenkins,kohsuke/hudson,azweb76/jenkins,rsandell/jenkins,Jimilian/jenkins,lilyJi/jenkins,amuniz/jenkins,dariver/jenkins,oleg-nenashev/jenkins,oleg-nenashev/jenkins,jglick/jenkins,bkmeneguello/jenkins,ErikVerheul/jenkins,Ykus/jenkins,evernat/jenkins,stephenc/jenkins,damianszczepanik/jenkins,ndeloof/jenkins,vjuranek/jenkins,christ66/jenkins,rlugojr/jenkins,escoem/jenkins,dennisjlee/jenkins,FarmGeek4Life/jenkins,evernat/jenkins,ajshastri/jenkins,godfath3r/jenkins,Jochen-A-Fuerbacher/jenkins,Jimilian/jenkins,bpzhang/jenkins,wuwen5/jenkins,batmat/jenkins,gitaccountforprashant/gittest,DanielWeber/jenkins,alvarolobato/jenkins,rsandell/jenkins,ajshastri/jenkins,FarmGeek4Life/jenkins,NehemiahMi/jenkins,NehemiahMi/jenkins,DanielWeber/jenkins,ndeloof/jenkins,tfennelly/jenkins,v1v/jenkins,SebastienGllmt/jenkins,andresrc/jenkins,aldaris/jenkins,kohsuke/hudson,samatdav/jenkins,DanielWeber/jenkins,godfath3r/jenkins,wuwen5/jenkins,dariver/jenkins,bkmeneguello/jenkins,jglick/jenkins,jenkinsci/jenkins,dariver/jenkins,tangkun75/jenkins,ikedam/jenkins,damianszczepanik/jenkins,tangkun75/jenkins,godfath3r/jenkins,v1v/jenkins,wuwen5/jenkins,hplatou/jenkins,damianszczepanik/jenkins,escoem/jenkins,stephenc/jenkins,MichaelPranovich/jenkins_sc,sathiya-mit/jenkins,Jimilian/jenkins,damianszczepanik/jenkins,christ66/jenkins,recena/jenkins,olivergondza/jenkins,samatdav/jenkins,vjuranek/jenkins,kohsuke/hudson,jglick/jenkins,lilyJi/jenkins,SebastienGllmt/jenkins,Jochen-A-Fuerbacher/jenkins,vjuranek/jenkins,escoem/jenkins,aldaris/jenkins,Jimilian/jenkins,recena/jenkins,batmat/jenkins,godfath3r/jenkins,viqueen/jenkins,varmenise/jenkins,jglick/jenkins,varmenise/jenkins,samatdav/jenkins,ydubreuil/jenkins,Ykus/jenkins,rsandell/jenkins,hplatou/jenkins,alvarolobato/jenkins,ydubreuil/jenkins,jenkinsci/jenkins,stephenc/jenkins,protazy/jenkins,oleg-nenashev/jenkins,jpbriend/jenkins,Vlatombe/jenkins,recena/jenkins,viqueen/jenkins,olivergondza/jenkins,DanielWeber/jenkins,hplatou/jenkins,protazy/jenkins,dennisjlee/jenkins,samatdav/jenkins,lilyJi/jenkins,protazy/jenkins,recena/jenkins,SebastienGllmt/jenkins,rsandell/jenkins,tangkun75/jenkins,tfennelly/jenkins,ErikVerheul/jenkins,NehemiahMi/jenkins,Vlatombe/jenkins,fbelzunc/jenkins,v1v/jenkins,alvarolobato/jenkins,recena/jenkins,patbos/jenkins,dennisjlee/jenkins,amuniz/jenkins,viqueen/jenkins,ajshastri/jenkins,Vlatombe/jenkins,ydubreuil/jenkins,ydubreuil/jenkins,amuniz/jenkins,batmat/jenkins,stephenc/jenkins,v1v/jenkins,jglick/jenkins,MichaelPranovich/jenkins_sc,evernat/jenkins,batmat/jenkins,bkmeneguello/jenkins,patbos/jenkins,alvarolobato/jenkins,Jochen-A-Fuerbacher/jenkins,DanielWeber/jenkins,dariver/jenkins,MichaelPranovich/jenkins_sc,azweb76/jenkins,ErikVerheul/jenkins,olivergondza/jenkins,jpbriend/jenkins,kohsuke/hudson,escoem/jenkins,aldaris/jenkins,samatdav/jenkins,vjuranek/jenkins,bpzhang/jenkins,Jimilian/jenkins,bkmeneguello/jenkins,viqueen/jenkins,wuwen5/jenkins,jpbriend/jenkins,FarmGeek4Life/jenkins,ikedam/jenkins,MarkEWaite/jenkins,ndeloof/jenkins,azweb76/jenkins,azweb76/jenkins,fbelzunc/jenkins,Ykus/jenkins,MichaelPranovich/jenkins_sc,jglick/jenkins,varmenise/jenkins,tangkun75/jenkins,rsandell/jenkins,daniel-beck/jenkins,protazy/jenkins,bkmeneguello/jenkins,fbelzunc/jenkins,tangkun75/jenkins,amuniz/jenkins,azweb76/jenkins,daniel-beck/jenkins,ikedam/jenkins,fbelzunc/jenkins,evernat/jenkins,lilyJi/jenkins,MarkEWaite/jenkins,ydubreuil/jenkins,damianszczepanik/jenkins,azweb76/jenkins,alvarolobato/jenkins,ajshastri/jenkins,wuwen5/jenkins,sathiya-mit/jenkins,NehemiahMi/jenkins,rlugojr/jenkins,jpbriend/jenkins,Vlatombe/jenkins,lilyJi/jenkins,ErikVerheul/jenkins,godfath3r/jenkins,MarkEWaite/jenkins,ydubreuil/jenkins,aldaris/jenkins,viqueen/jenkins,fbelzunc/jenkins,sathiya-mit/jenkins,pjanouse/jenkins,FarmGeek4Life/jenkins,kohsuke/hudson,ajshastri/jenkins,Vlatombe/jenkins,wuwen5/jenkins,jglick/jenkins,pjanouse/jenkins,hplatou/jenkins,Ykus/jenkins,patbos/jenkins,ndeloof/jenkins,v1v/jenkins,jpbriend/jenkins,fbelzunc/jenkins,kohsuke/hudson,MichaelPranovich/jenkins_sc,oleg-nenashev/jenkins,escoem/jenkins,bpzhang/jenkins,MarkEWaite/jenkins,v1v/jenkins,viqueen/jenkins,fbelzunc/jenkins,bpzhang/jenkins,andresrc/jenkins,lilyJi/jenkins,evernat/jenkins,aldaris/jenkins,Jochen-A-Fuerbacher/jenkins,aldaris/jenkins,gitaccountforprashant/gittest,sathiya-mit/jenkins,olivergondza/jenkins,recena/jenkins,SebastienGllmt/jenkins,evernat/jenkins,ndeloof/jenkins,batmat/jenkins,christ66/jenkins,MarkEWaite/jenkins,FarmGeek4Life/jenkins,aldaris/jenkins,tfennelly/jenkins,andresrc/jenkins,gitaccountforprashant/gittest,Jimilian/jenkins,MarkEWaite/jenkins,jenkinsci/jenkins,ikedam/jenkins,ndeloof/jenkins,wuwen5/jenkins,tangkun75/jenkins,tfennelly/jenkins,oleg-nenashev/jenkins,patbos/jenkins,daniel-beck/jenkins,dennisjlee/jenkins,bpzhang/jenkins,jenkinsci/jenkins,hplatou/jenkins,rlugojr/jenkins,stephenc/jenkins,Jochen-A-Fuerbacher/jenkins,amuniz/jenkins,Jochen-A-Fuerbacher/jenkins,MarkEWaite/jenkins,jpbriend/jenkins,SebastienGllmt/jenkins,evernat/jenkins,andresrc/jenkins,rlugojr/jenkins,dennisjlee/jenkins,protazy/jenkins,kohsuke/hudson,godfath3r/jenkins | /*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Michael B. Donohue
*
* 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.
*/
package hudson.model;
import hudson.diagnosis.OldDataMonitor;
import hudson.model.Queue.Task;
import hudson.model.queue.FoldableAction;
import hudson.util.XStream2;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import jenkins.model.RunAction2;
@ExportedBean
public class CauseAction implements FoldableAction, RunAction2 {
/**
* @deprecated since 2009-02-28
*/
@Deprecated
// there can be multiple causes, so this is deprecated
private transient Cause cause;
/** @deprecated JENKINS-33467 inefficient */
@Deprecated
private transient List<Cause> causes;
private Map<Cause,Integer> causeBag = new LinkedHashMap<>();
public CauseAction(Cause c) {
this.causeBag.put(c, 1);
}
private void addCause(Cause c) {
synchronized (causeBag) {
Integer cnt = causeBag.get(c);
causeBag.put(c, cnt == null ? 1 : cnt + 1);
}
}
private void addCauses(Collection<? extends Cause> causes) {
for (Cause cause : causes) {
addCause(cause);
}
}
public CauseAction(Cause... c) {
this(Arrays.asList(c));
}
public CauseAction(Collection<? extends Cause> causes) {
addCauses(causes);
}
public CauseAction(CauseAction ca) {
addCauses(ca.getCauses());
}
/**
* Lists all causes of this build.
* Note that the current implementation does not preserve insertion order of duplicates.
* @return an immutable list;
* to create an action with multiple causes use either of the constructors that support this;
* to append causes retroactively to a build you must create a new {@link CauseAction} and replace the old
*/
@Exported(visibility=2)
public List<Cause> getCauses() {
List<Cause> r = new ArrayList<>();
for (Map.Entry<Cause,Integer> entry : causeBag.entrySet()) {
r.addAll(Collections.nCopies(entry.getValue(), entry.getKey()));
}
return Collections.unmodifiableList(r);
}
/**
* Finds the cause of the specific type.
*/
public <T extends Cause> T findCause(Class<T> type) {
for (Cause c : causeBag.keySet())
if (type.isInstance(c))
return type.cast(c);
return null;
}
public String getDisplayName() {
return "Cause";
}
public String getIconFileName() {
// no icon
return null;
}
public String getUrlName() {
return "cause";
}
/**
* Get list of causes with duplicates combined into counters.
* @return Map of Cause to number of occurrences of that Cause
*/
public Map<Cause,Integer> getCauseCounts() {
return Collections.unmodifiableMap(causeBag);
}
/**
* @deprecated as of 1.288
* but left here for backward compatibility.
*/
@Deprecated
public String getShortDescription() {
if (causeBag.isEmpty()) {
return "N/A";
}
return causeBag.keySet().iterator().next().getShortDescription();
}
@Override public void onLoad(Run<?,?> owner) {
for (Cause c : causeBag.keySet()) {
if (c != null) {
c.onLoad(owner);
}
}
}
/**
* When hooked up to build, notify {@link Cause}s.
*/
@Override public void onAttached(Run<?,?> owner) {
for (Cause c : causeBag.keySet()) {
if (c != null) {
c.onAddedTo(owner);
}
}
}
public void foldIntoExisting(hudson.model.Queue.Item item, Task owner, List<Action> otherActions) {
CauseAction existing = item.getAction(CauseAction.class);
if (existing!=null) {
existing.addCauses(getCauses());
return;
}
// no CauseAction found, so add a copy of this one
item.addAction(new CauseAction(this));
}
public static class ConverterImpl extends XStream2.PassthruConverter<CauseAction> {
public ConverterImpl(XStream2 xstream) { super(xstream); }
@Override protected void callback(CauseAction ca, UnmarshallingContext context) {
// if we are being read in from an older version
if (ca.cause != null) {
if (ca.causeBag == null) {
ca.causeBag = new LinkedHashMap<>();
}
ca.addCause(ca.cause);
OldDataMonitor.report(context, "1.288");
ca.cause = null;
} else if (ca.causes != null) {
if (ca.causeBag == null) {
ca.causeBag = new LinkedHashMap<>();
}
ca.addCauses(ca.causes);
OldDataMonitor.report(context, "1.653");
ca.causes = null;
}
}
}
}
| core/src/main/java/hudson/model/CauseAction.java | /*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Michael B. Donohue
*
* 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.
*/
package hudson.model;
import hudson.diagnosis.OldDataMonitor;
import hudson.model.Queue.Task;
import hudson.model.queue.FoldableAction;
import hudson.util.XStream2;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import jenkins.model.RunAction2;
@ExportedBean
public class CauseAction implements FoldableAction, RunAction2 {
/**
* @deprecated since 2009-02-28
*/
@Deprecated
// there can be multiple causes, so this is deprecated
private transient Cause cause;
/** @deprecated JENKINS-33467 inefficient */
@Deprecated
private transient List<Cause> causes;
private Map<Cause,Integer> causeBag = new LinkedHashMap<>();
public CauseAction(Cause c) {
this.causeBag.put(c, 1);
}
private void addCause(Cause c) {
synchronized (causeBag) {
Integer cnt = causeBag.get(c);
causeBag.put(c, cnt == null ? 1 : cnt + 1);
}
}
private void addCauses(Collection<? extends Cause> causes) {
for (Cause cause : causes) {
addCause(cause);
}
}
public CauseAction(Cause... c) {
this(Arrays.asList(c));
}
public CauseAction(Collection<? extends Cause> causes) {
addCauses(causes);
}
public CauseAction(CauseAction ca) {
addCauses(ca.getCauses());
}
@Exported(visibility=2)
public List<Cause> getCauses() {
List<Cause> r = new ArrayList<>();
for (Map.Entry<Cause,Integer> entry : causeBag.entrySet()) {
r.addAll(Collections.nCopies(entry.getValue(), entry.getKey()));
}
return r;
}
/**
* Finds the cause of the specific type.
*/
public <T extends Cause> T findCause(Class<T> type) {
for (Cause c : causeBag.keySet())
if (type.isInstance(c))
return type.cast(c);
return null;
}
public String getDisplayName() {
return "Cause";
}
public String getIconFileName() {
// no icon
return null;
}
public String getUrlName() {
return "cause";
}
/**
* Get list of causes with duplicates combined into counters.
* @return Map of Cause to number of occurrences of that Cause
*/
public Map<Cause,Integer> getCauseCounts() {
return Collections.unmodifiableMap(causeBag);
}
/**
* @deprecated as of 1.288
* but left here for backward compatibility.
*/
@Deprecated
public String getShortDescription() {
if (causeBag.isEmpty()) {
return "N/A";
}
return causeBag.keySet().iterator().next().getShortDescription();
}
@Override public void onLoad(Run<?,?> owner) {
for (Cause c : causeBag.keySet()) {
if (c != null) {
c.onLoad(owner);
}
}
}
/**
* When hooked up to build, notify {@link Cause}s.
*/
@Override public void onAttached(Run<?,?> owner) {
for (Cause c : causeBag.keySet()) {
if (c != null) {
c.onAddedTo(owner);
}
}
}
public void foldIntoExisting(hudson.model.Queue.Item item, Task owner, List<Action> otherActions) {
CauseAction existing = item.getAction(CauseAction.class);
if (existing!=null) {
existing.addCauses(getCauses());
return;
}
// no CauseAction found, so add a copy of this one
item.addAction(new CauseAction(this));
}
public static class ConverterImpl extends XStream2.PassthruConverter<CauseAction> {
public ConverterImpl(XStream2 xstream) { super(xstream); }
@Override protected void callback(CauseAction ca, UnmarshallingContext context) {
// if we are being read in from an older version
if (ca.cause != null) {
if (ca.causeBag == null) {
ca.causeBag = new LinkedHashMap<>();
}
ca.addCause(ca.cause);
OldDataMonitor.report(context, "1.288");
ca.cause = null;
} else if (ca.causes != null) {
if (ca.causeBag == null) {
ca.causeBag = new LinkedHashMap<>();
}
ca.addCauses(ca.causes);
OldDataMonitor.report(context, "1.653");
ca.causes = null;
}
}
}
}
| [JENKINS-33467] Clarifying that CauseAction.getCauses is immutable and you should construct the action with the causes you want.
(cherry picked from commit 4adee7597aad7a338db8d3eb320575ae618a8c81)
| core/src/main/java/hudson/model/CauseAction.java | [JENKINS-33467] Clarifying that CauseAction.getCauses is immutable and you should construct the action with the causes you want. (cherry picked from commit 4adee7597aad7a338db8d3eb320575ae618a8c81) | <ide><path>ore/src/main/java/hudson/model/CauseAction.java
<ide> public CauseAction(CauseAction ca) {
<ide> addCauses(ca.getCauses());
<ide> }
<del>
<add>
<add> /**
<add> * Lists all causes of this build.
<add> * Note that the current implementation does not preserve insertion order of duplicates.
<add> * @return an immutable list;
<add> * to create an action with multiple causes use either of the constructors that support this;
<add> * to append causes retroactively to a build you must create a new {@link CauseAction} and replace the old
<add> */
<ide> @Exported(visibility=2)
<ide> public List<Cause> getCauses() {
<ide> List<Cause> r = new ArrayList<>();
<ide> for (Map.Entry<Cause,Integer> entry : causeBag.entrySet()) {
<ide> r.addAll(Collections.nCopies(entry.getValue(), entry.getKey()));
<ide> }
<del> return r;
<add> return Collections.unmodifiableList(r);
<ide> }
<ide>
<ide> /** |
|
Java | mit | 7dff1dd1dc6cc9327482686e97e737bec01f529e | 0 | JCThePants/NucleusFramework,JCThePants/NucleusFramework | /*
* This file is part of GenericsLib for Bukkit, licensed under the MIT License (MIT).
*
* Copyright (c) JCThePants (www.jcwhatever.com)
*
* 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.
*/
package com.jcwhatever.bukkit.generic.titles;
import com.jcwhatever.bukkit.generic.GenericsLib;
import com.jcwhatever.bukkit.generic.GenericsLib.NmsHandlers;
import com.jcwhatever.bukkit.generic.nms.INmsTitleHandler;
import com.jcwhatever.bukkit.generic.utils.PreCon;
import com.jcwhatever.bukkit.generic.utils.Utils;
import com.jcwhatever.bukkit.generic.utils.text.TextComponent;
import com.jcwhatever.bukkit.generic.utils.text.TextComponents;
import org.bukkit.entity.Player;
import javax.annotation.Nullable;
/**
* GenericsLib implementation of {@link ITitle}
*/
public class GenericsTitle implements ITitle {
private final String _title;
private final String _subTitle;
private final int _fadeInTime;
private final int _stayTime;
private final int _fadeOutTime;
private TextComponents _titleComponents;
private TextComponents _subTitleComponents;
/**
* Constructor.
*
* <p>Uses default times.</p>
*
* @param title The title text.
* @param subTitle The sub title text.
*/
public GenericsTitle(String title, @Nullable String subTitle) {
this(title, subTitle, -1, -1, -1);
}
/**
* Constructor.
*
* @param title The title text components.
* @param subTitle The sub title text components.
* @param fadeInTime The time spent fading in.
* @param stayTime The time spent being displayed.
* @param fadeOutTime The time spent fading out.
*/
public GenericsTitle(String title, @Nullable String subTitle,
int fadeInTime, int stayTime, int fadeOutTime) {
PreCon.notNull(title);
_title = title;
_subTitle = subTitle;
_fadeInTime = fadeInTime;
_stayTime = stayTime;
_fadeOutTime = fadeOutTime;
}
/**
* Get the time spent fading in.
*
* @return -1 if the default is used.
*/
@Override
public int getFadeInTime() {
return getTime(_fadeInTime);
}
/**
* Get the time spent being displayed.
*
* @return -1 if the default is used.
*/
@Override
public int getStayTime() {
return getTime(_stayTime);
}
/**
* Get the time spent fading out.
*
* @return -1 if the default is used.
*/
@Override
public int getFadeOutTime() {
return getTime(_fadeOutTime);
}
/**
* Get the title components.
*/
@Override
public String getTitle() {
return _title;
}
/**
* Get the sub-title components.
*/
@Override
@Nullable
public String getSubTitle() {
return _subTitle;
}
/**
* Show the title to the specified player.
*
* @param p The player to show the title to.
*/
@Override
public void showTo(Player p) {
PreCon.notNull(p);
INmsTitleHandler titleHandler = GenericsLib.getNmsManager().getNmsHandler(NmsHandlers.TITLES.name());
if (titleHandler != null) {
StringBuilder buffer = new StringBuilder(50);
getJson(buffer, getTitleComponents());
String title = buffer.toString();
String subTitle = null;
if (_subTitle != null) {
buffer.setLength(0);
getJson(buffer, getSubTitleComponents());
subTitle = buffer.toString();
}
titleHandler.send(p, title, subTitle, _fadeInTime, _stayTime, _fadeOutTime);
return;
}
// use commands as a fallback if there is no NMS title handler
String titleCommand = getCommand(p, TitleCommandType.TITLE);
String subTitleCommand = null;
String timesCommand = null;
if (_subTitleComponents != null) {
subTitleCommand = getCommand(p, TitleCommandType.SUBTITLE);
}
// if one time is -1 then all times are -1
if (getTime(_fadeInTime) != -1) {
timesCommand = getCommand(p, TitleCommandType.TIMES);
}
if (timesCommand != null) {
Utils.executeAsConsole(timesCommand);
}
if (subTitleCommand != null) {
Utils.executeAsConsole(subTitleCommand);
}
Utils.executeAsConsole(titleCommand);
}
public TextComponents getTitleComponents() {
if (_titleComponents == null) {
_titleComponents = new TextComponents(_title);
}
return _titleComponents;
}
@Nullable
public TextComponents getSubTitleComponents() {
if (_subTitle != null && _subTitleComponents == null) {
_subTitleComponents = new TextComponents(_subTitle);
}
return _subTitleComponents;
}
private String getCommand(Player p, TitleCommandType type) {
StringBuilder buffer = new StringBuilder(100);
buffer.append("title ");
buffer.append(p.getName());
buffer.append(' ');
buffer.append(type.name());
buffer.append(' ');
switch (type) {
case TITLE:
getJson(buffer, getTitleComponents());
break;
case SUBTITLE:
//noinspection ConstantConditions
getJson(buffer, getSubTitleComponents());
break;
case TIMES:
buffer.append(_fadeInTime);
buffer.append(' ');
buffer.append(_stayTime);
buffer.append(' ');
buffer.append(_fadeOutTime);
break;
case CLEAR:
break;
case RESET:
break;
default:
throw new AssertionError();
}
return buffer.toString();
}
private int getTime(int time) {
if (_fadeInTime < 0 || _stayTime < 0 || _fadeOutTime < 0)
return -1;
return time;
}
private void getJson(StringBuilder buffer, TextComponents segments) {
buffer.append('{');
getJsonSegment(buffer, segments.get(0));
if (segments.size() > 1) {
buffer.append(",extra:[");
for (int i=1; i < segments.size(); i++) {
buffer.append('{');
getJsonSegment(buffer, segments.get(i));
buffer.append('}');
if (i < segments.size() - 1) {
buffer.append(',');
}
}
buffer.append(']');
}
buffer.append('}');
}
private void getJsonSegment(StringBuilder buffer, TextComponent segment) {
buffer.append("text:\"");
buffer.append(segment.getText());
buffer.append('"');
if (segment.getTextColor() != null) {
buffer.append(",color:");
buffer.append(segment.getTextColor().name().toLowerCase());
}
}
protected enum TitleCommandType {
TITLE,
SUBTITLE,
TIMES,
CLEAR,
RESET
}
}
| src/com/jcwhatever/bukkit/generic/titles/GenericsTitle.java | /*
* This file is part of GenericsLib for Bukkit, licensed under the MIT License (MIT).
*
* Copyright (c) JCThePants (www.jcwhatever.com)
*
* 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.
*/
package com.jcwhatever.bukkit.generic.titles;
import com.jcwhatever.bukkit.generic.GenericsLib;
import com.jcwhatever.bukkit.generic.GenericsLib.NmsHandlers;
import com.jcwhatever.bukkit.generic.nms.INmsTitleHandler;
import com.jcwhatever.bukkit.generic.utils.PreCon;
import com.jcwhatever.bukkit.generic.utils.Utils;
import com.jcwhatever.bukkit.generic.utils.text.TextComponent;
import com.jcwhatever.bukkit.generic.utils.text.TextComponents;
import org.bukkit.entity.Player;
import javax.annotation.Nullable;
/**
* GenericsLib implementation of {@link ITitle}
*/
public class GenericsTitle implements ITitle {
private final String _title;
private final String _subTitle;
private final int _fadeInTime;
private final int _stayTime;
private final int _fadeOutTime;
private TextComponents _titleComponents;
private TextComponents _subTitleComponents;
private String _formattedTitle;
private String _formattedSubTitle;
/**
* Constructor.
*
* <p>Uses default times.</p>
*
* @param title The title text.
* @param subTitle The sub title text.
*/
public GenericsTitle(String title, @Nullable String subTitle) {
this(title, subTitle, -1, -1, -1);
}
/**
* Constructor.
*
* @param title The title text components.
* @param subTitle The sub title text components.
* @param fadeInTime The time spent fading in.
* @param stayTime The time spent being displayed.
* @param fadeOutTime The time spent fading out.
*/
public GenericsTitle(String title, @Nullable String subTitle,
int fadeInTime, int stayTime, int fadeOutTime) {
PreCon.notNull(title);
_title = title;
_subTitle = subTitle;
_fadeInTime = fadeInTime;
_stayTime = stayTime;
_fadeOutTime = fadeOutTime;
}
/**
* Get the time spent fading in.
*
* @return -1 if the default is used.
*/
@Override
public int getFadeInTime() {
return getTime(_fadeInTime);
}
/**
* Get the time spent being displayed.
*
* @return -1 if the default is used.
*/
@Override
public int getStayTime() {
return getTime(_stayTime);
}
/**
* Get the time spent fading out.
*
* @return -1 if the default is used.
*/
@Override
public int getFadeOutTime() {
return getTime(_fadeOutTime);
}
/**
* Get the title components.
*/
@Override
public String getTitle() {
return _title;
}
/**
* Get the sub-title components.
*/
@Override
@Nullable
public String getSubTitle() {
return _subTitle;
}
/**
* Show the title to the specified player.
*
* @param p The player to show the title to.
*/
@Override
public void showTo(Player p) {
PreCon.notNull(p);
INmsTitleHandler titleHandler = GenericsLib.getNmsManager().getNmsHandler(NmsHandlers.TITLES.name());
if (titleHandler != null) {
StringBuilder buffer = new StringBuilder(50);
getJson(buffer, getTitleComponents());
String title = buffer.toString();
String subTitle = null;
if (_subTitle != null) {
buffer.setLength(0);
getJson(buffer, getSubTitleComponents());
subTitle = buffer.toString();
}
titleHandler.send(p, title, subTitle, _fadeInTime, _stayTime, _fadeOutTime);
return;
}
// use commands as a fallback if there is no NMS title handler
String titleCommand = getCommand(p, TitleCommandType.TITLE);
String subTitleCommand = null;
String timesCommand = null;
if (_subTitleComponents != null) {
subTitleCommand = getCommand(p, TitleCommandType.SUBTITLE);
}
// if one time is -1 then all times are -1
if (getTime(_fadeInTime) != -1) {
timesCommand = getCommand(p, TitleCommandType.TIMES);
}
if (timesCommand != null) {
Utils.executeAsConsole(timesCommand);
}
if (subTitleCommand != null) {
Utils.executeAsConsole(subTitleCommand);
}
Utils.executeAsConsole(titleCommand);
}
public TextComponents getTitleComponents() {
if (_titleComponents == null) {
_titleComponents = new TextComponents(_title);
}
return _titleComponents;
}
@Nullable
public TextComponents getSubTitleComponents() {
if (_subTitle != null && _subTitleComponents == null) {
_subTitleComponents = new TextComponents(_subTitle);
}
return _subTitleComponents;
}
private String getCommand(Player p, TitleCommandType type) {
StringBuilder buffer = new StringBuilder(100);
buffer.append("title ");
buffer.append(p.getName());
buffer.append(' ');
buffer.append(type.name());
buffer.append(' ');
switch (type) {
case TITLE:
getJson(buffer, getTitleComponents());
break;
case SUBTITLE:
//noinspection ConstantConditions
getJson(buffer, getSubTitleComponents());
break;
case TIMES:
buffer.append(_fadeInTime);
buffer.append(' ');
buffer.append(_stayTime);
buffer.append(' ');
buffer.append(_fadeOutTime);
break;
case CLEAR:
break;
case RESET:
break;
default:
throw new AssertionError();
}
return buffer.toString();
}
private int getTime(int time) {
if (_fadeInTime < 0 || _stayTime < 0 || _fadeOutTime < 0)
return -1;
return time;
}
private void getJson(StringBuilder buffer, TextComponents segments) {
buffer.append('{');
getJsonSegment(buffer, segments.get(0));
if (segments.size() > 1) {
buffer.append(",extra:[");
for (int i=1; i < segments.size(); i++) {
buffer.append('{');
getJsonSegment(buffer, segments.get(i));
buffer.append('}');
if (i < segments.size() - 1) {
buffer.append(',');
}
}
buffer.append(']');
}
buffer.append('}');
}
private void getJsonSegment(StringBuilder buffer, TextComponent segment) {
buffer.append("text:\"");
buffer.append(segment.getText());
buffer.append('"');
if (segment.getTextColor() != null) {
buffer.append(",color:");
buffer.append(segment.getTextColor().name().toLowerCase());
}
}
protected enum TitleCommandType {
TITLE,
SUBTITLE,
TIMES,
CLEAR,
RESET
}
}
| remove unused fields
| src/com/jcwhatever/bukkit/generic/titles/GenericsTitle.java | remove unused fields | <ide><path>rc/com/jcwhatever/bukkit/generic/titles/GenericsTitle.java
<ide>
<ide> private TextComponents _titleComponents;
<ide> private TextComponents _subTitleComponents;
<del> private String _formattedTitle;
<del> private String _formattedSubTitle;
<ide>
<ide> /**
<ide> * Constructor. |
|
Java | apache-2.0 | 5bbd53135d30869a14c66eebf3d60f5454f0b5e5 | 0 | Sage-Bionetworks/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,Sage-Bionetworks/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,hhu94/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,xschildw/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,zimingd/Synapse-Repository-Services,xschildw/Synapse-Repository-Services | package org.sagebionetworks;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.sagebionetworks.bridge.model.data.ParticipantDataColumnDescriptor;
import org.sagebionetworks.bridge.model.data.ParticipantDataColumnType;
import org.sagebionetworks.bridge.model.data.ParticipantDataCurrentRow;
import org.sagebionetworks.bridge.model.data.ParticipantDataDescriptor;
import org.sagebionetworks.bridge.model.data.ParticipantDataDescriptorWithColumns;
import org.sagebionetworks.bridge.model.data.ParticipantDataRepeatType;
import org.sagebionetworks.bridge.model.data.ParticipantDataRow;
import org.sagebionetworks.bridge.model.data.ParticipantDataStatus;
import org.sagebionetworks.bridge.model.data.ParticipantDataStatusList;
import org.sagebionetworks.bridge.model.data.units.Units;
import org.sagebionetworks.bridge.model.data.value.ParticipantDataDatetimeValue;
import org.sagebionetworks.bridge.model.data.value.ParticipantDataDoubleValue;
import org.sagebionetworks.bridge.model.data.value.ParticipantDataEventValue;
import org.sagebionetworks.bridge.model.data.value.ParticipantDataLabValue;
import org.sagebionetworks.bridge.model.data.value.ParticipantDataLongValue;
import org.sagebionetworks.bridge.model.data.value.ParticipantDataStringValue;
import org.sagebionetworks.bridge.model.data.value.ParticipantDataValue;
import org.sagebionetworks.bridge.model.data.value.ValueFactory;
import org.sagebionetworks.bridge.model.timeseries.TimeSeriesTable;
import org.sagebionetworks.bridge.model.versionInfo.BridgeVersionInfo;
import org.sagebionetworks.client.BridgeClient;
import org.sagebionetworks.client.BridgeClientImpl;
import org.sagebionetworks.client.BridgeProfileProxy;
import org.sagebionetworks.client.SynapseAdminClient;
import org.sagebionetworks.client.SynapseAdminClientImpl;
import org.sagebionetworks.client.SynapseClient;
import org.sagebionetworks.client.SynapseClientImpl;
import org.sagebionetworks.client.exceptions.SynapseException;
import org.sagebionetworks.client.exceptions.SynapseNotFoundException;
import org.sagebionetworks.repo.model.IdList;
import org.sagebionetworks.repo.model.PaginatedResults;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
/**
* Run this integration test as a sanity check to ensure our Synapse Java Client is working
*
* @author deflaux
*/
public class IT610BridgeData {
private static SynapseAdminClient adminSynapse;
private static BridgeClient bridge = null;
private static BridgeClient bridgeTwo = null;
private static List<Long> usersToDelete;
public static final int PREVIEW_TIMOUT = 10 * 1000;
public static final int RDS_WORKER_TIMEOUT = 1000 * 60; // One min
private List<String> handlesToDelete;
private static BridgeClient createBridgeClient(SynapseAdminClient client) throws Exception {
SynapseClient synapse = new SynapseClientImpl();
usersToDelete.add(SynapseClientHelper.createUser(adminSynapse, synapse));
BridgeClient bridge = new BridgeClientImpl(synapse);
bridge.setBridgeEndpoint(StackConfiguration.getBridgeServiceEndpoint());
// Return a proxy
return BridgeProfileProxy.createProfileProxy(bridge);
}
@BeforeClass
public static void beforeClass() throws Exception {
usersToDelete = new ArrayList<Long>();
adminSynapse = new SynapseAdminClientImpl();
SynapseClientHelper.setEndpoints(adminSynapse);
adminSynapse.setUserName(StackConfiguration.getMigrationAdminUsername());
adminSynapse.setApiKey(StackConfiguration.getMigrationAdminAPIKey());
bridge = createBridgeClient(adminSynapse);
bridgeTwo = createBridgeClient(adminSynapse);
}
@Before
public void before() throws SynapseException {
handlesToDelete = new ArrayList<String>();
for (String id : handlesToDelete) {
try {
adminSynapse.deleteFileHandle(id);
} catch (SynapseNotFoundException e) {
}
}
}
@After
public void after() throws Exception {
}
@AfterClass
public static void afterClass() throws Exception {
for (Long id : usersToDelete) {
// TODO This delete should not need to be surrounded by a try-catch
// This means proper cleanup was not done by the test
try {
adminSynapse.deleteUser(id);
} catch (Exception e) {
}
}
}
@Test
public void saveDataAndRetrieveNormalized() throws Exception {
List<ParticipantDataRow> rows = Lists.newArrayList();
ParticipantDataRow row = new ParticipantDataRow();
row.setData(Maps.<String,ParticipantDataValue>newHashMap());
ParticipantDataLabValue lab = new ParticipantDataLabValue();
lab.setValue(1000d);
lab.setUnits(Units.MILLILITER.getLabels().get(0));
lab.setMinNormal(500d);
lab.setMaxNormal(1500d);
row.getData().put("lab", lab);
rows.add(row);
ParticipantDataDescriptor descriptor = createDescriptor(false);
createColumnDescriptor(descriptor, "lab", ParticipantDataColumnType.LAB);
List<ParticipantDataRow> saved = bridge.appendParticipantData(descriptor.getId(), rows);
Long rowId = saved.get(0).getRowId();
// Milliliters should be converted to liters.
ParticipantDataRow convertedRow = bridge.getParticipantDataRow(descriptor.getId(), rowId, true);
ParticipantDataLabValue savedLab = (ParticipantDataLabValue)convertedRow.getData().get("lab");
assertEquals(1d, savedLab.getValue(), 0.0);
assertEquals("L", savedLab.getUnits());
assertEquals(0.5d, savedLab.getMinNormal(), 0.0);
assertEquals(1.5d, savedLab.getMaxNormal(), 0.0);
}
@Test
public void testGetVersion() throws Exception {
BridgeVersionInfo versionInfo = bridge.getBridgeVersionInfo();
assertFalse(versionInfo.getVersion().isEmpty());
}
/**
* @throws Exception
*/
@Test
public void testCreateAndDeleteParticipantData() throws Exception {
ParticipantDataDescriptor participantDataDescriptor = createDescriptor(false);
createColumnDescriptor(participantDataDescriptor, "level", ParticipantDataColumnType.STRING);
createColumnDescriptor(participantDataDescriptor, "size", ParticipantDataColumnType.STRING);
String[] headers = { "level", "size" };
List<ParticipantDataRow> data1 = createRows(headers, null, "5", "200");
data1 = bridge.appendParticipantData(participantDataDescriptor.getId(), data1);
List<ParticipantDataRow> data2 = createRows(headers, null, "7", "250", null, "3", "300");
data2 = bridge.appendParticipantData(participantDataDescriptor.getId(), data2);
List<ParticipantDataRow> data3 = createRows(headers, null, "5", "200");
data3 = bridgeTwo.appendParticipantData(participantDataDescriptor.getId(), data3);
PaginatedResults<ParticipantDataRow> one = bridge.getRawParticipantData(participantDataDescriptor.getId(), Integer.MAX_VALUE, 0, false);
PaginatedResults<ParticipantDataRow> two = bridgeTwo.getRawParticipantData(participantDataDescriptor.getId(), Integer.MAX_VALUE, 0, false);
assertEquals(3, one.getResults().size());
assertEquals(1, two.getResults().size());
assertEquals(data3, two.getResults());
}
@Test
public void testPaginatedParticipantData() throws Exception {
ParticipantDataDescriptor participantDataDescriptor = createDescriptor(false);
createColumnDescriptor(participantDataDescriptor, "level", ParticipantDataColumnType.STRING);
createColumnDescriptor(participantDataDescriptor, "size", ParticipantDataColumnType.STRING);
String[] headers = { "level", "size" };
List<ParticipantDataRow> data1 = createRows(headers, null, "5", "200", null, "6", "200", null, "7", "200");
data1 = bridge.appendParticipantData(participantDataDescriptor.getId(), data1);
PaginatedResults<ParticipantDataRow> result;
result = bridge.getRawParticipantData(participantDataDescriptor.getId(), 1, 0, false);
assertEquals(1, result.getResults().size());
assertEquals("5", ((ParticipantDataStringValue) result.getResults().get(0).getData().get("level")).getValue());
result = bridge.getRawParticipantData(participantDataDescriptor.getId(), 1, 1, false);
assertEquals(1, result.getResults().size());
assertEquals("6", ((ParticipantDataStringValue) result.getResults().get(0).getData().get("level")).getValue());
result = bridge.getRawParticipantData(participantDataDescriptor.getId(), 10, 1, false);
assertEquals(2, result.getResults().size());
assertEquals("6", ((ParticipantDataStringValue) result.getResults().get(0).getData().get("level")).getValue());
assertEquals("7", ((ParticipantDataStringValue) result.getResults().get(1).getData().get("level")).getValue());
}
@Test
public void testReplaceParticipantData() throws Exception {
ParticipantDataDescriptor participantDataDescriptor = createDescriptor(false);
createColumnDescriptor(participantDataDescriptor, "level", ParticipantDataColumnType.STRING);
createColumnDescriptor(participantDataDescriptor, "size", ParticipantDataColumnType.STRING);
String[] headers = { "level", "size" };
List<ParticipantDataRow> data1 = createRows(headers, null, "5", "200", null, "6", "200", null, "7", "200");
data1 = bridge.appendParticipantData(participantDataDescriptor.getId(), data1);
List<ParticipantDataRow> dataToReplace = createRows(headers, data1.get(1).getRowId(), "8", "200");
dataToReplace = bridge.updateParticipantData(participantDataDescriptor.getId(), dataToReplace);
PaginatedResults<ParticipantDataRow> result = bridge.getRawParticipantData(participantDataDescriptor.getId(), Integer.MAX_VALUE, 0, false);
assertEquals(3, result.getResults().size());
assertEquals("5", ((ParticipantDataStringValue) result.getResults().get(0).getData().get("level")).getValue());
assertEquals("8", ((ParticipantDataStringValue) result.getResults().get(1).getData().get("level")).getValue());
assertEquals("7", ((ParticipantDataStringValue) result.getResults().get(2).getData().get("level")).getValue());
}
@Test
public void testGetCurrentParticipantData() throws Exception {
ParticipantDataDescriptor participantDataDescriptor = createDescriptor(false);
createColumnDescriptor(participantDataDescriptor, "level", ParticipantDataColumnType.STRING);
createColumnDescriptor(participantDataDescriptor, "size", ParticipantDataColumnType.STRING);
String[] headers = { "level", "size" };
ParticipantDataStatusList statuses = new ParticipantDataStatusList();
ParticipantDataStatus update = new ParticipantDataStatus();
update.setParticipantDataDescriptorId(participantDataDescriptor.getId());
List<ParticipantDataStatus> updates = Collections.singletonList(update);
statuses.setUpdates(updates);
List<ParticipantDataRow> data1 = createRows(headers, null, "5", "200", null, "6", "200", null, "7", "200");
data1 = bridge.appendParticipantData(participantDataDescriptor.getId(), data1);
update.setLastEntryComplete(true);
bridge.sendParticipantDataDescriptorUpdates(statuses);
ParticipantDataCurrentRow currentRow = bridge.getCurrentParticipantData(participantDataDescriptor.getId(), false);
assertTrue(currentRow.getCurrentData().getData().isEmpty());
assertEquals("7", ((ParticipantDataStringValue) currentRow.getPreviousData().getData().get("level")).getValue());
update.setLastEntryComplete(false);
bridge.sendParticipantDataDescriptorUpdates(statuses);
currentRow = bridge.getCurrentParticipantData(participantDataDescriptor.getId(), false);
assertEquals("6", ((ParticipantDataStringValue) currentRow.getPreviousData().getData().get("level")).getValue());
assertEquals("7", ((ParticipantDataStringValue) currentRow.getCurrentData().getData().get("level")).getValue());
List<ParticipantDataRow> dataToReplace = createRows(headers, data1.get(2).getRowId(), "8", "200");
dataToReplace = bridge.updateParticipantData(participantDataDescriptor.getId(), dataToReplace);
currentRow = bridge.getCurrentParticipantData(participantDataDescriptor.getId(), false);
assertEquals("6", ((ParticipantDataStringValue) currentRow.getPreviousData().getData().get("level")).getValue());
assertEquals("8", ((ParticipantDataStringValue) currentRow.getCurrentData().getData().get("level")).getValue());
List<ParticipantDataRow> data3 = createRows(headers, null, "9", "200");
data3 = bridge.appendParticipantData(participantDataDescriptor.getId(), data3);
currentRow = bridge.getCurrentParticipantData(participantDataDescriptor.getId(), false);
assertEquals("8", ((ParticipantDataStringValue) currentRow.getPreviousData().getData().get("level")).getValue());
assertEquals("9", ((ParticipantDataStringValue) currentRow.getCurrentData().getData().get("level")).getValue());
update.setLastEntryComplete(true);
bridge.sendParticipantDataDescriptorUpdates(statuses);
currentRow = bridge.getCurrentParticipantData(participantDataDescriptor.getId(), false);
assertTrue(currentRow.getCurrentData().getData().isEmpty());
assertEquals("9", ((ParticipantDataStringValue) currentRow.getPreviousData().getData().get("level")).getValue());
}
@Test
public void testDeleteParticipantDataRows() throws Exception {
ParticipantDataDescriptor participantDataDescriptor = createDescriptor(false);
createColumnDescriptor(participantDataDescriptor, "level", ParticipantDataColumnType.STRING);
String[] headers = { "level" };
List<ParticipantDataRow> data1 = createRows(headers, null, "5", null, "200", null, "6");
data1 = bridge.appendParticipantData(participantDataDescriptor.getId(), data1);
List<Long> rowIds = Lists.newArrayListWithCapacity(data1.size());
for (ParticipantDataRow row : data1) {
rowIds.add(row.getRowId());
}
IdList idList = new IdList();
idList.setList(rowIds);
bridge.deleteParticipantDataRows(participantDataDescriptor.getId(), idList);
PaginatedResults<ParticipantDataRow> result = bridge.getRawParticipantData(participantDataDescriptor.getId(), 1000, 0, false);
assertEquals(0, result.getResults().size());
}
@Test
public void testGetCurrentRows() throws Exception {
ParticipantDataDescriptor participantDataDescriptor = createDescriptor(true);
createColumnDescriptor(participantDataDescriptor, "event", ParticipantDataColumnType.EVENT);
createColumnDescriptor(participantDataDescriptor, "level", ParticipantDataColumnType.DOUBLE);
String[] headers = { "event", "level" };
List<ParticipantDataRow> data1 = createRows(headers, null, ValueFactory.createEventValue(30000L, null, "a", null), 1.0, null,
ValueFactory.createEventValue(40000L, 50000L, "b", null), 2.0, null, ValueFactory.createEventValue(20000L, null, "c", null),
3.0);
data1 = bridge.appendParticipantData(participantDataDescriptor.getId(), data1);
List<ParticipantDataRow> currentRows = bridge.getCurrentRows(participantDataDescriptor.getId(), false);
assertEquals(2, currentRows.size());
assertEquals(20000L, getEvent(currentRows, 0, "event").getStart().longValue());
assertEquals(30000L, getEvent(currentRows, 1, "event").getStart().longValue());
}
@Test
public void testGetHistoryRows() throws Exception {
ParticipantDataDescriptor participantDataDescriptor = createDescriptor(true);
createColumnDescriptor(participantDataDescriptor, "event", ParticipantDataColumnType.EVENT);
createColumnDescriptor(participantDataDescriptor, "level", ParticipantDataColumnType.DOUBLE);
String[] headers = { "event", "level" };
List<ParticipantDataRow> data1 = createRows(headers, null, ValueFactory.createEventValue(40000L, null, "a", null), 1.0, null,
ValueFactory.createEventValue(30000L, 40000L, "b", null), 2.0, null,
ValueFactory.createEventValue(20000L, 30000L, "c", null), 3.0);
data1 = bridge.appendParticipantData(participantDataDescriptor.getId(), data1);
List<ParticipantDataRow> currentRows = bridge.getHistoryRows(participantDataDescriptor.getId(), null, null, false);
assertEquals(3, currentRows.size());
assertEquals(20000L, getEvent(currentRows, 0, "event").getStart().longValue());
assertEquals(30000L, getEvent(currentRows, 1, "event").getStart().longValue());
assertEquals(40000L, getEvent(currentRows, 2, "event").getStart().longValue());
currentRows = bridge.getHistoryRows(participantDataDescriptor.getId(), new Date(30000L), null, false);
assertEquals(2, currentRows.size());
assertEquals(30000L, getEvent(currentRows, 0, "event").getStart().longValue());
assertEquals(40000L, getEvent(currentRows, 1, "event").getStart().longValue());
currentRows = bridge.getHistoryRows(participantDataDescriptor.getId(), null, new Date(35000L), false);
assertEquals(2, currentRows.size());
assertEquals(20000L, getEvent(currentRows, 0, "event").getStart().longValue());
assertEquals(30000L, getEvent(currentRows, 1, "event").getStart().longValue());
currentRows = bridge.getHistoryRows(participantDataDescriptor.getId(), new Date(25000L), new Date(35000L), false);
assertEquals(1, currentRows.size());
assertEquals(30000L, getEvent(currentRows, 0, "event").getStart().longValue());
}
private ParticipantDataEventValue getEvent(List<ParticipantDataRow> rows, int index, String column) {
return ((ParticipantDataEventValue) rows.get(index).getData().get(column));
}
@Test
public void testGetTimeSeries() throws Exception {
ParticipantDataDescriptor participantDataDescriptor = createDescriptor(false);
createColumnDescriptor(participantDataDescriptor, "date", ParticipantDataColumnType.DATETIME);
createColumnDescriptor(participantDataDescriptor, "level", ParticipantDataColumnType.DOUBLE);
createColumnDescriptor(participantDataDescriptor, "size", ParticipantDataColumnType.LONG);
String[] headers = { "date", "level", "size" };
ParticipantDataStatusList statuses = new ParticipantDataStatusList();
ParticipantDataStatus update = new ParticipantDataStatus();
update.setParticipantDataDescriptorId(participantDataDescriptor.getId());
List<ParticipantDataStatus> updates = Collections.singletonList(update);
statuses.setUpdates(updates);
List<ParticipantDataRow> data1 = createRows(headers, null, new Date(10000), 5.5, 400L, null, new Date(20000), 6.6, null, null,
new Date(30000), 7.7, 200L);
data1 = bridge.appendParticipantData(participantDataDescriptor.getId(), data1);
TimeSeriesTable timeSeries = bridge.getTimeSeries(participantDataDescriptor.getId(), null, false);
assertEquals(3, timeSeries.getColumns().size());
assertEquals(3, timeSeries.getRows().size());
assertEquals(0, timeSeries.getEvents().size());
assertEquals(3, timeSeries.getRows().get(0).getValues().size());
assertEquals(3, timeSeries.getRows().get(1).getValues().size());
assertEquals(3, timeSeries.getRows().get(2).getValues().size());
assertEquals(0, timeSeries.getDateIndex().intValue());
int levelIndex = 1;
int sizeIndex = 2;
if (timeSeries.getColumns().get(1).equals("size")) {
levelIndex = 2;
sizeIndex = 1;
}
assertEquals(new Date(30000).getTime(),
Long.parseLong(timeSeries.getRows().get(2).getValues().get(timeSeries.getDateIndex().intValue())));
assertEquals(7.7, Double.parseDouble(timeSeries.getRows().get(2).getValues().get(levelIndex)), 0.0001);
assertEquals(200.0, Double.parseDouble(timeSeries.getRows().get(2).getValues().get(sizeIndex)), 0.0001);
assertNull(timeSeries.getRows().get(1).getValues().get(sizeIndex));
TimeSeriesTable level = bridge.getTimeSeries(participantDataDescriptor.getId(), Lists.newArrayList("level"), false);
assertEquals(2, level.getColumns().size());
assertEquals(3, level.getRows().size());
assertEquals(2, level.getRows().get(0).getValues().size());
assertEquals(2, level.getRows().get(1).getValues().size());
assertEquals(2, level.getRows().get(2).getValues().size());
assertEquals(0, level.getDateIndex().intValue());
assertEquals(7.7, Double.parseDouble(level.getRows().get(2).getValues().get(1)), 0.0001);
TimeSeriesTable size = bridge.getTimeSeries(participantDataDescriptor.getId(), Lists.newArrayList("size"), false);
assertEquals(2, size.getColumns().size());
assertEquals(3, size.getRows().size());
assertEquals(2, size.getRows().get(0).getValues().size());
assertEquals(2, size.getRows().get(1).getValues().size());
assertEquals(2, size.getRows().get(2).getValues().size());
assertEquals(0, size.getDateIndex().intValue());
assertEquals(200.0, Double.parseDouble(size.getRows().get(2).getValues().get(1)), 0.0001);
TimeSeriesTable namedColumns = bridge.getTimeSeries(participantDataDescriptor.getId(), Lists.newArrayList("level", "size"), false);
assertEquals(timeSeries, namedColumns);
}
@Test
public void testGetEventTimeSeries() throws Exception {
ParticipantDataDescriptor participantDataDescriptor = createDescriptor(true);
createColumnDescriptor(participantDataDescriptor, "event", ParticipantDataColumnType.EVENT);
createColumnDescriptor(participantDataDescriptor, "level", ParticipantDataColumnType.DOUBLE);
createColumnDescriptor(participantDataDescriptor, "size", ParticipantDataColumnType.LONG);
String[] headers = { "event", "level", "size" };
ParticipantDataStatusList statuses = new ParticipantDataStatusList();
ParticipantDataStatus update = new ParticipantDataStatus();
update.setParticipantDataDescriptorId(participantDataDescriptor.getId());
List<ParticipantDataStatus> updates = Collections.singletonList(update);
statuses.setUpdates(updates);
List<ParticipantDataRow> data1 = createRows(headers, null, ValueFactory.createEventValue(50000L, 60000L, "a1", "aa"), 5.5, 400L,
null, ValueFactory.createEventValue(40000L, 50000L, "a2", "aa"), 5.5, 400L, null,
ValueFactory.createEventValue(10000L, 20000L, "b1", "bb"), 6.61, null, null,
ValueFactory.createEventValue(30000L, null, "b2", "bb"), 6.63, null, null,
ValueFactory.createEventValue(20000L, 30000L, "b2", "bb"), 6.62, null, null,
ValueFactory.createEventValue(20000L, 30000L, "c", null), 7.7, 200L, null,
ValueFactory.createEventValue(60000L, 30000L, "d", null), 8.8, 300L);
data1 = bridge.appendParticipantData(participantDataDescriptor.getId(), data1);
TimeSeriesTable timeSeries = bridge.getTimeSeries(participantDataDescriptor.getId(), null, false);
assertEquals(3, timeSeries.getColumns().size());
assertEquals(0, timeSeries.getRows().size());
assertEquals(4, timeSeries.getEvents().size());
assertEquals(ValueFactory.createEventValue(10000L, null, "b1", "bb"), timeSeries.getEvents().get(0));
assertEquals(ValueFactory.createEventValue(20000L, 30000L, "c", null), timeSeries.getEvents().get(1));
assertEquals(ValueFactory.createEventValue(40000L, 60000L, "a2", "aa"), timeSeries.getEvents().get(2));
assertEquals(ValueFactory.createEventValue(60000L, 30000L, "d", null), timeSeries.getEvents().get(3));
}
@Test
public void testGetParticipantDataDescriptorWithColumnsAndStatus() throws Exception {
java.util.Date lastPrompted = new java.util.Date();
ParticipantDataDescriptor descriptor = createDescriptor(false);
createColumnDescriptor(descriptor, "date", ParticipantDataColumnType.DATETIME);
createColumnDescriptor(descriptor, "level", ParticipantDataColumnType.DOUBLE);
createColumnDescriptor(descriptor, "size", ParticipantDataColumnType.LONG);
// Create some data so status can be updated
String[] headers = { "date", "level", "size" };
List<ParticipantDataRow> data1 = createRows(headers, null, new Date(10000), 5.5, 400L, null, new Date(20000),
6.6, null, null, new Date(30000), 7.7, 200L);
bridge.appendParticipantData(descriptor.getId(), data1);
ParticipantDataStatusList statuses = new ParticipantDataStatusList();
ParticipantDataStatus status = new ParticipantDataStatus();
status.setLastEntryComplete(true);
status.setLastPrompted(lastPrompted);
status.setParticipantDataDescriptorId(descriptor.getId());
statuses.setUpdates(Collections.singletonList(status));
bridge.sendParticipantDataDescriptorUpdates(statuses);
ParticipantDataDescriptorWithColumns descriptorWithColumns = bridge
.getParticipantDataDescriptorWithColumns(descriptor.getId());
assertEquals(descriptor.getId(), descriptorWithColumns.getDescriptor().getId());
assertEquals(3, descriptorWithColumns.getColumns().size());
assertEquals("date", descriptorWithColumns.getColumns().get(0).getName());
assertEquals(lastPrompted, descriptorWithColumns.getDescriptor().getStatus().getLastPrompted());
assertTrue(descriptorWithColumns.getDescriptor().getStatus().getLastEntryComplete());
}
private void createColumnDescriptor(ParticipantDataDescriptor participantDataDescriptor, String columnName,
ParticipantDataColumnType columnType) throws SynapseException {
ParticipantDataColumnDescriptor participantDataColumnDescriptor1 = new ParticipantDataColumnDescriptor();
participantDataColumnDescriptor1.setParticipantDataDescriptorId(participantDataDescriptor.getId());
participantDataColumnDescriptor1.setColumnType(columnType);
participantDataColumnDescriptor1.setName(columnName);
bridge.createParticipantDataColumnDescriptor(participantDataColumnDescriptor1);
}
private ParticipantDataDescriptor createDescriptor(boolean hasEvents) throws SynapseException {
ParticipantDataDescriptor participantDataDescriptor = new ParticipantDataDescriptor();
participantDataDescriptor.setName("my-first-participantData-" + System.currentTimeMillis());
participantDataDescriptor.setRepeatType(ParticipantDataRepeatType.ALWAYS);
participantDataDescriptor.setDatetimeStartColumnName("date");
if (hasEvents) {
participantDataDescriptor.setEventColumnName("event");
}
participantDataDescriptor = bridge.createParticipantDataDescriptor(participantDataDescriptor);
return participantDataDescriptor;
}
private List<ParticipantDataRow> createRows(String[] headers, Object... values) {
List<ParticipantDataRow> data = Lists.newArrayList();
for (int i = 0; i < values.length; i += headers.length + 1) {
ParticipantDataRow row = new ParticipantDataRow();
row.setData(Maps.<String, ParticipantDataValue> newHashMap());
row.setRowId((Long) values[i]);
data.add(row);
for (int j = 0; j < headers.length; j++) {
if (values[i + j + 1] != null) {
row.getData().put(headers[j], getValue(values[i + j + 1]));
}
}
}
return data;
}
private ParticipantDataValue getValue(Object value) {
if (value instanceof Date) {
ParticipantDataDatetimeValue result = new ParticipantDataDatetimeValue();
result.setValue(((Date) value).getTime());
return result;
}
if (value instanceof Long) {
ParticipantDataLongValue result = new ParticipantDataLongValue();
result.setValue((Long) value);
return result;
}
if (value instanceof Double) {
ParticipantDataDoubleValue result = new ParticipantDataDoubleValue();
result.setValue((Double) value);
return result;
}
if (value instanceof String) {
ParticipantDataStringValue result = new ParticipantDataStringValue();
result.setValue((String) value);
return result;
}
if (value instanceof ParticipantDataEventValue) {
return (ParticipantDataEventValue) value;
}
throw new IllegalArgumentException(value.getClass().getName());
}
}
| integration-test/src/test/java/org/sagebionetworks/IT610BridgeData.java | package org.sagebionetworks;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.sagebionetworks.bridge.model.data.ParticipantDataColumnDescriptor;
import org.sagebionetworks.bridge.model.data.ParticipantDataColumnType;
import org.sagebionetworks.bridge.model.data.ParticipantDataCurrentRow;
import org.sagebionetworks.bridge.model.data.ParticipantDataDescriptor;
import org.sagebionetworks.bridge.model.data.ParticipantDataDescriptorWithColumns;
import org.sagebionetworks.bridge.model.data.ParticipantDataRepeatType;
import org.sagebionetworks.bridge.model.data.ParticipantDataRow;
import org.sagebionetworks.bridge.model.data.ParticipantDataStatus;
import org.sagebionetworks.bridge.model.data.ParticipantDataStatusList;
import org.sagebionetworks.bridge.model.data.value.ParticipantDataDatetimeValue;
import org.sagebionetworks.bridge.model.data.value.ParticipantDataDoubleValue;
import org.sagebionetworks.bridge.model.data.value.ParticipantDataEventValue;
import org.sagebionetworks.bridge.model.data.value.ParticipantDataLongValue;
import org.sagebionetworks.bridge.model.data.value.ParticipantDataStringValue;
import org.sagebionetworks.bridge.model.data.value.ParticipantDataValue;
import org.sagebionetworks.bridge.model.data.value.ValueFactory;
import org.sagebionetworks.bridge.model.timeseries.TimeSeriesTable;
import org.sagebionetworks.bridge.model.versionInfo.BridgeVersionInfo;
import org.sagebionetworks.client.BridgeClient;
import org.sagebionetworks.client.BridgeClientImpl;
import org.sagebionetworks.client.BridgeProfileProxy;
import org.sagebionetworks.client.SynapseAdminClient;
import org.sagebionetworks.client.SynapseAdminClientImpl;
import org.sagebionetworks.client.SynapseClient;
import org.sagebionetworks.client.SynapseClientImpl;
import org.sagebionetworks.client.exceptions.SynapseException;
import org.sagebionetworks.client.exceptions.SynapseNotFoundException;
import org.sagebionetworks.repo.model.IdList;
import org.sagebionetworks.repo.model.PaginatedResults;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
/**
* Run this integration test as a sanity check to ensure our Synapse Java Client is working
*
* @author deflaux
*/
public class IT610BridgeData {
private static SynapseAdminClient adminSynapse;
private static BridgeClient bridge = null;
private static BridgeClient bridgeTwo = null;
private static List<Long> usersToDelete;
public static final int PREVIEW_TIMOUT = 10 * 1000;
public static final int RDS_WORKER_TIMEOUT = 1000 * 60; // One min
private List<String> handlesToDelete;
private static BridgeClient createBridgeClient(SynapseAdminClient client) throws Exception {
SynapseClient synapse = new SynapseClientImpl();
usersToDelete.add(SynapseClientHelper.createUser(adminSynapse, synapse));
BridgeClient bridge = new BridgeClientImpl(synapse);
bridge.setBridgeEndpoint(StackConfiguration.getBridgeServiceEndpoint());
// Return a proxy
return BridgeProfileProxy.createProfileProxy(bridge);
}
@BeforeClass
public static void beforeClass() throws Exception {
usersToDelete = new ArrayList<Long>();
adminSynapse = new SynapseAdminClientImpl();
SynapseClientHelper.setEndpoints(adminSynapse);
adminSynapse.setUserName(StackConfiguration.getMigrationAdminUsername());
adminSynapse.setApiKey(StackConfiguration.getMigrationAdminAPIKey());
bridge = createBridgeClient(adminSynapse);
bridgeTwo = createBridgeClient(adminSynapse);
}
@Before
public void before() throws SynapseException {
handlesToDelete = new ArrayList<String>();
for (String id : handlesToDelete) {
try {
adminSynapse.deleteFileHandle(id);
} catch (SynapseNotFoundException e) {
}
}
}
@After
public void after() throws Exception {
}
@AfterClass
public static void afterClass() throws Exception {
for (Long id : usersToDelete) {
// TODO This delete should not need to be surrounded by a try-catch
// This means proper cleanup was not done by the test
try {
adminSynapse.deleteUser(id);
} catch (Exception e) {
}
}
}
@Test
public void testGetVersion() throws Exception {
BridgeVersionInfo versionInfo = bridge.getBridgeVersionInfo();
assertFalse(versionInfo.getVersion().isEmpty());
}
/**
* @throws Exception
*/
@Test
public void testCreateAndDeleteParticipantData() throws Exception {
ParticipantDataDescriptor participantDataDescriptor = createDescriptor(false);
createColumnDescriptor(participantDataDescriptor, "level", ParticipantDataColumnType.STRING);
createColumnDescriptor(participantDataDescriptor, "size", ParticipantDataColumnType.STRING);
String[] headers = { "level", "size" };
List<ParticipantDataRow> data1 = createRows(headers, null, "5", "200");
data1 = bridge.appendParticipantData(participantDataDescriptor.getId(), data1);
List<ParticipantDataRow> data2 = createRows(headers, null, "7", "250", null, "3", "300");
data2 = bridge.appendParticipantData(participantDataDescriptor.getId(), data2);
List<ParticipantDataRow> data3 = createRows(headers, null, "5", "200");
data3 = bridgeTwo.appendParticipantData(participantDataDescriptor.getId(), data3);
PaginatedResults<ParticipantDataRow> one = bridge.getRawParticipantData(participantDataDescriptor.getId(), Integer.MAX_VALUE, 0, false);
PaginatedResults<ParticipantDataRow> two = bridgeTwo.getRawParticipantData(participantDataDescriptor.getId(), Integer.MAX_VALUE, 0, false);
assertEquals(3, one.getResults().size());
assertEquals(1, two.getResults().size());
assertEquals(data3, two.getResults());
}
@Test
public void testPaginatedParticipantData() throws Exception {
ParticipantDataDescriptor participantDataDescriptor = createDescriptor(false);
createColumnDescriptor(participantDataDescriptor, "level", ParticipantDataColumnType.STRING);
createColumnDescriptor(participantDataDescriptor, "size", ParticipantDataColumnType.STRING);
String[] headers = { "level", "size" };
List<ParticipantDataRow> data1 = createRows(headers, null, "5", "200", null, "6", "200", null, "7", "200");
data1 = bridge.appendParticipantData(participantDataDescriptor.getId(), data1);
PaginatedResults<ParticipantDataRow> result;
result = bridge.getRawParticipantData(participantDataDescriptor.getId(), 1, 0, false);
assertEquals(1, result.getResults().size());
assertEquals("5", ((ParticipantDataStringValue) result.getResults().get(0).getData().get("level")).getValue());
result = bridge.getRawParticipantData(participantDataDescriptor.getId(), 1, 1, false);
assertEquals(1, result.getResults().size());
assertEquals("6", ((ParticipantDataStringValue) result.getResults().get(0).getData().get("level")).getValue());
result = bridge.getRawParticipantData(participantDataDescriptor.getId(), 10, 1, false);
assertEquals(2, result.getResults().size());
assertEquals("6", ((ParticipantDataStringValue) result.getResults().get(0).getData().get("level")).getValue());
assertEquals("7", ((ParticipantDataStringValue) result.getResults().get(1).getData().get("level")).getValue());
}
@Test
public void testReplaceParticipantData() throws Exception {
ParticipantDataDescriptor participantDataDescriptor = createDescriptor(false);
createColumnDescriptor(participantDataDescriptor, "level", ParticipantDataColumnType.STRING);
createColumnDescriptor(participantDataDescriptor, "size", ParticipantDataColumnType.STRING);
String[] headers = { "level", "size" };
List<ParticipantDataRow> data1 = createRows(headers, null, "5", "200", null, "6", "200", null, "7", "200");
data1 = bridge.appendParticipantData(participantDataDescriptor.getId(), data1);
List<ParticipantDataRow> dataToReplace = createRows(headers, data1.get(1).getRowId(), "8", "200");
dataToReplace = bridge.updateParticipantData(participantDataDescriptor.getId(), dataToReplace);
PaginatedResults<ParticipantDataRow> result = bridge.getRawParticipantData(participantDataDescriptor.getId(), Integer.MAX_VALUE, 0, false);
assertEquals(3, result.getResults().size());
assertEquals("5", ((ParticipantDataStringValue) result.getResults().get(0).getData().get("level")).getValue());
assertEquals("8", ((ParticipantDataStringValue) result.getResults().get(1).getData().get("level")).getValue());
assertEquals("7", ((ParticipantDataStringValue) result.getResults().get(2).getData().get("level")).getValue());
}
@Test
public void testGetCurrentParticipantData() throws Exception {
ParticipantDataDescriptor participantDataDescriptor = createDescriptor(false);
createColumnDescriptor(participantDataDescriptor, "level", ParticipantDataColumnType.STRING);
createColumnDescriptor(participantDataDescriptor, "size", ParticipantDataColumnType.STRING);
String[] headers = { "level", "size" };
ParticipantDataStatusList statuses = new ParticipantDataStatusList();
ParticipantDataStatus update = new ParticipantDataStatus();
update.setParticipantDataDescriptorId(participantDataDescriptor.getId());
List<ParticipantDataStatus> updates = Collections.singletonList(update);
statuses.setUpdates(updates);
List<ParticipantDataRow> data1 = createRows(headers, null, "5", "200", null, "6", "200", null, "7", "200");
data1 = bridge.appendParticipantData(participantDataDescriptor.getId(), data1);
update.setLastEntryComplete(true);
bridge.sendParticipantDataDescriptorUpdates(statuses);
ParticipantDataCurrentRow currentRow = bridge.getCurrentParticipantData(participantDataDescriptor.getId(), false);
assertTrue(currentRow.getCurrentData().getData().isEmpty());
assertEquals("7", ((ParticipantDataStringValue) currentRow.getPreviousData().getData().get("level")).getValue());
update.setLastEntryComplete(false);
bridge.sendParticipantDataDescriptorUpdates(statuses);
currentRow = bridge.getCurrentParticipantData(participantDataDescriptor.getId(), false);
assertEquals("6", ((ParticipantDataStringValue) currentRow.getPreviousData().getData().get("level")).getValue());
assertEquals("7", ((ParticipantDataStringValue) currentRow.getCurrentData().getData().get("level")).getValue());
List<ParticipantDataRow> dataToReplace = createRows(headers, data1.get(2).getRowId(), "8", "200");
dataToReplace = bridge.updateParticipantData(participantDataDescriptor.getId(), dataToReplace);
currentRow = bridge.getCurrentParticipantData(participantDataDescriptor.getId(), false);
assertEquals("6", ((ParticipantDataStringValue) currentRow.getPreviousData().getData().get("level")).getValue());
assertEquals("8", ((ParticipantDataStringValue) currentRow.getCurrentData().getData().get("level")).getValue());
List<ParticipantDataRow> data3 = createRows(headers, null, "9", "200");
data3 = bridge.appendParticipantData(participantDataDescriptor.getId(), data3);
currentRow = bridge.getCurrentParticipantData(participantDataDescriptor.getId(), false);
assertEquals("8", ((ParticipantDataStringValue) currentRow.getPreviousData().getData().get("level")).getValue());
assertEquals("9", ((ParticipantDataStringValue) currentRow.getCurrentData().getData().get("level")).getValue());
update.setLastEntryComplete(true);
bridge.sendParticipantDataDescriptorUpdates(statuses);
currentRow = bridge.getCurrentParticipantData(participantDataDescriptor.getId(), false);
assertTrue(currentRow.getCurrentData().getData().isEmpty());
assertEquals("9", ((ParticipantDataStringValue) currentRow.getPreviousData().getData().get("level")).getValue());
}
@Test
public void testDeleteParticipantDataRows() throws Exception {
ParticipantDataDescriptor participantDataDescriptor = createDescriptor(false);
createColumnDescriptor(participantDataDescriptor, "level", ParticipantDataColumnType.STRING);
String[] headers = { "level" };
List<ParticipantDataRow> data1 = createRows(headers, null, "5", null, "200", null, "6");
data1 = bridge.appendParticipantData(participantDataDescriptor.getId(), data1);
List<Long> rowIds = Lists.newArrayListWithCapacity(data1.size());
for (ParticipantDataRow row : data1) {
rowIds.add(row.getRowId());
}
IdList idList = new IdList();
idList.setList(rowIds);
bridge.deleteParticipantDataRows(participantDataDescriptor.getId(), idList);
PaginatedResults<ParticipantDataRow> result = bridge.getRawParticipantData(participantDataDescriptor.getId(), 1000, 0, false);
assertEquals(0, result.getResults().size());
}
@Test
public void testGetCurrentRows() throws Exception {
ParticipantDataDescriptor participantDataDescriptor = createDescriptor(true);
createColumnDescriptor(participantDataDescriptor, "event", ParticipantDataColumnType.EVENT);
createColumnDescriptor(participantDataDescriptor, "level", ParticipantDataColumnType.DOUBLE);
String[] headers = { "event", "level" };
List<ParticipantDataRow> data1 = createRows(headers, null, ValueFactory.createEventValue(30000L, null, "a", null), 1.0, null,
ValueFactory.createEventValue(40000L, 50000L, "b", null), 2.0, null, ValueFactory.createEventValue(20000L, null, "c", null),
3.0);
data1 = bridge.appendParticipantData(participantDataDescriptor.getId(), data1);
List<ParticipantDataRow> currentRows = bridge.getCurrentRows(participantDataDescriptor.getId(), false);
assertEquals(2, currentRows.size());
assertEquals(20000L, getEvent(currentRows, 0, "event").getStart().longValue());
assertEquals(30000L, getEvent(currentRows, 1, "event").getStart().longValue());
}
@Test
public void testGetHistoryRows() throws Exception {
ParticipantDataDescriptor participantDataDescriptor = createDescriptor(true);
createColumnDescriptor(participantDataDescriptor, "event", ParticipantDataColumnType.EVENT);
createColumnDescriptor(participantDataDescriptor, "level", ParticipantDataColumnType.DOUBLE);
String[] headers = { "event", "level" };
List<ParticipantDataRow> data1 = createRows(headers, null, ValueFactory.createEventValue(40000L, null, "a", null), 1.0, null,
ValueFactory.createEventValue(30000L, 40000L, "b", null), 2.0, null,
ValueFactory.createEventValue(20000L, 30000L, "c", null), 3.0);
data1 = bridge.appendParticipantData(participantDataDescriptor.getId(), data1);
List<ParticipantDataRow> currentRows = bridge.getHistoryRows(participantDataDescriptor.getId(), null, null, false);
assertEquals(3, currentRows.size());
assertEquals(20000L, getEvent(currentRows, 0, "event").getStart().longValue());
assertEquals(30000L, getEvent(currentRows, 1, "event").getStart().longValue());
assertEquals(40000L, getEvent(currentRows, 2, "event").getStart().longValue());
currentRows = bridge.getHistoryRows(participantDataDescriptor.getId(), new Date(30000L), null, false);
assertEquals(2, currentRows.size());
assertEquals(30000L, getEvent(currentRows, 0, "event").getStart().longValue());
assertEquals(40000L, getEvent(currentRows, 1, "event").getStart().longValue());
currentRows = bridge.getHistoryRows(participantDataDescriptor.getId(), null, new Date(35000L), false);
assertEquals(2, currentRows.size());
assertEquals(20000L, getEvent(currentRows, 0, "event").getStart().longValue());
assertEquals(30000L, getEvent(currentRows, 1, "event").getStart().longValue());
currentRows = bridge.getHistoryRows(participantDataDescriptor.getId(), new Date(25000L), new Date(35000L), false);
assertEquals(1, currentRows.size());
assertEquals(30000L, getEvent(currentRows, 0, "event").getStart().longValue());
}
private ParticipantDataEventValue getEvent(List<ParticipantDataRow> rows, int index, String column) {
return ((ParticipantDataEventValue) rows.get(index).getData().get(column));
}
@Test
public void testGetTimeSeries() throws Exception {
ParticipantDataDescriptor participantDataDescriptor = createDescriptor(false);
createColumnDescriptor(participantDataDescriptor, "date", ParticipantDataColumnType.DATETIME);
createColumnDescriptor(participantDataDescriptor, "level", ParticipantDataColumnType.DOUBLE);
createColumnDescriptor(participantDataDescriptor, "size", ParticipantDataColumnType.LONG);
String[] headers = { "date", "level", "size" };
ParticipantDataStatusList statuses = new ParticipantDataStatusList();
ParticipantDataStatus update = new ParticipantDataStatus();
update.setParticipantDataDescriptorId(participantDataDescriptor.getId());
List<ParticipantDataStatus> updates = Collections.singletonList(update);
statuses.setUpdates(updates);
List<ParticipantDataRow> data1 = createRows(headers, null, new Date(10000), 5.5, 400L, null, new Date(20000), 6.6, null, null,
new Date(30000), 7.7, 200L);
data1 = bridge.appendParticipantData(participantDataDescriptor.getId(), data1);
TimeSeriesTable timeSeries = bridge.getTimeSeries(participantDataDescriptor.getId(), null, false);
assertEquals(3, timeSeries.getColumns().size());
assertEquals(3, timeSeries.getRows().size());
assertEquals(0, timeSeries.getEvents().size());
assertEquals(3, timeSeries.getRows().get(0).getValues().size());
assertEquals(3, timeSeries.getRows().get(1).getValues().size());
assertEquals(3, timeSeries.getRows().get(2).getValues().size());
assertEquals(0, timeSeries.getDateIndex().intValue());
int levelIndex = 1;
int sizeIndex = 2;
if (timeSeries.getColumns().get(1).equals("size")) {
levelIndex = 2;
sizeIndex = 1;
}
assertEquals(new Date(30000).getTime(),
Long.parseLong(timeSeries.getRows().get(2).getValues().get(timeSeries.getDateIndex().intValue())));
assertEquals(7.7, Double.parseDouble(timeSeries.getRows().get(2).getValues().get(levelIndex)), 0.0001);
assertEquals(200.0, Double.parseDouble(timeSeries.getRows().get(2).getValues().get(sizeIndex)), 0.0001);
assertNull(timeSeries.getRows().get(1).getValues().get(sizeIndex));
TimeSeriesTable level = bridge.getTimeSeries(participantDataDescriptor.getId(), Lists.newArrayList("level"), false);
assertEquals(2, level.getColumns().size());
assertEquals(3, level.getRows().size());
assertEquals(2, level.getRows().get(0).getValues().size());
assertEquals(2, level.getRows().get(1).getValues().size());
assertEquals(2, level.getRows().get(2).getValues().size());
assertEquals(0, level.getDateIndex().intValue());
assertEquals(7.7, Double.parseDouble(level.getRows().get(2).getValues().get(1)), 0.0001);
TimeSeriesTable size = bridge.getTimeSeries(participantDataDescriptor.getId(), Lists.newArrayList("size"), false);
assertEquals(2, size.getColumns().size());
assertEquals(3, size.getRows().size());
assertEquals(2, size.getRows().get(0).getValues().size());
assertEquals(2, size.getRows().get(1).getValues().size());
assertEquals(2, size.getRows().get(2).getValues().size());
assertEquals(0, size.getDateIndex().intValue());
assertEquals(200.0, Double.parseDouble(size.getRows().get(2).getValues().get(1)), 0.0001);
TimeSeriesTable namedColumns = bridge.getTimeSeries(participantDataDescriptor.getId(), Lists.newArrayList("level", "size"), false);
assertEquals(timeSeries, namedColumns);
}
@Test
public void testGetEventTimeSeries() throws Exception {
ParticipantDataDescriptor participantDataDescriptor = createDescriptor(true);
createColumnDescriptor(participantDataDescriptor, "event", ParticipantDataColumnType.EVENT);
createColumnDescriptor(participantDataDescriptor, "level", ParticipantDataColumnType.DOUBLE);
createColumnDescriptor(participantDataDescriptor, "size", ParticipantDataColumnType.LONG);
String[] headers = { "event", "level", "size" };
ParticipantDataStatusList statuses = new ParticipantDataStatusList();
ParticipantDataStatus update = new ParticipantDataStatus();
update.setParticipantDataDescriptorId(participantDataDescriptor.getId());
List<ParticipantDataStatus> updates = Collections.singletonList(update);
statuses.setUpdates(updates);
List<ParticipantDataRow> data1 = createRows(headers, null, ValueFactory.createEventValue(50000L, 60000L, "a1", "aa"), 5.5, 400L,
null, ValueFactory.createEventValue(40000L, 50000L, "a2", "aa"), 5.5, 400L, null,
ValueFactory.createEventValue(10000L, 20000L, "b1", "bb"), 6.61, null, null,
ValueFactory.createEventValue(30000L, null, "b2", "bb"), 6.63, null, null,
ValueFactory.createEventValue(20000L, 30000L, "b2", "bb"), 6.62, null, null,
ValueFactory.createEventValue(20000L, 30000L, "c", null), 7.7, 200L, null,
ValueFactory.createEventValue(60000L, 30000L, "d", null), 8.8, 300L);
data1 = bridge.appendParticipantData(participantDataDescriptor.getId(), data1);
TimeSeriesTable timeSeries = bridge.getTimeSeries(participantDataDescriptor.getId(), null, false);
assertEquals(3, timeSeries.getColumns().size());
assertEquals(0, timeSeries.getRows().size());
assertEquals(4, timeSeries.getEvents().size());
assertEquals(ValueFactory.createEventValue(10000L, null, "b1", "bb"), timeSeries.getEvents().get(0));
assertEquals(ValueFactory.createEventValue(20000L, 30000L, "c", null), timeSeries.getEvents().get(1));
assertEquals(ValueFactory.createEventValue(40000L, 60000L, "a2", "aa"), timeSeries.getEvents().get(2));
assertEquals(ValueFactory.createEventValue(60000L, 30000L, "d", null), timeSeries.getEvents().get(3));
}
@Test
public void testGetParticipantDataDescriptorWithColumnsAndStatus() throws Exception {
java.util.Date lastPrompted = new java.util.Date();
ParticipantDataDescriptor descriptor = createDescriptor(false);
createColumnDescriptor(descriptor, "date", ParticipantDataColumnType.DATETIME);
createColumnDescriptor(descriptor, "level", ParticipantDataColumnType.DOUBLE);
createColumnDescriptor(descriptor, "size", ParticipantDataColumnType.LONG);
// Create some data so status can be updated
String[] headers = { "date", "level", "size" };
List<ParticipantDataRow> data1 = createRows(headers, null, new Date(10000), 5.5, 400L, null, new Date(20000),
6.6, null, null, new Date(30000), 7.7, 200L);
bridge.appendParticipantData(descriptor.getId(), data1);
ParticipantDataStatusList statuses = new ParticipantDataStatusList();
ParticipantDataStatus status = new ParticipantDataStatus();
status.setLastEntryComplete(true);
status.setLastPrompted(lastPrompted);
status.setParticipantDataDescriptorId(descriptor.getId());
statuses.setUpdates(Collections.singletonList(status));
bridge.sendParticipantDataDescriptorUpdates(statuses);
ParticipantDataDescriptorWithColumns descriptorWithColumns = bridge
.getParticipantDataDescriptorWithColumns(descriptor.getId());
assertEquals(descriptor.getId(), descriptorWithColumns.getDescriptor().getId());
assertEquals(3, descriptorWithColumns.getColumns().size());
assertEquals("date", descriptorWithColumns.getColumns().get(0).getName());
assertEquals(lastPrompted, descriptorWithColumns.getDescriptor().getStatus().getLastPrompted());
assertTrue(descriptorWithColumns.getDescriptor().getStatus().getLastEntryComplete());
}
private void createColumnDescriptor(ParticipantDataDescriptor participantDataDescriptor, String columnName,
ParticipantDataColumnType columnType) throws SynapseException {
ParticipantDataColumnDescriptor participantDataColumnDescriptor1 = new ParticipantDataColumnDescriptor();
participantDataColumnDescriptor1.setParticipantDataDescriptorId(participantDataDescriptor.getId());
participantDataColumnDescriptor1.setColumnType(columnType);
participantDataColumnDescriptor1.setName(columnName);
bridge.createParticipantDataColumnDescriptor(participantDataColumnDescriptor1);
}
private ParticipantDataDescriptor createDescriptor(boolean hasEvents) throws SynapseException {
ParticipantDataDescriptor participantDataDescriptor = new ParticipantDataDescriptor();
participantDataDescriptor.setName("my-first-participantData-" + System.currentTimeMillis());
participantDataDescriptor.setRepeatType(ParticipantDataRepeatType.ALWAYS);
participantDataDescriptor.setDatetimeStartColumnName("date");
if (hasEvents) {
participantDataDescriptor.setEventColumnName("event");
}
participantDataDescriptor = bridge.createParticipantDataDescriptor(participantDataDescriptor);
return participantDataDescriptor;
}
private List<ParticipantDataRow> createRows(String[] headers, Object... values) {
List<ParticipantDataRow> data = Lists.newArrayList();
for (int i = 0; i < values.length; i += headers.length + 1) {
ParticipantDataRow row = new ParticipantDataRow();
row.setData(Maps.<String, ParticipantDataValue> newHashMap());
row.setRowId((Long) values[i]);
data.add(row);
for (int j = 0; j < headers.length; j++) {
if (values[i + j + 1] != null) {
row.getData().put(headers[j], getValue(values[i + j + 1]));
}
}
}
return data;
}
private ParticipantDataValue getValue(Object value) {
if (value instanceof Date) {
ParticipantDataDatetimeValue result = new ParticipantDataDatetimeValue();
result.setValue(((Date) value).getTime());
return result;
}
if (value instanceof Long) {
ParticipantDataLongValue result = new ParticipantDataLongValue();
result.setValue((Long) value);
return result;
}
if (value instanceof Double) {
ParticipantDataDoubleValue result = new ParticipantDataDoubleValue();
result.setValue((Double) value);
return result;
}
if (value instanceof String) {
ParticipantDataStringValue result = new ParticipantDataStringValue();
result.setValue((String) value);
return result;
}
if (value instanceof ParticipantDataEventValue) {
return (ParticipantDataEventValue) value;
}
throw new IllegalArgumentException(value.getClass().getName());
}
}
| IT test
| integration-test/src/test/java/org/sagebionetworks/IT610BridgeData.java | IT test | <ide><path>ntegration-test/src/test/java/org/sagebionetworks/IT610BridgeData.java
<ide> import java.sql.Date;
<ide> import java.util.ArrayList;
<ide> import java.util.Collections;
<add>import java.util.HashMap;
<ide> import java.util.List;
<ide>
<ide> import org.junit.After;
<ide> import org.sagebionetworks.bridge.model.data.ParticipantDataRow;
<ide> import org.sagebionetworks.bridge.model.data.ParticipantDataStatus;
<ide> import org.sagebionetworks.bridge.model.data.ParticipantDataStatusList;
<add>import org.sagebionetworks.bridge.model.data.units.Units;
<ide> import org.sagebionetworks.bridge.model.data.value.ParticipantDataDatetimeValue;
<ide> import org.sagebionetworks.bridge.model.data.value.ParticipantDataDoubleValue;
<ide> import org.sagebionetworks.bridge.model.data.value.ParticipantDataEventValue;
<add>import org.sagebionetworks.bridge.model.data.value.ParticipantDataLabValue;
<ide> import org.sagebionetworks.bridge.model.data.value.ParticipantDataLongValue;
<ide> import org.sagebionetworks.bridge.model.data.value.ParticipantDataStringValue;
<ide> import org.sagebionetworks.bridge.model.data.value.ParticipantDataValue;
<ide> }
<ide>
<ide> @Test
<add> public void saveDataAndRetrieveNormalized() throws Exception {
<add> List<ParticipantDataRow> rows = Lists.newArrayList();
<add> ParticipantDataRow row = new ParticipantDataRow();
<add> row.setData(Maps.<String,ParticipantDataValue>newHashMap());
<add> ParticipantDataLabValue lab = new ParticipantDataLabValue();
<add> lab.setValue(1000d);
<add> lab.setUnits(Units.MILLILITER.getLabels().get(0));
<add> lab.setMinNormal(500d);
<add> lab.setMaxNormal(1500d);
<add> row.getData().put("lab", lab);
<add> rows.add(row);
<add>
<add> ParticipantDataDescriptor descriptor = createDescriptor(false);
<add> createColumnDescriptor(descriptor, "lab", ParticipantDataColumnType.LAB);
<add>
<add> List<ParticipantDataRow> saved = bridge.appendParticipantData(descriptor.getId(), rows);
<add> Long rowId = saved.get(0).getRowId();
<add>
<add> // Milliliters should be converted to liters.
<add> ParticipantDataRow convertedRow = bridge.getParticipantDataRow(descriptor.getId(), rowId, true);
<add> ParticipantDataLabValue savedLab = (ParticipantDataLabValue)convertedRow.getData().get("lab");
<add> assertEquals(1d, savedLab.getValue(), 0.0);
<add> assertEquals("L", savedLab.getUnits());
<add> assertEquals(0.5d, savedLab.getMinNormal(), 0.0);
<add> assertEquals(1.5d, savedLab.getMaxNormal(), 0.0);
<add> }
<add>
<add> @Test
<ide> public void testGetVersion() throws Exception {
<ide> BridgeVersionInfo versionInfo = bridge.getBridgeVersionInfo();
<ide> assertFalse(versionInfo.getVersion().isEmpty()); |
|
Java | apache-2.0 | 13f897b83e8c5188187589d60fe6b6b86a840cbe | 0 | etiennestuder/teamcity-build-scan-plugin,etiennestuder/teamcity-build-scan-plugin,etiennestuder/teamcity-build-scan-plugin | package nu.studer.teamcity.buildscan.agent;
import jetbrains.buildServer.agent.AgentLifeCycleAdapter;
import jetbrains.buildServer.agent.AgentLifeCycleListener;
import jetbrains.buildServer.agent.BuildRunnerContext;
import jetbrains.buildServer.util.EventDispatcher;
import jetbrains.buildServer.util.FileUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* This class is responsible for injecting a Gradle init script into all Gradle build runners. This init script itself registers a callback on the build scan plugin for any
* published build scans and emits a TeamCity {@link jetbrains.buildServer.messages.serviceMessages.ServiceMessage} containing the scan URL.
* <p>
* In the presence of certain configuration parameters, this class will also inject Gradle Enterprise and Common Custom User Data plugins and extensions into Gradle and Maven
* builds.
*/
public final class BuildScanServiceMessageInjector extends AgentLifeCycleAdapter {
// TeamCity Gradle runner
private static final String GRADLE_RUNNER = "gradle-runner";
private static final String GRADLE_CMD_PARAMS = "ui.gradleRunner.additional.gradle.cmd.params";
private static final String BUILD_SCAN_INIT_GRADLE = "build-scan-init.gradle";
// TeamCity Maven runner
private static final String MAVEN_RUNNER = "Maven2";
private static final String MAVEN_CMD_PARAMS = "runnerArgs";
private static final String BUILD_SCAN_EXT_MAVEN = "service-message-maven-extension-1.0.jar";
private static final String GRADLE_ENTERPRISE_EXT_MAVEN = "gradle-enterprise-maven-extension-1.14.1.jar";
private static final String COMMON_CUSTOM_USER_DATA_EXT_MAVEN = "common-custom-user-data-maven-extension-1.10.1.jar";
// Gradle TeamCity Build Scan plugin
private static final String GRADLE_BUILDSCAN_TEAMCITY_PLUGIN = "GRADLE_BUILDSCAN_TEAMCITY_PLUGIN";
// TeamCity GE configuration parameters
private static final String GE_URL_CONFIG_PARAM = "buildScanPlugin.gradle-enterprise.url";
private static final String GE_PLUGIN_VERSION_CONFIG_PARAM = "buildScanPlugin.gradle-enterprise.plugin.version";
private static final String CCUD_PLUGIN_VERSION_CONFIG_PARAM = "buildScanPlugin.ccud.plugin.version";
private static final String GE_EXTENSION_VERSION_CONFIG_PARAM = "buildScanPlugin.gradle-enterprise.extension.version";
private static final String CCUD_EXTENSION_VERSION_CONFIG_PARAM = "buildScanPlugin.ccud.extension.version";
// Gradle properties and Maven system properties passed to the artifact instrumenting the Gradle / Maven build
private static final String GE_URL_GRADLE_PROPERTY = "teamCityBuildScanPlugin.gradle-enterprise.url";
private static final String GE_PLUGIN_VERSION_GRADLE_PROPERTY = "teamCityBuildScanPlugin.gradle-enterprise.plugin.version";
private static final String CCUD_PLUGIN_VERSION_GRADLE_PROPERTY = "teamCityBuildScanPlugin.ccud.plugin.version";
private static final String GE_URL_MAVEN_PROPERTY = "gradle.enterprise.url";
private static final MavenCoordinates GE_EXTENSION_MAVEN_COORDINATES = new MavenCoordinates("com.gradle", "gradle-enterprise-maven-extension");
private static final MavenCoordinates CCUD_EXTENSION_MAVEN_COORDINATES = new MavenCoordinates("com.gradle", "common-custom-user-data-maven-extension");
public BuildScanServiceMessageInjector(@NotNull EventDispatcher<AgentLifeCycleListener> eventDispatcher) {
eventDispatcher.addListener(this);
}
@Override
public void beforeRunnerStart(@NotNull BuildRunnerContext runner) {
if (runner.getRunType().equalsIgnoreCase(GRADLE_RUNNER)) {
addGradleSysPropIfSet(GE_URL_CONFIG_PARAM, GE_URL_GRADLE_PROPERTY, runner);
addGradleSysPropIfSet(GE_PLUGIN_VERSION_CONFIG_PARAM, GE_PLUGIN_VERSION_GRADLE_PROPERTY, runner);
addGradleSysPropIfSet(CCUD_PLUGIN_VERSION_CONFIG_PARAM, CCUD_PLUGIN_VERSION_GRADLE_PROPERTY, runner);
String initScriptParam = "--init-script " + getInitScript(runner).getAbsolutePath();
addGradleCmdParam(initScriptParam, runner);
addEnvVar(GRADLE_BUILDSCAN_TEAMCITY_PLUGIN, "1", runner);
} else if (runner.getRunType().equalsIgnoreCase(MAVEN_RUNNER)) {
// for now, this intentionally ignores the configured extension versions and applies the bundled jars
String extJarParam = "-Dmaven.ext.class.path=" + getExtensionsClasspath(runner);
addMavenCmdParam(extJarParam, runner);
addEnvVar(GRADLE_BUILDSCAN_TEAMCITY_PLUGIN, "1", runner);
}
}
private File getInitScript(BuildRunnerContext runner) {
File initScript = new File(runner.getBuild().getAgentTempDirectory(), BUILD_SCAN_INIT_GRADLE);
FileUtil.copyResourceIfNotExists(BuildScanServiceMessageInjector.class, "/" + BUILD_SCAN_INIT_GRADLE, initScript);
return initScript;
}
private String getExtensionsClasspath(BuildRunnerContext runner) {
List<File> extensionJars = new ArrayList<File>();
// add extension to capture build scan URL
extensionJars.add(getExtensionJar(BUILD_SCAN_EXT_MAVEN, runner));
// optionally add extensions that connect the Maven build with Gradle Enterprise
MavenExtensions extensions = getMavenExtensions(runner);
String geExtensionVersion = getOptionalConfigParam(GE_EXTENSION_VERSION_CONFIG_PARAM, runner);
if (geExtensionVersion != null) {
if (!extensions.hasExtension(GE_EXTENSION_MAVEN_COORDINATES)) {
extensionJars.add(getExtensionJar(GRADLE_ENTERPRISE_EXT_MAVEN, runner));
addMavenSysPropIfSet(GE_URL_CONFIG_PARAM, GE_URL_MAVEN_PROPERTY, runner);
}
}
String ccudExtensionVersion = getOptionalConfigParam(CCUD_EXTENSION_VERSION_CONFIG_PARAM, runner);
if (ccudExtensionVersion != null) {
if (!extensions.hasExtension(CCUD_EXTENSION_MAVEN_COORDINATES)) {
extensionJars.add(getExtensionJar(COMMON_CUSTOM_USER_DATA_EXT_MAVEN, runner));
}
}
return asClasspath(extensionJars);
}
private File getExtensionJar(String name, BuildRunnerContext runner) {
File extensionJar = new File(runner.getBuild().getAgentTempDirectory(), name);
FileUtil.copyResourceIfNotExists(BuildScanServiceMessageInjector.class, "/" + name, extensionJar);
return extensionJar;
}
private MavenExtensions getMavenExtensions(BuildRunnerContext runner) {
String checkoutDirParam = getOptionalRunnerParam("teamcity.build.checkoutDir", runner);
String workingDirParam = getOptionalRunnerParam("teamcity.build.workingDir", runner);
String pomLocation = getOptionalRunnerParam("pomLocation", runner);
File workingDir;
if (checkoutDirParam != null && pomLocation != null) {
// in TC, the pomLocation is always relative to the checkout dir, even if a specific working dir has been configured
workingDir = new File(checkoutDirParam, pomLocation).getParentFile();
} else if (workingDirParam != null) {
// either the working dir is set explicitly in the TC config, or it is set implicitly as the value of the checkout dir
workingDir = new File(workingDirParam);
} else {
// should never be the case
workingDir = null;
}
return workingDir != null ? MavenExtensions.fromFile(new File(workingDir, ".mvn/extensions.xml")) : MavenExtensions.empty();
}
@SuppressWarnings("SameParameterValue")
private static void addEnvVar(@NotNull String key, @NotNull String value, @NotNull BuildRunnerContext runner) {
runner.addEnvironmentVariable(key, value);
}
private static void addGradleSysPropIfSet(@NotNull String configParameter, @NotNull String property, @NotNull BuildRunnerContext runner) {
String value = getOptionalConfigParam(configParameter, runner);
if (value != null) {
addGradleSysProp(property, value, runner);
}
}
private static void addGradleSysProp(@NotNull String key, @NotNull String value, @NotNull BuildRunnerContext runner) {
String systemProp = String.format("-D%s=%s", key, value);
addGradleCmdParam(systemProp, runner);
}
private static void addGradleCmdParam(@NotNull String param, @NotNull BuildRunnerContext runner) {
String gradleCmdParam = getOptionalRunnerParam(GRADLE_CMD_PARAMS, runner);
runner.addRunnerParameter(GRADLE_CMD_PARAMS, gradleCmdParam != null ? param + " " + gradleCmdParam : param);
}
private static void addMavenSysPropIfSet(@NotNull String configParameter, @NotNull String property, @NotNull BuildRunnerContext runner) {
String value = getOptionalConfigParam(configParameter, runner);
if (value != null) {
addMavenSysProp(property, value, runner);
}
}
private static void addMavenSysProp(@NotNull String key, @NotNull String value, @NotNull BuildRunnerContext runner) {
String systemProp = String.format("-D%s=%s", key, value);
addMavenCmdParam(systemProp, runner);
}
private static void addMavenCmdParam(@NotNull String param, @NotNull BuildRunnerContext runner) {
String mavenCmdParam = getOptionalRunnerParam(MAVEN_CMD_PARAMS, runner);
runner.addRunnerParameter(MAVEN_CMD_PARAMS, mavenCmdParam != null ? param + " " + mavenCmdParam : param);
}
@Nullable
private static String getOptionalConfigParam(@NotNull String paramName, @NotNull BuildRunnerContext runner) {
return getOptionalParam(paramName, runner.getConfigParameters());
}
@Nullable
private static String getOptionalRunnerParam(@NotNull String paramName, @NotNull BuildRunnerContext runner) {
return getOptionalParam(paramName, runner.getRunnerParameters());
}
@Nullable
private static String getOptionalParam(@NotNull String paramName, @NotNull Map<String, String> params) {
if (!params.containsKey(paramName)) {
return null;
}
String value = params.get(paramName).trim();
return value.isEmpty() ? null : value;
}
@NotNull
private static String asClasspath(List<File> files) {
StringBuilder sb = new StringBuilder();
for (File file : files) {
if (sb.length() > 0) {
sb.append(File.pathSeparator);
}
sb.append(file.getAbsolutePath());
}
return sb.toString();
}
}
| agent/src/main/java/nu/studer/teamcity/buildscan/agent/BuildScanServiceMessageInjector.java | package nu.studer.teamcity.buildscan.agent;
import jetbrains.buildServer.agent.AgentLifeCycleAdapter;
import jetbrains.buildServer.agent.AgentLifeCycleListener;
import jetbrains.buildServer.agent.BuildRunnerContext;
import jetbrains.buildServer.util.EventDispatcher;
import jetbrains.buildServer.util.FileUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* This class is responsible for injecting a Gradle init script into all Gradle build runners. This init script itself registers a callback on the build scan plugin for any
* published build scans and emits a TeamCity {@link jetbrains.buildServer.messages.serviceMessages.ServiceMessage} containing the scan URL.
* <p>
* In the presence of certain configuration parameters, this class will also inject Gradle Enterprise and Common Custom User Data plugins and extensions into Gradle and Maven
* builds.
*/
public final class BuildScanServiceMessageInjector extends AgentLifeCycleAdapter {
// TeamCity Gradle runner
private static final String GRADLE_RUNNER = "gradle-runner";
private static final String GRADLE_CMD_PARAMS = "ui.gradleRunner.additional.gradle.cmd.params";
private static final String BUILD_SCAN_INIT_GRADLE = "build-scan-init.gradle";
// TeamCity Maven runner
private static final String MAVEN_RUNNER = "Maven2";
private static final String MAVEN_CMD_PARAMS = "runnerArgs";
private static final String BUILD_SCAN_EXT_MAVEN = "service-message-maven-extension-1.0.jar";
private static final String GRADLE_ENTERPRISE_EXT_MAVEN = "gradle-enterprise-maven-extension-1.14.1.jar";
private static final String COMMON_CUSTOM_USER_DATA_EXT_MAVEN = "common-custom-user-data-maven-extension-1.10.1.jar";
// Gradle TeamCity Build Scan plugin
private static final String GRADLE_BUILDSCAN_TEAMCITY_PLUGIN = "GRADLE_BUILDSCAN_TEAMCITY_PLUGIN";
// TeamCity GE configuration parameters
private static final String GE_URL_CONFIG_PARAM = "buildScanPlugin.gradle-enterprise.url";
private static final String GE_PLUGIN_VERSION_CONFIG_PARAM = "buildScanPlugin.gradle-enterprise.plugin.version";
private static final String CCUD_PLUGIN_VERSION_CONFIG_PARAM = "buildScanPlugin.ccud.plugin.version";
private static final String GE_EXTENSION_VERSION_CONFIG_PARAM = "buildScanPlugin.gradle-enterprise.extension.version";
private static final String CCUD_EXTENSION_VERSION_CONFIG_PARAM = "buildScanPlugin.ccud.extension.version";
// Gradle properties and Maven system properties passed to the artifact instrumenting the Gradle / Maven build
private static final String GE_URL_GRADLE_PROPERTY = "teamCityBuildScanPlugin.gradle-enterprise.url";
private static final String GE_PLUGIN_VERSION_GRADLE_PROPERTY = "teamCityBuildScanPlugin.gradle-enterprise.plugin.version";
private static final String CCUD_PLUGIN_VERSION_GRADLE_PROPERTY = "teamCityBuildScanPlugin.ccud.plugin.version";
private static final String GE_URL_MAVEN_PROPERTY = "gradle.enterprise.url";
private static final MavenCoordinates GE_EXTENSION_MAVEN_COORDINATES = new MavenCoordinates("com.gradle", "gradle-enterprise-maven-extension");
private static final MavenCoordinates CCUD_EXTENSION_MAVEN_COORDINATES = new MavenCoordinates("com.gradle", "common-custom-user-data-maven-extension");
public BuildScanServiceMessageInjector(@NotNull EventDispatcher<AgentLifeCycleListener> eventDispatcher) {
eventDispatcher.addListener(this);
}
@Override
public void beforeRunnerStart(@NotNull BuildRunnerContext runner) {
if (runner.getRunType().equalsIgnoreCase(GRADLE_RUNNER)) {
addGradleSysPropIfSet(GE_URL_CONFIG_PARAM, GE_URL_GRADLE_PROPERTY, runner);
addGradleSysPropIfSet(GE_PLUGIN_VERSION_CONFIG_PARAM, GE_PLUGIN_VERSION_GRADLE_PROPERTY, runner);
addGradleSysPropIfSet(CCUD_PLUGIN_VERSION_CONFIG_PARAM, CCUD_PLUGIN_VERSION_GRADLE_PROPERTY, runner);
String initScriptParam = "--init-script " + getInitScript(runner).getAbsolutePath();
addGradleCmdParam(initScriptParam, runner);
addEnvVar(GRADLE_BUILDSCAN_TEAMCITY_PLUGIN, "1", runner);
} else if (runner.getRunType().equalsIgnoreCase(MAVEN_RUNNER)) {
// for now, this intentionally ignores the configured extension versions and applies the bundled jars
String extJarParam = "-Dmaven.ext.class.path=" + getExtensionsClasspath(runner);
addMavenCmdParam(extJarParam, runner);
addEnvVar(GRADLE_BUILDSCAN_TEAMCITY_PLUGIN, "1", runner);
}
}
private File getInitScript(BuildRunnerContext runner) {
File initScript = new File(runner.getBuild().getAgentTempDirectory(), BUILD_SCAN_INIT_GRADLE);
FileUtil.copyResourceIfNotExists(BuildScanServiceMessageInjector.class, "/" + BUILD_SCAN_INIT_GRADLE, initScript);
return initScript;
}
private String getExtensionsClasspath(BuildRunnerContext runner) {
List<File> extensionJars = new ArrayList<File>();
// add extension to capture build scan URL
extensionJars.add(getExtensionJar(BUILD_SCAN_EXT_MAVEN, runner));
// optionally add extensions that connect the Maven build with Gradle Enterprise
MavenExtensions extensions = getMavenExtensions(runner);
String geExtensionVersion = getOptionalConfigParam(GE_EXTENSION_VERSION_CONFIG_PARAM, runner);
if (geExtensionVersion != null) {
if (!extensions.hasExtension(GE_EXTENSION_MAVEN_COORDINATES)) {
extensionJars.add(getExtensionJar(GRADLE_ENTERPRISE_EXT_MAVEN, runner));
addMavenSysPropIfSet(GE_URL_CONFIG_PARAM, GE_URL_MAVEN_PROPERTY, runner);
}
}
String ccudExtensionVersion = getOptionalConfigParam(CCUD_EXTENSION_VERSION_CONFIG_PARAM, runner);
if (ccudExtensionVersion != null) {
if (!extensions.hasExtension(CCUD_EXTENSION_MAVEN_COORDINATES)) {
extensionJars.add(getExtensionJar(COMMON_CUSTOM_USER_DATA_EXT_MAVEN, runner));
}
}
return asClasspath(extensionJars);
}
private File getExtensionJar(String name, BuildRunnerContext runner) {
File extensionJar = new File(runner.getBuild().getAgentTempDirectory(), name);
FileUtil.copyResourceIfNotExists(BuildScanServiceMessageInjector.class, "/" + name, extensionJar);
return extensionJar;
}
private MavenExtensions getMavenExtensions(BuildRunnerContext runner) {
String workingDirParam = getOptionalRunnerParam("teamcity.build.workingDir", runner);
String pomLocation = getOptionalRunnerParam("pomLocation", runner);
File workingDir;
if (pomLocation != null) {
String checkoutDirParam = getOptionalRunnerParam("teamcity.build.checkoutDir", runner);
workingDir = new File(checkoutDirParam, pomLocation).getParentFile();
} else if (workingDirParam != null) {
workingDir = new File(workingDirParam);
} else {
return MavenExtensions.empty();
}
File extensionFile = new File(workingDir, ".mvn/extensions.xml");
return MavenExtensions.fromFile(extensionFile);
}
@SuppressWarnings("SameParameterValue")
private static void addEnvVar(@NotNull String key, @NotNull String value, @NotNull BuildRunnerContext runner) {
runner.addEnvironmentVariable(key, value);
}
private static void addGradleSysPropIfSet(@NotNull String configParameter, @NotNull String property, @NotNull BuildRunnerContext runner) {
String value = getOptionalConfigParam(configParameter, runner);
if (value != null) {
addGradleSysProp(property, value, runner);
}
}
private static void addGradleSysProp(@NotNull String key, @NotNull String value, @NotNull BuildRunnerContext runner) {
String systemProp = String.format("-D%s=%s", key, value);
addGradleCmdParam(systemProp, runner);
}
private static void addGradleCmdParam(@NotNull String param, @NotNull BuildRunnerContext runner) {
String existingParams = getOrDefault(GRADLE_CMD_PARAMS, runner);
runner.addRunnerParameter(GRADLE_CMD_PARAMS, param + " " + existingParams);
}
private static void addMavenSysPropIfSet(@NotNull String configParameter, @NotNull String property, @NotNull BuildRunnerContext runner) {
String value = getOptionalConfigParam(configParameter, runner);
if (value != null) {
addMavenSysProp(property, value, runner);
}
}
private static void addMavenSysProp(@NotNull String key, @NotNull String value, @NotNull BuildRunnerContext runner) {
String systemProp = String.format("-D%s=%s", key, value);
addMavenCmdParam(systemProp, runner);
}
private static void addMavenCmdParam(@NotNull String param, @NotNull BuildRunnerContext runner) {
String existingParams = getOrDefault(MAVEN_CMD_PARAMS, runner);
runner.addRunnerParameter(MAVEN_CMD_PARAMS, param + " " + existingParams);
}
@Nullable
private static String getOptionalConfigParam(@NotNull String paramName, @NotNull BuildRunnerContext runner) {
return getOptionalParam(paramName, runner.getConfigParameters());
}
@Nullable
private static String getOptionalRunnerParam(@NotNull String paramName, @NotNull BuildRunnerContext runner) {
return getOptionalParam(paramName, runner.getRunnerParameters());
}
@Nullable
private static String getOptionalParam(@NotNull String paramName, @NotNull Map<String, String> params) {
if (!params.containsKey(paramName)) {
return null;
}
String value = params.get(paramName).trim();
return value.isEmpty() ? null : value;
}
private static String getOrDefault(@NotNull String paramName, @NotNull BuildRunnerContext runner) {
Map<String, String> runnerParameters = runner.getRunnerParameters();
return runnerParameters.containsKey(paramName) ? runnerParameters.get(paramName) : "";
}
@NotNull
private static String asClasspath(List<File> files) {
StringBuilder sb = new StringBuilder();
for (File file : files) {
if (sb.length() > 0) {
sb.append(File.pathSeparator);
}
sb.append(file.getAbsolutePath());
}
return sb.toString();
}
}
| Add some comments
| agent/src/main/java/nu/studer/teamcity/buildscan/agent/BuildScanServiceMessageInjector.java | Add some comments | <ide><path>gent/src/main/java/nu/studer/teamcity/buildscan/agent/BuildScanServiceMessageInjector.java
<ide> }
<ide>
<ide> private MavenExtensions getMavenExtensions(BuildRunnerContext runner) {
<add> String checkoutDirParam = getOptionalRunnerParam("teamcity.build.checkoutDir", runner);
<ide> String workingDirParam = getOptionalRunnerParam("teamcity.build.workingDir", runner);
<ide> String pomLocation = getOptionalRunnerParam("pomLocation", runner);
<ide>
<ide> File workingDir;
<del> if (pomLocation != null) {
<del> String checkoutDirParam = getOptionalRunnerParam("teamcity.build.checkoutDir", runner);
<add> if (checkoutDirParam != null && pomLocation != null) {
<add> // in TC, the pomLocation is always relative to the checkout dir, even if a specific working dir has been configured
<ide> workingDir = new File(checkoutDirParam, pomLocation).getParentFile();
<ide> } else if (workingDirParam != null) {
<add> // either the working dir is set explicitly in the TC config, or it is set implicitly as the value of the checkout dir
<ide> workingDir = new File(workingDirParam);
<ide> } else {
<del> return MavenExtensions.empty();
<del> }
<del>
<del> File extensionFile = new File(workingDir, ".mvn/extensions.xml");
<del> return MavenExtensions.fromFile(extensionFile);
<add> // should never be the case
<add> workingDir = null;
<add> }
<add>
<add> return workingDir != null ? MavenExtensions.fromFile(new File(workingDir, ".mvn/extensions.xml")) : MavenExtensions.empty();
<ide> }
<ide>
<ide> @SuppressWarnings("SameParameterValue")
<ide> }
<ide>
<ide> private static void addGradleCmdParam(@NotNull String param, @NotNull BuildRunnerContext runner) {
<del> String existingParams = getOrDefault(GRADLE_CMD_PARAMS, runner);
<del> runner.addRunnerParameter(GRADLE_CMD_PARAMS, param + " " + existingParams);
<add> String gradleCmdParam = getOptionalRunnerParam(GRADLE_CMD_PARAMS, runner);
<add> runner.addRunnerParameter(GRADLE_CMD_PARAMS, gradleCmdParam != null ? param + " " + gradleCmdParam : param);
<ide> }
<ide>
<ide> private static void addMavenSysPropIfSet(@NotNull String configParameter, @NotNull String property, @NotNull BuildRunnerContext runner) {
<ide> }
<ide>
<ide> private static void addMavenCmdParam(@NotNull String param, @NotNull BuildRunnerContext runner) {
<del> String existingParams = getOrDefault(MAVEN_CMD_PARAMS, runner);
<del> runner.addRunnerParameter(MAVEN_CMD_PARAMS, param + " " + existingParams);
<add> String mavenCmdParam = getOptionalRunnerParam(MAVEN_CMD_PARAMS, runner);
<add> runner.addRunnerParameter(MAVEN_CMD_PARAMS, mavenCmdParam != null ? param + " " + mavenCmdParam : param);
<ide> }
<ide>
<ide> @Nullable
<ide>
<ide> String value = params.get(paramName).trim();
<ide> return value.isEmpty() ? null : value;
<del> }
<del>
<del> private static String getOrDefault(@NotNull String paramName, @NotNull BuildRunnerContext runner) {
<del> Map<String, String> runnerParameters = runner.getRunnerParameters();
<del> return runnerParameters.containsKey(paramName) ? runnerParameters.get(paramName) : "";
<ide> }
<ide>
<ide> @NotNull |
|
Java | apache-2.0 | 3ac7d90e76ee06ebc9b8f92bfd7747d9598e62e8 | 0 | Shan1024/carbon-uuf,this/carbon-uuf,manuranga/carbon-uuf,manuranga/carbon-uuf,wso2/carbon-uuf,wso2/carbon-uuf,Shan1024/carbon-uuf,this/carbon-uuf,rasika90/carbon-uuf,this/carbon-uuf,sajithar/carbon-uuf,manuranga/carbon-uuf,sajithar/carbon-uuf,wso2/carbon-uuf,rasika90/carbon-uuf,Shan1024/carbon-uuf,manuranga/carbon-uuf,rasika90/carbon-uuf,wso2/carbon-uuf,this/carbon-uuf,Shan1024/carbon-uuf | /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.uuf.renderablecreator.hbs.renderable;
import com.github.jknack.handlebars.Context;
import com.github.jknack.handlebars.Template;
import com.github.jknack.handlebars.io.TemplateSource;
import org.wso2.carbon.uuf.core.API;
import org.wso2.carbon.uuf.core.Lookup;
import org.wso2.carbon.uuf.core.RequestLookup;
import org.wso2.carbon.uuf.exception.UUFException;
import org.wso2.carbon.uuf.renderablecreator.hbs.PlaceholderWriter;
import org.wso2.carbon.uuf.spi.model.Model;
import java.io.IOException;
public class HbsLayoutRenderable extends AbstractRenderable {
private final String path;
private final Template template;
protected HbsLayoutRenderable() {
this.path = null;
this.template = null;
}
public HbsLayoutRenderable(TemplateSource templateSource) {
this.path = templateSource.filename();
this.template = compileTemplate(templateSource);
}
@Override
public String getPath() {
return path;
}
@Override
public Template getTemplate() {
return template;
}
@Override
public String render(Model model, Lookup lookup, RequestLookup requestLookup, API api) {
Context context = Context.newContext(getHbsModel(model, lookup, requestLookup, api));
context.data(DATA_KEY_LOOKUP, lookup);
context.data(DATA_KEY_REQUEST_LOOKUP, requestLookup);
context.data(DATA_KEY_API, api);
PlaceholderWriter writer = new PlaceholderWriter();
context.data(DATA_KEY_CURRENT_WRITER, writer);
try {
getTemplate().apply(context, writer);
} catch (IOException e) {
throw new UUFException("An error occurred when rendering the compiled Handlebars template of layout '" +
getPath() + "'.", e);
}
String out = writer.toString(requestLookup.getPlaceholderContents());
writer.close();
return out;
}
}
| uuf-renderablecreator-hbs/src/main/java/org/wso2/carbon/uuf/renderablecreator/hbs/renderable/HbsLayoutRenderable.java | /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.uuf.renderablecreator.hbs.renderable;
import com.github.jknack.handlebars.Context;
import com.github.jknack.handlebars.io.TemplateSource;
import org.wso2.carbon.uuf.core.API;
import org.wso2.carbon.uuf.core.Lookup;
import org.wso2.carbon.uuf.core.RequestLookup;
import org.wso2.carbon.uuf.exception.UUFException;
import org.wso2.carbon.uuf.renderablecreator.hbs.PlaceholderWriter;
import org.wso2.carbon.uuf.spi.model.Model;
import java.io.IOException;
public class HbsLayoutRenderable extends AbstractRenderable {
protected HbsLayoutRenderable() {
}
public HbsLayoutRenderable(TemplateSource template) {
super(template);
}
@Override
public String render(Model model, Lookup lookup, RequestLookup requestLookup, API api) {
Context context = Context.newContext(getHbsModel(model, lookup, requestLookup, api));
context.data(DATA_KEY_LOOKUP, lookup);
context.data(DATA_KEY_REQUEST_LOOKUP, requestLookup);
context.data(DATA_KEY_API, api);
PlaceholderWriter writer = new PlaceholderWriter();
context.data(DATA_KEY_CURRENT_WRITER, writer);
try {
getCompiledTemplate().apply(context, writer);
} catch (IOException e) {
throw new UUFException("An error occurred when rendering the compiled Handlebars template of layout '" +
getPath() + "'.", e);
}
String out = writer.toString(requestLookup.getPlaceholderContents());
writer.close();
return out;
}
@Override
public String toString() {
return "{\"path\": \"" + getPath() + "\"}";
}
}
| changed HbsLayoutRenderable class accordingly to AbstractRenderable class
| uuf-renderablecreator-hbs/src/main/java/org/wso2/carbon/uuf/renderablecreator/hbs/renderable/HbsLayoutRenderable.java | changed HbsLayoutRenderable class accordingly to AbstractRenderable class | <ide><path>uf-renderablecreator-hbs/src/main/java/org/wso2/carbon/uuf/renderablecreator/hbs/renderable/HbsLayoutRenderable.java
<ide> package org.wso2.carbon.uuf.renderablecreator.hbs.renderable;
<ide>
<ide> import com.github.jknack.handlebars.Context;
<add>import com.github.jknack.handlebars.Template;
<ide> import com.github.jknack.handlebars.io.TemplateSource;
<ide> import org.wso2.carbon.uuf.core.API;
<ide> import org.wso2.carbon.uuf.core.Lookup;
<ide>
<ide> public class HbsLayoutRenderable extends AbstractRenderable {
<ide>
<add> private final String path;
<add> private final Template template;
<add>
<ide> protected HbsLayoutRenderable() {
<add> this.path = null;
<add> this.template = null;
<ide> }
<ide>
<del> public HbsLayoutRenderable(TemplateSource template) {
<del> super(template);
<add> public HbsLayoutRenderable(TemplateSource templateSource) {
<add> this.path = templateSource.filename();
<add> this.template = compileTemplate(templateSource);
<add> }
<add>
<add> @Override
<add> public String getPath() {
<add> return path;
<add> }
<add>
<add> @Override
<add> public Template getTemplate() {
<add> return template;
<ide> }
<ide>
<ide> @Override
<ide> PlaceholderWriter writer = new PlaceholderWriter();
<ide> context.data(DATA_KEY_CURRENT_WRITER, writer);
<ide> try {
<del> getCompiledTemplate().apply(context, writer);
<add> getTemplate().apply(context, writer);
<ide> } catch (IOException e) {
<ide> throw new UUFException("An error occurred when rendering the compiled Handlebars template of layout '" +
<ide> getPath() + "'.", e);
<ide> writer.close();
<ide> return out;
<ide> }
<del>
<del> @Override
<del> public String toString() {
<del> return "{\"path\": \"" + getPath() + "\"}";
<del> }
<ide> } |
|
Java | apache-2.0 | 35490df55c510bb0c477eeb80e699eeeb9204d86 | 0 | NarutoActor/Conway-Game-of-Life | import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.TitledBorder;
public class GoL extends JFrame{
JPanel p1 = new JPanel(new BorderLayout());
JPanel p2 = new JPanel(new GridLayout(32,32));//Table Panel
//JPanel p3 = new JPanel();//Tool Panel
JPanel p4 = new JPanel();//Signiture
JPanel p5 = new JPanel(new GridLayout(2,1));//PreMade Set
JPanel p6 = new JPanel(new GridLayout(2,1));
JPanel p7 = new JPanel();//front
JPanel p8 = new JPanel();//back
JPanel p9 = new JPanel(new BorderLayout());//Padding
JLabel l1 = new JLabel((char)169 +"Lucas Rivera & Hans Kiessler 2014 for Rutgers University-HACK RU");
JLabel l2 = new JLabel("PreMade Sets");
JLabel l3 = new JLabel("Stop At N=:");
JButton b1 = new JButton("Play");
JButton b2 = new JButton("Stop");
JButton b3 = new JButton("About");
JTextField t1 = new JTextField("N=0");
JTextField t2 = new JTextField("-1");
Cell[][] ppl = new Cell[32][32];
String s[] = {"Space Ship","Rotator"};
JComboBox c1 = new JComboBox(s);
JScrollBar sb = new JScrollBar();
JSplitPane p3 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,p5,p6);
public GoL(){
p9.add(p3,BorderLayout.CENTER);
p9.add(p4, BorderLayout.SOUTH);
p2.setMaximumSize(new Dimension(800,200));
p2.setSize(800, 200);
t1.setEditable(false);
p3.setMinimumSize(new Dimension(100,50));
p7.add(t1);
p7.add(b1);
p7.add(b2);
p7.add(b3);
p8.add(l3);
p8.add(t2);
p6.add(p7);
p6.add(p8);
p5.add(l2);
p5.add(c1);
//p3.add(p5);
TitledBorder title = BorderFactory.createTitledBorder("CUSTOM");
p6.setBorder(title);
for(int i=0;i<ppl.length;i++){
for(int j=0;j<ppl[0].length;j++){
ppl[i][j] = new Cell();
ppl[i][j].addActionListener(new userClick());
p2.add(ppl[i][j]);
}
}
p4.add(l1);
p1.add(p2, BorderLayout.CENTER);
p1.add(p9, BorderLayout.SOUTH);//used to be p3
//p1.add(p4, BorderLayout.SOUTH);
add(p1);
}
public static void main(String[] args) {
GoL r1 = new GoL();
r1.setSize(800, 780);
r1.setMinimumSize(new Dimension(600, 400));
r1.setVisible(true);
r1.setTitle("Conway's - The Game of Life");
r1.setLocationRelativeTo(null);
r1.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public class Cell extends JButton{
//JButton b;
boolean alive;
Cell(){
//b = new JButton();
}
}
public class userClick implements ActionListener{
public void actionPerformed(ActionEvent e) {
Cell p = (Cell)e.getSource();
p.setBackground(Color.black);
p.setOpaque(true);
System.out.println("Did I get here?");
if(p.alive==false){
System.out.println("Did I get here?2");
p.setBackground(Color.BLACK);
p.setOpaque(true);
p.setText("X");
p.revalidate();
p.alive = true;
}
else{
p.setBackground(b1.getBackground());
p.setText("");
p.alive = false;
}
}
}
}
| src/GoL.java | import java.awt.*;
import javax.swing.*;
public class GoL extends JFrame{
JPanel p1 = new JPanel(new BorderLayout());
JPanel p2 = new JPanel(new GridLayout(16,16));//Table Panel
//JPanel p3 = new JPanel();//Tool Panel
JPanel p4 = new JPanel();//Signiture
JPanel p5 = new JPanel(new GridLayout(2,1));//PreMade Set
JPanel p6 = new JPanel(new GridLayout(2,1));
JPanel p7 = new JPanel();//front
JPanel p8 = new JPanel();//back
JLabel l1 = new JLabel((char)169 +"Lucas Rivera 2014 for Rutgers University-HACK RU");
JLabel l2 = new JLabel("PreMade Sets");
JLabel l3 = new JLabel("Stop At N=:");
JButton b1 = new JButton("Play");
JButton b2 = new JButton("Stop");
JButton b3 = new JButton("About");
JTextField t1 = new JTextField("N=0");
JTextField t2 = new JTextField("-1");
JButton[][] ppl = new JButton[16][16];
String s[] = {"Space Ship","Rotator"};
JComboBox c1 = new JComboBox(s);
JScrollBar sb = new JScrollBar();
JSplitPane p3 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,p5,p6);
public GoL(){
p2.setMaximumSize(new Dimension(800,200));
p2.setSize(800, 200);
t1.setEditable(false);
p3.setMinimumSize(new Dimension(100,50));
p7.add(t1);
p7.add(b1);
p7.add(b2);
p7.add(b3);
p8.add(l3);
p8.add(t2);
p6.add(p7);
p6.add(p8);
p5.add(l2);
p5.add(c1);
//p3.add(p5);
TitledBorder title = BorderFactory.createTitledBorder("CUSTOM");
p6.setBorder(title);
for(int i=0;i<ppl.length;i++){
for(int j=0;j<ppl[0].length;j++){
ppl[i][j] = new JButton();
p2.add(ppl[i][j]);
}
}
p4.add(l1);
p1.add(p2, BorderLayout.NORTH);
p1.add(p3, BorderLayout.CENTER);
p1.add(p4, BorderLayout.SOUTH);
add(p1);
}
public static void main(String[] args) {
GoL r1 = new GoL();
r1.setSize(800, 520);
r1.setMinimumSize(new Dimension(800, 400));
r1.setVisible(true);
r1.setTitle("The Game of Life");
r1.setLocationRelativeTo(null);
r1.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
| Update GoL.java | src/GoL.java | Update GoL.java | <ide><path>rc/GoL.java
<ide> import java.awt.*;
<add>import java.awt.event.ActionEvent;
<add>import java.awt.event.ActionListener;
<ide>
<ide> import javax.swing.*;
<add>import javax.swing.border.TitledBorder;
<ide>
<ide>
<ide> public class GoL extends JFrame{
<ide> JPanel p1 = new JPanel(new BorderLayout());
<del>JPanel p2 = new JPanel(new GridLayout(16,16));//Table Panel
<add>JPanel p2 = new JPanel(new GridLayout(32,32));//Table Panel
<ide> //JPanel p3 = new JPanel();//Tool Panel
<ide> JPanel p4 = new JPanel();//Signiture
<ide> JPanel p5 = new JPanel(new GridLayout(2,1));//PreMade Set
<ide> JPanel p6 = new JPanel(new GridLayout(2,1));
<ide> JPanel p7 = new JPanel();//front
<ide> JPanel p8 = new JPanel();//back
<del>JLabel l1 = new JLabel((char)169 +"Lucas Rivera 2014 for Rutgers University-HACK RU");
<add>JPanel p9 = new JPanel(new BorderLayout());//Padding
<add>JLabel l1 = new JLabel((char)169 +"Lucas Rivera & Hans Kiessler 2014 for Rutgers University-HACK RU");
<ide> JLabel l2 = new JLabel("PreMade Sets");
<ide> JLabel l3 = new JLabel("Stop At N=:");
<ide> JButton b1 = new JButton("Play");
<ide> JButton b3 = new JButton("About");
<ide> JTextField t1 = new JTextField("N=0");
<ide> JTextField t2 = new JTextField("-1");
<del>JButton[][] ppl = new JButton[16][16];
<add>Cell[][] ppl = new Cell[32][32];
<ide> String s[] = {"Space Ship","Rotator"};
<ide> JComboBox c1 = new JComboBox(s);
<ide> JScrollBar sb = new JScrollBar();
<ide> JSplitPane p3 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,p5,p6);
<ide>
<ide> public GoL(){
<add> p9.add(p3,BorderLayout.CENTER);
<add> p9.add(p4, BorderLayout.SOUTH);
<add>
<ide> p2.setMaximumSize(new Dimension(800,200));
<ide> p2.setSize(800, 200);
<ide>
<ide> p6.setBorder(title);
<ide> for(int i=0;i<ppl.length;i++){
<ide> for(int j=0;j<ppl[0].length;j++){
<del> ppl[i][j] = new JButton();
<add> ppl[i][j] = new Cell();
<add> ppl[i][j].addActionListener(new userClick());
<ide> p2.add(ppl[i][j]);
<ide> }
<ide> }
<ide> p4.add(l1);
<del> p1.add(p2, BorderLayout.NORTH);
<del> p1.add(p3, BorderLayout.CENTER);
<del> p1.add(p4, BorderLayout.SOUTH);
<add> p1.add(p2, BorderLayout.CENTER);
<add> p1.add(p9, BorderLayout.SOUTH);//used to be p3
<add> //p1.add(p4, BorderLayout.SOUTH);
<ide> add(p1);
<ide>
<ide>
<ide> }
<ide> public static void main(String[] args) {
<ide> GoL r1 = new GoL();
<del> r1.setSize(800, 520);
<del> r1.setMinimumSize(new Dimension(800, 400));
<add> r1.setSize(800, 780);
<add> r1.setMinimumSize(new Dimension(600, 400));
<ide> r1.setVisible(true);
<del> r1.setTitle("The Game of Life");
<add> r1.setTitle("Conway's - The Game of Life");
<ide> r1.setLocationRelativeTo(null);
<ide> r1.setDefaultCloseOperation(EXIT_ON_CLOSE);
<ide>
<ide> }
<add> public class Cell extends JButton{
<add> //JButton b;
<add> boolean alive;
<add> Cell(){
<add> //b = new JButton();
<add> }
<add> }
<add> public class userClick implements ActionListener{
<add> public void actionPerformed(ActionEvent e) {
<add> Cell p = (Cell)e.getSource();
<add> p.setBackground(Color.black);
<add> p.setOpaque(true);
<add> System.out.println("Did I get here?");
<add> if(p.alive==false){
<add> System.out.println("Did I get here?2");
<add> p.setBackground(Color.BLACK);
<add> p.setOpaque(true);
<add> p.setText("X");
<add> p.revalidate();
<add> p.alive = true;
<add>
<add> }
<add> else{
<add> p.setBackground(b1.getBackground());
<add> p.setText("");
<add> p.alive = false;
<add> }
<add> }
<add> }
<ide>
<ide> } |
|
Java | apache-2.0 | 64a358e1f50f869db69d6dc6ed7e84ca12383930 | 0 | jnidzwetzki/scalephant,jnidzwetzki/bboxdb,jnidzwetzki/bboxdb,jnidzwetzki/scalephant,jnidzwetzki/bboxdb | /*******************************************************************************
*
* Copyright (C) 2015-2017 the BBoxDB project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*******************************************************************************/
package org.bboxdb.distribution.mode;
public enum DistributionRegionState {
UNKNOWN("unknown"),
CREATING("creating"),
ACTIVE("active"),
ACTIVE_FULL("active-full"),
SPLITTING("splitting"),
SPLIT("split"),
SPLIT_MERGING("split-merging"),
MERGING("merging");
/**
* The string representation
*/
protected final String stringValue;
private DistributionRegionState(final String stringValue) {
this.stringValue = stringValue;
}
/**
* Get the string representation
* @return
*/
public String getStringValue() {
return stringValue;
}
/**
* Convert the string value into an enum
* @param stringValue
* @return
*/
public static DistributionRegionState fromString(final String stringValue) {
if (stringValue == null) {
throw new RuntimeException("stringValue is null");
}
for(final DistributionRegionState nodeState : DistributionRegionState.values()) {
if(stringValue.equals(nodeState.getStringValue())) {
return nodeState;
}
}
throw new RuntimeException("Unable to convert " + stringValue + " into enum");
}
}
| src/main/java/org/bboxdb/distribution/mode/DistributionRegionState.java | /*******************************************************************************
*
* Copyright (C) 2015-2017 the BBoxDB project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*******************************************************************************/
package org.bboxdb.distribution.mode;
public enum DistributionRegionState {
UNKNOWN("unknown"),
CREATING("creating"),
ACTIVE("active"),
ACTIVE_FULL("active-full"),
SPLITTING("splitting"),
SPLIT("split");
/**
* The string representation
*/
protected final String stringValue;
private DistributionRegionState(final String stringValue) {
this.stringValue = stringValue;
}
/**
* Get the string representation
* @return
*/
public String getStringValue() {
return stringValue;
}
/**
* Convert the string value into an enum
* @param stringValue
* @return
*/
public static DistributionRegionState fromString(final String stringValue) {
if (stringValue == null) {
throw new RuntimeException("stringValue is null");
}
for(final DistributionRegionState nodeState : DistributionRegionState.values()) {
if(stringValue.equals(nodeState.getStringValue())) {
return nodeState;
}
}
throw new RuntimeException("Unable to convert " + stringValue + " into enum");
}
}
| Added merge states | src/main/java/org/bboxdb/distribution/mode/DistributionRegionState.java | Added merge states | <ide><path>rc/main/java/org/bboxdb/distribution/mode/DistributionRegionState.java
<ide> ACTIVE("active"),
<ide> ACTIVE_FULL("active-full"),
<ide> SPLITTING("splitting"),
<del> SPLIT("split");
<add> SPLIT("split"),
<add> SPLIT_MERGING("split-merging"),
<add> MERGING("merging");
<ide>
<ide> /**
<ide> * The string representation |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.