Merge branch 'main' into translations-system

This commit is contained in:
Ne_Eo
2024-07-18 22:06:47 +02:00
29 changed files with 2322 additions and 1168 deletions
+1 -1
View File
@@ -7,7 +7,7 @@ jobs:
build:
name: Linux Build
permissions: write-all
runs-on: ubuntu-20.04
runs-on: ubuntu-latest
steps:
- name: Pulling the source
uses: actions/checkout@v2
+1
View File
@@ -9,3 +9,4 @@ latest/windows/haxe/
pages/
docs/doc.xml
mods/Baldi's Basics in Funkin'/
dev-libs/
+69
View File
@@ -0,0 +1,69 @@
package;
using StringTools;
class Utils {
// trace(evaluateArgsCondition("hello && (world || world)", ["hello", "world"])); // true
// trace(evaluateArgsCondition("hello && (!world || world)", ["hello"])); // true
// trace(evaluateArgsCondition("hello && (!world && world)", ["hello", "world"])); // false
public static function evaluateArgsCondition(condition:String, args:Array<String>):Bool {
function evaluateToken(token:String):Bool {
if (token.charAt(0) == '!') {
return !args.contains(token.substr(1));
} else {
return args.contains(token);
}
}
condition = condition.replace('&&', '&').replace('||', '|').replace(" ", "");
var stack:Array<Dynamic> = [];
var i = 0;
while (i < condition.length) {
var char = condition.charAt(i);
switch (char) {
case '(':
var j = i;
var balance = 1;
while (balance != 0) {
j++;
if (condition.charAt(j) == '(') balance++;
if (condition.charAt(j) == ')') balance--;
}
var subExpr = condition.substr(i + 1, j - i - 1);
stack.push(evaluateArgsCondition(subExpr, args));
i = j;
case '&', '|':
stack.push(char);
default:
var token = "";
while (i < condition.length && condition.charAt(i) != '&' && condition.charAt(i) != '|' && condition.charAt(i) != '(' && condition.charAt(i) != ')') {
token += condition.charAt(i);
i++;
}
stack.push(evaluateToken(token));
i--;
}
i++;
}
return evaluate(stack);
}
public static function evaluate(stack:Array<Dynamic>):Bool {
var result = stack.shift();
while (stack.length > 0) {
var op = stack.shift();
var next = stack.shift();
switch(op) {
case '&':
result = result && next;
case '|':
result = result || next;
}
}
return result;
}
}
+7 -9
View File
@@ -15,21 +15,19 @@ class Compiler {
}
private static function __build(args:Array<String>, arg:Array<String>) {
arg.insert(0, "lime");
arg.insert(0, "run");
for(a in args)
arg.push(a);
Sys.command("lime", arg);
Sys.command("haxelib", arg);
}
public static function getBuildTarget() {
return switch(Sys.systemName()) {
case "Windows":
"windows";
case "Mac":
"macos";
case "Linux":
"linux";
case def:
def.toLowerCase();
case "Windows": "windows";
case "Mac": "macos";
case "Linux": "linux";
case def: def.toLowerCase();
}
}
}
+177 -34
View File
@@ -8,11 +8,9 @@ import sys.FileSystem;
class Update {
public static function main(args:Array<String>) {
prettyPrint("Preparing installation...");
var args = ArgParser.parse(args, ["S" => "silent-progress", "silent" => "silent-progress"]);
var CHECK_VSTUDIO = !args.existsOption("no-vscheck");
var REINSTALL_ALL = args.existsOption("all");
var REINSTALL_ALL = args.existsOption("reinstall");
var SILENT = args.existsOption("silent-progress");
// to prevent messing with currently installed libs
@@ -24,46 +22,170 @@ class Update {
FileSystem.createDirectory('.haxelib');
}
var libs:Array<Library> = [];
var libsXML:Access = new Access(Xml.parse(File.getContent('./libs.xml')).firstElement());
var libFile = "./libs.xml";
if(args.existsOption("lib")) {
libFile = args.getOption("lib");
if(libFile == null) {
Sys.println('Please specify a file with the --lib option as --lib=path/to/libs.xml');
return;
}
}
if(!FileSystem.exists(libFile)) {
Sys.println('File $libFile does not exist.');
return;
}
var events:Array<Event> = [];
var libsXML:Access = new Access(Xml.parse(File.getContent(libFile)).firstElement());
function handleLib(libNode:Access) {
switch(libNode.name) {
case "lib" | "git":
var lib:Library = {
name: libNode.att.name,
type: libNode.name
};
if (libNode.has.global) lib.global = libNode.att.global;
switch (lib.type) {
case "lib":
if (libNode.has.version) lib.version = libNode.att.version;
case "git":
if (libNode.has.url) lib.url = libNode.att.url;
if (libNode.has.ref) lib.ref = libNode.att.ref;
}
events.push({
type: INSTALL,
data: lib
});
case "cmd":
events.push({
type: CMD,
data: {
inLib: libNode.has.inLib ? libNode.att.inLib : null,
lines: {
if(Lambda.count(libNode.nodes.line) > 0)
[
for(line in libNode.nodes.line)
line.innerData
];
else
[
libNode.has.cmd ? libNode.att.cmd : "echo 'No command specified'"
];
}
}
});
case "print":
events.push({
type: PRINT,
data: {
text: libNode.innerData,
pretty: libNode.has.pretty && libNode.att.pretty == "true"
}
});
default:
Sys.println('Unknown library type ${libNode.name}');
}
}
var platform = switch(Sys.systemName()) {
case "Windows": "windows";
case "Mac": "mac";
case "Linux": "linux";
case def: def.toLowerCase();
}
var defines = args.args.copy();
defines.push(platform);
if(args.args.length == 0) defines.push("all");
function parse(libNode:Access) {
if(libNode.name == "if") {
var cond = libNode.att.cond;
if(!Utils.evaluateArgsCondition(cond, defines)) {
return;
}
for(child in libNode.elements) {
parse(child);
}
} else {
handleLib(libNode);
}
}
for (libNode in libsXML.elements) {
var lib:Library = {
name: libNode.att.name,
type: libNode.name
};
if (libNode.has.global) lib.global = libNode.att.global;
switch (lib.type) {
case "lib":
if (libNode.has.version) lib.version = libNode.att.version;
case "git":
if (libNode.has.url) lib.url = libNode.att.url;
if (libNode.has.ref) lib.ref = libNode.att.ref;
}
libs.push(lib);
parse(libNode);
}
var commandSuffix = " --always";
if (SILENT) commandSuffix += " --silent";
for(lib in libs) {
var globalism:Null<String> = lib.global == "true" ? "--global" : null;
var globalSuffix = globalism != null ? ' $globalism' : '';
switch(lib.type) {
case "lib":
prettyPrint((lib.global == "true" ? "Globally installing" : "Locally installing") + ' "${lib.name}"...');
Sys.command('haxelib install ${lib.name} ${lib.version != null ? " " + lib.version : " "}$globalSuffix$commandSuffix');
case "git":
prettyPrint((lib.global == "true" ? "Globally installing" : "Locally installing") + ' "${lib.name}" from git url "${lib.url}"');
Sys.command('haxelib git ${lib.name} ${lib.url}${lib.ref != null ? ' ${lib.ref}' : ''}$globalSuffix$commandSuffix');
case "custom":
Sys.command('haxelib dev ${lib.name} "./libraries/${lib.name}"');
default:
prettyPrint('Cannot resolve library of type "${lib.type}"');
for(event in events) {
switch(event.type) {
case INSTALL:
var lib:Library = event.data;
var globalism:Null<String> = lib.global == "true" ? "--global" : null;
var globalSuffix = globalism != null ? ' $globalism' : '';
switch(lib.type) {
case "lib":
prettyPrint((lib.global == "true" ? "Globally installing" : "Locally installing") + ' "${lib.name}"...');
Sys.command('haxelib install ${lib.name} ${lib.version != null ? " " + lib.version : " "}$globalSuffix$commandSuffix');
case "git":
prettyPrint((lib.global == "true" ? "Globally installing" : "Locally installing") + ' "${lib.name}" from git url "${lib.url}"');
Sys.command('haxelib git ${lib.name} ${lib.url}${lib.ref != null ? ' ${lib.ref}' : ''}$globalSuffix$commandSuffix');
case "custom":
Sys.command('haxelib dev ${lib.name} "./libraries/${lib.name}"');
default:
prettyPrint('Cannot resolve library of type "${lib.type}"');
}
case CMD:
var cmd:CmdData = event.data;
var lib = cmd.inLib;
var oldCwd = Sys.getCwd();
if(lib != null) {
var libPrefix = '.haxelib/$lib';
if(FileSystem.exists(libPrefix)) {
if(FileSystem.exists(libPrefix + '/.dev')) { // haxelib dev
var devPath = File.getContent(libPrefix + '/.dev');
if(!FileSystem.exists(devPath)) {
Sys.println('Cannot find dev path $devPath for $lib');
Sys.setCwd(oldCwd);
continue;
}
Sys.setCwd(devPath);
} else if(FileSystem.exists(libPrefix + '/.current')) {
var version = StringTools.replace(File.getContent(libPrefix + '/.current'), ".", ",");
if(!FileSystem.exists(libPrefix + '/$version')) {
Sys.println('Cannot find version $version of $lib');
Sys.setCwd(oldCwd);
continue;
}
Sys.setCwd(libPrefix + '/$version');
} else {
Sys.println('Cannot find .dev or .current file in $libPrefix');
Sys.setCwd(oldCwd);
continue;
}
}
}
for(line in cmd.lines) {
var line = StringTools.replace(line, "$PLATFORM", platform);
//Sys.println(line);
Sys.command(line);
}
Sys.setCwd(oldCwd);
case PRINT:
var data:PrintData = event.data;
if(data.pretty)
prettyPrint(data.text);
else
Sys.println(data.text);
}
}
var proc = new Process('haxe --version');
/*var proc = new Process('haxe --version');
proc.exitCode(true);
var haxeVer = proc.stdout.readLine();
if (haxeVer != "4.2.5") {
@@ -86,7 +208,7 @@ class Update {
break;
}
}
}
}*/
// vswhere.exe its used to find any visual studio related installations on the system, including full visual studio ide installations, visual studio build tools installations, and other related components - Nex
if (CHECK_VSTUDIO && Compiler.getBuildTarget().toLowerCase() == "windows" && new Process('"C:/Program Files (x86)/Microsoft Visual Studio/Installer/vswhere.exe" -property catalog_productDisplayVersion').exitCode(true) == 1) {
@@ -144,3 +266,24 @@ typedef Library = {
var ?ref:String;
var ?url:String;
}
typedef Event = {
var type:EventType;
var data:Dynamic;
}
typedef CmdData = {
var ?inLib:String;
var lines:Array<String>;
}
typedef PrintData = {
var text:String;
var ?pretty:Bool;
}
enum abstract EventType(Int) {
var INSTALL = 0;
var CMD = 1;
var PRINT = 2;
}
+38 -17
View File
@@ -1,24 +1,45 @@
<?xml version="1.0" encoding="UTF-8"?>
<libraries>
<!-- OpenFL & Lime (Required for Flixel) -->
<lib name="openfl" version="9.2.2" />
<lib name="lime" version="8.1.2" />
<if cond="update || all">
<print pretty="true">Preparing installation...</print>
<!-- Flixel -->
<git name="flixel" url="https://github.com/FNF-CNE-Devs/flixel" />
<git name="flixel-addons" url="https://github.com/FNF-CNE-Devs/flixel-addons" />
<!-- OpenFL & Lime (Required for Flixel) -->
<git name="openfl" url="https://github.com/FNF-CNE-Devs/openfl" />
<git name="lime" url="https://github.com/FNF-CNE-Devs/lime" />
<!-- Other Libraries -->
<git name="hscript-improved" url="https://github.com/FNF-CNE-Devs/hscript-improved" ref="custom-classes" />
<git name="flxanimate" url="https://github.com/FNF-CNE-Devs/flxanimate" />
<git name="hxdiscord_rpc" url="https://github.com/FNF-CNE-Devs/hxdiscord_rpc" />
<lib name="hxvlc" />
<!-- Flixel -->
<git name="flixel" url="https://github.com/FNF-CNE-Devs/flixel" />
<git name="flixel-addons" url="https://github.com/FNF-CNE-Devs/flixel-addons" />
<!-- Documentation and other features -->
<git name="away3d" url="https://github.com/FNF-CNE-Devs/away3d" />
<!-- <lib name="dox" /> -->
<lib name="format" />
<lib name="markdown" />
<!-- Other Libraries -->
<git name="hscript-improved" url="https://github.com/FNF-CNE-Devs/hscript-improved" ref="custom-classes" />
<git name="flxanimate" url="https://github.com/FNF-CNE-Devs/flxanimate" />
<git name="hxdiscord_rpc" url="https://github.com/FNF-CNE-Devs/hxdiscord_rpc" />
<lib name="hxvlc" />
<custom name="macro-fixer" />
<!-- Documentation and other features -->
<git name="away3d" url="https://github.com/FNF-CNE-Devs/away3d" />
<!-- <lib name="dox" /> -->
<lib name="format" />
<lib name="markdown" />
<custom name="macro-fixer" />
<!-- For building lime -->
<lib global="true" name="hxp" />
<lib global="true" name="format" />
</if>
<!-- Lime Building -->
<if cond="build-lime || all">
<print pretty="true">Rebuilding Lime...</print>
<!-- Build lime -->
<cmd inLib="lime" cmd="lime rebuild . $PLATFORM" />
<cmd inLib="lime" >
<line>cd tools</line>
<line>haxe tools.hxml</line>
<line>cd ..</line>s
</cmd>
</if>
</libraries>
+1 -1
View File
@@ -69,7 +69,7 @@
<!-- ______________________________ Haxedefines _____________________________ -->
<haxeflag name="--macro" value="funkin.backend.system.macros.NewHaxeWarning.warn()" />
<haxeflag name="--macro" value="funkin.backend.system.macros.BuildInfo.printBuildInfo()" />
<haxedef name="FLX_NO_FOCUS_LOST_SCREEN" />
+30
View File
@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<libraries>
<if cond="time-fix">
<print pretty="true">Switching to branch 'time-fix'...</print>
<cmd inLib="lime" cmd="git checkout time-fix" />
<cmd inLib="openfl" cmd="git checkout time-fix" />
<cmd inLib="away3d" cmd="git checkout time-fix" />
<cmd inLib="flixel" cmd="git checkout time-fix" />
<cmd inLib="flixel-addons" cmd="git checkout time-fix" />
<print pretty="true">Done!&#10;Make sure to switch the branch on Codename Engine to 'time-fix' before compiling!</print>
</if>
<if cond="normal">
<print pretty="true">Switching to branch 'dev'...</print>
<cmd inLib="lime" cmd="git checkout develop" />
<cmd inLib="openfl" cmd="git checkout develop" />
<cmd inLib="away3d" cmd="git checkout master" />
<cmd inLib="flixel" cmd="git checkout dev" />
<cmd inLib="flixel-addons" cmd="git checkout dev" />
<print pretty="true">Done!&#10;Make sure to switch the branch on Codename Engine to 'main' before compiling!</print>
</if>
<print pretty="true">Rebuilding Lime...</print>
<cmd inLib="lime" cmd="lime rebuild . $PLATFORM" />
<cmd inLib="lime" >
<line>cd tools</line>
<line>haxe tools.hxml</line>
<line>cd ..</line>s
</cmd>
</libraries>
+90
View File
@@ -0,0 +1,90 @@
<?xml version="1.0" encoding="UTF-8"?>
<libraries>
<print pretty="true">Setting up dev libs...</print>
<cmd>
<line>mkdir dev-libs</line>
</cmd>
<if cond="openfl || all">
<cmd>
<line>cd dev-libs</line>
<line>git clone https://github.com/FNF-CNE-Devs/openfl openfl</line>
<line>cd ..</line>
<line>haxelib dev openfl dev-libs/openfl</line>
</cmd>
</if>
<if cond="lime || all">
<cmd>
<line>cd dev-libs</line>
<line>git clone https://github.com/FNF-CNE-Devs/lime lime</line>
<line>cd ..</line>
<line>haxelib dev lime dev-libs/lime</line>
</cmd>
<!-- Build lime -->
<cmd inLib="lime" cmd="lime rebuild . $PLATFORM" />
<cmd inLib="lime" >
<line>cd tools</line>
<line>haxe tools.hxml</line>
<line>cd ..</line>s
</cmd>
</if>
<if cond="flixel || all">
<cmd>
<line>cd dev-libs</line>
<line>git clone https://github.com/FNF-CNE-Devs/flixel flixel</line>
<line>cd ..</line>
<line>haxelib dev flixel dev-libs/flixel</line>
</cmd>
</if>
<if cond="flixel-addons || all">
<cmd>
<line>cd dev-libs</line>
<line>git clone https://github.com/FNF-CNE-Devs/flixel-addons flixel-addons</line>
<line>cd ..</line>
<line>haxelib dev flixel-addons dev-libs/flixel-addons</line>
</cmd>
</if>
<if cond="hscript-improved || all">
<cmd>
<line>cd dev-libs</line>
<line>git clone https://github.com/FNF-CNE-Devs/hscript-improved hscript-improved</line>
<line>cd ..</line>
<line>haxelib dev hscript-improved dev-libs/hscript-improved</line>
</cmd>
</if>
<if cond="flxanimate || all">
<cmd>
<line>cd dev-libs</line>
<line>git clone https://github.com/FNF-CNE-Devs/flxanimate flxanimate</line>
<line>cd ..</line>
<line>haxelib dev flxanimate dev-libs/flxanimate</line>
</cmd>
</if>
<if cond="hxdiscord_rpc || all">
<cmd>
<line>cd dev-libs</line>
<line>git clone https://github.com/FNF-CNE-Devs/hxdiscord_rpc hxdiscord_rpc</line>
<line>cd ..</line>
<line>haxelib dev hxdiscord_rpc dev-libs/hxdiscord_rpc</line>
</cmd>
</if>
<if cond="away3d || all">
<cmd>
<line>cd dev-libs</line>
<line>git clone https://github.com/FNF-CNE-Devs/away3d away3d</line>
<line>cd ..</line>
<line>haxelib dev away3d dev-libs/away3d</line>
</cmd>
</if>
<print pretty="true">Setup for dev libs complete!</print>
</libraries>
+410
View File
@@ -0,0 +1,410 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* 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.
*/
/**
Xml node types.
@see https://haxe.org/manual/std-Xml.html
**/
enum abstract XmlType(Int) {
/**
Represents an XML element type.
**/
var Element = 0;
/**
Represents XML parsed character data type.
**/
var PCData = 1;
/**
Represents XML character data type.
**/
var CData = 2;
/**
Represents an XML comment type.
**/
var Comment = 3;
/**
Represents an XML doctype element type.
**/
var DocType = 4;
/**
Represents an XML processing instruction type.
**/
var ProcessingInstruction = 5;
/**
Represents an XML document type.
**/
var Document = 6;
public function toString():String {
return switch (cast this : XmlType) {
case Element: "Element";
case PCData: "PCData";
case CData: "CData";
case Comment: "Comment";
case DocType: "DocType";
case ProcessingInstruction: "ProcessingInstruction";
case Document: "Document";
};
}
}
/**
Cross-platform Xml API.
@see https://haxe.org/manual/std-Xml.html
**/
class Xml {
/**
XML element type.
**/
static public var Element(default, never) = XmlType.Element;
/**
XML parsed character data type.
**/
static public var PCData(default, never) = XmlType.PCData;
/**
XML character data type.
**/
static public var CData(default, never) = XmlType.CData;
/**
XML comment type.
**/
static public var Comment(default, never) = XmlType.Comment;
/**
XML doctype element type.
**/
static public var DocType(default, never) = XmlType.DocType;
/**
XML processing instruction type.
**/
static public var ProcessingInstruction(default, never) = XmlType.ProcessingInstruction;
/**
XML document type.
**/
static public var Document(default, never) = XmlType.Document;
/**
Parses the String into an Xml document.
**/
static public function parse(str:String):Xml {
return haxe.xml.Parser.parse(str);
}
/**
Returns the type of the Xml Node. This should be used before
accessing other functions since some might raise an exception
if the node type is not correct.
**/
public var nodeType(default, null):XmlType;
/**
Returns the node name of an Element.
**/
@:isVar public var nodeName(get, set):String;
/**
Returns the node value. Only works if the Xml node is not an Element or a Document.
**/
@:isVar public var nodeValue(get, set):String;
/**
Returns the parent object in the Xml hierarchy.
The parent can be `null`, an Element or a Document.
**/
public var parent(default, null):Xml;
var children:Array<Xml>;
var attributeMap:Map<String, String>;
public var attributeOrder:Array<String>;
#if !cppia inline #end function get_nodeName() {
if (nodeType != Element) {
throw 'Bad node type, expected Element but found $nodeType';
}
return nodeName;
}
#if !cppia inline #end function set_nodeName(v) {
if (nodeType != Element) {
throw 'Bad node type, expected Element but found $nodeType';
}
return this.nodeName = v;
}
#if !cppia inline #end function get_nodeValue() {
if (nodeType == Document || nodeType == Element) {
throw 'Bad node type, unexpected $nodeType';
}
return nodeValue;
}
#if !cppia inline #end function set_nodeValue(v) {
if (nodeType == Document || nodeType == Element) {
throw 'Bad node type, unexpected $nodeType';
}
return this.nodeValue = v;
}
/**
Creates a node of the given type.
**/
static public function createElement(name:String):Xml {
var xml = new Xml(Element);
xml.nodeName = name;
return xml;
}
/**
Creates a node of the given type.
**/
static public function createPCData(data:String):Xml {
var xml = new Xml(PCData);
xml.nodeValue = data;
return xml;
}
/**
Creates a node of the given type.
**/
static public function createCData(data:String):Xml {
var xml = new Xml(CData);
xml.nodeValue = data;
return xml;
}
/**
Creates a node of the given type.
**/
static public function createComment(data:String):Xml {
var xml = new Xml(Comment);
xml.nodeValue = data;
return xml;
}
/**
Creates a node of the given type.
**/
static public function createDocType(data:String):Xml {
var xml = new Xml(DocType);
xml.nodeValue = data;
return xml;
}
/**
Creates a node of the given type.
**/
static public function createProcessingInstruction(data:String):Xml {
var xml = new Xml(ProcessingInstruction);
xml.nodeValue = data;
return xml;
}
/**
Creates a node of the given type.
**/
static public function createDocument():Xml {
return new Xml(Document);
}
/**
Get the given attribute of an Element node. Returns `null` if not found.
Attributes are case-sensitive.
**/
public function get(att:String):String {
if (nodeType != Element) {
throw 'Bad node type, expected Element but found $nodeType';
}
return attributeMap[att];
}
/**
Set the given attribute value for an Element node.
Attributes are case-sensitive.
**/
public function set(att:String, value:String):Void {
if (nodeType != Element) {
throw 'Bad node type, expected Element but found $nodeType';
}
attributeMap.set(att, value);
}
/**
Removes an attribute for an Element node.
Attributes are case-sensitive.
**/
public function remove(att:String):Void {
if (nodeType != Element) {
throw 'Bad node type, expected Element but found $nodeType';
}
attributeMap.remove(att);
}
/**
Tells if the Element node has a given attribute.
Attributes are case-sensitive.
**/
public function exists(att:String):Bool {
if (nodeType != Element) {
throw 'Bad node type, expected Element but found $nodeType';
}
return attributeMap.exists(att);
}
/**
Returns an `Iterator` on all the attribute names.
**/
public function attributes():Iterator<String> {
if (nodeType != Element) {
throw 'Bad node type, expected Element but found $nodeType';
}
return attributeMap.keys();
}
/**
Returns an iterator of all child nodes.
Only works if the current node is an Element or a Document.
**/
public #if !cppia inline #end function iterator():Iterator<Xml> {
ensureElementType();
return children.iterator();
}
/**
Returns an iterator of all child nodes which are Elements.
Only works if the current node is an Element or a Document.
**/
public function elements():Iterator<Xml> {
ensureElementType();
var ret = [for (child in children) if (child.nodeType == Element) child];
return ret.iterator();
}
/**
Returns an iterator of all child nodes which are Elements with the given nodeName.
Only works if the current node is an Element or a Document.
**/
public function elementsNamed(name:String):Iterator<Xml> {
ensureElementType();
var ret = [
for (child in children)
if (child.nodeType == Element && child.nodeName == name) child
];
return ret.iterator();
}
/**
Returns the first child node.
**/
public #if !cppia inline #end function firstChild():Xml {
ensureElementType();
return children[0];
}
/**
Returns the first child node which is an Element.
**/
public function firstElement():Xml {
ensureElementType();
for (child in children) {
if (child.nodeType == Element) {
return child;
}
}
return null;
}
/**
Adds a child node to the Document or Element.
A child node can only be inside one given parent node, which is indicated by the `parent` property.
If the child is already inside this Document or Element, it will be moved to the last position among the Document or Element's children.
If the child node was previously inside a different node, it will be moved to this Document or Element.
**/
public function addChild(x:Xml):Void {
ensureElementType();
if (x.parent != null) {
x.parent.removeChild(x);
}
children.push(x);
x.parent = this;
}
/**
Removes a child from the Document or Element.
Returns true if the child was successfuly removed.
**/
public function removeChild(x:Xml):Bool {
ensureElementType();
if (children.remove(x)) {
x.parent = null;
return true;
}
return false;
}
/**
Inserts a child at the given position among the other childs.
A child node can only be inside one given parent node, which is indicated by the [parent] property.
If the child is already inside this Document or Element, it will be moved to the new position among the Document or Element's children.
If the child node was previously inside a different node, it will be moved to this Document or Element.
**/
public function insertChild(x:Xml, pos:Int):Void {
ensureElementType();
if (x.parent != null) {
x.parent.children.remove(x);
}
children.insert(pos, x);
x.parent = this;
}
/**
Returns a String representation of the Xml node.
**/
public #if !cppia inline #end function toString():String {
return haxe.xml.Printer.print(this);
}
function new(nodeType:XmlType) {
this.nodeType = nodeType;
children = [];
attributeMap = new Map();
}
inline function ensureElementType() {
if (nodeType != Document && nodeType != Element) {
throw 'Bad node type, expected Element or Document but found $nodeType';
}
}
}
@@ -17,7 +17,7 @@ class ModsFolderLibrary extends AssetLibrary implements IModsAssetLibrary {
public var basePath:String;
public var modName:String;
public var libName:String;
public var useImageCache:Bool = true;
//public var useImageCache:Bool = true;
public var prefix = 'assets/';
public function new(basePath:String, libName:String, ?modName:String) {
+1 -1
View File
@@ -168,7 +168,7 @@ class Conductor
// update conductor
songPosition = lastSongPos;
} else {
songPosition = songPosition + songOffset + elapsed * 1000;
songPosition += songOffset + elapsed * 1000;
}
}
+142 -706
View File
@@ -8,53 +8,6 @@ import flixel.input.actions.FlxActionSet;
import flixel.input.gamepad.FlxGamepadInputID;
import flixel.input.keyboard.FlxKey;
enum abstract Action(String) to String from String {
var UP = "up";
var LEFT = "left";
var RIGHT = "right";
var DOWN = "down";
var UP_P = "up-press";
var LEFT_P = "left-press";
var RIGHT_P = "right-press";
var DOWN_P = "down-press";
var UP_R = "up-release";
var LEFT_R = "left-release";
var RIGHT_R = "right-release";
var DOWN_R = "down-release";
var NOTE_UP = "note-up";
var NOTE_LEFT = "note-left";
var NOTE_RIGHT = "note-right";
var NOTE_DOWN = "note-down";
var NOTE_UP_P = "note-up-press";
var NOTE_LEFT_P = "note-left-press";
var NOTE_RIGHT_P = "note-right-press";
var NOTE_DOWN_P = "note-down-press";
var NOTE_UP_R = "note-up-release";
var NOTE_LEFT_R = "note-left-release";
var NOTE_RIGHT_R = "note-right-release";
var NOTE_DOWN_R = "note-down-release";
var ACCEPT = "accept";
var BACK = "back";
var PAUSE = "pause";
var RESET = "reset";
var CHEAT = "cheat";
var SWITCHMOD = "switchmod";
}
enum Device
{
Keys;
Gamepad(id:Int);
}
/**
* Since, in many cases multiple actions should use similar keys, we don't want the
* rebinding UI to list every action. ActionBinders are what the user perceives as
* an input so, for instance, they can't set jump-press and jump-release to different keys.
*/
enum Control
{
UP;
@@ -69,7 +22,7 @@ enum Control
ACCEPT;
BACK;
PAUSE;
CHEAT;
//CHEAT;
SWITCHMOD;
}
@@ -85,327 +38,128 @@ enum KeyboardScheme
* A list of actions that a player would invoke via some input device.
* Uses FlxActions to funnel various inputs to a single action.
*/
// Macro generated
// A and B are swapped for switch
@:noCustomClass
@:nullSafety
@:build(funkin.backend.system.macros.ControlsMacro.build())
class Controls extends FlxActionSet
{
var _up = new FlxActionDigital(Action.UP);
var _left = new FlxActionDigital(Action.LEFT);
var _right = new FlxActionDigital(Action.RIGHT);
var _down = new FlxActionDigital(Action.DOWN);
var _upP = new FlxActionDigital(Action.UP_P);
var _leftP = new FlxActionDigital(Action.LEFT_P);
var _rightP = new FlxActionDigital(Action.RIGHT_P);
var _downP = new FlxActionDigital(Action.DOWN_P);
var _upR = new FlxActionDigital(Action.UP_R);
var _leftR = new FlxActionDigital(Action.LEFT_R);
var _rightR = new FlxActionDigital(Action.RIGHT_R);
var _downR = new FlxActionDigital(Action.DOWN_R);
var _noteUp = new FlxActionDigital(Action.NOTE_UP);
var _noteLeft = new FlxActionDigital(Action.NOTE_LEFT);
var _noteRight = new FlxActionDigital(Action.NOTE_RIGHT);
var _noteDown = new FlxActionDigital(Action.NOTE_DOWN);
var _noteUpP = new FlxActionDigital(Action.NOTE_UP_P);
var _noteLeftP = new FlxActionDigital(Action.NOTE_LEFT_P);
var _noteRightP = new FlxActionDigital(Action.NOTE_RIGHT_P);
var _noteDownP = new FlxActionDigital(Action.NOTE_DOWN_P);
var _noteUpR = new FlxActionDigital(Action.NOTE_UP_R);
var _noteLeftR = new FlxActionDigital(Action.NOTE_LEFT_R);
var _noteRightR = new FlxActionDigital(Action.NOTE_RIGHT_R);
var _noteDownR = new FlxActionDigital(Action.NOTE_DOWN_R);
var _accept = new FlxActionDigital(Action.ACCEPT);
var _back = new FlxActionDigital(Action.BACK);
var _pause = new FlxActionDigital(Action.PAUSE);
var _reset = new FlxActionDigital(Action.RESET);
var _cheat = new FlxActionDigital(Action.CHEAT);
var _switchMod = new FlxActionDigital(Action.SWITCHMOD);
#if (haxe >= "4.0.0")
var byName:Map<String, FlxActionDigital> = [];
// Menus
#if !switch
@:rawGamepad([DPAD_UP, LEFT_STICK_DIGITAL_UP])
#else
var byName:Map<String, FlxActionDigital> = new Map<String, FlxActionDigital>();
@:rawGamepad([DPAD_UP, LEFT_STICK_DIGITAL_UP, RIGHT_STICK_DIGITAL_UP])
#end
@:pressed("up") public var UP(get, set): Bool;
@:justPressed("up") public var UP_P(get, set): Bool;
@:justReleased("up") public var UP_R(get, set): Bool;
#if !switch
@:rawGamepad([DPAD_LEFT, LEFT_STICK_DIGITAL_LEFT])
#else
@:rawGamepad([DPAD_LEFT, LEFT_STICK_DIGITAL_LEFT, RIGHT_STICK_DIGITAL_LEFT])
#end
@:pressed("left") public var LEFT(get, set): Bool;
@:justPressed("left") public var LEFT_P(get, set): Bool;
@:justReleased("left") public var LEFT_R(get, set): Bool;
#if !switch
@:rawGamepad([DPAD_RIGHT, LEFT_STICK_DIGITAL_RIGHT])
#else
@:rawGamepad([DPAD_RIGHT, LEFT_STICK_DIGITAL_RIGHT, RIGHT_STICK_DIGITAL_RIGHT])
#end
@:pressed("right") public var RIGHT(get, set): Bool;
@:justPressed("right") public var RIGHT_P(get, set): Bool;
@:justReleased("right") public var RIGHT_R(get, set): Bool;
#if !switch
@:rawGamepad([DPAD_DOWN, LEFT_STICK_DIGITAL_DOWN])
#else
@:rawGamepad([DPAD_DOWN, LEFT_STICK_DIGITAL_DOWN, RIGHT_STICK_DIGITAL_DOWN])
#end
@:pressed("down") public var DOWN(get, set): Bool;
@:justPressed("down") public var DOWN_P(get, set): Bool;
@:justReleased("down") public var DOWN_R(get, set): Bool;
// Note Controls
#if !switch
@:rawGamepad([DPAD_UP, LEFT_STICK_DIGITAL_UP])
#else
@:rawGamepad([DPAD_UP, LEFT_STICK_DIGITAL_UP, RIGHT_STICK_DIGITAL_UP])
#end
@:pressed("note-up") public var NOTE_UP(get, set): Bool;
@:justPressed("note-up") public var NOTE_UP_P(get, set): Bool;
@:justReleased("note-up") public var NOTE_UP_R(get, set): Bool;
#if !switch
@:rawGamepad([DPAD_LEFT, LEFT_STICK_DIGITAL_LEFT])
#else
@:rawGamepad([DPAD_LEFT, LEFT_STICK_DIGITAL_LEFT, RIGHT_STICK_DIGITAL_LEFT])
#end
@:pressed("note-left") public var NOTE_LEFT(get, set): Bool;
@:justPressed("note-left") public var NOTE_LEFT_P(get, set): Bool;
@:justReleased("note-left") public var NOTE_LEFT_R(get, set): Bool;
#if !switch
@:rawGamepad([DPAD_RIGHT, LEFT_STICK_DIGITAL_RIGHT])
#else
@:rawGamepad([DPAD_RIGHT, LEFT_STICK_DIGITAL_RIGHT, RIGHT_STICK_DIGITAL_RIGHT])
#end
@:pressed("note-right") public var NOTE_RIGHT(get, set): Bool;
@:justPressed("note-right") public var NOTE_RIGHT_P(get, set): Bool;
@:justReleased("note-right") public var NOTE_RIGHT_R(get, set): Bool;
#if !switch
@:rawGamepad([DPAD_DOWN, LEFT_STICK_DIGITAL_DOWN])
#else
@:rawGamepad([DPAD_DOWN, LEFT_STICK_DIGITAL_DOWN, RIGHT_STICK_DIGITAL_DOWN])
#end
@:pressed("note-down") public var NOTE_DOWN(get, set): Bool;
@:justPressed("note-down") public var NOTE_DOWN_P(get, set): Bool;
@:justReleased("note-down") public var NOTE_DOWN_R(get, set): Bool;
@:gamepad([A])
@:justPressed("accept") public var ACCEPT(get, set): Bool;
@:pressed("accept") public var ACCEPT_HOLD(get, set): Bool;
@:justReleased("accept") public var ACCEPT_R(get, set): Bool;
@:gamepad([B])
@:justPressed("back") public var BACK(get, set): Bool;
@:pressed("back") public var BACK_HOLD(get, set): Bool;
@:justReleased("back") public var BACK_R(get, set): Bool;
@:gamepad([START])
@:justPressed("pause") public var PAUSE(get, set): Bool;
@:pressed("pause") public var PAUSE_HOLD(get, set): Bool;
@:justReleased("pause") public var PAUSE_R(get, set): Bool;
@:gamepad([Y])
@:justPressed("reset") public var RESET(get, set): Bool;
@:pressed("reset") public var RESET_HOLD(get, set): Bool;
@:justReleased("reset") public var RESET_R(get, set): Bool;
//@:gamepad([])
//@:justPressed("cheat") public var CHEAT(get, set): Bool;
//@:pressed("cheat") public var CHEAT_HOLD(get, set): Bool;
//@:justReleased("cheat") public var CHEAT_R(get, set): Bool;
@:gamepad([FlxGamepadInputID.BACK]) // select button
@:justPressed("switchmod") public var SWITCHMOD(get, set): Bool;
@:pressed("switchmod") public var SWITCHMOD_HOLD(get, set): Bool;
@:justReleased("switchmod") public var SWITCHMOD_R(get, set): Bool;
var byName:Map<String, FlxActionDigital> = [];
public var gamepadsAdded:Array<Int> = [];
public var keyboardScheme = KeyboardScheme.None;
public var UP(get, set):Bool;
inline function get_UP()
return _up.check();
inline function set_UP(val)
return @:privateAccess _up._checked = val;
public var LEFT(get, set):Bool;
inline function get_LEFT()
return _left.check();
inline function set_LEFT(val)
return @:privateAccess _left._checked = val;
public var RIGHT(get, set):Bool;
inline function get_RIGHT()
return _right.check();
inline function set_RIGHT(val)
return @:privateAccess _right._checked = val;
public var DOWN(get, set):Bool;
inline function get_DOWN()
return _down.check();
inline function set_DOWN(val)
return @:privateAccess _down._checked = val;
public var UP_P(get, set):Bool;
inline function get_UP_P()
return _upP.check();
inline function set_UP_P(val)
return @:privateAccess _upP._checked = val;
public var LEFT_P(get, set):Bool;
inline function get_LEFT_P()
return _leftP.check();
inline function set_LEFT_P(val)
return @:privateAccess _leftP._checked = val;
public var RIGHT_P(get, set):Bool;
inline function get_RIGHT_P()
return _rightP.check();
inline function set_RIGHT_P(val)
return @:privateAccess _rightP._checked = val;
public var DOWN_P(get, set):Bool;
inline function get_DOWN_P()
return _downP.check();
inline function set_DOWN_P(val)
return @:privateAccess _downP._checked = val;
public var UP_R(get, set):Bool;
inline function get_UP_R()
return _upR.check();
inline function set_UP_R(val)
return @:privateAccess _upR._checked = val;
public var LEFT_R(get, set):Bool;
inline function get_LEFT_R()
return _leftR.check();
inline function set_LEFT_R(val)
return @:privateAccess _leftR._checked = val;
public var RIGHT_R(get, set):Bool;
inline function get_RIGHT_R()
return _rightR.check();
inline function set_RIGHT_R(val)
return @:privateAccess _rightR._checked = val;
public var DOWN_R(get, set):Bool;
inline function get_DOWN_R()
return _downR.check();
inline function set_DOWN_R(val)
return @:privateAccess _downR._checked = val;
public var NOTE_UP(get, set):Bool;
inline function get_NOTE_UP()
return _noteUp.check();
inline function set_NOTE_UP(val)
return @:privateAccess _noteUp._checked = val;
public var NOTE_LEFT(get, set):Bool;
inline function get_NOTE_LEFT()
return _noteLeft.check();
inline function set_NOTE_LEFT(val)
return @:privateAccess _noteLeft._checked = val;
public var NOTE_RIGHT(get, set):Bool;
inline function get_NOTE_RIGHT()
return _noteRight.check();
inline function set_NOTE_RIGHT(val)
return @:privateAccess _noteRight._checked = val;
public var NOTE_DOWN(get, set):Bool;
inline function get_NOTE_DOWN()
return _noteDown.check();
inline function set_NOTE_DOWN(val)
return @:privateAccess _noteDown._checked = val;
public var NOTE_UP_P(get, set):Bool;
inline function get_NOTE_UP_P()
return _noteUpP.check();
inline function set_NOTE_UP_P(val)
return @:privateAccess _noteUpP._checked = val;
public var NOTE_LEFT_P(get, set):Bool;
inline function get_NOTE_LEFT_P()
return _noteLeftP.check();
inline function set_NOTE_LEFT_P(val)
return @:privateAccess _noteLeftP._checked = val;
public var NOTE_RIGHT_P(get, set):Bool;
inline function get_NOTE_RIGHT_P()
return _noteRightP.check();
inline function set_NOTE_RIGHT_P(val)
return @:privateAccess _noteRightP._checked = val;
public var NOTE_DOWN_P(get, set):Bool;
inline function get_NOTE_DOWN_P()
return _noteDownP.check();
inline function set_NOTE_DOWN_P(val)
return @:privateAccess _noteDownP._checked = val;
public var NOTE_UP_R(get, set):Bool;
inline function get_NOTE_UP_R()
return _noteUpR.check();
inline function set_NOTE_UP_R(val)
return @:privateAccess _noteUpR._checked = val;
public var NOTE_LEFT_R(get, set):Bool;
inline function get_NOTE_LEFT_R()
return _noteLeftR.check();
inline function set_NOTE_LEFT_R(val)
return @:privateAccess _noteLeftR._checked = val;
public var NOTE_RIGHT_R(get, set):Bool;
inline function get_NOTE_RIGHT_R()
return _noteRightR.check();
inline function set_NOTE_RIGHT_R(val)
return @:privateAccess _noteRightR._checked = val;
public var NOTE_DOWN_R(get, set):Bool;
inline function get_NOTE_DOWN_R()
return _noteDownR.check();
inline function set_NOTE_DOWN_R(val)
return @:privateAccess _noteDownR._checked = val;
public var ACCEPT(get, set):Bool;
inline function get_ACCEPT()
return _accept.check();
inline function set_ACCEPT(val)
return @:privateAccess _accept._checked = val;
public var BACK(get, set):Bool;
inline function get_BACK()
return _back.check();
inline function set_BACK(val)
return @:privateAccess _back._checked = val;
public var PAUSE(get, set):Bool;
inline function get_PAUSE()
return _pause.check();
inline function set_PAUSE(val)
return @:privateAccess _pause._checked = val;
public var RESET(get, set):Bool;
inline function get_RESET()
return _reset.check();
inline function set_RESET(val)
return @:privateAccess _reset._checked = val;
public var CHEAT(get, set):Bool;
inline function get_CHEAT()
return _cheat.check();
inline function set_CHEAT(val)
return @:privateAccess _cheat._checked = val;
public var SWITCHMOD(get, set):Bool;
inline function get_SWITCHMOD()
return _switchMod.check();
inline function set_SWITCHMOD(val)
return @:privateAccess _switchMod._checked = val;
public var keyboardScheme:KeyboardScheme = None;
public function new(name, scheme = None)
{
super(name);
add(_up);
add(_left);
add(_right);
add(_down);
add(_upP);
add(_leftP);
add(_rightP);
add(_downP);
add(_upR);
add(_leftR);
add(_rightR);
add(_downR);
add(_noteUp);
add(_noteLeft);
add(_noteRight);
add(_noteDown);
add(_noteUpP);
add(_noteLeftP);
add(_noteRightP);
add(_noteDownP);
add(_noteUpR);
add(_noteLeftR);
add(_noteRightR);
add(_noteDownR);
add(_accept);
add(_back);
add(_pause);
add(_reset);
add(_cheat);
add(_switchMod);
macro_addKeysToActions();
for (action in digitalActions)
byName[action.name] = action;
@@ -413,29 +167,10 @@ class Controls extends FlxActionSet
setKeyboardScheme(scheme, false);
}
override function update()
public function getKeyName(control:Control, idx:Int = 0):String
{
super.update();
}
// inline
public function checkByName(name:Action):Bool
{
#if debug
if (!byName.exists(name))
throw 'Invalid name: $name';
#end
return byName[name].check();
}
public function getKeyName(control:Control):String
{
return getDialogueName(getActionFromControl(control));
}
public function getDialogueName(action:FlxActionDigital):String
{
var input = action.inputs[0];
var action = macro_getActionFromControl(control);
var input = action.inputs[idx];
return switch input.device
{
case KEYBOARD: return '${(input.inputID : FlxKey)}';
@@ -444,198 +179,44 @@ class Controls extends FlxActionSet
}
}
public function getDialogueNameFromToken(token:String):String
{
return getDialogueName(getActionFromControl(Control.createByName(token.toUpperCase())));
}
function getActionFromControl(control:Control):FlxActionDigital
{
return switch (control)
{
case UP: _up;
case DOWN: _down;
case LEFT: _left;
case RIGHT: _right;
case NOTE_UP: _noteUp;
case NOTE_DOWN: _noteDown;
case NOTE_LEFT: _noteLeft;
case NOTE_RIGHT: _noteRight;
case ACCEPT: _accept;
case BACK: _back;
case PAUSE: _pause;
case RESET: _reset;
case CHEAT: _cheat;
case SWITCHMOD: _switchMod;
}
}
static function init():Void
{
var actions = new FlxActionManager();
FlxG.inputs.add(actions);
}
/**
* Calls a function passing each action bound by the specified control
* @param control
* @param func
* @return ->Void)
*/
function forEachBound(control:Control, func:FlxActionDigital->FlxInputState->Void)
{
switch (control)
{
case NOTE_UP:
func(_noteUp, PRESSED);
func(_noteUpP, JUST_PRESSED);
func(_noteUpR, JUST_RELEASED);
case NOTE_LEFT:
func(_noteLeft, PRESSED);
func(_noteLeftP, JUST_PRESSED);
func(_noteLeftR, JUST_RELEASED);
case NOTE_RIGHT:
func(_noteRight, PRESSED);
func(_noteRightP, JUST_PRESSED);
func(_noteRightR, JUST_RELEASED);
case NOTE_DOWN:
func(_noteDown, PRESSED);
func(_noteDownP, JUST_PRESSED);
func(_noteDownR, JUST_RELEASED);
case UP:
func(_up, PRESSED);
func(_upP, JUST_PRESSED);
func(_upR, JUST_RELEASED);
case LEFT:
func(_left, PRESSED);
func(_leftP, JUST_PRESSED);
func(_leftR, JUST_RELEASED);
case RIGHT:
func(_right, PRESSED);
func(_rightP, JUST_PRESSED);
func(_rightR, JUST_RELEASED);
case DOWN:
func(_down, PRESSED);
func(_downP, JUST_PRESSED);
func(_downR, JUST_RELEASED);
case ACCEPT:
func(_accept, JUST_PRESSED);
case BACK:
func(_back, JUST_PRESSED);
case PAUSE:
func(_pause, JUST_PRESSED);
case RESET:
func(_reset, JUST_PRESSED);
case CHEAT:
func(_cheat, JUST_PRESSED);
case SWITCHMOD:
func(_switchMod, JUST_PRESSED);
}
}
public function replaceBinding(control:Control, device:Device, ?toAdd:Int, ?toRemove:Int)
public function replaceBindingKeyboard(control:Control, ?toAdd:Int, ?toRemove:Int)
{
if (toAdd == toRemove)
return;
switch (device)
{
case Keys:
if (toRemove != null)
unbindKeys(control, [toRemove]);
if (toAdd != null)
bindKeys(control, [toAdd]);
case Gamepad(id):
if (toRemove != null)
unbindButtons(control, id, [toRemove]);
if (toAdd != null)
bindButtons(control, id, [toAdd]);
}
if (toRemove != null)
unbindKeys(control, [toRemove]);
if (toAdd != null)
bindKeys(control, [toAdd]);
}
public function copyFrom(controls:Controls, ?device:Device)
public function replaceBindingGamepad(control:Control, deviceID:Int, ?toAdd:Int, ?toRemove:Int)
{
#if (haxe >= "4.0.0")
for (name => action in controls.byName)
{
for (input in action.inputs)
{
if (device == null || isDevice(input, device))
byName[name].add(cast input);
}
}
#else
for (name in controls.byName.keys())
{
var action = controls.byName[name];
for (input in action.inputs)
{
if (device == null || isDevice(input, device))
byName[name].add(cast input);
}
}
#end
if (toAdd == toRemove)
return;
switch (device)
{
case null:
// add all
for (gamepad in controls.gamepadsAdded)
gamepadsAdded.pushOnce(gamepad);
mergeKeyboardScheme(controls.keyboardScheme);
case Gamepad(id):
gamepadsAdded.push(id);
case Keys:
mergeKeyboardScheme(controls.keyboardScheme);
}
}
inline public function copyTo(controls:Controls, ?device:Device)
{
controls.copyFrom(this, device);
}
function mergeKeyboardScheme(scheme:KeyboardScheme):Void
{
if (scheme != None)
{
switch (keyboardScheme)
{
case None:
keyboardScheme = scheme;
default:
keyboardScheme = Custom;
}
}
if (toRemove != null)
unbindButtons(control, deviceID, [toRemove]);
if (toAdd != null)
bindButtons(control, deviceID, [toAdd]);
}
/**
* Sets all actions that pertain to the binder to trigger when the supplied keys are used.
* If binder is a literal you can inline this
*/
public function bindKeys(control:Control, keys:Array<FlxKey>)
public inline function bindKeys(control:Control, keys:Array<FlxKey>)
{
#if (haxe >= "4.0.0")
inline forEachBound(control, (action, state) -> addKeys(action, keys, state));
#else
forEachBound(control, function(action, state) addKeys(action, keys, state));
#end
macro_forEachBound(control, (action, state) -> addKeys(action, keys, state));
}
/**
* Sets all actions that pertain to the binder to trigger when the supplied keys are used.
* If binder is a literal you can inline this
*/
public function unbindKeys(control:Control, keys:Array<FlxKey>)
public inline function unbindKeys(control:Control, keys:Array<FlxKey>)
{
#if (haxe >= "4.0.0")
inline forEachBound(control, (action, _) -> removeKeys(action, keys));
#else
forEachBound(control, function(action, _) removeKeys(action, keys));
#end
macro_forEachBound(control, (action, _) -> removeKeys(action, keys));
}
inline static function addKeys(action:FlxActionDigital, keys:Array<FlxKey>, state:FlxInputState)
@@ -662,53 +243,7 @@ class Controls extends FlxActionSet
keyboardScheme = scheme;
switch (scheme)
{
case Solo:
inline bindKeys(Control.UP, Options.SOLO_UP);
inline bindKeys(Control.DOWN, Options.SOLO_DOWN);
inline bindKeys(Control.LEFT, Options.SOLO_LEFT);
inline bindKeys(Control.RIGHT, Options.SOLO_RIGHT);
inline bindKeys(Control.NOTE_UP, Options.SOLO_NOTE_UP);
inline bindKeys(Control.NOTE_DOWN, Options.SOLO_NOTE_DOWN);
inline bindKeys(Control.NOTE_LEFT, Options.SOLO_NOTE_LEFT);
inline bindKeys(Control.NOTE_RIGHT, Options.SOLO_NOTE_RIGHT);
inline bindKeys(Control.ACCEPT, Options.SOLO_ACCEPT);
inline bindKeys(Control.BACK, Options.SOLO_BACK);
inline bindKeys(Control.PAUSE, Options.SOLO_PAUSE);
inline bindKeys(Control.RESET, Options.SOLO_RESET);
inline bindKeys(Control.SWITCHMOD, Options.SOLO_SWITCHMOD);
case Duo(true):
inline bindKeys(Control.UP, Options.P1_UP);
inline bindKeys(Control.DOWN, Options.P1_DOWN);
inline bindKeys(Control.LEFT, Options.P1_LEFT);
inline bindKeys(Control.RIGHT, Options.P1_RIGHT);
inline bindKeys(Control.NOTE_UP, Options.P1_NOTE_UP);
inline bindKeys(Control.NOTE_DOWN, Options.P1_NOTE_DOWN);
inline bindKeys(Control.NOTE_LEFT, Options.P1_NOTE_LEFT);
inline bindKeys(Control.NOTE_RIGHT, Options.P1_NOTE_RIGHT);
inline bindKeys(Control.ACCEPT, Options.P1_ACCEPT);
inline bindKeys(Control.BACK, Options.P1_BACK);
inline bindKeys(Control.PAUSE, Options.P1_PAUSE);
inline bindKeys(Control.RESET, Options.P1_RESET);
inline bindKeys(Control.SWITCHMOD, Options.P1_SWITCHMOD);
case Duo(false):
inline bindKeys(Control.UP, Options.P2_UP);
inline bindKeys(Control.DOWN, Options.P2_DOWN);
inline bindKeys(Control.LEFT, Options.P2_LEFT);
inline bindKeys(Control.RIGHT, Options.P2_RIGHT);
inline bindKeys(Control.NOTE_UP, Options.P2_NOTE_UP);
inline bindKeys(Control.NOTE_DOWN, Options.P2_NOTE_DOWN);
inline bindKeys(Control.NOTE_LEFT, Options.P2_NOTE_LEFT);
inline bindKeys(Control.NOTE_RIGHT, Options.P2_NOTE_RIGHT);
inline bindKeys(Control.ACCEPT, Options.P2_ACCEPT);
inline bindKeys(Control.BACK, Options.P2_BACK);
inline bindKeys(Control.PAUSE, Options.P2_PAUSE);
inline bindKeys(Control.RESET, Options.P2_RESET);
inline bindKeys(Control.SWITCHMOD, Options.P2_SWITCHMOD);
case None: // nothing
case Custom: // nothing
}
macro_bindControls(scheme);
}
function removeKeyboard()
@@ -725,30 +260,12 @@ class Controls extends FlxActionSet
}
}
public function addGamepad(id:Int, ?buttonMap:Map<Control, Array<FlxGamepadInputID>>):Void
public function addGamepad(id:Int, buttonMap:Map<Control, Array<FlxGamepadInputID>>):Void
{
gamepadsAdded.push(id);
#if (haxe >= "4.0.0")
for (control => buttons in buttonMap)
inline bindButtons(control, id, buttons);
#else
for (control in buttonMap.keys())
bindButtons(control, id, buttonMap[control]);
#end
}
inline function addGamepadLiteral(id:Int, ?buttonMap:Map<Control, Array<FlxGamepadInputID>>):Void
{
gamepadsAdded.push(id);
#if (haxe >= "4.0.0")
for (control => buttons in buttonMap)
inline bindButtons(control, id, buttons);
#else
for (control in buttonMap.keys())
bindButtons(control, id, buttonMap[control]);
#end
bindButtons(control, id, buttons);
}
public function removeGamepad(deviceID:Int = FlxInputDeviceID.ALL):Void
@@ -759,7 +276,7 @@ class Controls extends FlxActionSet
while (i-- > 0)
{
var input = action.inputs[i];
if (input.device == GAMEPAD && (deviceID == FlxInputDeviceID.ALL || input.deviceID == deviceID))
if (isGamepad(input, deviceID))
action.remove(input);
}
}
@@ -767,60 +284,22 @@ class Controls extends FlxActionSet
gamepadsAdded.remove(deviceID);
}
public function addDefaultGamepad(id):Void
/**
* Sets all actions that pertain to the binder to trigger when the supplied keys are used.
* If binder is a literal you can inline this
*/
public inline function bindButtons(control:Control, id, buttons)
{
#if !switch
addGamepadLiteral(id, [
Control.ACCEPT => [A],
Control.BACK => [B],
Control.UP => [DPAD_UP, LEFT_STICK_DIGITAL_UP],
Control.DOWN => [DPAD_DOWN, LEFT_STICK_DIGITAL_DOWN],
Control.LEFT => [DPAD_LEFT, LEFT_STICK_DIGITAL_LEFT],
Control.RIGHT => [DPAD_RIGHT, LEFT_STICK_DIGITAL_RIGHT],
Control.PAUSE => [START],
Control.RESET => [Y]
]);
#else
addGamepadLiteral(id, [
//Swap A and B for switch
Control.ACCEPT => [B],
Control.BACK => [A],
Control.UP => [DPAD_UP, LEFT_STICK_DIGITAL_UP, RIGHT_STICK_DIGITAL_UP],
Control.DOWN => [DPAD_DOWN, LEFT_STICK_DIGITAL_DOWN, RIGHT_STICK_DIGITAL_DOWN],
Control.LEFT => [DPAD_LEFT, LEFT_STICK_DIGITAL_LEFT, RIGHT_STICK_DIGITAL_LEFT],
Control.RIGHT => [DPAD_RIGHT, LEFT_STICK_DIGITAL_RIGHT, RIGHT_STICK_DIGITAL_RIGHT],
Control.PAUSE => [START],
//Swap Y and X for switch
Control.RESET => [Y],
Control.CHEAT => [X]
]);
#end
macro_forEachBound(control, (action, state) -> addButtons(action, buttons, state, id));
}
/**
* Sets all actions that pertain to the binder to trigger when the supplied keys are used.
* If binder is a literal you can inline this
*/
public function bindButtons(control:Control, id, buttons)
public inline function unbindButtons(control:Control, gamepadID:Int, buttons)
{
#if (haxe >= "4.0.0")
inline forEachBound(control, (action, state) -> addButtons(action, buttons, state, id));
#else
forEachBound(control, function(action, state) addButtons(action, buttons, state, id));
#end
}
/**
* Sets all actions that pertain to the binder to trigger when the supplied keys are used.
* If binder is a literal you can inline this
*/
public function unbindButtons(control:Control, gamepadID:Int, buttons)
{
#if (haxe >= "4.0.0")
inline forEachBound(control, (action, _) -> removeButtons(action, gamepadID, buttons));
#else
forEachBound(control, function(action, _) removeButtons(action, gamepadID, buttons));
#end
macro_forEachBound(control, (action, _) -> removeButtons(action, gamepadID, buttons));
}
inline static function addButtons(action:FlxActionDigital, buttons:Array<FlxGamepadInputID>, state, id)
@@ -840,49 +319,6 @@ class Controls extends FlxActionSet
}
}
public function getInputsFor(control:Control, device:Device, ?list:Array<Int>):Array<Int>
{
if (list == null)
list = [];
switch (device)
{
case Keys:
for (input in getActionFromControl(control).inputs)
{
if (input.device == KEYBOARD)
list.push(input.inputID);
}
case Gamepad(id):
for (input in getActionFromControl(control).inputs)
{
if (input.deviceID == id)
list.push(input.inputID);
}
}
return list;
}
public function removeDevice(device:Device)
{
switch (device)
{
case Keys:
setKeyboardScheme(None);
case Gamepad(id):
removeGamepad(id);
}
}
static function isDevice(input:FlxActionInput, device:Device)
{
return switch device
{
case Keys: input.device == KEYBOARD;
case Gamepad(id): isGamepad(input, id);
}
}
inline static function isGamepad(input:FlxActionInput, deviceID:Int)
{
return input.device == GAMEPAD && (deviceID == FlxInputDeviceID.ALL || input.deviceID == deviceID);
+1 -1
View File
@@ -72,6 +72,6 @@ class MainState extends FlxState {
}
#end
CoolUtil.safeSetAttribute('./.temp/', HIDDEN);
CoolUtil.safeAddAttributes('./.temp/', NativeAPI.FileAttribute.HIDDEN);
}
}
@@ -1,17 +1,28 @@
package funkin.backend.system.framerate;
import haxe.ds.Vector;
import openfl.display.Sprite;
import openfl.text.TextField;
import openfl.text.TextFormat;
inline final FRAME_TIME_HISTORY = 20;
class FramerateCounter extends Sprite {
public var fpsNum:TextField;
public var fpsLabel:TextField;
public var lastFPS:Float = 0;
public var fpsHistoryIndex:Int = 0;
public var fpsHistory:Vector<Float>;
public function new() {
super();
fpsHistory = new Vector(FRAME_TIME_HISTORY);
// Initialize to 60 FPS, so that the initial estimation until we get enough data is always reasonable.
for(i in 0...FRAME_TIME_HISTORY) {
fpsHistory[i] = 1000.0 / 60.0;
}
fpsNum = new TextField();
fpsLabel = new TextField();
@@ -30,8 +41,20 @@ class FramerateCounter extends Sprite {
if (alpha <= 0.05) return;
super.__enterFrame(t);
lastFPS = CoolUtil.fpsLerp(lastFPS, FlxG.elapsed == 0 ? 0 : (1 / FlxG.elapsed), 0.25);
fpsNum.text = Std.string(Math.floor(lastFPS));
// todo use gpu time
fpsHistory[fpsHistoryIndex] = FlxG.elapsed * 1000;
fpsHistoryIndex = (fpsHistoryIndex + 1) % FRAME_TIME_HISTORY;
// Calculate average CPU time.
// Code based on Godot's FPS counter.
var cpuTime = 0.0;
for(i in 0...FRAME_TIME_HISTORY) {
cpuTime += fpsHistory[i];
}
cpuTime /= FRAME_TIME_HISTORY;
cpuTime = Math.max(0.01, cpuTime); // Prevent unrealistically low values.
fpsNum.text = Std.string(Math.floor(1000.0 / cpuTime));
fpsLabel.x = fpsNum.x + fpsNum.width;
fpsLabel.y = (fpsNum.y + fpsNum.height) - fpsLabel.height;
}
@@ -0,0 +1,43 @@
package funkin.backend.system.macros;
using StringTools;
#if macro
class BuildInfo {
public static function printBuildInfo() {
var haxeVersion = haxe.macro.Context.definedValue("haxe");
Sys.println('[ BUILD INFO ]');
Sys.println('Haxe Version: ${haxeVersion}');
try {
var lastBuiltWith:Null<String> = null;
var compiling = #if final "final" #elseif debug "debug" #else "release" #end;
var target = #if windows "windows" #elseif mac "macos" #elseif linux "linux" #elseif android "android" #elseif ios "ios" #elseif html5 "html5" #else "" #end;
if(target == "") throw "Unknown target";
var exportPath = Sys.getCwd() + "/export/" + compiling + "/" + target + "/";
exportPath += "obj/Options.txt";
var options = sys.io.File.getContent(exportPath);
for(option in options.split("\n")) {
if(option.startsWith("haxe=")) {
lastBuiltWith = option.substr(5);
break;
}
}
if(lastBuiltWith != null && lastBuiltWith != haxeVersion)
Sys.println('Last Built With Haxe: ${lastBuiltWith} [!!!! MAKE SURE IF YOU SWITCHED VERSIONS YOU DELETE EXPORT FOLDERS !!!!]');
} catch(e) {}
Sys.println('Target Platform: ${
#if windows "Windows"
#elseif mac "Mac"
#elseif linux "Linux"
#elseif android "Android"
#elseif ios "iOS"
#else "Unknown"
#end
}');
Sys.println('Build Date: ${Date.now().toString()}');
Sys.println('');
}
}
#end
@@ -0,0 +1,369 @@
package funkin.backend.system.macros;
import haxe.macro.Context;
import haxe.macro.Expr;
using StringTools;
using haxe.macro.Tools;
// Macro made by Ne_Eo
class ControlsMacro
{
static var _allControls: Array<String> = null;
static var _allInternalControls: Array<String> = null;
static var _currentControls: Map<String, Array<Expr>> = null;
static var _currentGamepadControls: Map<String, Expr> = null;
static var _keySet: Map<String, String> = null;
static var _internalMap: Map<String, String> = null;
public static macro function build(): Array<Field>
{
var fields = Context.getBuildFields();
var clRef = Context.getLocalClass();
if (clRef == null)
return fields;
var cl = clRef.get();
_allControls = [];
_allInternalControls = [];
_currentControls = [];
_currentGamepadControls = [];
_keySet = [];
_internalMap = [];
var fields = Context.getBuildFields();
for (field in fields.copy())
{
switch (field.kind)
{
case FProp(g, s, t, e):
var controlFields = handleControl(field, g, s, t, e);
for (field in controlFields)
if (field != null)
fields.push(field);
default:
}
}
// Public fields
fields.push({
name: "addDefaultGamepad",
access: [APublic],
kind: FFun({
ret: macro : Void,
params: [],
expr: generateGamepadCode(),
args: [{name: "id", type: macro : Int}]
}),
pos: Context.currentPos(),
doc: null,
meta: []
});
// Private fields, are prefixed with macro_, for readability
fields.push({
name: "macro_addKeysToActions",
access: [APublic, AInline],
kind: FFun({
ret: macro : Void,
params: [],
expr: macro $b{_allInternalControls.map((s) -> macro add($i{s}))},
args: []
}),
pos: Context.currentPos(),
doc: null,
meta: []
});
function buildBindControl(s:String, prefix:String) {
var prefixxed = prefix + s;
return macro bindKeys(Control.$s, Options.$prefixxed);
}
fields.push({
name: "macro_bindControls",
access: [],
kind: FFun({
ret: macro : Void,
params: [],
expr: macro switch(keyScheme) {
case Solo:
$a{_allControls.map(buildBindControl.bind(_, "SOLO_"))};
case Duo(true):
$a{_allControls.map(buildBindControl.bind(_, "P1_"))};
case Duo(false):
$a{_allControls.map(buildBindControl.bind(_, "P2_"))};
case None: // nothing
case Custom: // nothing
},
args: [{
name: "keyScheme",
type: macro : funkin.backend.system.Controls.KeyboardScheme
}]
}),
pos: Context.currentPos(),
doc: null,
meta: []
});
fields.push({
name: "macro_forEachBound",
access: [],
kind: FFun({
ret: macro : Void,
params: [],
expr: generateForEachBoundCode(macro control),
args: [
{
name: "control",
type: macro : Control
},
{
name: "func",
type: macro : FlxActionDigital -> FlxInputState -> Void
}
]
}),
pos: Context.currentPos(),
doc: null,
meta: []
});
fields.push({
name: "macro_getActionFromControl",
access: [APrivate],
kind: FFun({
ret: macro : FlxActionDigital,
params: [],
expr: generateGetActionFromControlCode(macro control),
args: [{
name: "control",
type: macro : Control
}]
}),
pos: Context.currentPos(),
doc: null,
meta: []
});
// for (field in fields)
// trace(new haxe.macro.Printer().printField(field));
_allControls = null;
_allInternalControls = null;
_currentControls = null;
_currentGamepadControls = null;
_keySet = null;
_internalMap = null;
return fields;
}
static function generateSwitchCase(expr:Expr, cases:Array<Case>, defaultCase:Expr): Expr
{
return {
expr: ESwitch(expr, cases, defaultCase),
pos: Context.currentPos()
}
}
static function generateGetActionFromControlCode(value:Expr): Expr
{
return macro return ${generateSwitchCase(value, [
for (short => internal in _internalMap)
{
values: [macro Control.$short],
expr: macro $i{internal}
}
], macro null)};
}
static function generateForEachBoundCode(value:Expr): Expr
{
return generateSwitchCase(value, [
for (field => code in _currentControls)
{
values: [macro Control.$field],
expr: macro $b{code}
}
], macro {});
}
static function generateGamepadCode(): Expr
{
var map: Array<Expr> = [];
for (name in _allControls)
{
var expr = _currentGamepadControls.get(name);
if(expr == null) continue;
map.push(macro @:pos(expr.pos) Control.$name => ${expr});
}
return macro addGamepad(id, $a{map});
}
static function extractString(e: Expr): String
{
switch (e.expr)
{
case EConst(CString(s)):
return s;
default:
Context.error("Expected a string", e.pos);
throw "Expected a String";
}
}
static function camelCase(s: String): String
{
s = s.split("_").map((s) ->
{
return s.charAt(0).toUpperCase() + s.substr(1).toLowerCase();
}).join("");
return s.charAt(0).toLowerCase() + s.substr(1);
}
static function swapAB(e: Expr): Expr
{
return switch (e.expr)
{
case EConst(CIdent('A')): macro B;
case EConst(CIdent('B')): macro A;
default: e.map(swapAB);
}
}
static function handleControl(field: Field, get: String, set: String, _: ComplexType, e: Expr): Array<Field>
{
var name = field.name;
var shortName = name;
var type = "";
if (shortName.endsWith(type = "_P"))
shortName = shortName.substr(0, shortName.length - 2);
else if (shortName.endsWith(type = "_R"))
shortName = shortName.substr(0, shortName.length - 2);
else if (shortName.endsWith(type = "_H"))
shortName = shortName.substr(0, shortName.length - 2);
else if (shortName.endsWith(type = "_HOLD"))
shortName = shortName.substr(0, shortName.length - 5);
else
type = "";
var internalName = "_" + camelCase(shortName);
var internalNameNoType = internalName;
if (type != "")
internalName += type.substr(1);
var keyset: Null<String> = null;
var expr: Expr = null;
var metasToRemove = [];
for (meta in field.meta)
{
var shouldRemove = true;
switch (meta.name)
{
case ":gamepad" | ":rawGamepad":
if (!_currentGamepadControls.exists(shortName))
{
var expr = meta.params[0];
var shouldRemap = meta.name != ":rawGamepad";
if (shouldRemap && Context.defined("switch"))
{
expr = swapAB(expr);
}
_currentGamepadControls.set(shortName, expr);
}
case ":pressed":
keyset = extractString(meta.params[0]);
expr = macro func($i{internalName}, PRESSED);
case ":justPressed":
keyset = extractString(meta.params[0]);
expr = macro func($i{internalName}, JUST_PRESSED);
case ":released":
keyset = extractString(meta.params[0]);
expr = macro func($i{internalName}, RELEASED);
case ":justReleased":
keyset = extractString(meta.params[0]);
expr = macro func($i{internalName}, JUST_RELEASED);
default:
shouldRemove = false;
}
if (shouldRemove)
metasToRemove.push(meta);
}
for (meta in metasToRemove)
field.meta.remove(meta);
if (_currentControls.exists(shortName))
_currentControls.get(shortName).push(expr);
else
_currentControls.set(shortName, [expr]);
if (!_allInternalControls.contains(internalName))
_allInternalControls.push(internalName);
if (!_allControls.contains(shortName))
_allControls.push(shortName);
_keySet.set(shortName, keyset);
if (!_internalMap.exists(internalNameNoType))
_internalMap.set(shortName, internalNameNoType);
// Generated Code: var _uiUp = new FlxActionDigital("_uiUp");
var internalField: Field = {
name: internalName,
access: [APrivate],
kind: FVar(macro : FlxActionDigital, macro new FlxActionDigital($v{internalName})),
pos: field.pos,
doc: null,
meta: []
};
// Generated Code:
// inline function get_UI_UP(): Bool
// return _uiUp.check();
var getField: Field = {
name: "get_" + name,
access: [APrivate, AInline],
kind: FFun({
ret: macro : Bool,
params: [],
expr: macro
{
return $i{internalName}.check();
},
args: []
}),
pos: field.pos,
doc: field.doc,
meta: []
};
// Generated Code:
// inline function set_UI_UP(val: Bool): Bool
// return @:privateAccess _uiUp._checked = val;
var setField: Field = {
name: "set_" + name,
access: [APrivate, AInline],
kind: FFun({
ret: macro : Bool,
params: [],
expr: macro
{
return @:privateAccess $i{internalName}._checked = val;
},
args: [{name: "val", type: macro : Bool}]
}),
pos: field.pos,
doc: field.doc,
meta: []
};
return [internalField, getField, set == "set" ? setField : null];
}
}
@@ -1,16 +0,0 @@
package funkin.backend.system.macros;
#if macro
class NewHaxeWarning {
public static function warn() {
#if (haxe >= "4.3.0" && !display)
Sys.println("====================");
Sys.println("[ WARNING ]");
Sys.println("Compiling with Haxe 4.3.0 isnt fully recommended yet, but it does work.");
Sys.println("We recommend building the project using Haxe 4.2.5.");
Sys.println("You can download it here -> https://haxe.org/download/version/4.2.5/");
Sys.println("====================");
#end
}
}
#end
+80 -7
View File
@@ -3,6 +3,21 @@ package funkin.backend.utils;
#if sys
import sys.FileSystem;
#end
import flixel.text.FlxText;
import funkin.backend.utils.XMLUtil.TextFormat;
import flixel.util.typeLimit.OneOfTwo;
import flixel.util.typeLimit.OneOfThree;
import flixel.tweens.FlxTween;
import flixel.system.frontEnds.SoundFrontEnd;
import flixel.sound.FlxSound;
import funkin.backend.system.Conductor;
import flixel.sound.FlxSoundGroup;
import haxe.Json;
import haxe.io.Path;
import haxe.io.Bytes;
import haxe.xml.Access;
import flixel.input.keyboard.FlxKey;
import lime.utils.Assets;
import flixel.animation.FlxAnimation;
import flixel.input.keyboard.FlxKey;
import flixel.sound.FlxSound;
@@ -110,18 +125,66 @@ class CoolUtil
}
/**
* Sets an attribute to a file or a folder adding eventual missing folders in the path
* (WARNING: Only works on `windows`. On other platforms the return code it's always going to be `0` but still creates eventual missing folders if the platforms allows it to).
* Gets file attributes from a file or a folder adding eventual missing folders in the path
* (WARNING: Only works on `windows` for now. On other platforms the attributes' value it's always going to be `0` -thanks to the wrapper you can also use `isNothing` for checking- but still creates eventual missing folders if the platforms allows it to).
* @param path Path to the file or folder
* @param attrib The attribute to set (WARNING: There are some non settable attributes, such as the `COMPRESSED` one)
* @param useAbsol If it should use the absolute path (By default it's `true` but if it's `false` you can use files outside from this program's directory for example)
* @return The result code: 0 means that it failed setting
* @return The attributes through the `FileAttributeWrapper`
*/
@:noUsing public static inline function safeSetAttribute(path:String, attrib:NativeAPI.FileAttribute, useAbsol:Bool = true) {
@:noUsing public static inline function safeGetAttributes(path:String, useAbsol:Bool = true):FileAttributeWrapper {
addMissingFolders(Path.directory(path));
var result = NativeAPI.setFileAttribute(path, attrib, useAbsol);
if(result == 0) Logs.trace('Failed to set attribute to $path with a code of: $result', WARNING);
var result = NativeAPI.getFileAttributes(path, useAbsol);
if(result.isNothing) Logs.trace('The file where it has been tried to get the attributes from, might be corrupted or inexistent (code: ${result.getValue()})', WARNING);
return result;
}
/**
* Sets file attributes to a file or a folder adding eventual missing folders in the path
* (WARNING: Only works on `windows` for now. On other platforms the return code it's always going to be `0` but still creates eventual missing folders if the platforms allows it to).
* @param path Path to the file or folder
* @param attrib The attribute(s) to set (WARNING: There are some non settable attributes, such as the `COMPRESSED` one)
* @param useAbsol If it should use the absolute path (By default it's `true` but if it's `false` you can use files outside from this program's directory for example)
* @return The result code: `0` means that it failed setting
*/
@:noUsing public static inline function safeSetAttributes(path:String, attrib:OneOfThree<NativeAPI.FileAttribute, FileAttributeWrapper, Int>, useAbsol:Bool = true):Int {
// yes, i'm aware that FileAttribute is also an Int so need to include it too, but at least like this we don't have to make cast sometimes while passing the arguments - Nex
addMissingFolders(Path.directory(path));
var result = NativeAPI.setFileAttributes(path, attrib, useAbsol);
if(result == 0) Logs.trace('Failed to set attributes to $path with a code of: $result', WARNING);
return result;
}
/**
* Adds one (or more) file attributes to a file or a folder adding eventual missing folders in the path
* (WARNING: Only works on `windows` for now. On other platforms the return code it's always going to be `0` but still creates eventual missing folders if the platforms allows it to).
* @param path Path to the file or folder
* @param attrib The attribute(s) to add (WARNING: There are some non settable attributes, such as the `COMPRESSED` one)
* @param useAbsol If it should use the absolute path (By default it's `true` but if it's `false` you can use files outside from this program's directory for example)
* @return The result code: `0` means that it failed setting
*/
@:noUsing public static inline function safeAddAttributes(path:String, attrib:OneOfTwo<NativeAPI.FileAttribute, Int>, useAbsol:Bool = true):Int {
addMissingFolders(Path.directory(path));
var result = NativeAPI.addFileAttributes(path, attrib, useAbsol);
if(result == 0) Logs.trace('Failed to add attributes to $path with a code of: $result', WARNING);
return result;
}
/**
* Removes one (or more) file attributes to a file or a folder adding eventual missing folders in the path
* (WARNING: Only works on `windows` for now. On other platforms the return code it's always going to be `0` but still creates eventual missing folders if the platforms allows it to).
* @param path Path to the file or folder
* @param attrib The attribute(s) to remove (WARNING: There are some non settable attributes, such as the `COMPRESSED` one)
* @param useAbsol If it should use the absolute path (By default it's `true` but if it's `false` you can use files outside from this program's directory for example)
* @return The result code: `0` means that it failed setting
*/
@:noUsing public static inline function safeRemoveAttributes(path:String, attrib:OneOfTwo<NativeAPI.FileAttribute, Int>, useAbsol:Bool = true):Int {
addMissingFolders(Path.directory(path));
var result = NativeAPI.removeFileAttributes(path, attrib, useAbsol);
if(result == 0) Logs.trace('Failed to remove attributes to $path with a code of: $result', WARNING);
return result;
}
@@ -775,6 +838,16 @@ class CoolUtil
r.add(str);
return r.toString();
}
/*
* Returns the filename of a path, without the extension.
* @param path Path to get the filename from
* @return Filename
*/
@:noUsing public static inline function getFilename(file:String) {
var file = new haxe.io.Path(file);
return file.file;
}
}
/**
@@ -0,0 +1,283 @@
package funkin.backend.utils;
import flixel.util.FlxStringUtil;
import funkin.backend.utils.NativeAPI.FileAttribute;
/**
* Currently only for Windows, but planned to work on other platforms later.
*/
class FileAttributeWrapper
{
private var flags:Int;
inline public function getValue():Int
{
return flags;
}
public function new(flags:Int)
{
this.flags = flags == -1 ? 0 : flags;
}
/**
* Returns a string representation of the attributes.
*/
inline public function toString():String
{
return FlxStringUtil.getDebugString([
for (field in Reflect.fields(this))
{
LabelValuePair.weak(field, Reflect.getProperty(this, field));
}
]);
}
// Settables
public var isArchived(get, set):Bool;
private function get_isArchived():Bool
{
#if windows
return (flags & FileAttribute.ARCHIVE) != 0;
#else
return false;
#end
}
private function set_isArchived(value:Bool):Bool
{
#if windows
if (value)
flags |= FileAttribute.ARCHIVE;
else
flags &= ~FileAttribute.ARCHIVE;
return value;
#else
return false;
#end
}
public var isHidden(get, set):Bool;
private function get_isHidden():Bool
{
#if windows
return (flags & FileAttribute.HIDDEN) != 0;
#else
return false;
#end
}
private function set_isHidden(value:Bool):Bool
{
#if windows
if (value)
flags |= FileAttribute.HIDDEN;
else
flags &= ~FileAttribute.HIDDEN;
return value;
#else
return false;
#end
}
public var isNormal(get, set):Bool;
private function get_isNormal():Bool
{
#if windows
return (flags & FileAttribute.NORMAL) != 0;
#else
return false;
#end
}
private function set_isNormal(value:Bool):Bool
{
#if windows
if (value)
flags |= FileAttribute.NORMAL;
else
flags &= ~FileAttribute.NORMAL;
return value;
#else
return false;
#end
}
public var isNotContentIndexed(get, set):Bool;
private function get_isNotContentIndexed():Bool
{
#if windows
return (flags & FileAttribute.NOT_CONTENT_INDEXED) != 0;
#else
return false;
#end
}
private function set_isNotContentIndexed(value:Bool):Bool
{
#if windows
if (value)
flags |= FileAttribute.NOT_CONTENT_INDEXED;
else
flags &= ~FileAttribute.NOT_CONTENT_INDEXED;
return value;
#else
return false;
#end
}
public var isOffline(get, set):Bool;
private function get_isOffline():Bool
{
#if windows
return (flags & FileAttribute.OFFLINE) != 0;
#else
return false;
#end
}
private function set_isOffline(value:Bool):Bool
{
#if windows
if (value)
flags |= FileAttribute.OFFLINE;
else
flags &= ~FileAttribute.OFFLINE;
return value;
#else
return false;
#end
}
public var isReadOnly(get, set):Bool;
private function get_isReadOnly():Bool
{
#if windows
return (flags & FileAttribute.READONLY) != 0;
#else
return false;
#end
}
private function set_isReadOnly(value:Bool):Bool
{
#if windows
if (value)
flags |= FileAttribute.READONLY;
else
flags &= ~FileAttribute.READONLY;
return value;
#else
return false;
#end
}
public var isSystem(get, set):Bool;
private function get_isSystem():Bool
{
#if windows
return (flags & FileAttribute.SYSTEM) != 0;
#else
return false;
#end
}
private function set_isSystem(value:Bool):Bool
{
#if windows
if (value)
flags |= FileAttribute.SYSTEM;
else
flags &= ~FileAttribute.SYSTEM;
return value;
#else
return false;
#end
}
public var isTemporary(get, set):Bool;
private function get_isTemporary():Bool
{
#if windows
return (flags & FileAttribute.TEMPORARY) != 0;
#else
return false;
#end
}
private function set_isTemporary(value:Bool):Bool
{
#if windows
if (value)
flags |= FileAttribute.TEMPORARY;
else
flags &= ~FileAttribute.TEMPORARY;
return value;
#else
return false;
#end
}
// Non Settables
public var isCompressed(get, never):Bool;
private function get_isCompressed():Bool
{
#if windows
return (flags & FileAttribute.COMPRESSED) != 0;
#else
return false;
#end
}
public var isDevice(get, never):Bool;
private function get_isDevice():Bool
{
#if windows
return (flags & FileAttribute.DEVICE) != 0;
#else
return false;
#end
}
public var isDirectory(get, never):Bool;
private function get_isDirectory():Bool
{
#if windows
return (flags & FileAttribute.DIRECTORY) != 0;
#else
return false;
#end
}
public var isEncrypted(get, never):Bool;
private function get_isEncrypted():Bool
{
#if windows
return (flags & FileAttribute.ENCRYPTED) != 0;
#else
return false;
#end
}
public var isReparsePoint(get, never):Bool;
private function get_isReparsePoint():Bool
{
#if windows
return (flags & FileAttribute.REPARSE_POINT) != 0;
#else
return false;
#end
}
public var isSparseFile(get, never):Bool;
private function get_isSparseFile():Bool
{
#if windows
return (flags & FileAttribute.SPARSE_FILE) != 0;
#else
return false;
#end
}
// For checking
public var isNothing(get, never):Bool;
private function get_isNothing():Bool
{
#if windows
return flags == 0;
#else
return true;
#end
}
}
+39 -8
View File
@@ -1,6 +1,8 @@
package funkin.backend.utils;
import funkin.backend.utils.native.*;
import flixel.util.typeLimit.OneOfTwo;
import flixel.util.typeLimit.OneOfThree;
/**
* Class for functions that talk to a lower level than haxe, such as message boxes, and more.
@@ -30,24 +32,53 @@ class NativeAPI {
}
/**
* Gets the specified file's (or folder) attribute.
* Gets the specified file's (or folder) attributes.
*/
public static function getFileAttribute(path:String, useAbsol:Bool = true):FileAttribute {
public static function getFileAttributesRaw(path:String, useAbsol:Bool = true):Int {
#if windows
if(useAbsol) path = sys.FileSystem.absolutePath(path);
return Windows.getFileAttribute(path);
return Windows.getFileAttributes(path);
#else
return NORMAL;
return -1;
#end
}
/**
* Sets the specified file's (or folder) attribute. If it fails, the return value is `0`.
* Gets the specified file's (or folder) attributes and passes it to `FileAttributeWrapper`.
*/
public static function setFileAttribute(path:String, attrib:FileAttribute, useAbsol:Bool = true):Int {
public static function getFileAttributes(path:String, useAbsol:Bool = true):FileAttributeWrapper {
return new FileAttributeWrapper(getFileAttributesRaw(path, useAbsol));
}
/**
* Sets the specified file's (or folder) attributes. If it fails, the return value is `0`.
*/
public static function setFileAttributes(path:String, attrib:OneOfThree<NativeAPI.FileAttribute, FileAttributeWrapper, Int>, useAbsol:Bool = true):Int {
#if windows
if(useAbsol) path = sys.FileSystem.absolutePath(path);
return Windows.setFileAttribute(path, attrib);
return Windows.setFileAttributes(path, attrib is FileAttributeWrapper ? cast(attrib, FileAttributeWrapper).getValue() : cast(attrib, Int));
#else
return 0;
#end
}
/**
* Removes from the specified file's (or folder) one (or more) specific attribute.
*/
public static function addFileAttributes(path:String, attrib:OneOfTwo<NativeAPI.FileAttribute, Int>, useAbsol:Bool = true):Int {
#if windows
return setFileAttributes(path, getFileAttributesRaw(path, useAbsol) | cast(attrib, Int), useAbsol);
#else
return 0;
#end
}
/**
* Removes from the specified file's (or folder) one (or more) specific attribute.
*/
public static function removeFileAttributes(path:String, attrib:OneOfTwo<NativeAPI.FileAttribute, Int>, useAbsol:Bool = true):Int {
#if windows
return setFileAttributes(path, getFileAttributesRaw(path, useAbsol) & ~cast(attrib, Int), useAbsol);
#else
return 0;
#end
@@ -137,7 +168,7 @@ class NativeAPI {
}
}
enum abstract FileAttribute(Int) {
enum abstract FileAttribute(Int) from Int to Int {
// Settables
var ARCHIVE = 0x20;
var HIDDEN = 0x2;
@@ -157,7 +157,7 @@ class Windows {
@:functionCode('
return GetFileAttributes(path);
')
public static function getFileAttribute(path:String):FileAttribute
public static function getFileAttributes(path:String):FileAttribute
{
return NORMAL;
}
@@ -165,7 +165,7 @@ class Windows {
@:functionCode('
return SetFileAttributes(path, attrib);
')
public static function setFileAttribute(path:String, attrib:FileAttribute):Int
public static function setFileAttributes(path:String, attrib:FileAttribute):Int
{
return 0;
}
@@ -348,10 +348,6 @@ class CharacterEditor extends UIState {
}
function buildCharacter():String {
if (character.isPlayer != character.playerOffsets) {
character.switchOffset('singLEFT', 'singRIGHT');
character.switchOffset('singLEFTmiss', 'singRIGHTmiss');
}
var charXML:Xml = character.buildXML([
for (button in characterAnimsWindow.buttons.members)
button.anim
@@ -588,6 +584,12 @@ class CharacterEditor extends UIState {
function changeOffset(anim:String, change:FlxPoint, addtoUndo:Bool = true) {
if (character.getNameList().length == 0) return;
var animData = character.animDatas.get(anim);
if (animData != null) {
animData.x += change.x;
animData.y += change.y;
}
character.animOffsets.set(anim, character.getAnimOffset(anim) + change);
for (i in characterAnimsWindow.buttons.members)
if (i.anim == anim)
@@ -119,7 +119,7 @@ class CharacterInfoScreen extends UISubstateWindow {
add(isPlayerCheckbox);
addLabelOn(isPlayerCheckbox, "Is Player");
isGFCheckbox = new UICheckbox(isPlayerCheckbox.x + 128, positionXStepper.y + 10 + 32 + 28, "isGF", character.isGF);
isGFCheckbox = new UICheckbox(isPlayerCheckbox.x + 128, positionXStepper.y + 10 + 32 + 28, "isGF", false);
add(isGFCheckbox);
addLabelOn(isGFCheckbox, "Is GF");
@@ -168,7 +168,6 @@ class CharacterInfoScreen extends UISubstateWindow {
var xml = Xml.createElement("character");
xml.set("isPlayer", isPlayerCheckbox.checked ? "true" : "false");
xml.set("isGF", isGFCheckbox.checked ? "true" : "false");
xml.set("x", Std.string(positionXStepper.value));
xml.set("y", Std.string(positionYStepper.value));
xml.set("gameOverChar", gameOverCharTextBox.label.text);
+231 -313
View File
@@ -1,5 +1,6 @@
package funkin.game;
import flixel.util.typeLimit.OneOfTwo;
import flixel.graphics.frames.FlxFrame;
import flixel.math.FlxPoint;
import flixel.math.FlxRect;
@@ -26,15 +27,8 @@ using StringTools;
@:allow(funkin.desktop.editors.CharacterEditor)
@:allow(funkin.game.StrumLine)
@:allow(funkin.game.PlayState)
class Character extends FunkinSprite implements IBeatReceiver implements IOffsetCompatible
{
private var __stunnedTime:Float = 0;
private var __lockAnimThisFrame:Bool = false;
public var stunned(default, set):Bool = false;
class Character extends FunkinSprite implements IBeatReceiver implements IOffsetCompatible {
public var isPlayer:Bool = false;
public var isGF:Bool = false;
public var curCharacter:String = 'bf';
public var sprite:String = 'bf';
@@ -45,163 +39,87 @@ class Character extends FunkinSprite implements IBeatReceiver implements IOffset
public var icon:String = null;
public var iconColor:Null<FlxColor> = null;
public var gameOverCharacter:String = "bf-dead";
public var gameOverCharacter:String = Character.FALLBACK_DEAD_CHARACTER;
public var cameraOffset:FlxPoint = new FlxPoint(0, 0);
public var globalOffset:FlxPoint = new FlxPoint(0, 0);
public var cameraOffset:FlxPoint = FlxPoint.get(0, 0);
public var globalOffset:FlxPoint = FlxPoint.get(0, 0);
public var script:Script;
public var xml:Access;
public var shadowFrame:CharacterShadowFrame;
public var idleSuffix:String = "";
public var stunned(default, set):Bool = false;
public var anims = ["singLEFT", "singDOWN", "singUP", "singRIGHT"]; // Not making these inline so theyre editable through scripts! - Nex
@:noCompletion var __stunnedTime:Float = 0;
@:noCompletion var __lockAnimThisFrame:Bool = false;
public inline function getCameraPosition()
{
var midpoint = getMidpoint();
var event = EventManager.get(PointEvent).recycle(
midpoint.x + (isPlayer ? -100 : 150) + globalOffset.x + cameraOffset.x,
midpoint.y - 100 + globalOffset.y + cameraOffset.y);
script.call("onGetCamPos", [event]);
midpoint.put();
// this event cannot be cancelled
return new FlxPoint(event.x, event.y);
}
@:noCompletion var __switchAnims:Bool = true;
public inline function getSingAnim(direction:Int, suffix:String = ""):String
{
return anims[direction % anims.length] + suffix;
}
/**
* Like `playSingAnimUnsafe` but checks if the character has the animation with the suffix part, otherwhise tries to play the animation without the suffix part.
*/
public function playSingAnim(direction:Int, suffix:String = "", Context:PlayAnimContext = SING, Force:Bool = true, Reversed:Bool = false, Frame:Int = 0)
{
var event = EventManager.get(DirectionAnimEvent).recycle(getSingAnim(direction, suffix), direction, suffix, Context, Reversed, Frame, Force);
script.call("onPlaySingAnim", [event]);
if (!event.cancelled)
playSingAnimUnsafe(event.direction, hasAnimation(event.animName) ? event.suffix : "", event.context, event.force, event.reversed, event.frame);
}
public function playSingAnimUnsafe(direction:Int, suffix:String = "", Context:PlayAnimContext = SING, Force:Bool = true, Reversed:Bool = false, Frame:Int = 0)
{
var event = EventManager.get(DirectionAnimEvent).recycle(getSingAnim(direction, suffix), direction, suffix, Context, Reversed, Frame, Force);
script.call("onPlaySingAnimUnsafe", [event]);
if (!event.cancelled)
playAnim(event.animName, event.force, event.context, event.reversed, event.frame);
}
public function new(x:Float, y:Float, ?character:String = "bf", isPlayer:Bool = false, switchAnims:Bool = true)
public function new(x:Float, y:Float, ?character:String = "bf", isPlayer:Bool = false, switchAnims:Bool = true, disableScripts:Bool = false)
{
super(x, y);
animOffsets = new Map<String, FlxPoint>();
curCharacter = character;
this.isPlayer = isPlayer;
__switchAnims = switchAnims;
antialiasing = true;
while (true)
{
switch (curCharacter)
{
// case 'your-char': // To hardcode characters
default:
// load xml
var xmlPath = Paths.xml('characters/$curCharacter');
if (!Assets.exists(xmlPath))
{
curCharacter = "bf";
continue;
}
xml = getXMLFromCharName(this);
if(!disableScripts)
script = Script.create(Paths.script(Path.withoutExtension(Paths.xml('characters/$curCharacter')), null, true));
else
script = new DummyScript(curCharacter);
script.setParent(this);
script.load();
buildCharacter(xml);
script.call("create");
var plainXML = Assets.getText(xmlPath);
try
{
var charXML = Xml.parse(plainXML).firstElement();
if (charXML == null) throw new Exception("Missing \"character\" node in XML.");
xml = new Access(charXML);
} catch (e) {
Logs.error('Error while loading character ${curCharacter}: ${e}');
curCharacter = "bf";
continue;
}
// Loads the script
script = Script.create(Paths.script(Path.withoutExtension(xmlPath), null, true));
script.setParent(this);
script.load();
applyXML(xml);
script.call("create");
}
break;
}
if (script == null)
script = new DummyScript(curCharacter);
/**
NON CONVERTED CHARACTERS - DO NOT REMOVE
**/
// case 'bf-pixel-dead':
// frames = Paths.getSparrowAtlas('weeb/bfPixelsDEAD');
// animation.addByPrefix('singUP', "BF Dies pixel", 24, false);
// animation.addByPrefix('firstDeath', "BF Dies pixel", 24, false);
// animation.addByPrefix('deathLoop', "Retry Loop", 24, true);
// animation.addByPrefix('deathConfirm', "RETRY CONFIRM", 24, false);
// animation.play('firstDeath');
// addOffset('firstDeath');
// addOffset('deathLoop', -37);
// addOffset('deathConfirm', -37);
// playAnim('firstDeath');
// // pixel bullshit
// setGraphicSize(Std.int(width * 6));
// updateHitbox();
// antialiasing = false;
// flipX = true;
script.call("postCreate");
}
public function fixChar(switchAnims:Bool = false, autoInterval:Bool = false)
{
@:noCompletion var __swappedLeftRightAnims:Bool = false;
@:noCompletion var __autoInterval:Bool = false;
public function fixChar(switchAnims:Bool = false, autoInterval:Bool = false) {
if ((isDanceLeftDanceRight = hasAnimation("danceLeft") && hasAnimation("danceRight")) && autoInterval)
beatInterval = 1;
__autoInterval = autoInterval;
// alternative to xor operator
// for people who dont believe it, heres the truth table
// [ a ][ b ][ a!= b ]
// [ true ][ true ][ false ]
// [ true ][ false ][ true ]
// [ false ][ true ][ true ]
// [ true ][ true ][ false ]
// bros provided evidence :skull:
// character is flipped
if (isPlayer != playerOffsets && switchAnims)
{
// character is flipped
CoolUtil.switchAnimFrames(animation.getByName('singRIGHT'), animation.getByName('singLEFT'));
CoolUtil.switchAnimFrames(animation.getByName('singRIGHTmiss'), animation.getByName('singLEFTmiss'));
swapLeftRightAnimations();
switchOffset('singLEFT', 'singRIGHT');
switchOffset('singLEFTmiss', 'singRIGHTmiss');
}
frameOffset.set(getAnimOffset(getAnimName()).x, getAnimOffset(getAnimName()).y);
if (isPlayer)
flipX = !flipX;
var o:FlxPoint = getAnimOffset(getAnimName());
frameOffset.set(o.x, o.y);
o.put();
if (isPlayer) flipX = !flipX;
__baseFlipped = flipX;
}
var __baseFlipped:Bool = false;
var isDanceLeftDanceRight:Bool = false;
public function swapLeftRightAnimations() {
CoolUtil.switchAnimFrames(animation.getByName('singRIGHT'), animation.getByName('singLEFT'));
CoolUtil.switchAnimFrames(animation.getByName('singRIGHTmiss'), animation.getByName('singLEFTmiss'));
override function update(elapsed:Float)
{
switchOffset('singLEFT', 'singRIGHT');
switchOffset('singLEFTmiss', 'singRIGHTmiss');
__swappedLeftRightAnims = true;
}
@:noCompletion var __baseFlipped:Bool = false;
@:noCompletion var isDanceLeftDanceRight:Bool = false;
override function update(elapsed:Float) {
super.update(elapsed);
script.call("update", [elapsed]);
if (stunned)
{
if (stunned) {
__stunnedTime += elapsed;
if (__stunnedTime > 5 / 60)
stunned = false;
@@ -215,33 +133,20 @@ class Character extends FunkinSprite implements IBeatReceiver implements IOffset
private var danced:Bool = false;
/**
* FOR GF DANCING SHIT
*/
public function dance()
{
public function dance() {
if(debugMode) return;
var event = EventManager.get(DanceEvent).recycle(danced);
script.call("onDance", [event]);
if (event.cancelled)
return;
if (event.cancelled) return;
switch (curCharacter)
{
// hardcode custom dance animations here
default:
if (isDanceLeftDanceRight)
{
playAnim(((danced = !danced) ? 'danceLeft' : 'danceRight') + idleSuffix, DANCE);
}
else
playAnim('idle' + idleSuffix, DANCE);
}
if (isDanceLeftDanceRight)
playAnim(((danced = !danced) ? 'danceLeft' : 'danceRight') + idleSuffix, DANCE);
else
playAnim('idle' + idleSuffix, DANCE);
}
public function tryDance()
{
public function tryDance() {
switch (lastAnimContext) {
case SING | MISS:
if (lastHit + (Conductor.stepCrochet * holdTime) < Conductor.songPosition)
@@ -261,96 +166,79 @@ class Character extends FunkinSprite implements IBeatReceiver implements IOffset
* Whenever the character should dance on beat or not. Set to false for `gf`, since the dance animation is automatically handled by PlayState.
*/
public var danceOnBeat:Bool = true;
public override function beatHit(curBeat:Int) {
script.call("beatHit", [curBeat]);
if (danceOnBeat && (curBeat + beatOffset) % beatInterval == 0 && !__lockAnimThisFrame)
{
tryDance();
}
}
public override function stepHit(curStep:Int) {
public override function stepHit(curStep:Int)
script.call("stepHit", [curStep]);
// nothing
}
var __reverseDrawProcedure:Bool = false;
@:noCompletion var __reverseDrawProcedure:Bool = false;
public override function getScreenBounds(?newRect:FlxRect, ?camera:FlxCamera):FlxRect {
if (__reverseDrawProcedure)
{
if (__reverseDrawProcedure) {
scale.x *= -1;
var bounds = super.getScreenBounds(newRect, camera);
var bounds:FlxRect = super.getScreenBounds(newRect, camera);
scale.x *= -1;
return bounds;
}
return super.getScreenBounds(newRect, camera);
}
public function isFlippedOffsets() {
return (isPlayer != playerOffsets) != (flipX != __baseFlipped);
public override function isOnScreen(?camera:FlxCamera):Bool {
if (debugMode) return true;
return super.isOnScreen(camera);
}
var __drawingShadowFrame = false;
var __oldColorTransform = new ColorTransform();
public function isFlippedOffsets()
return (isPlayer != playerOffsets) != (flipX != __baseFlipped);
public override function draw() {
if (!__drawingShadowFrame && shadowFrame != null) {
__drawingShadowFrame = true;
var oldFrame = _frame;
var oldPos = FlxPoint.get(frameOffset.x, frameOffset.y);
__oldColorTransform.copyColorTransform(colorTransform);
colorTransform.alphaMultiplier = 1;
colorTransform.alphaOffset = 0;
colorTransform.blueMultiplier = 0;
colorTransform.blueOffset = 25;
colorTransform.greenMultiplier = 0;
colorTransform.greenOffset = 25;
colorTransform.redMultiplier = 0;
colorTransform.redOffset = 25;
_frame = shadowFrame.frame;
var o = getAnimOffset(shadowFrame.anim);
frameOffset.set(o.x, o.y);
super.draw();
_frame = oldFrame;
frameOffset.set(oldPos.x, oldPos.y);
colorTransform.copyColorTransform(__oldColorTransform);
oldPos.put();
__drawingShadowFrame = false;
}
if (isFlippedOffsets())
{
if (isFlippedOffsets()) {
__reverseDrawProcedure = true;
flipX = !flipX;
scale.x *= -1;
super.draw();
flipX = !flipX;
scale.x *= -1;
__reverseDrawProcedure = false;
}
else
super.draw();
} else super.draw();
}
public override function playAnim(AnimName:String, Force:Bool = false, Context:PlayAnimContext = NONE, Reversed:Bool = false, Frame:Int = 0):Void
public var singAnims = ["singLEFT", "singDOWN", "singUP", "singRIGHT"];
public inline function getSingAnim(direction:Int, suffix:String = ""):String
{
return singAnims[direction % singAnims.length] + suffix;
}
/**
* Like `playSingAnimUnsafe` but checks if the character has the animation with the suffix part, otherwise it plays the animation without the suffix part.
*/
public function playSingAnim(direction:Int, suffix:String = "", Context:PlayAnimContext = SING, Force:Bool = true, Reversed:Bool = false, Frame:Int = 0)
{
var event = EventManager.get(DirectionAnimEvent).recycle(getSingAnim(direction, suffix), direction, suffix, Context, Reversed, Frame, Force);
script.call("onPlaySingAnim", [event]);
if (event.cancelled) return;
playSingAnimUnsafe(event.direction, hasAnimation(event.animName) ? event.suffix : "", event.context, event.force, event.reversed, event.frame);
}
public function playSingAnimUnsafe(direction:Int, suffix:String = "", Context:PlayAnimContext = SING, Force:Bool = true, Reversed:Bool = false, Frame:Int = 0) {
var event = EventManager.get(DirectionAnimEvent).recycle(getSingAnim(direction, suffix), direction, suffix, Context, Reversed, Frame, Force);
script.call("playSingAnimUnsafe", [event]);
if (event.cancelled) return;
playAnim(event.animName, event.force, event.context, event.reversed, event.frame);
}
public override function playAnim(AnimName:String, Force:Bool = false, Context:PlayAnimContext = NONE, Reversed:Bool = false, Frame:Int = 0) {
var event = EventManager.get(PlayAnimEvent).recycle(AnimName, Force, Reversed, Frame, Context);
script.call("onPlayAnim", [event]);
if (event.cancelled)
return;
if (event.cancelled) return;
super.playAnim(event.animName, event.force, event.context, event.reverse, event.startingFrame);
@@ -359,50 +247,67 @@ class Character extends FunkinSprite implements IBeatReceiver implements IOffset
lastHit = Conductor.songPosition;
}
public override function destroy()
{
public inline function getCameraPosition() {
var midpoint:FlxPoint = getMidpoint();
var event = EventManager.get(PointEvent).recycle(
midpoint.x + (isPlayer ? -100 : 150) + globalOffset.x + cameraOffset.x,
midpoint.y - 100 + globalOffset.y + cameraOffset.y);
script.call("onGetCamPos", [event]);
midpoint.put();
return new FlxPoint(event.x, event.y);
}
public override function destroy() {
if(script != null) {
script.call('destroy');
script.destroy();
}
super.destroy();
cameraOffset.put();
globalOffset.put();
}
// FlxTrail Stuff for fixing position
@:noCompletion var __reverseTrailProcedure:Bool = false;
var __reverseTrailProcedure:Bool = false;
/**
* When using trails on characters you should do `trail.beforeCache = char.beforeTrailCache;`
**/
dynamic function beforeTrailCache() {
if (isFlippedOffsets())
{
// When using trails on characters you should do `trail.beforeCache = char.beforeTrailCache;`
public dynamic function beforeTrailCache()
if (isFlippedOffsets()) {
flipX = !flipX;
scale.x *= -1;
__reverseTrailProcedure = true;
}
}
/**
* When using trails on characters you should do `trail.afterCache = char.afterTrailCache;`
**/
dynamic function afterTrailCache() {
if (__reverseTrailProcedure)
{
// When using trails on characters you should do `trail.afterCache = char.afterTrailCache;`
public dynamic function afterTrailCache()
if (__reverseTrailProcedure) {
flipX = !flipX;
scale.x *= -1;
__reverseTrailProcedure = false;
}
public function applyXML(xml:Access) { // just for now till i remake the dumb editor
gameOverCharacter = Character.FALLBACK_DEAD_CHARACTER;
cameraOffset.set(0, 0);
globalOffset.set(0, 0);
playerOffsets = false;
flipX = false;
holdTime = 4;
iconColor = null;
animation.destroyAnimations();
animDatas.clear();
__baseFlipped = false;
buildCharacter(xml);
}
// Character editor and loading
public function applyXML(xml:Access) {
this.xml = xml; // modders wassup
public inline function buildCharacter(xml:Access) {
this.xml = xml; // Modders wassup :D
sprite = curCharacter;
if (xml.x.exists("isPlayer")) playerOffsets = (xml.x.get("isPlayer") == "true");
if (xml.x.exists("isGF")) isGF = (xml.x.get("isGF") == "true");
if (xml.x.exists("x")) globalOffset.x = Std.parseFloat(xml.x.get("x"));
if (xml.x.exists("y")) globalOffset.y = Std.parseFloat(xml.x.get("y"));
if (xml.x.exists("gameOverChar")) gameOverCharacter = xml.x.get("gameOverChar");
@@ -413,7 +318,7 @@ class Character extends FunkinSprite implements IBeatReceiver implements IOffset
if (xml.x.exists("icon")) icon = xml.x.get("icon");
if (xml.x.exists("color")) iconColor = FlxColor.fromString(xml.x.get("color"));
if (xml.x.exists("scale")) {
var scale = Std.parseFloat(xml.x.get("scale")).getDefault(1);
var scale:Float = Std.parseFloat(xml.x.get("scale")).getDefault(1);
this.scale.set(scale, scale);
updateHitbox();
}
@@ -423,46 +328,51 @@ class Character extends FunkinSprite implements IBeatReceiver implements IOffset
var hasInterval:Bool = xml.x.exists("interval");
if (hasInterval) beatInterval = Std.parseInt(xml.x.get("interval"));
var tempList = ["isPlayer", "isGF", "x", "y", "gameOverChar", "camx", "camy", "holdTime", "flipX", "icon", "color", "scale", "antialiasing", "sprite", "interval"];
var atts = xml.x.attributes();
for (i in atts)
if (!tempList.contains(i))
extra[i] = xml.x.get(i);
loadSprite(Paths.image('characters/$sprite'));
animation.destroyAnimations();
animDatas.clear();
for (anim in xml.nodes.anim)
{
XMLUtil.addXMLAnimation(this, anim);
}
fixChar(true, !hasInterval);
for (attribute in xml.x.attributes())
if (!characterProperties.contains(attribute))
extra[attribute] = xml.x.get(attribute);
fixChar(__switchAnims, !hasInterval);
dance();
}
public function buildXML(?animsOrder:Array<String>):Xml {
var xml = Xml.createElement("character");
xml.set("isPlayer", playerOffsets == true ? "true" : "false");
xml.set("isGF", isGF == true ? "true" : "false");
xml.set("x", Std.string(globalOffset.x));
xml.set("y", Std.string(globalOffset.y));
xml.set("gameOverChar", gameOverCharacter);
xml.set("camx", Std.string(cameraOffset.x));
xml.set("camy", Std.string(cameraOffset.y));
xml.set("holdTime", Std.string(holdTime));
xml.set("flipX", Std.string(flipX));
xml.set("icon", getIcon());
if (iconColor != null)
xml.set("color", iconColor.toWebString());
xml.set("scale", Std.string(scale.x));
xml.set("antialiasing", antialiasing == true ? "true" : "false");
xml.set("sprite", sprite);
public static var characterProperties:Array<String> = [
"x", "y", "sprite", "scale", "antialiasing",
"flipX", "camx", "camy", "isPlayer", "icon",
"color", "gameOverChar", "holdTime"
];
public static var characterAnimProperties:Array<String> = [
"name", "anim", "x", "y", "fps", "loop", "indices"
];
for (prop=>val in extra) {
xml.set(prop, Std.string(val));
}
public inline function buildXML(?animsOrder:Array<String>):Xml {
var xml:Xml = Xml.createElement("character");
xml.attributeOrder = characterProperties.copy();
if (globalOffset.x != 0) xml.set("x", Std.string(FlxMath.roundDecimal(globalOffset.x, 2)));
if (globalOffset.y != 0) xml.set("y", Std.string(FlxMath.roundDecimal(globalOffset.y, 2)));
if (cameraOffset.x != 0) xml.set("camx", Std.string(FlxMath.roundDecimal(cameraOffset.x, 2)));
if (cameraOffset.y != 0) xml.set("camy", Std.string(FlxMath.roundDecimal(cameraOffset.y, 2)));
if (holdTime != 4) xml.set("holdTime", Std.string(FlxMath.roundDecimal(holdTime, 4)));
if (flipX) xml.set("flipX", Std.string(flipX));
xml.set("icon", getIcon());
if (gameOverCharacter != Character.FALLBACK_DEAD_CHARACTER) xml.set("gameOverChar", gameOverCharacter);
if (iconColor != null) xml.set("color", iconColor.toWebString());
xml.set("sprite", sprite);
if (scale.x != 1) xml.set("scale", Std.string(FlxMath.roundDecimal(scale.x, 4)));
if (!antialiasing) xml.set("antialiasing", antialiasing == true ? "true" : "false");
if (playerOffsets) xml.set("isPlayer", playerOffsets == true ? "true" : "false");
var anims:Array<AnimData> = [];
if (animsOrder != null) {
@@ -471,22 +381,32 @@ class Character extends FunkinSprite implements IBeatReceiver implements IOffset
} else
anims = Lambda.array(animDatas);
for (anim in anims)
{
for (anim in anims) {
var animXml:Xml = Xml.createElement('anim');
animXml.attributeOrder = characterAnimProperties;
animXml.set("name", anim.name);
animXml.set("anim", anim.anim);
animXml.set("loop", Std.string(anim.loop));
animXml.set("fps", Std.string(anim.fps));
animXml.set("fps", Std.string(FlxMath.roundDecimal(anim.fps, 2)));
var offset:FlxPoint = getAnimOffset(anim.name);
animXml.set("x", Std.string(offset.x));
animXml.set("y", Std.string(offset.y));
animXml.set("x", Std.string(FlxMath.roundDecimal(offset.x, 2)));
animXml.set("y", Std.string(FlxMath.roundDecimal(offset.y, 2)));
offset.putWeak();
if (anim.indices.length > 0)
animXml.set("indices", anim.indices.join(","));
xml.addChild(animXml);
}
for (name => val in extra)
if (!xml.attributeOrder.contains(name)) {
xml.attributeOrder.push(name);
xml.set(name, Std.string(val));
}
this.xml = new Access(xml);
return xml;
}
@@ -494,74 +414,72 @@ class Character extends FunkinSprite implements IBeatReceiver implements IOffset
public inline function getIcon()
return (icon != null) ? icon : curCharacter;
public function getAnimOrder() {
public function getAnimOrder()
return [for(a in xml.nodes.anim) if(a.has.name) a.att.name];
}
// Getters / Setters
@:noCompletion private function set_stunned(b:Bool)
{
@:noCompletion private function set_stunned(b:Bool) {
__stunnedTime = 0;
return stunned = b;
}
// Backwards Compat
/**
* Interval at which the character will dance (higher number = slower dance)
*/
// Interval at which the character will dance (higher number = slower dance)
@:noCompletion public var danceInterval(get, set):Int;
@:noCompletion private function set_danceInterval(v:Int)
return beatInterval = v;
@:noCompletion private function get_danceInterval()
return beatInterval;
// Statics
public static function getIconFromCharName(?curCharacter:String) {
if(curCharacter == null) return "face";
var icon = curCharacter;
while(true) {
switch (curCharacter) {
// case 'your-char': // To hardcode characters icons
default:
// load xml
var xmlPath = Paths.xml('characters/$curCharacter');
if (!Assets.exists(xmlPath)) {
curCharacter = "bf";
continue;
}
public static var FALLBACK_CHARACTER:String = "bf";
public static var FALLBACK_DEAD_CHARACTER:String = "bf-dead";
public static function getXMLFromCharName(character:OneOfTwo<String, Character>):Access {
var char:Character = null;
if (character is Character) {
char = cast(character, Character);
character = char.curCharacter;
}
var xml = null;
var plainXML = Assets.getText(xmlPath);
try {
var charXML = Xml.parse(plainXML).firstElement();
if (charXML == null) throw new Exception("Missing \"character\" node in XML.");
xml = new Access(charXML);
} catch(e) {
Logs.error('Error while loading character ${curCharacter}: ${e}');
curCharacter = "bf";
continue;
}
var xml:Access = null;
while (true) {
var xmlPath:String = Paths.xml('characters/$character');
if (!Assets.exists(xmlPath)) {
character = FALLBACK_CHARACTER;
if (char != null)
char.curCharacter = character;
continue;
}
if (xml.x.exists("icon")) icon = xml.x.get("icon");
}
var plainXML:String = Assets.getText(xmlPath);
try {
var charXML:Xml = Xml.parse(plainXML).firstElement();
if (charXML == null) throw new Exception("Missing \"character\" node in XML.");
xml = new Access(charXML);
} catch (e) {
Logs.trace('Error while loading character ${character}: ${e}', ERROR);
character = FALLBACK_CHARACTER;
if (char != null)
char.curCharacter = character;
continue;
}
break;
}
return xml;
}
public static function getIconFromCharName(?character:String) {
if(character == null) return "face";
var icon:String = character;
var xml:Access = getXMLFromCharName(character);
if (xml != null && xml.x.exists("icon")) icon = xml.x.get("icon");
return icon;
}
public static function getList(?mods:Bool = false):Array<String> {
public static function getList(?mods:Bool = false):Array<String>
return [
for (path in Paths.getFolderContent('data/characters/', true, mods ? MODS : BOTH))
if (Path.extension(path) == "xml") Path.withoutDirectory(Path.withoutExtension(path))
if (Path.extension(path) == "xml") CoolUtil.getFilename(path)
];
}
}
typedef CharacterShadowFrame =
{
var anim:String;
var frame:FlxFrame;
}
+28 -12
View File
@@ -210,9 +210,13 @@ class PlayState extends MusicBeatState
*/
public var canAccessDebugMenus:Bool = true;
/**
* Wether or not to show the secret gitaroo pause.
* Whether or not to show the secret gitaroo pause.
*/
public var allowGitaroo:Bool = true;
/**
* Whether or not to bop the icons on beat.
*/
public var doIconBop:Bool = true;
/**
* Whenever cam zooming is enabled, enables on a note hit if not cancelled.
@@ -354,11 +358,19 @@ class PlayState extends MusicBeatState
* Camera zoom at which the game lerps to.
*/
public var defaultCamZoom:Float = 1.05;
/**
* Speed at which the game camera zoom lerps to.
*/
public var camGameZoomLerp:Float = 0.05;
/**
* Camera zoom at which the hud lerps to.
*/
public var defaultHudZoom:Float = 1.0;
/**
* Speed at which the hud camera zoom lerps to.
*/
public var camHUDZoomLerp:Float = 0.05;
/**
* Zoom for the pixel assets.
@@ -1232,12 +1244,13 @@ class PlayState extends MusicBeatState
}
}
iconP1.scale.set(lerp(iconP1.scale.x, 1, 0.33), lerp(iconP1.scale.y, 1, 0.33));
iconP2.scale.set(lerp(iconP2.scale.x, 1, 0.33), lerp(iconP2.scale.y, 1, 0.33));
iconP1.updateHitbox();
iconP2.updateHitbox();
if (doIconBop) {
iconP1.scale.set(lerp(iconP1.scale.x, 1, 0.33), lerp(iconP1.scale.y, 1, 0.33));
iconP2.scale.set(lerp(iconP2.scale.x, 1, 0.33), lerp(iconP2.scale.y, 1, 0.33));
iconP1.updateHitbox();
iconP2.updateHitbox();
}
updateIconPositions();
if (startingSong)
@@ -1286,8 +1299,8 @@ class PlayState extends MusicBeatState
if (camZooming)
{
FlxG.camera.zoom = lerp(FlxG.camera.zoom, defaultCamZoom, 0.05);
camHUD.zoom = lerp(camHUD.zoom, defaultHudZoom, 0.05);
FlxG.camera.zoom = lerp(FlxG.camera.zoom, defaultCamZoom, camGameZoomLerp);
camHUD.zoom = lerp(camHUD.zoom, defaultHudZoom, camHUDZoomLerp);
}
// RESET = Quick Game Over Screen
@@ -1788,11 +1801,14 @@ class PlayState extends MusicBeatState
camHUD.zoom += 0.03 * camZoomingStrength;
}
iconP1.scale.set(1.2, 1.2);
iconP2.scale.set(1.2, 1.2);
if (doIconBop)
{
iconP1.scale.set(1.2, 1.2);
iconP2.scale.set(1.2, 1.2);
iconP1.updateHitbox();
iconP2.updateHitbox();
iconP1.updateHitbox();
iconP2.updateHitbox();
}
scripts.call("beatHit", [curBeat]);
}
+137
View File
@@ -0,0 +1,137 @@
/*
* Copyright (C)2005-2019 Haxe Foundation
*
* 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 haxe.xml;
using StringTools;
/**
This class provides utility methods to convert Xml instances to
String representation.
**/
class Printer {
/**
Convert `Xml` to string representation.
Set `pretty` to `true` to prettify the result.
**/
static public function print(xml:Xml, ?pretty = false) {
var printer = new Printer(pretty);
printer.writeNode(xml, "");
return printer.output.toString();
}
var output:StringBuf;
var pretty:Bool;
function new(pretty) {
output = new StringBuf();
this.pretty = pretty;
}
function writeNode(value:Xml, tabs:String) {
switch (value.nodeType) {
case CData:
write(tabs + "<![CDATA[");
write(value.nodeValue);
write("]]>");
newline();
case Comment:
var commentContent:String = value.nodeValue;
commentContent = ~/[\n\r\t]+/g.replace(commentContent, "");
commentContent = "<!--" + commentContent + "-->";
write(tabs);
write(StringTools.trim(commentContent));
newline();
case Document:
for (child in value) {
writeNode(child, tabs);
}
case Element:
write(tabs + "<");
write(value.nodeName);
var attributes:Array<String> = value.attributeOrder;
if (attributes == null)
attributes = [for (att in value.attributes()) att];
for (attribute in attributes) {
if (!value.exists(attribute) || value.get(attribute).trim() == "") continue;
write(" " + attribute + "=\"");
write(StringTools.htmlEscape(value.get(attribute), true));
write("\"");
}
if (hasChildren(value)) {
write(">");
newline();
for (child in value) {
writeNode(child, pretty ? tabs + "\t" : tabs);
}
write(tabs + "</");
write(value.nodeName);
write(">");
newline();
} else {
write("/>");
newline();
}
case PCData:
var nodeValue:String = value.nodeValue;
if (nodeValue.length != 0) {
write(tabs + StringTools.htmlEscape(nodeValue));
newline();
}
case ProcessingInstruction:
write("<?" + value.nodeValue + "?>");
newline();
case DocType:
write("<!DOCTYPE " + value.nodeValue + ">");
newline();
}
}
inline function write(input:String) {
output.add(input);
}
inline function newline() {
if (pretty) {
output.add("\n");
}
}
function hasChildren(value:Xml):Bool {
for (child in value) {
switch (child.nodeType) {
case Element, PCData:
return true;
case CData, Comment:
if (StringTools.ltrim(child.nodeValue).length != 0) {
return true;
}
case _:
}
}
return false;
}
}
+75 -7
View File
@@ -25,6 +25,9 @@ import js.Browser;
import sys.io.Process;
#end
/**
Access operating system level settings and operations.
**/
#if !lime_debug
@:fileXml('tags="haxe,release"')
@:noDebug
@@ -44,21 +47,68 @@ extern "C" {
#end
class System
{
/**
Determines if the screen saver is allowed to start or not.
**/
public static var allowScreenTimeout(get, set):Bool;
/**
The path to the directory where the application is installed, along with
its supporting files. In many cases, this directory is read-only, and
attempts to write to files, create new files, or delete files in this
directory are likely fail.
**/
public static var applicationDirectory(get, never):String;
/**
The application's dedicated storage directory, which unique to each
application and user. Useful for storing settings on a user-specific
and application-specific basis.
This directory may or may not be removed when the application is
uninstalled, and it depends on the platform and installer technology
that is used.
**/
public static var applicationStorageDirectory(get, never):String;
/**
The path to the directory containing the user's desktop.
**/
public static var desktopDirectory(get, never):String;
public static var deviceModel(get, never):String;
public static var deviceVendor(get, never):String;
public static var disableCFFI:Bool;
/**
The path to the directory containing the user's documents.
**/
public static var documentsDirectory(get, never):String;
/**
The platform's default endianness for bytes.
**/
public static var endianness(get, never):Endian;
/**
The path to the directory where fonts are installed.
**/
public static var fontsDirectory(get, never):String;
/**
The number of available video displays.
**/
public static var numDisplays(get, never):Int;
public static var platformLabel(get, never):String;
public static var platformName(get, never):String;
public static var platformVersion(get, never):String;
/**
The path to the user's home directory.
**/
public static var userDirectory(get, never):String;
@:noCompletion private static var __applicationDirectory:String;
@:noCompletion private static var __applicationEntryPoint:Map<String, Function>;
@:noCompletion private static var __applicationStorageDirectory:String;
@@ -84,7 +134,7 @@ class System
{
var htmlElement:Element = null;
if (Std.is(element, String))
if ((element is String))
{
htmlElement = cast Browser.document.getElementById(element);
}
@@ -115,7 +165,7 @@ class System
if (config == null) config = {};
if (Reflect.hasField(config, "background") && Std.is(config.background, String))
if (Reflect.hasField(config, "background") && (config.background is String))
{
var background = StringTools.replace(Std.string(config.background), "#", "");
@@ -139,6 +189,10 @@ class System
#end
#if (!lime_doc_gen || sys)
/**
Attempts to exit the application. Dispatches `onExit`, and will not
exit if the event is canceled.
**/
public static function exit(code:Int):Void
{
var currentApp = Application.current;
@@ -167,6 +221,9 @@ class System
}
#end
/**
Returns information about the video display with the specified ID.
**/
public static function getDisplay(id:Int):Display
{
#if (lime_cffi && !macro)
@@ -265,11 +322,12 @@ class System
return null;
}
/**
The number of milliseconds since the application was initialized.
**/
public static function getTimer():Int
{
#if (kha && !macro)
return Std.int(kha.System.time * 1000);
#elseif flash
#if flash
return flash.Lib.getTimer();
#elseif ((js && !nodejs) || electron)
return Std.int(Browser.window.performance.now());
@@ -295,6 +353,11 @@ class System
}
#end
/**
Opens a file with the suste, default application.
In a web browser, opens a URL with target `_blank`.
**/
public static function openFile(path:String):Void
{
if (path != null)
@@ -304,7 +367,7 @@ class System
#elseif mac
Sys.command("/usr/bin/open", [path]);
#elseif linux
Sys.command("/usr/bin/xdg-open", [path, "&"]);
Sys.command("/usr/bin/xdg-open", [path]);
#elseif (js && html5)
Browser.window.open(path, "_blank");
#elseif flash
@@ -318,6 +381,9 @@ class System
}
}
/**
Opens a URL with the specified target web browser window.
**/
public static function openURL(url:String, target:String = "_blank"):Void
{
if (url != null)
@@ -430,6 +496,8 @@ class System
#if sys
private static function __parseArguments(attributes:WindowAttributes):Void
{
// TODO: Handle default arguments, like --window-fps=60
var arguments = Sys.args();
var stripQuotes = ~/^['"](.*)['"]$/;
var equals, argValue, parameters = null;
@@ -825,7 +893,7 @@ class System
}
}
enum abstract SystemDirectory(Int) from Int to Int from UInt to UInt
#if (haxe_ver >= 4.0) enum #else @:enum #end abstract SystemDirectory(Int) from Int to Int from UInt to UInt
{
var APPLICATION = 0;
var APPLICATION_STORAGE = 1;
+30 -20
View File
@@ -12,17 +12,17 @@ import funkin.backend.system.Logs as FunkinLogs;
class Log
{
public static var level:LogLevel;
public static var throwErrors:Bool = false;
public static function debug(message:Dynamic, ?info:PosInfos):Void
{
if (level >= LogLevel.DEBUG)
{
#if js
untyped __js__("console").debug("[" + info.className + "] " + message);
untyped #if haxe4 js.Syntax.code #else __js__ #end ("console").debug("[" + info.className + "] " + message);
#else
println("[" + info.className + "] " + Std.string(message));
#end
}
}
@@ -30,23 +30,32 @@ class Log
{
if (level >= LogLevel.ERROR)
{
var message = '[${info.className}] $message';
#if !macro
FunkinLogs.trace(message, ERROR, RED);
#else
trace(message);
#end
if (throwErrors)
{
#if webassembly
println(message);
#end
throw message;
}
else
{
#if !macro
FunkinLogs.trace('[${info.className}] $message', ERROR, RED);
#else
println("[" + info.className + "] ERROR: " + message);
#end
}
}
}
public static function info(message:Dynamic, ?info:PosInfos):Void
{
if (level >= LogLevel.INFO) {
if (level >= LogLevel.INFO)
{
#if !macro
FunkinLogs.trace('[${info.className}] $message', INFO, RED);
#else
trace('[${info.className}] $message');
println("[" + info.className + "] " + Std.string(message));
#end
}
}
@@ -58,7 +67,7 @@ class Log
#elseif flash
untyped __global__["trace"](Std.string(message));
#elseif js
untyped __js__("console").log(message);
untyped #if haxe4 js.Syntax.code #else __js__ #end ("console").log(message);
#else
trace(message);
#end
@@ -71,7 +80,7 @@ class Log
#elseif flash
untyped __global__["trace"](Std.string(message));
#elseif js
untyped __js__("console").log(message);
untyped #if haxe4 js.Syntax.code #else __js__ #end ("console").log(message);
#else
trace(Std.string(message));
#end
@@ -79,11 +88,12 @@ class Log
public static function verbose(message:Dynamic, ?info:PosInfos):Void
{
if (level >= LogLevel.VERBOSE) {
if (level >= LogLevel.VERBOSE)
{
#if !macro
FunkinLogs.trace('[${info.className}] $message', VERBOSE);
#else
trace('[${info.className}] $message');
println("[" + info.className + "] " + message);
#end
}
}
@@ -95,7 +105,7 @@ class Log
#if !macro
FunkinLogs.trace('[${info.className}] $message', WARNING, YELLOW);
#else
trace('[${info.className}] $message');
println("[" + info.className + "] WARNING: " + Std.string(message));
#end
}
}
@@ -125,13 +135,13 @@ class Log
#end
#if js
if (untyped __js__("typeof console") == "undefined")
if (untyped #if haxe4 js.Syntax.code #else __js__ #end ("typeof console") == "undefined")
{
untyped __js__("console = {}");
untyped #if haxe4 js.Syntax.code #else __js__ #end ("console = {}");
}
if (untyped __js__("console").log == null)
if (untyped #if haxe4 js.Syntax.code #else __js__ #end ("console").log == null)
{
untyped __js__("console").log = function() {};
untyped #if haxe4 js.Syntax.code #else __js__ #end ("console").log = function() {};
}
#end
}