1
0
Fork 0
mirror of https://github.com/ninjamuffin99/Funkin.git synced 2025-11-26 06:09:02 +00:00

Merge branch 'rewrite/master' into input-offsets

This commit is contained in:
EliteMasterEric 2024-03-28 20:23:31 -04:00
commit 35f99b49a4
57 changed files with 1865 additions and 308 deletions

View file

@ -13,8 +13,9 @@ jobs:
apt update apt update
apt install -y sudo git curl unzip apt install -y sudo git curl unzip
- name: Fix git config on posix runner - name: Fix git config on posix runner
# this can't be {{ github.workspace }} because that's not docker-aware
run: | run: |
git config --global --add safe.directory ${{ github.workspace }} git config --global --add safe.directory $GITHUB_WORKSPACE
- name: Get checkout token - name: Get checkout token
uses: actions/create-github-app-token@v1 uses: actions/create-github-app-token@v1
id: app_token id: app_token
@ -90,8 +91,9 @@ jobs:
runs-on: [self-hosted, macos] runs-on: [self-hosted, macos]
steps: steps:
- name: Fix git config on posix runner - name: Fix git config on posix runner
# this can't be {{ github.workspace }} because that's not docker-aware
run: | run: |
git config --global --add safe.directory ${{ github.workspace }} git config --global --add safe.directory $GITHUB_WORKSPACE
- name: Get checkout token - name: Get checkout token
uses: actions/create-github-app-token@v1 uses: actions/create-github-app-token@v1
id: app_token id: app_token

15
.vscode/settings.json vendored
View file

@ -204,6 +204,21 @@
"label": "HTML5 / Debug (Watch)", "label": "HTML5 / Debug (Watch)",
"target": "html5", "target": "html5",
"args": ["-debug", "-watch", "-DFORCE_DEBUG_VERSION"] "args": ["-debug", "-watch", "-DFORCE_DEBUG_VERSION"]
},
{
"label": "macOS / Debug",
"target": "mac",
"args": ["-debug", "-DFORCE_DEBUG_VERSION"]
},
{
"label": "macOS / Release",
"target": "mac",
"args": ["-release"]
},
{
"label": "macOS / Release (GitHub Actions)",
"target": "mac",
"args": ["-release", "-DGITHUB_BUILD"]
} }
], ],
"cmake.configureOnOpen": false, "cmake.configureOnOpen": false,

View file

@ -4,12 +4,19 @@
<app title="Friday Night Funkin'" file="Funkin" packageName="com.funkin.fnf" package="com.funkin.fnf" main="Main" version="0.3.0" company="ninjamuffin99" /> <app title="Friday Night Funkin'" file="Funkin" packageName="com.funkin.fnf" package="com.funkin.fnf" main="Main" version="0.3.0" company="ninjamuffin99" />
<!--Switch Export with Unique ApplicationID and Icon--> <!--Switch Export with Unique ApplicationID and Icon-->
<set name="APP_ID" value="0x0100f6c013bbc000" /> <set name="APP_ID" value="0x0100f6c013bbc000" />
<app preloader="funkin.Preloader" />
<!--
Define the OpenFL sprite which displays the preloader.
You can't replace the preloader's logic here, sadly, but you can extend it.
Basic preloading logic is done by `openfl.display.Preloader`.
-->
<app preloader="funkin.ui.transition.preload.FunkinPreloader" />
<!--Minimum without FLX_NO_GAMEPAD: 11.8, without FLX_NO_NATIVE_CURSOR: 11.2--> <!--Minimum without FLX_NO_GAMEPAD: 11.8, without FLX_NO_NATIVE_CURSOR: 11.2-->
<set name="SWF_VERSION" value="11.8" /> <set name="SWF_VERSION" value="11.8" />
<!-- ____________________________ Window Settings ___________________________ --> <!-- ____________________________ Window Settings ___________________________ -->
<!--These window settings apply to all targets--> <!--These window settings apply to all targets-->
<window width="1280" height="720" fps="" background="#000000" hardware="true" vsync="false" /> <window width="1280" height="720" fps="60" background="#000000" hardware="true" vsync="false" />
<!--HTML5-specific--> <!--HTML5-specific-->
<window if="html5" resizable="true" /> <window if="html5" resizable="true" />
<!--Desktop-specific--> <!--Desktop-specific-->
@ -95,6 +102,7 @@
<!-- If compiled via github actions, show debug version number. --> <!-- If compiled via github actions, show debug version number. -->
<define name="FORCE_DEBUG_VERSION" if="GITHUB_BUILD" /> <define name="FORCE_DEBUG_VERSION" if="GITHUB_BUILD" />
<define name="NO_REDIRECT_ASSETS_FOLDER" if="GITHUB_BUILD" /> <define name="NO_REDIRECT_ASSETS_FOLDER" if="GITHUB_BUILD" />
<define name="TOUCH_HERE_TO_PLAY" if="web" />
<!-- _______________________________ Libraries ______________________________ --> <!-- _______________________________ Libraries ______________________________ -->
<haxelib name="lime" /> <!-- Game engine backend --> <haxelib name="lime" /> <!-- Game engine backend -->

2
art

@ -1 +1 @@
Subproject commit 03e7c2a2353b184e45955c96d763b7cdf1acbc34 Subproject commit 00463685fa570f0c853d08e250b46ef80f30bc48

2
assets

@ -1 +1 @@
Subproject commit 52674391511577300cdb8c08df293ea72099aa82 Subproject commit 485243fdd44acbc4db6a97ec7bf10a8b18350be9

View file

@ -38,7 +38,15 @@ class Conductor
* You can also do stuff like store a reference to the Conductor and pass it around or temporarily replace it, * You can also do stuff like store a reference to the Conductor and pass it around or temporarily replace it,
* or have a second Conductor running at the same time, or other weird stuff like that if you need to. * or have a second Conductor running at the same time, or other weird stuff like that if you need to.
*/ */
public static var instance:Conductor = new Conductor(); public static var instance(get, never):Conductor;
static var _instance:Null<Conductor> = null;
static function get_instance():Conductor
{
if (_instance == null) _instance = new Conductor();
return _instance;
}
/** /**
* Signal fired when the current Conductor instance advances to a new measure. * Signal fired when the current Conductor instance advances to a new measure.
@ -597,6 +605,6 @@ class Conductor
*/ */
public static function reset():Void public static function reset():Void
{ {
Conductor.instance = new Conductor(); _instance = new Conductor();
} }
} }

View file

@ -1,65 +0,0 @@
package funkin;
import flash.Lib;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.Sprite;
import flixel.system.FlxBasePreloader;
import openfl.display.Sprite;
import funkin.util.CLIUtil;
import openfl.text.TextField;
import openfl.text.TextFormat;
import flixel.system.FlxAssets;
@:bitmap('art/preloaderArt.png')
class LogoImage extends BitmapData {}
class Preloader extends FlxBasePreloader
{
public function new(MinDisplayTime:Float = 0, ?AllowedURLs:Array<String>)
{
super(MinDisplayTime, AllowedURLs);
CLIUtil.resetWorkingDir(); // Bug fix for drag-and-drop.
}
var logo:Sprite;
var _text:TextField;
override function create():Void
{
this._width = Lib.current.stage.stageWidth;
this._height = Lib.current.stage.stageHeight;
_text = new TextField();
_text.width = 500;
_text.text = "Loading FNF";
_text.defaultTextFormat = new TextFormat(FlxAssets.FONT_DEFAULT, 16, 0xFFFFFFFF);
_text.embedFonts = true;
_text.selectable = false;
_text.multiline = false;
_text.wordWrap = false;
_text.autoSize = LEFT;
_text.x = 2;
_text.y = 2;
addChild(_text);
var ratio:Float = this._width / 2560; // This allows us to scale assets depending on the size of the screen.
logo = new Sprite();
logo.addChild(new Bitmap(new LogoImage(0, 0))); // Sets the graphic of the sprite to a Bitmap object, which uses our embedded BitmapData class.
logo.scaleX = logo.scaleY = ratio;
logo.x = ((this._width) / 2) - ((logo.width) / 2);
logo.y = (this._height / 2) - ((logo.height) / 2);
// addChild(logo); // Adds the graphic to the NMEPreloader's buffer.
super.create();
}
override function update(Percent:Float):Void
{
_text.text = "FNF: " + Math.round(Percent * 100) + "%";
super.update(Percent);
}
}

View file

@ -1,16 +1,18 @@
package funkin.audio; package funkin.audio;
import flixel.sound.FlxSound;
import flixel.group.FlxGroup.FlxTypedGroup; import flixel.group.FlxGroup.FlxTypedGroup;
import flixel.util.FlxSignal.FlxTypedSignal; import flixel.math.FlxMath;
import flixel.sound.FlxSound;
import flixel.system.FlxAssets.FlxSoundAsset; import flixel.system.FlxAssets.FlxSoundAsset;
import funkin.util.tools.ICloneable; import flixel.tweens.FlxTween;
import funkin.data.song.SongData.SongMusicData; import flixel.util.FlxSignal.FlxTypedSignal;
import funkin.data.song.SongRegistry;
import funkin.audio.waveform.WaveformData; import funkin.audio.waveform.WaveformData;
import funkin.audio.waveform.WaveformDataParser; import funkin.audio.waveform.WaveformDataParser;
import flixel.math.FlxMath; import funkin.data.song.SongData.SongMusicData;
import funkin.data.song.SongRegistry;
import funkin.util.tools.ICloneable;
import openfl.Assets; import openfl.Assets;
import openfl.media.SoundMixer;
#if (openfl >= "8.0.0") #if (openfl >= "8.0.0")
import openfl.utils.AssetType; import openfl.utils.AssetType;
#end #end
@ -18,6 +20,7 @@ import openfl.utils.AssetType;
/** /**
* A FlxSound which adds additional functionality: * A FlxSound which adds additional functionality:
* - Delayed playback via negative song position. * - Delayed playback via negative song position.
* - Easy functions for immediate playback and recycling.
*/ */
@:nullSafety @:nullSafety
class FunkinSound extends FlxSound implements ICloneable<FunkinSound> class FunkinSound extends FlxSound implements ICloneable<FunkinSound>
@ -48,6 +51,11 @@ class FunkinSound extends FlxSound implements ICloneable<FunkinSound>
*/ */
static var pool(default, null):FlxTypedGroup<FunkinSound> = new FlxTypedGroup<FunkinSound>(); static var pool(default, null):FlxTypedGroup<FunkinSound> = new FlxTypedGroup<FunkinSound>();
/**
* Calculate the current time of the sound.
* NOTE: You need to `add()` the sound to the scene for `update()` to increment the time.
*/
//
public var muted(default, set):Bool = false; public var muted(default, set):Bool = false;
function set_muted(value:Bool):Bool function set_muted(value:Bool):Bool
@ -286,15 +294,28 @@ class FunkinSound extends FlxSound implements ICloneable<FunkinSound>
* Creates a new `FunkinSound` object and loads it as the current music track. * Creates a new `FunkinSound` object and loads it as the current music track.
* *
* @param key The key of the music you want to play. Music should be at `music/<key>/<key>.ogg`. * @param key The key of the music you want to play. Music should be at `music/<key>/<key>.ogg`.
* @param overrideExisting Whether to override music if it is already playing. * @param params A set of additional optional parameters.
* @param mapTimeChanges Whether to check for `SongMusicData` to update the Conductor with.
* Data should be at `music/<key>/<key>-metadata.json`. * Data should be at `music/<key>/<key>-metadata.json`.
* @return Whether the music was started. `false` if music was already playing or could not be started
*/ */
public static function playMusic(key:String, overrideExisting:Bool = false, mapTimeChanges:Bool = true):Void public static function playMusic(key:String, params:FunkinSoundPlayMusicParams):Bool
{ {
if (!overrideExisting && FlxG.sound.music?.playing) return; if (!(params.overrideExisting ?? false) && (FlxG.sound.music?.exists ?? false) && FlxG.sound.music.playing) return false;
if (mapTimeChanges) if (!(params.restartTrack ?? false) && FlxG.sound.music?.playing)
{
if (FlxG.sound.music != null && Std.isOfType(FlxG.sound.music, FunkinSound))
{
var existingSound:FunkinSound = cast FlxG.sound.music;
// Stop here if we would play a matching music track.
if (existingSound._label == Paths.music('$key/$key'))
{
return false;
}
}
}
if (params?.mapTimeChanges ?? true)
{ {
var songMusicData:Null<SongMusicData> = SongRegistry.instance.parseMusicData(key); var songMusicData:Null<SongMusicData> = SongRegistry.instance.parseMusicData(key);
// Will fall back and return null if the metadata doesn't exist or can't be parsed. // Will fall back and return null if the metadata doesn't exist or can't be parsed.
@ -308,10 +329,27 @@ class FunkinSound extends FlxSound implements ICloneable<FunkinSound>
} }
} }
FlxG.sound.music = FunkinSound.load(Paths.music('$key/$key')); if (FlxG.sound.music != null)
{
FlxG.sound.music.fadeTween?.cancel();
FlxG.sound.music.stop();
FlxG.sound.music.kill();
}
var music = FunkinSound.load(Paths.music('$key/$key'), params?.startingVolume ?? 1.0, params.loop ?? true, false, true);
if (music != null)
{
FlxG.sound.music = music;
// Prevent repeat update() and onFocus() calls. // Prevent repeat update() and onFocus() calls.
FlxG.sound.list.remove(FlxG.sound.music); FlxG.sound.list.remove(FlxG.sound.music);
return true;
}
else
{
return false;
}
} }
/** /**
@ -326,11 +364,18 @@ class FunkinSound extends FlxSound implements ICloneable<FunkinSound>
* @param autoPlay Whether to play the sound immediately or wait for a `play()` call. * @param autoPlay Whether to play the sound immediately or wait for a `play()` call.
* @param onComplete Called when the sound finished playing. * @param onComplete Called when the sound finished playing.
* @param onLoad Called when the sound finished loading. Called immediately for succesfully loaded embedded sounds. * @param onLoad Called when the sound finished loading. Called immediately for succesfully loaded embedded sounds.
* @return A `FunkinSound` object. * @return A `FunkinSound` object, or `null` if the sound could not be loaded.
*/ */
public static function load(embeddedSound:FlxSoundAsset, volume:Float = 1.0, looped:Bool = false, autoDestroy:Bool = false, autoPlay:Bool = false, public static function load(embeddedSound:FlxSoundAsset, volume:Float = 1.0, looped:Bool = false, autoDestroy:Bool = false, autoPlay:Bool = false,
?onComplete:Void->Void, ?onLoad:Void->Void):FunkinSound ?onComplete:Void->Void, ?onLoad:Void->Void):Null<FunkinSound>
{ {
@:privateAccess
if (SoundMixer.__soundChannels.length >= SoundMixer.MAX_ACTIVE_CHANNELS)
{
FlxG.log.error('FunkinSound could not play sound, channels exhausted! Found ${SoundMixer.__soundChannels.length} active sound channels.');
return null;
}
var sound:FunkinSound = pool.recycle(construct); var sound:FunkinSound = pool.recycle(construct);
// Load the sound. // Load the sound.
@ -341,6 +386,10 @@ class FunkinSound extends FlxSound implements ICloneable<FunkinSound>
{ {
sound._label = embeddedSound; sound._label = embeddedSound;
} }
else
{
sound._label = 'unknown';
}
sound.volume = volume; sound.volume = volume;
sound.group = FlxG.sound.defaultSoundGroup; sound.group = FlxG.sound.defaultSoundGroup;
@ -350,11 +399,41 @@ class FunkinSound extends FlxSound implements ICloneable<FunkinSound>
// Call onLoad() because the sound already loaded // Call onLoad() because the sound already loaded
if (onLoad != null && sound._sound != null) onLoad(); if (onLoad != null && sound._sound != null) onLoad();
FlxG.sound.list.remove(FlxG.sound.music);
return sound; return sound;
} }
public override function destroy():Void
{
// trace('[FunkinSound] Destroying sound "${this._label}"');
super.destroy();
FlxTween.cancelTweensOf(this);
this._label = 'unknown';
}
/**
* Play a sound effect once, then destroy it.
* @param key
* @param volume
* @return static function construct():FunkinSound
*/
public static function playOnce(key:String, volume:Float = 1.0, ?onComplete:Void->Void, ?onLoad:Void->Void):Void
{
var result = FunkinSound.load(key, volume, false, true, true, onComplete, onLoad);
}
/**
* Stop all sounds in the pool and allow them to be recycled.
*/
public static function stopAllAudio(musicToo:Bool = false):Void
{
for (sound in pool)
{
if (sound == null) continue;
if (!musicToo && sound == FlxG.sound.music) continue;
sound.destroy();
}
}
static function construct():FunkinSound static function construct():FunkinSound
{ {
var sound:FunkinSound = new FunkinSound(); var sound:FunkinSound = new FunkinSound();
@ -365,3 +444,39 @@ class FunkinSound extends FlxSound implements ICloneable<FunkinSound>
return sound; return sound;
} }
} }
/**
* Additional parameters for `FunkinSound.playMusic()`
*/
typedef FunkinSoundPlayMusicParams =
{
/**
* The volume you want the music to start at.
* @default `1.0`
*/
var ?startingVolume:Float;
/**
* Whether to override music if a different track is already playing.
* @default `false`
*/
var ?overrideExisting:Bool;
/**
* Whether to override music if the same track is already playing.
* @default `false`
*/
var ?restartTrack:Bool;
/**
* Whether the music should loop or play once.
* @default `true`
*/
var ?loop:Bool;
/**
* Whether to check for `SongMusicData` to update the Conductor with.
* @default `true`
*/
var ?mapTimeChanges:Bool;
}

View file

@ -1,7 +1,6 @@
package funkin.audio; package funkin.audio;
import flixel.group.FlxGroup.FlxTypedGroup; import flixel.group.FlxGroup.FlxTypedGroup;
import flixel.sound.FlxSound;
import funkin.audio.FunkinSound; import funkin.audio.FunkinSound;
import flixel.tweens.FlxTween; import flixel.tweens.FlxTween;
@ -152,11 +151,14 @@ class SoundGroup extends FlxTypedGroup<FunkinSound>
* Stop all the sounds in the group. * Stop all the sounds in the group.
*/ */
public function stop() public function stop()
{
if (members != null)
{ {
forEachAlive(function(sound:FunkinSound) { forEachAlive(function(sound:FunkinSound) {
sound.stop(); sound.stop();
}); });
} }
}
public override function destroy() public override function destroy()
{ {

View file

@ -160,7 +160,9 @@ class VoicesGroup extends SoundGroup
public override function destroy():Void public override function destroy():Void
{ {
playerVoices.destroy(); playerVoices.destroy();
playerVoices = null;
opponentVoices.destroy(); opponentVoices.destroy();
opponentVoices = null;
super.destroy(); super.destroy();
} }
} }

View file

@ -55,6 +55,13 @@ abstract class BaseRegistry<T:(IRegistryEntry<J> & Constructible<EntryConstructo
this.entries = new Map<String, T>(); this.entries = new Map<String, T>();
this.scriptedEntryIds = []; this.scriptedEntryIds = [];
// Lazy initialization of singletons should let this get called,
// but we have this check just in case.
if (FlxG.game != null)
{
FlxG.console.registerObject('registry$registryId', this);
}
} }
/** /**

View file

@ -15,7 +15,14 @@ class ConversationRegistry extends BaseRegistry<Conversation, ConversationData>
public static final CONVERSATION_DATA_VERSION_RULE:thx.semver.VersionRule = "1.0.x"; public static final CONVERSATION_DATA_VERSION_RULE:thx.semver.VersionRule = "1.0.x";
public static final instance:ConversationRegistry = new ConversationRegistry(); public static var instance(get, never):ConversationRegistry;
static var _instance:Null<ConversationRegistry> = null;
static function get_instance():ConversationRegistry
{
if (_instance == null) _instance = new ConversationRegistry();
return _instance;
}
public function new() public function new()
{ {

View file

@ -15,7 +15,14 @@ class DialogueBoxRegistry extends BaseRegistry<DialogueBox, DialogueBoxData>
public static final DIALOGUEBOX_DATA_VERSION_RULE:thx.semver.VersionRule = "1.1.x"; public static final DIALOGUEBOX_DATA_VERSION_RULE:thx.semver.VersionRule = "1.1.x";
public static final instance:DialogueBoxRegistry = new DialogueBoxRegistry(); public static var instance(get, never):DialogueBoxRegistry;
static var _instance:Null<DialogueBoxRegistry> = null;
static function get_instance():DialogueBoxRegistry
{
if (_instance == null) _instance = new DialogueBoxRegistry();
return _instance;
}
public function new() public function new()
{ {

View file

@ -15,7 +15,14 @@ class SpeakerRegistry extends BaseRegistry<Speaker, SpeakerData>
public static final SPEAKER_DATA_VERSION_RULE:thx.semver.VersionRule = "1.0.x"; public static final SPEAKER_DATA_VERSION_RULE:thx.semver.VersionRule = "1.0.x";
public static final instance:SpeakerRegistry = new SpeakerRegistry(); public static var instance(get, never):SpeakerRegistry;
static var _instance:Null<SpeakerRegistry> = null;
static function get_instance():SpeakerRegistry
{
if (_instance == null) _instance = new SpeakerRegistry();
return _instance;
}
public function new() public function new()
{ {

View file

@ -15,7 +15,14 @@ class NoteStyleRegistry extends BaseRegistry<NoteStyle, NoteStyleData>
public static final NOTE_STYLE_DATA_VERSION_RULE:thx.semver.VersionRule = "1.0.x"; public static final NOTE_STYLE_DATA_VERSION_RULE:thx.semver.VersionRule = "1.0.x";
public static final instance:NoteStyleRegistry = new NoteStyleRegistry(); public static var instance(get, never):NoteStyleRegistry;
static var _instance:Null<NoteStyleRegistry> = null;
static function get_instance():NoteStyleRegistry
{
if (_instance == null) _instance = new NoteStyleRegistry();
return _instance;
}
public function new() public function new()
{ {

View file

@ -40,10 +40,17 @@ class SongRegistry extends BaseRegistry<Song, SongMetadata>
} }
/** /**
* TODO: What if there was a Singleton macro which created static functions * TODO: What if there was a Singleton macro which automatically created the property for us?
* that redirected to the instance?
*/ */
public static final instance:SongRegistry = new SongRegistry(); public static var instance(get, never):SongRegistry;
static var _instance:Null<SongRegistry> = null;
static function get_instance():SongRegistry
{
if (_instance == null) _instance = new SongRegistry();
return _instance;
}
public function new() public function new()
{ {
@ -424,7 +431,11 @@ class SongRegistry extends BaseRegistry<Song, SongMetadata>
{ {
variation = variation == null ? Constants.DEFAULT_VARIATION : variation; variation = variation == null ? Constants.DEFAULT_VARIATION : variation;
var entryFilePath:String = Paths.json('$dataFilePath/$id/$id-metadata${variation == Constants.DEFAULT_VARIATION ? '' : '-$variation'}'); var entryFilePath:String = Paths.json('$dataFilePath/$id/$id-metadata${variation == Constants.DEFAULT_VARIATION ? '' : '-$variation'}');
if (!openfl.Assets.exists(entryFilePath)) return null; if (!openfl.Assets.exists(entryFilePath))
{
trace(' [WARN] Could not locate file $entryFilePath');
return null;
}
var rawJson:Null<String> = openfl.Assets.getText(entryFilePath); var rawJson:Null<String> = openfl.Assets.getText(entryFilePath);
if (rawJson == null) return null; if (rawJson == null) return null;
rawJson = rawJson.trim(); rawJson = rawJson.trim();

View file

@ -15,7 +15,14 @@ class StageRegistry extends BaseRegistry<Stage, StageData>
public static final STAGE_DATA_VERSION_RULE:thx.semver.VersionRule = "1.0.x"; public static final STAGE_DATA_VERSION_RULE:thx.semver.VersionRule = "1.0.x";
public static final instance:StageRegistry = new StageRegistry(); public static var instance(get, never):StageRegistry;
static var _instance:Null<StageRegistry> = null;
static function get_instance():StageRegistry
{
if (_instance == null) _instance = new StageRegistry();
return _instance;
}
public function new() public function new()
{ {

View file

@ -15,7 +15,14 @@ class LevelRegistry extends BaseRegistry<Level, LevelData>
public static final LEVEL_DATA_VERSION_RULE:thx.semver.VersionRule = "1.0.x"; public static final LEVEL_DATA_VERSION_RULE:thx.semver.VersionRule = "1.0.x";
public static final instance:LevelRegistry = new LevelRegistry(); public static var instance(get, never):LevelRegistry;
static var _instance:Null<LevelRegistry> = null;
static function get_instance():LevelRegistry
{
if (_instance == null) _instance = new LevelRegistry();
return _instance;
}
public function new() public function new()
{ {

View file

@ -79,6 +79,23 @@ class FlxAtlasSprite extends FlxAnimate
return this.currentAnimation; return this.currentAnimation;
} }
/**
* `anim.finished` always returns false on looping animations,
* but this function will return true if we are on the last frame of the looping animation.
*/
public function isLoopFinished():Bool
{
if (this.anim == null) return false;
if (!this.anim.isPlaying) return false;
// Reverse animation finished.
if (this.anim.reversed && this.anim.curFrame == 0) return true;
// Forward animation finished.
if (!this.anim.reversed && this.anim.curFrame >= (this.anim.length - 1)) return true;
return false;
}
/** /**
* Plays an animation. * Plays an animation.
* @param id A string ID of the animation to play. * @param id A string ID of the animation to play.

View file

@ -209,7 +209,6 @@ class PolymodHandler
// Add import aliases for certain classes. // Add import aliases for certain classes.
// NOTE: Scripted classes are automatically aliased to their parent class. // NOTE: Scripted classes are automatically aliased to their parent class.
Polymod.addImportAlias('flixel.math.FlxPoint', flixel.math.FlxPoint.FlxBasePoint); Polymod.addImportAlias('flixel.math.FlxPoint', flixel.math.FlxPoint.FlxBasePoint);
Polymod.addImportAlias('flixel.system.FlxSound', flixel.sound.FlxSound);
// Add blacklisting for prohibited classes and packages. // Add blacklisting for prohibited classes and packages.
// `polymod.*` // `polymod.*`

View file

@ -9,6 +9,7 @@ import funkin.modding.module.ModuleHandler;
import funkin.modding.events.ScriptEvent; import funkin.modding.events.ScriptEvent;
import funkin.modding.events.ScriptEvent.CountdownScriptEvent; import funkin.modding.events.ScriptEvent.CountdownScriptEvent;
import flixel.util.FlxTimer; import flixel.util.FlxTimer;
import funkin.audio.FunkinSound;
class Countdown class Countdown
{ {
@ -282,7 +283,7 @@ class Countdown
if (soundPath == null) return; if (soundPath == null) return;
FlxG.sound.play(Paths.sound(soundPath), Constants.COUNTDOWN_VOLUME); FunkinSound.playOnce(Paths.sound(soundPath), Constants.COUNTDOWN_VOLUME);
} }
public static function decrement(step:CountdownStep):CountdownStep public static function decrement(step:CountdownStep):CountdownStep

View file

@ -3,7 +3,6 @@ package funkin.play;
import flixel.FlxG; import flixel.FlxG;
import flixel.FlxObject; import flixel.FlxObject;
import flixel.FlxSprite; import flixel.FlxSprite;
import flixel.sound.FlxSound;
import funkin.audio.FunkinSound; import funkin.audio.FunkinSound;
import flixel.util.FlxColor; import flixel.util.FlxColor;
import flixel.util.FlxTimer; import flixel.util.FlxTimer;
@ -418,7 +417,7 @@ class GameOverSubState extends MusicBeatSubState
blueballed = true; blueballed = true;
if (Assets.exists(Paths.sound('gameplay/gameover/fnf_loss_sfx' + blueBallSuffix))) if (Assets.exists(Paths.sound('gameplay/gameover/fnf_loss_sfx' + blueBallSuffix)))
{ {
FlxG.sound.play(Paths.sound('gameplay/gameover/fnf_loss_sfx' + blueBallSuffix)); FunkinSound.playOnce(Paths.sound('gameplay/gameover/fnf_loss_sfx' + blueBallSuffix));
} }
else else
{ {
@ -438,7 +437,7 @@ class GameOverSubState extends MusicBeatSubState
if (!Preferences.naughtyness) randomCensor = [1, 3, 8, 13, 17, 21]; if (!Preferences.naughtyness) randomCensor = [1, 3, 8, 13, 17, 21];
FlxG.sound.play(Paths.sound('jeffGameover/jeffGameover-' + FlxG.random.int(1, 25, randomCensor)), 1, false, null, true, function() { FunkinSound.playOnce(Paths.sound('jeffGameover/jeffGameover-' + FlxG.random.int(1, 25, randomCensor)), function() {
// Once the quote ends, fade in the game over music. // Once the quote ends, fade in the game over music.
if (!isEnding && gameOverMusic != null) if (!isEnding && gameOverMusic != null)
{ {

View file

@ -26,7 +26,11 @@ class GitarooPause extends MusicBeatState
override function create():Void override function create():Void
{ {
if (FlxG.sound.music != null) FlxG.sound.music.stop(); if (FlxG.sound.music != null)
{
FlxG.sound.music.destroy();
FlxG.sound.music = null;
}
var bg:FunkinSprite = FunkinSprite.create('pauseAlt/pauseBG'); var bg:FunkinSprite = FunkinSprite.create('pauseAlt/pauseBG');
add(bg); add(bg);

View file

@ -369,7 +369,7 @@ class PauseSubState extends MusicBeatSubState
*/ */
function changeSelection(change:Int = 0):Void function changeSelection(change:Int = 0):Void
{ {
FlxG.sound.play(Paths.sound('scrollMenu'), 0.4); FunkinSound.playOnce(Paths.sound('scrollMenu'), 0.4);
currentEntry += change; currentEntry += change;

View file

@ -1,20 +1,15 @@
package funkin.play; package funkin.play;
import funkin.audio.FunkinSound;
import flixel.addons.display.FlxPieDial; import flixel.addons.display.FlxPieDial;
import flixel.addons.transition.FlxTransitionableState; import flixel.addons.transition.FlxTransitionableState;
import flixel.addons.transition.Transition; import flixel.addons.transition.Transition;
import flixel.addons.transition.Transition;
import flixel.FlxCamera; import flixel.FlxCamera;
import flixel.FlxObject; import flixel.FlxObject;
import flixel.FlxState; import flixel.FlxState;
import funkin.graphics.FunkinSprite;
import flixel.FlxSubState; import flixel.FlxSubState;
import funkin.graphics.FunkinSprite;
import flixel.math.FlxMath; import flixel.math.FlxMath;
import flixel.math.FlxPoint; import flixel.math.FlxPoint;
import flixel.math.FlxRect; import flixel.math.FlxRect;
import funkin.graphics.FunkinSprite;
import flixel.text.FlxText; import flixel.text.FlxText;
import flixel.tweens.FlxEase; import flixel.tweens.FlxEase;
import flixel.tweens.FlxTween; import flixel.tweens.FlxTween;
@ -22,18 +17,19 @@ import flixel.ui.FlxBar;
import flixel.util.FlxColor; import flixel.util.FlxColor;
import flixel.util.FlxTimer; import flixel.util.FlxTimer;
import funkin.api.newgrounds.NGio; import funkin.api.newgrounds.NGio;
import funkin.audio.VoicesGroup; import funkin.audio.FunkinSound;
import funkin.audio.VoicesGroup; import funkin.audio.VoicesGroup;
import funkin.data.dialogue.conversation.ConversationRegistry; import funkin.data.dialogue.conversation.ConversationRegistry;
import funkin.data.event.SongEventRegistry; import funkin.data.event.SongEventRegistry;
import funkin.data.notestyle.NoteStyleData; import funkin.data.notestyle.NoteStyleData;
import funkin.data.notestyle.NoteStyleRegistry; import funkin.data.notestyle.NoteStyleRegistry;
import funkin.data.notestyle.NoteStyleRegistry;
import funkin.data.song.SongData.SongCharacterData; import funkin.data.song.SongData.SongCharacterData;
import funkin.data.song.SongData.SongEventData; import funkin.data.song.SongData.SongEventData;
import funkin.data.song.SongData.SongNoteData; import funkin.data.song.SongData.SongNoteData;
import funkin.data.song.SongRegistry; import funkin.data.song.SongRegistry;
import funkin.data.stage.StageRegistry; import funkin.data.stage.StageRegistry;
import funkin.graphics.FunkinCamera;
import funkin.graphics.FunkinSprite;
import funkin.Highscore.Tallies; import funkin.Highscore.Tallies;
import funkin.input.PreciseInputManager; import funkin.input.PreciseInputManager;
import funkin.modding.events.ScriptEvent; import funkin.modding.events.ScriptEvent;
@ -44,14 +40,11 @@ import funkin.play.components.ComboMilestone;
import funkin.play.components.HealthIcon; import funkin.play.components.HealthIcon;
import funkin.play.components.PopUpStuff; import funkin.play.components.PopUpStuff;
import funkin.play.cutscene.dialogue.Conversation; import funkin.play.cutscene.dialogue.Conversation;
import funkin.play.cutscene.dialogue.Conversation;
import funkin.play.cutscene.VanillaCutscenes; import funkin.play.cutscene.VanillaCutscenes;
import funkin.play.cutscene.VideoCutscene; import funkin.play.cutscene.VideoCutscene;
import funkin.play.notes.NoteDirection; import funkin.play.notes.NoteDirection;
import funkin.play.notes.NoteSplash; import funkin.play.notes.NoteSplash;
import funkin.play.notes.NoteSprite; import funkin.play.notes.NoteSprite;
import funkin.play.notes.NoteSprite;
import funkin.play.notes.notestyle.NoteStyle;
import funkin.play.notes.notestyle.NoteStyle; import funkin.play.notes.notestyle.NoteStyle;
import funkin.play.notes.Strumline; import funkin.play.notes.Strumline;
import funkin.play.notes.SustainTrail; import funkin.play.notes.SustainTrail;
@ -65,7 +58,6 @@ import funkin.ui.mainmenu.MainMenuState;
import funkin.ui.MusicBeatSubState; import funkin.ui.MusicBeatSubState;
import funkin.ui.options.PreferencesMenu; import funkin.ui.options.PreferencesMenu;
import funkin.ui.story.StoryMenuState; import funkin.ui.story.StoryMenuState;
import funkin.graphics.FunkinCamera;
import funkin.ui.transition.LoadingState; import funkin.ui.transition.LoadingState;
import funkin.util.SerializerUtil; import funkin.util.SerializerUtil;
import haxe.Int64; import haxe.Int64;
@ -1293,6 +1285,24 @@ class PlayState extends MusicBeatSubState
currentStage = null; currentStage = null;
} }
if (!overrideMusic)
{
// Stop the instrumental.
if (FlxG.sound.music != null)
{
FlxG.sound.music.destroy();
FlxG.sound.music = null;
}
// Stop the vocals.
if (vocals != null && vocals.exists)
{
vocals.destroy();
vocals = null;
}
}
else
{
// Stop the instrumental. // Stop the instrumental.
if (FlxG.sound.music != null) if (FlxG.sound.music != null)
{ {
@ -1304,6 +1314,7 @@ class PlayState extends MusicBeatSubState
{ {
vocals.stop(); vocals.stop();
} }
}
super.debug_refreshModules(); super.debug_refreshModules();
@ -1353,7 +1364,10 @@ class PlayState extends MusicBeatSubState
} }
// Only zoom camera if we are zoomed by less than 35%. // Only zoom camera if we are zoomed by less than 35%.
if (FlxG.camera.zoom < (1.35 * defaultCameraZoom) && cameraZoomRate > 0 && Conductor.instance.currentBeat % cameraZoomRate == 0) if (Preferences.zoomCamera
&& FlxG.camera.zoom < (1.35 * defaultCameraZoom)
&& cameraZoomRate > 0
&& Conductor.instance.currentBeat % cameraZoomRate == 0)
{ {
// Zoom camera in (1.5%) // Zoom camera in (1.5%)
currentCameraZoom += cameraZoomIntensity * defaultCameraZoom; currentCameraZoom += cameraZoomIntensity * defaultCameraZoom;
@ -1899,20 +1913,26 @@ class PlayState extends MusicBeatSubState
currentChart.playInst(1.0, false); currentChart.playInst(1.0, false);
} }
if (FlxG.sound.music == null)
{
FlxG.log.error('PlayState failed to initialize instrumental!');
return;
}
FlxG.sound.music.onComplete = endSong.bind(false); FlxG.sound.music.onComplete = endSong.bind(false);
// A negative instrumental offset means the song skips the first few milliseconds of the track. // A negative instrumental offset means the song skips the first few milliseconds of the track.
// This just gets added into the startTimestamp behavior so we don't need to do anything extra. // This just gets added into the startTimestamp behavior so we don't need to do anything extra.
FlxG.sound.music.play(true, startTimestamp - Conductor.instance.instrumentalOffset); FlxG.sound.music.play(true, startTimestamp - Conductor.instance.instrumentalOffset);
FlxG.sound.music.pitch = playbackRate; FlxG.sound.music.pitch = playbackRate;
// I am going insane. // Prevent the volume from being wrong.
FlxG.sound.music.volume = 1.0; FlxG.sound.music.volume = 1.0;
FlxG.sound.music.fadeTween?.cancel(); FlxG.sound.music.fadeTween?.cancel();
trace('Playing vocals...'); trace('Playing vocals...');
add(vocals); add(vocals);
vocals.play(); vocals.play();
vocals.volume = 1.0;
vocals.pitch = playbackRate; vocals.pitch = playbackRate;
resyncVocals(); resyncVocals();
@ -2089,8 +2109,7 @@ class PlayState extends MusicBeatSubState
holdNote.handledMiss = true; holdNote.handledMiss = true;
// We dropped a hold note. // We dropped a hold note.
// Mute vocals and play miss animation, but don't penalize. // Play miss animation, but don't penalize.
vocals.opponentVolume = 0;
currentStage.getOpponent().playSingAnimation(holdNote.noteData.getDirection(), true); currentStage.getOpponent().playSingAnimation(holdNote.noteData.getDirection(), true);
} }
} }
@ -2428,7 +2447,7 @@ class PlayState extends MusicBeatSubState
if (playSound) if (playSound)
{ {
vocals.playerVolume = 0; vocals.playerVolume = 0;
FlxG.sound.play(Paths.soundRandom('missnote', 1, 3), FlxG.random.float(0.1, 0.2)); FunkinSound.playOnce(Paths.soundRandom('missnote', 1, 3), FlxG.random.float(0.5, 0.6));
} }
} }
@ -2483,7 +2502,7 @@ class PlayState extends MusicBeatSubState
if (event.playSound) if (event.playSound)
{ {
vocals.playerVolume = 0; vocals.playerVolume = 0;
FlxG.sound.play(Paths.soundRandom('missnote', 1, 3), FlxG.random.float(0.1, 0.2)); FunkinSound.playOnce(Paths.soundRandom('missnote', 1, 3), FlxG.random.float(0.1, 0.2));
} }
} }
@ -2766,7 +2785,11 @@ class PlayState extends MusicBeatSubState
if (targetSongId == null) if (targetSongId == null)
{ {
FunkinSound.playMusic('freakyMenu'); FunkinSound.playMusic('freakyMenu',
{
overrideExisting: true,
restartTrack: false
});
// transIn = FlxTransitionableState.defaultTransIn; // transIn = FlxTransitionableState.defaultTransIn;
// transOut = FlxTransitionableState.defaultTransOut; // transOut = FlxTransitionableState.defaultTransOut;
@ -2844,7 +2867,7 @@ class PlayState extends MusicBeatSubState
camHUD.visible = false; camHUD.visible = false;
isInCutscene = true; isInCutscene = true;
FlxG.sound.play(Paths.sound('Lights_Shut_off'), function() { FunkinSound.playOnce(Paths.sound('Lights_Shut_off'), function() {
// no camFollow so it centers on horror tree // no camFollow so it centers on horror tree
var targetSong:Song = SongRegistry.instance.fetchEntry(targetSongId); var targetSong:Song = SongRegistry.instance.fetchEntry(targetSongId);
LoadingState.loadPlayState( LoadingState.loadPlayState(
@ -2904,6 +2927,9 @@ class PlayState extends MusicBeatSubState
// If the camera is being tweened, stop it. // If the camera is being tweened, stop it.
cancelAllCameraTweens(); cancelAllCameraTweens();
// Dispatch the destroy event.
dispatchEvent(new ScriptEvent(DESTROY, false));
if (currentConversation != null) if (currentConversation != null)
{ {
remove(currentConversation); remove(currentConversation);
@ -2918,7 +2944,7 @@ class PlayState extends MusicBeatSubState
if (overrideMusic) if (overrideMusic)
{ {
// Stop the music. Do NOT destroy it, something still references it! // Stop the music. Do NOT destroy it, something still references it!
FlxG.sound.music.pause(); if (FlxG.sound.music != null) FlxG.sound.music.pause();
if (vocals != null) if (vocals != null)
{ {
vocals.pause(); vocals.pause();
@ -2928,7 +2954,7 @@ class PlayState extends MusicBeatSubState
else else
{ {
// Stop and destroy the music. // Stop and destroy the music.
FlxG.sound.music.pause(); if (FlxG.sound.music != null) FlxG.sound.music.pause();
if (vocals != null) if (vocals != null)
{ {
vocals.destroy(); vocals.destroy();
@ -2941,7 +2967,6 @@ class PlayState extends MusicBeatSubState
{ {
remove(currentStage); remove(currentStage);
currentStage.kill(); currentStage.kill();
dispatchEvent(new ScriptEvent(DESTROY, false));
currentStage = null; currentStage = null;
} }

View file

@ -13,6 +13,7 @@ import flixel.text.FlxBitmapText;
import flixel.tweens.FlxEase; import flixel.tweens.FlxEase;
import funkin.ui.freeplay.FreeplayState; import funkin.ui.freeplay.FreeplayState;
import flixel.tweens.FlxTween; import flixel.tweens.FlxTween;
import funkin.audio.FunkinSound;
import flixel.util.FlxGradient; import flixel.util.FlxGradient;
import flixel.util.FlxTimer; import flixel.util.FlxTimer;
import funkin.graphics.shaders.LeftMaskShader; import funkin.graphics.shaders.LeftMaskShader;
@ -48,9 +49,13 @@ class ResultState extends MusicBeatSubState
else else
resultsVariation = NORMAL; resultsVariation = NORMAL;
var loops:Bool = resultsVariation != SHIT; FunkinSound.playMusic('results$resultsVariation',
{
FlxG.sound.playMusic(Paths.music("results" + resultsVariation), 1, loops); startingVolume: 1.0,
overrideExisting: true,
restartTrack: true,
loop: resultsVariation != SHIT
});
// TEMP-ish, just used to sorta "cache" the 3000x3000 image! // TEMP-ish, just used to sorta "cache" the 3000x3000 image!
var cacheBullShit:FlxSprite = new FlxSprite().loadGraphic(Paths.image("resultScreen/soundSystem")); var cacheBullShit:FlxSprite = new FlxSprite().loadGraphic(Paths.image("resultScreen/soundSystem"));
@ -104,7 +109,7 @@ class ResultState extends MusicBeatSubState
add(gf); add(gf);
var boyfriend:FlxSprite = FunkinSprite.createSparrow(640, -200, 'resultScreen/resultBoyfriendGOOD'); var boyfriend:FlxSprite = FunkinSprite.createSparrow(640, -200, 'resultScreen/resultBoyfriendGOOD');
boyfriend.animation.addByPrefix("fall", "Boyfriend Good", 24, false); boyfriend.animation.addByPrefix("fall", "Boyfriend Good Anim0", 24, false);
boyfriend.visible = false; boyfriend.visible = false;
boyfriend.animation.finishCallback = function(_) { boyfriend.animation.finishCallback = function(_) {
boyfriend.animation.play('fall', true, false, 14); boyfriend.animation.play('fall', true, false, 14);
@ -159,7 +164,7 @@ class ResultState extends MusicBeatSubState
add(blackTopBar); add(blackTopBar);
var resultsAnim:FunkinSprite = FunkinSprite.createSparrow(-200, -10, "resultScreen/results"); var resultsAnim:FunkinSprite = FunkinSprite.createSparrow(-200, -10, "resultScreen/results");
resultsAnim.animation.addByPrefix("result", "results", 24, false); resultsAnim.animation.addByPrefix("result", "results instance 1", 24, false);
resultsAnim.animation.play("result"); resultsAnim.animation.play("result");
add(resultsAnim); add(resultsAnim);
@ -348,9 +353,12 @@ class ResultState extends MusicBeatSubState
if (controls.PAUSE) if (controls.PAUSE)
{ {
FlxTween.tween(FlxG.sound.music, {volume: 0}, 0.8); FlxTween.tween(FlxG.sound.music, {volume: 0}, 0.8);
FlxTween.tween(FlxG.sound.music, {pitch: 3}, 0.1, {onComplete: _ -> { FlxTween.tween(FlxG.sound.music, {pitch: 3}, 0.1,
{
onComplete: _ -> {
FlxTween.tween(FlxG.sound.music, {pitch: 0.5}, 0.4); FlxTween.tween(FlxG.sound.music, {pitch: 0.5}, 0.4);
}}); }
});
if (params.storyMode) if (params.storyMode)
{ {
openSubState(new funkin.ui.transition.StickerSubState(null, (sticker) -> new StoryMenuState(sticker))); openSubState(new funkin.ui.transition.StickerSubState(null, (sticker) -> new StoryMenuState(sticker)));

View file

@ -76,10 +76,17 @@ class AnimateAtlasCharacter extends BaseCharacter
{ {
trace('Creating Animate Atlas character: ' + this.characterId); trace('Creating Animate Atlas character: ' + this.characterId);
try
{
var atlasSprite:FlxAtlasSprite = loadAtlasSprite(); var atlasSprite:FlxAtlasSprite = loadAtlasSprite();
setSprite(atlasSprite); setSprite(atlasSprite);
loadAnimations(); loadAnimations();
}
catch (e)
{
throw "Exception thrown while building FlxAtlasSprite: " + e;
}
super.onCreate(event); super.onCreate(event);
} }

View file

@ -4,6 +4,7 @@ import flixel.FlxSprite;
import flixel.group.FlxGroup.FlxTypedGroup; import flixel.group.FlxGroup.FlxTypedGroup;
import flixel.group.FlxSpriteGroup.FlxTypedSpriteGroup; import flixel.group.FlxSpriteGroup.FlxTypedSpriteGroup;
import flixel.util.FlxTimer; import flixel.util.FlxTimer;
import funkin.audio.FunkinSound;
class ComboMilestone extends FlxTypedSpriteGroup<FlxSprite> class ComboMilestone extends FlxTypedSpriteGroup<FlxSprite>
{ {
@ -78,7 +79,7 @@ class ComboMilestone extends FlxTypedSpriteGroup<FlxSprite>
function setupCombo(daCombo:Int) function setupCombo(daCombo:Int)
{ {
FlxG.sound.play(Paths.sound('comboSound')); FunkinSound.playOnce(Paths.sound('comboSound'));
wasComboSetup = true; wasComboSetup = true;
var loopNum:Int = 0; var loopNum:Int = 0;

View file

@ -4,6 +4,7 @@ import flixel.FlxSprite;
import flixel.tweens.FlxEase; import flixel.tweens.FlxEase;
import flixel.tweens.FlxTween; import flixel.tweens.FlxTween;
import flixel.util.FlxColor; import flixel.util.FlxColor;
import funkin.audio.FunkinSound;
import flixel.util.FlxTimer; import flixel.util.FlxTimer;
/** /**
@ -40,7 +41,7 @@ class VanillaCutscenes
FlxG.camera.zoom = 2.5; FlxG.camera.zoom = 2.5;
// Play the Sound effect. // Play the Sound effect.
FlxG.sound.play(Paths.sound('Lights_Turn_On'), function() { FunkinSound.playOnce(Paths.sound('Lights_Turn_On'), function() {
// Fade in the HUD. // Fade in the HUD.
trace('SFX done...'); trace('SFX done...');
PlayState.instance.camHUD.visible = true; PlayState.instance.camHUD.visible = true;

View file

@ -5,6 +5,7 @@ import flixel.FlxSprite;
import flixel.tweens.FlxEase; import flixel.tweens.FlxEase;
import flixel.tweens.FlxTween; import flixel.tweens.FlxTween;
import flixel.util.FlxColor; import flixel.util.FlxColor;
import flixel.util.FlxSignal;
import flixel.util.FlxTimer; import flixel.util.FlxTimer;
#if html5 #if html5
import funkin.graphics.video.FlxVideo; import funkin.graphics.video.FlxVideo;
@ -28,6 +29,31 @@ class VideoCutscene
static var vid:FlxVideoSprite; static var vid:FlxVideoSprite;
#end #end
/**
* Called when the video is started.
*/
public static final onVideoStarted:FlxSignal = new FlxSignal();
/**
* Called if the video is paused.
*/
public static final onVideoPaused:FlxSignal = new FlxSignal();
/**
* Called if the video is resumed.
*/
public static final onVideoResumed:FlxSignal = new FlxSignal();
/**
* Called if the video is restarted. onVideoStarted is not called.
*/
public static final onVideoRestarted:FlxSignal = new FlxSignal();
/**
* Called when the video is ended or skipped.
*/
public static final onVideoEnded:FlxSignal = new FlxSignal();
/** /**
* Play a video cutscene. * Play a video cutscene.
* TODO: Currently this is hardcoded to start the countdown after the video is done. * TODO: Currently this is hardcoded to start the countdown after the video is done.
@ -94,6 +120,8 @@ class VideoCutscene
PlayState.instance.add(vid); PlayState.instance.add(vid);
PlayState.instance.refresh(); PlayState.instance.refresh();
onVideoStarted.dispatch();
} }
else else
{ {
@ -129,6 +157,8 @@ class VideoCutscene
vid.y = 0; vid.y = 0;
// vid.scale.set(0.5, 0.5); // vid.scale.set(0.5, 0.5);
}); });
onVideoStarted.dispatch();
} }
else else
{ {
@ -143,6 +173,7 @@ class VideoCutscene
if (vid != null) if (vid != null)
{ {
vid.restartVideo(); vid.restartVideo();
onVideoRestarted.dispatch();
} }
#end #end
@ -156,6 +187,8 @@ class VideoCutscene
// Resume the video if it was paused. // Resume the video if it was paused.
vid.resume(); vid.resume();
} }
onVideoRestarted.dispatch();
} }
#end #end
} }
@ -166,6 +199,7 @@ class VideoCutscene
if (vid != null) if (vid != null)
{ {
vid.pauseVideo(); vid.pauseVideo();
onVideoPaused.dispatch();
} }
#end #end
@ -173,6 +207,45 @@ class VideoCutscene
if (vid != null) if (vid != null)
{ {
vid.pause(); vid.pause();
onVideoPaused.dispatch();
}
#end
}
public static function hideVideo():Void
{
#if html5
if (vid != null)
{
vid.visible = false;
blackScreen.visible = false;
}
#end
#if hxCodec
if (vid != null)
{
vid.visible = false;
blackScreen.visible = false;
}
#end
}
public static function showVideo():Void
{
#if html5
if (vid != null)
{
vid.visible = true;
blackScreen.visible = false;
}
#end
#if hxCodec
if (vid != null)
{
vid.visible = true;
blackScreen.visible = false;
} }
#end #end
} }
@ -183,6 +256,7 @@ class VideoCutscene
if (vid != null) if (vid != null)
{ {
vid.resumeVideo(); vid.resumeVideo();
onVideoResumed.dispatch();
} }
#end #end
@ -190,6 +264,7 @@ class VideoCutscene
if (vid != null) if (vid != null)
{ {
vid.resume(); vid.resume();
onVideoResumed.dispatch();
} }
#end #end
} }
@ -240,6 +315,7 @@ class VideoCutscene
{ {
ease: FlxEase.quadInOut, ease: FlxEase.quadInOut,
onComplete: function(twn:FlxTween) { onComplete: function(twn:FlxTween) {
onVideoEnded.dispatch();
onCutsceneFinish(cutsceneType); onCutsceneFinish(cutsceneType);
} }
}); });

View file

@ -1,28 +1,28 @@
package funkin.play.cutscene.dialogue; package funkin.play.cutscene.dialogue;
import funkin.data.IRegistryEntry; import flixel.addons.display.FlxPieDial;
import flixel.FlxSprite; import flixel.FlxSprite;
import flixel.group.FlxSpriteGroup; import flixel.group.FlxSpriteGroup;
import flixel.util.FlxColor;
import funkin.graphics.FunkinSprite;
import flixel.tweens.FlxTween;
import flixel.tweens.FlxEase; import flixel.tweens.FlxEase;
import flixel.sound.FlxSound; import flixel.tweens.FlxTween;
import funkin.util.SortUtil; import flixel.util.FlxColor;
import flixel.util.FlxSort; import flixel.util.FlxSort;
import funkin.modding.events.ScriptEvent; import funkin.audio.FunkinSound;
import funkin.modding.IScriptedClass.IEventHandler;
import funkin.play.cutscene.dialogue.DialogueBox;
import funkin.modding.IScriptedClass.IDialogueScriptedClass;
import funkin.modding.events.ScriptEventDispatcher;
import flixel.addons.display.FlxPieDial;
import funkin.data.dialogue.conversation.ConversationData; import funkin.data.dialogue.conversation.ConversationData;
import funkin.data.dialogue.conversation.ConversationData.DialogueEntryData; import funkin.data.dialogue.conversation.ConversationData.DialogueEntryData;
import funkin.data.dialogue.conversation.ConversationRegistry; import funkin.data.dialogue.conversation.ConversationRegistry;
import funkin.data.dialogue.speaker.SpeakerData;
import funkin.data.dialogue.speaker.SpeakerRegistry;
import funkin.data.dialogue.dialoguebox.DialogueBoxData; import funkin.data.dialogue.dialoguebox.DialogueBoxData;
import funkin.data.dialogue.dialoguebox.DialogueBoxRegistry; import funkin.data.dialogue.dialoguebox.DialogueBoxRegistry;
import funkin.data.dialogue.speaker.SpeakerData;
import funkin.data.dialogue.speaker.SpeakerRegistry;
import funkin.data.IRegistryEntry;
import funkin.graphics.FunkinSprite;
import funkin.modding.events.ScriptEvent;
import funkin.modding.events.ScriptEventDispatcher;
import funkin.modding.IScriptedClass.IDialogueScriptedClass;
import funkin.modding.IScriptedClass.IEventHandler;
import funkin.play.cutscene.dialogue.DialogueBox;
import funkin.util.SortUtil;
/** /**
* A high-level handler for dialogue. * A high-level handler for dialogue.
@ -90,7 +90,7 @@ class Conversation extends FlxSpriteGroup implements IDialogueScriptedClass impl
/** /**
* AUDIO * AUDIO
*/ */
var music:FlxSound; var music:FunkinSound;
/** /**
* GRAPHICS * GRAPHICS
@ -129,8 +129,7 @@ class Conversation extends FlxSpriteGroup implements IDialogueScriptedClass impl
{ {
if (_data.music == null) return; if (_data.music == null) return;
music = new FlxSound().loadEmbedded(Paths.music(_data.music.asset), true, true); music = FunkinSound.load(Paths.music(_data.music.asset), 0.0, true, true, true);
music.volume = 0;
if (_data.music.fadeTime > 0.0) if (_data.music.fadeTime > 0.0)
{ {
@ -140,9 +139,6 @@ class Conversation extends FlxSpriteGroup implements IDialogueScriptedClass impl
{ {
music.volume = 1.0; music.volume = 1.0;
} }
FlxG.sound.list.add(music);
music.play();
} }
public function pauseMusic():Void public function pauseMusic():Void

View file

@ -43,7 +43,7 @@ class Scoring
case WEEK7: scoreNoteWEEK7(msTiming); case WEEK7: scoreNoteWEEK7(msTiming);
case PBOT1: scoreNotePBOT1(msTiming); case PBOT1: scoreNotePBOT1(msTiming);
default: default:
trace('ERROR: Unknown scoring system: ' + scoringSystem); FlxG.log.error('Unknown scoring system: ${scoringSystem}');
0; 0;
} }
} }
@ -62,7 +62,7 @@ class Scoring
case WEEK7: judgeNoteWEEK7(msTiming); case WEEK7: judgeNoteWEEK7(msTiming);
case PBOT1: judgeNotePBOT1(msTiming); case PBOT1: judgeNotePBOT1(msTiming);
default: default:
trace('ERROR: Unknown scoring system: ' + scoringSystem); FlxG.log.error('Unknown scoring system: ${scoringSystem}');
'miss'; 'miss';
} }
} }
@ -145,7 +145,9 @@ class Scoring
case(_ < PBOT1_PERFECT_THRESHOLD) => true: case(_ < PBOT1_PERFECT_THRESHOLD) => true:
PBOT1_MAX_SCORE; PBOT1_MAX_SCORE;
default: default:
// Fancy equation.
var factor:Float = 1.0 - (1.0 / (1.0 + Math.exp(-PBOT1_SCORING_SLOPE * (absTiming - PBOT1_SCORING_OFFSET)))); var factor:Float = 1.0 - (1.0 / (1.0 + Math.exp(-PBOT1_SCORING_SLOPE * (absTiming - PBOT1_SCORING_OFFSET))));
var score:Int = Std.int(PBOT1_MAX_SCORE * factor + PBOT1_MIN_SCORE); var score:Int = Std.int(PBOT1_MAX_SCORE * factor + PBOT1_MIN_SCORE);
score; score;
@ -169,6 +171,7 @@ class Scoring
case(_ < PBOT1_SHIT_THRESHOLD) => true: case(_ < PBOT1_SHIT_THRESHOLD) => true:
'shit'; 'shit';
default: default:
FlxG.log.warn('Missed note: Bad timing ($absTiming < $PBOT1_SHIT_THRESHOLD)');
'miss'; 'miss';
} }
} }
@ -257,6 +260,7 @@ class Scoring
case(_ < LEGACY_HIT_WINDOW * LEGACY_SHIT_THRESHOLD) => true: case(_ < LEGACY_HIT_WINDOW * LEGACY_SHIT_THRESHOLD) => true:
'shit'; 'shit';
default: default:
FlxG.log.warn('Missed note: Bad timing ($absTiming < $LEGACY_SHIT_THRESHOLD)');
'miss'; 'miss';
} }
} }
@ -336,6 +340,7 @@ class Scoring
} }
else else
{ {
FlxG.log.warn('Missed note: Bad timing ($absTiming < $WEEK7_HIT_WINDOW)');
return 'miss'; return 'miss';
} }
} }

View file

@ -139,7 +139,16 @@ class Song implements IPlayStateScriptedClass implements IRegistryEntry<SongMeta
for (vari in _data.playData.songVariations) for (vari in _data.playData.songVariations)
{ {
var variMeta:Null<SongMetadata> = fetchVariationMetadata(id, vari); var variMeta:Null<SongMetadata> = fetchVariationMetadata(id, vari);
if (variMeta != null) _metadata.set(variMeta.variation, variMeta); if (variMeta != null)
{
_metadata.set(variMeta.variation, variMeta);
trace(' Loaded variation: $vari');
}
else
{
FlxG.log.warn('[SONG] Failed to load variation metadata (${id}:${vari}), is the path correct?');
trace(' FAILED to load variation: $vari');
}
} }
} }
@ -374,12 +383,17 @@ class Song implements IPlayStateScriptedClass implements IRegistryEntry<SongMeta
public function getFirstValidVariation(?diffId:String, ?possibleVariations:Array<String>):Null<String> public function getFirstValidVariation(?diffId:String, ?possibleVariations:Array<String>):Null<String>
{ {
if (variations == null) possibleVariations = variations; if (possibleVariations == null)
{
possibleVariations = variations;
possibleVariations.sort(SortUtil.defaultsThenAlphabetically.bind(Constants.DEFAULT_VARIATION_LIST));
}
if (diffId == null) diffId = listDifficulties(null, possibleVariations)[0]; if (diffId == null) diffId = listDifficulties(null, possibleVariations)[0];
for (variation in variations) for (variationId in possibleVariations)
{ {
if (difficulties.exists('$diffId-$variation')) return variation; var variationSuffix = (variationId != Constants.DEFAULT_VARIATION) ? '-$variationId' : '';
if (difficulties.exists('$diffId$variationSuffix')) return variationId;
} }
return null; return null;

View file

@ -5,6 +5,7 @@ import flixel.group.FlxSpriteGroup;
import flixel.math.FlxMath; import flixel.math.FlxMath;
import flixel.util.FlxTimer; import flixel.util.FlxTimer;
import funkin.util.MathUtil; import funkin.util.MathUtil;
import funkin.audio.FunkinSound;
/** /**
* Loosley based on FlxTypeText lolol * Loosley based on FlxTypeText lolol
@ -200,7 +201,7 @@ class Alphabet extends FlxSpriteGroup
if (FlxG.random.bool(40)) if (FlxG.random.bool(40))
{ {
var daSound:String = "GF_"; var daSound:String = "GF_";
FlxG.sound.play(Paths.soundRandom(daSound, 1, 4)); FunkinSound.playOnce(Paths.soundRandom(daSound, 1, 4));
} }
add(letter); add(letter);

View file

@ -5,6 +5,7 @@ import flixel.effects.FlxFlicker;
import flixel.group.FlxGroup; import flixel.group.FlxGroup;
import flixel.math.FlxPoint; import flixel.math.FlxPoint;
import flixel.util.FlxSignal; import flixel.util.FlxSignal;
import funkin.audio.FunkinSound;
class MenuTypedList<T:MenuListItem> extends FlxTypedGroup<T> class MenuTypedList<T:MenuListItem> extends FlxTypedGroup<T>
{ {
@ -93,7 +94,7 @@ class MenuTypedList<T:MenuListItem> extends FlxTypedGroup<T>
if (newIndex != selectedIndex) if (newIndex != selectedIndex)
{ {
FlxG.sound.play(Paths.sound('scrollMenu')); FunkinSound.playOnce(Paths.sound('scrollMenu'));
selectItem(newIndex); selectItem(newIndex);
} }
@ -163,7 +164,7 @@ class MenuTypedList<T:MenuListItem> extends FlxTypedGroup<T>
else else
{ {
busy = true; busy = true;
FlxG.sound.play(Paths.sound('confirmMenu')); FunkinSound.playOnce(Paths.sound('confirmMenu'));
FlxFlicker.flicker(selected, 1, 0.06, true, false, function(_) { FlxFlicker.flicker(selected, 1, 0.06, true, false, function(_) {
busy = false; busy = false;
selected.callback(); selected.callback();

View file

@ -7,6 +7,7 @@ import flixel.FlxSubState;
import flixel.addons.transition.FlxTransitionableState; import flixel.addons.transition.FlxTransitionableState;
import flixel.text.FlxText; import flixel.text.FlxText;
import flixel.util.FlxColor; import flixel.util.FlxColor;
import funkin.audio.FunkinSound;
import flixel.util.FlxSort; import flixel.util.FlxSort;
import funkin.modding.PolymodHandler; import funkin.modding.PolymodHandler;
import funkin.modding.events.ScriptEvent; import funkin.modding.events.ScriptEvent;
@ -166,6 +167,8 @@ class MusicBeatState extends FlxTransitionableState implements IEventHandler
} }
else else
{ {
FunkinSound.stopAllAudio();
onComplete(); onComplete();
} }
} }

View file

@ -4,6 +4,7 @@ import flixel.math.FlxPoint;
import flixel.FlxObject; import flixel.FlxObject;
import flixel.FlxSprite; import flixel.FlxSprite;
import funkin.ui.MusicBeatSubState; import funkin.ui.MusicBeatSubState;
import funkin.audio.FunkinSound;
import funkin.ui.TextMenuList; import funkin.ui.TextMenuList;
import funkin.ui.debug.charting.ChartEditorState; import funkin.ui.debug.charting.ChartEditorState;
import funkin.ui.MusicBeatSubState; import funkin.ui.MusicBeatSubState;
@ -76,7 +77,7 @@ class DebugMenuSubState extends MusicBeatSubState
if (controls.BACK) if (controls.BACK)
{ {
FlxG.sound.play(Paths.sound('cancelMenu')); FunkinSound.playOnce(Paths.sound('cancelMenu'));
exitDebugMenu(); exitDebugMenu();
} }
} }

View file

@ -1,32 +1,35 @@
package funkin.ui.debug.anim; package funkin.ui.debug.anim;
import funkin.util.SerializerUtil;
import funkin.play.character.CharacterData;
import flixel.FlxCamera;
import flixel.FlxSprite;
import flixel.FlxState;
import flixel.addons.display.FlxGridOverlay; import flixel.addons.display.FlxGridOverlay;
import flixel.addons.ui.FlxInputText; import flixel.addons.ui.FlxInputText;
import flixel.addons.ui.FlxUIDropDownMenu; import flixel.addons.ui.FlxUIDropDownMenu;
import flixel.FlxCamera;
import flixel.FlxSprite;
import flixel.FlxState;
import flixel.graphics.frames.FlxAtlasFrames; import flixel.graphics.frames.FlxAtlasFrames;
import flixel.graphics.frames.FlxFrame; import flixel.graphics.frames.FlxFrame;
import flixel.group.FlxGroup; import flixel.group.FlxGroup;
import flixel.math.FlxPoint; import flixel.math.FlxPoint;
import flixel.sound.FlxSound;
import flixel.text.FlxText; import flixel.text.FlxText;
import flixel.util.FlxColor; import flixel.util.FlxColor;
import funkin.util.MouseUtil;
import flixel.util.FlxSpriteUtil; import flixel.util.FlxSpriteUtil;
import flixel.util.FlxTimer; import flixel.util.FlxTimer;
import funkin.audio.FunkinSound;
import funkin.input.Cursor;
import funkin.play.character.BaseCharacter; import funkin.play.character.BaseCharacter;
import funkin.play.character.CharacterData;
import funkin.play.character.CharacterData.CharacterDataParser; import funkin.play.character.CharacterData.CharacterDataParser;
import funkin.play.character.SparrowCharacter; import funkin.play.character.SparrowCharacter;
import haxe.ui.RuntimeComponentBuilder; import funkin.ui.mainmenu.MainMenuState;
import funkin.util.MouseUtil;
import funkin.util.SerializerUtil;
import funkin.util.SortUtil;
import haxe.ui.components.DropDown; import haxe.ui.components.DropDown;
import haxe.ui.core.Component; import haxe.ui.core.Component;
import haxe.ui.core.Screen;
import haxe.ui.events.ItemEvent; import haxe.ui.events.ItemEvent;
import haxe.ui.events.UIEvent; import haxe.ui.events.UIEvent;
import funkin.ui.mainmenu.MainMenuState; import haxe.ui.RuntimeComponentBuilder;
import lime.utils.Assets as LimeAssets; import lime.utils.Assets as LimeAssets;
import openfl.Assets; import openfl.Assets;
import openfl.events.Event; import openfl.events.Event;
@ -34,13 +37,8 @@ import openfl.events.IOErrorEvent;
import openfl.geom.Rectangle; import openfl.geom.Rectangle;
import openfl.net.FileReference; import openfl.net.FileReference;
import openfl.net.URLLoader; import openfl.net.URLLoader;
import funkin.ui.mainmenu.MainMenuState;
import openfl.net.URLRequest; import openfl.net.URLRequest;
import openfl.utils.ByteArray; import openfl.utils.ByteArray;
import funkin.input.Cursor;
import funkin.play.character.CharacterData.CharacterDataParser;
import funkin.util.SortUtil;
import haxe.ui.core.Screen;
using flixel.util.FlxSpriteUtil; using flixel.util.FlxSpriteUtil;
@ -179,7 +177,7 @@ class DebugBoundingState extends FlxState
var objShit = js.html.URL.createObjectURL(swagList.item(0)); var objShit = js.html.URL.createObjectURL(swagList.item(0));
trace(objShit); trace(objShit);
var funnysound = new FlxSound().loadStream('https://cdn.discordapp.com/attachments/767500676166451231/817821618251759666/Flutter.mp3', false, false, var funnysound = new FunkinSound().loadStream('https://cdn.discordapp.com/attachments/767500676166451231/817821618251759666/Flutter.mp3', false, false,
null, function() { null, function() {
trace('LOADED SHIT??'); trace('LOADED SHIT??');
}); });

View file

@ -15,7 +15,6 @@ import flixel.input.mouse.FlxMouseEvent;
import flixel.math.FlxMath; import flixel.math.FlxMath;
import flixel.math.FlxPoint; import flixel.math.FlxPoint;
import flixel.math.FlxRect; import flixel.math.FlxRect;
import flixel.sound.FlxSound;
import flixel.system.debug.log.LogStyle; import flixel.system.debug.log.LogStyle;
import flixel.system.FlxAssets.FlxSoundAsset; import flixel.system.FlxAssets.FlxSoundAsset;
import flixel.text.FlxText; import flixel.text.FlxText;
@ -1091,7 +1090,7 @@ class ChartEditorState extends UIState // UIState derives from MusicBeatState
* The chill audio track that plays in the chart editor. * The chill audio track that plays in the chart editor.
* Plays when the main music is NOT being played. * Plays when the main music is NOT being played.
*/ */
var welcomeMusic:FlxSound = new FlxSound(); var welcomeMusic:FunkinSound = new FunkinSound();
/** /**
* The audio track for the instrumental. * The audio track for the instrumental.
@ -3888,8 +3887,8 @@ class ChartEditorState extends UIState // UIState derives from MusicBeatState
function handleCursor():Void function handleCursor():Void
{ {
// Mouse sounds // Mouse sounds
if (FlxG.mouse.justPressed) FlxG.sound.play(Paths.sound("chartingSounds/ClickDown")); if (FlxG.mouse.justPressed) FunkinSound.playOnce(Paths.sound("chartingSounds/ClickDown"));
if (FlxG.mouse.justReleased) FlxG.sound.play(Paths.sound("chartingSounds/ClickUp")); if (FlxG.mouse.justReleased) FunkinSound.playOnce(Paths.sound("chartingSounds/ClickUp"));
// Note: If a menu is open in HaxeUI, don't handle cursor behavior. // Note: If a menu is open in HaxeUI, don't handle cursor behavior.
var shouldHandleCursor:Bool = !(isHaxeUIFocused || playbarHeadDragging || isHaxeUIDialogOpen) var shouldHandleCursor:Bool = !(isHaxeUIFocused || playbarHeadDragging || isHaxeUIDialogOpen)
@ -4949,7 +4948,7 @@ class ChartEditorState extends UIState // UIState derives from MusicBeatState
playbarNoteSnap.text = '1/${noteSnapQuant}'; playbarNoteSnap.text = '1/${noteSnapQuant}';
playbarDifficulty.text = '${selectedDifficulty.toTitleCase()}'; playbarDifficulty.text = '${selectedDifficulty.toTitleCase()}';
// playbarBPM.text = 'BPM: ${(Conductor.currentTimeChange?.bpm ?? 0.0)}'; playbarBPM.text = 'BPM: ${(Conductor.instance.bpm ?? 0.0)}';
} }
function handlePlayhead():Void function handlePlayhead():Void

View file

@ -1,7 +1,6 @@
package funkin.ui.debug.charting.handlers; package funkin.ui.debug.charting.handlers;
import flixel.system.FlxAssets.FlxSoundAsset; import flixel.system.FlxAssets.FlxSoundAsset;
import flixel.sound.FlxSound;
import funkin.audio.VoicesGroup; import funkin.audio.VoicesGroup;
import funkin.audio.FunkinSound; import funkin.audio.FunkinSound;
import funkin.play.character.BaseCharacter.CharacterType; import funkin.play.character.BaseCharacter.CharacterType;
@ -302,7 +301,8 @@ class ChartEditorAudioHandler
trace('WARN: Failed to play sound $path, asset not found.'); trace('WARN: Failed to play sound $path, asset not found.');
return; return;
} }
var snd:FunkinSound = FunkinSound.load(asset); var snd:Null<FunkinSound> = FunkinSound.load(asset);
if (snd == null) return;
snd.autoDestroy = true; snd.autoDestroy = true;
snd.play(true); snd.play(true);
snd.volume = volume; snd.volume = volume;

View file

@ -96,7 +96,28 @@ class LatencyState extends MusicBeatSubState
localConductor.forceBPM(60); localConductor.forceBPM(60);
noteGrp = []; FlxG.stage.addEventListener(KeyboardEvent.KEY_DOWN, key -> {
trace(key.charCode);
if (key.charCode == 120) generateBeatStuff();
trace("\tEVENT PRESS: \t" + FlxG.sound.music.time + " " + Timer.stamp());
// trace(FlxG.sound.music.prevTimestamp);
trace(FlxG.sound.music.time);
trace("\tFR FR PRESS: \t" + swagSong.getTimeWithDiff());
// trace("\tREDDIT: \t" + swagSong.frfrTime + " " + Timer.stamp());
@:privateAccess
trace("\tREDDIT: \t" + FlxG.sound.music._channel.position + " " + Timer.stamp());
// trace("EVENT LISTENER: " + key);
});
// funnyStatsGraph.hi
Conductor.instance.forceBPM(60);
noteGrp = new FlxTypedGroup<NoteSprite>();
add(noteGrp);
diffGrp = new FlxTypedGroup<FlxText>(); diffGrp = new FlxTypedGroup<FlxText>();
add(diffGrp); add(diffGrp);
@ -313,6 +334,18 @@ class LatencyState extends MusicBeatSubState
{ {
close(); close();
} }
noteGrp.forEach(function(daNote:NoteSprite) {
daNote.y = (strumLine.y - ((Conductor.instance.songPosition - Conductor.instance.instrumentalOffset) - daNote.noteData.time) * 0.45);
daNote.x = strumLine.x + 30;
if (daNote.y < strumLine.y) daNote.alpha = 0.5;
if (daNote.y < 0 - daNote.height)
{
daNote.alpha = 1;
// daNote.data.strumTime += Conductor.instance.beatLengthMs * 8;
}
});
super.update(elapsed); super.update(elapsed);
} }

View file

@ -37,8 +37,6 @@ class StageBuilderState extends MusicBeatState
FlxG.mouse.visible = true; FlxG.mouse.visible = true;
// var alsoSnd:FlxSound = new FlxSound();
// snd = new Sound(); // snd = new Sound();
// var swagBytes:ByteArray = new ByteArray(8192); // var swagBytes:ByteArray = new ByteArray(8192);

View file

@ -4,8 +4,9 @@ import flixel.FlxSprite;
import flixel.util.FlxSignal; import flixel.util.FlxSignal;
import funkin.util.assets.FlxAnimationUtil; import funkin.util.assets.FlxAnimationUtil;
import funkin.graphics.adobeanimate.FlxAtlasSprite; import funkin.graphics.adobeanimate.FlxAtlasSprite;
import flixel.sound.FlxSound; import funkin.audio.FunkinSound;
import flixel.util.FlxTimer; import flixel.util.FlxTimer;
import funkin.audio.FunkinSound;
import funkin.audio.FlxStreamSound; import funkin.audio.FlxStreamSound;
class DJBoyfriend extends FlxAtlasSprite class DJBoyfriend extends FlxAtlasSprite
@ -26,8 +27,8 @@ class DJBoyfriend extends FlxAtlasSprite
var gotSpooked:Bool = false; var gotSpooked:Bool = false;
static final SPOOK_PERIOD:Float = 120.0; static final SPOOK_PERIOD:Float = 10.0;
static final TV_PERIOD:Float = 180.0; static final TV_PERIOD:Float = 10.0;
// Time since dad last SPOOKED you. // Time since dad last SPOOKED you.
var timeSinceSpook:Float = 0; var timeSinceSpook:Float = 0;
@ -48,7 +49,6 @@ class DJBoyfriend extends FlxAtlasSprite
}; };
setupAnimations(); setupAnimations();
trace(listAnimations());
FlxG.debugger.track(this); FlxG.debugger.track(this);
FlxG.console.registerObject("dj", this); FlxG.console.registerObject("dj", this);
@ -87,20 +87,21 @@ class DJBoyfriend extends FlxAtlasSprite
timeSinceSpook = 0; timeSinceSpook = 0;
case Idle: case Idle:
// We are in this state the majority of the time. // We are in this state the majority of the time.
if (getCurrentAnimation() != 'Boyfriend DJ' || anim.finished) if (getCurrentAnimation() != 'Boyfriend DJ')
{ {
if (timeSinceSpook > SPOOK_PERIOD && !gotSpooked) playFlashAnimation('Boyfriend DJ', true);
}
if (getCurrentAnimation() == 'Boyfriend DJ' && this.isLoopFinished())
{
if (timeSinceSpook >= SPOOK_PERIOD && !gotSpooked)
{ {
currentState = Spook; currentState = Spook;
} }
else if (timeSinceSpook > TV_PERIOD) else if (timeSinceSpook >= TV_PERIOD)
{ {
currentState = TV; currentState = TV;
} }
else
{
playFlashAnimation('Boyfriend DJ', false);
}
} }
timeSinceSpook += elapsed; timeSinceSpook += elapsed;
case Confirm: case Confirm:
@ -111,6 +112,7 @@ class DJBoyfriend extends FlxAtlasSprite
{ {
onSpook.dispatch(); onSpook.dispatch();
playFlashAnimation('bf dj afk', false); playFlashAnimation('bf dj afk', false);
gotSpooked = true;
} }
timeSinceSpook = 0; timeSinceSpook = 0;
case TV: case TV:
@ -119,6 +121,34 @@ class DJBoyfriend extends FlxAtlasSprite
default: default:
// I shit myself. // I shit myself.
} }
if (FlxG.keys.pressed.CONTROL)
{
if (FlxG.keys.justPressed.LEFT)
{
this.offsetX -= FlxG.keys.pressed.ALT ? 0.1 : (FlxG.keys.pressed.SHIFT ? 10.0 : 1.0);
}
if (FlxG.keys.justPressed.RIGHT)
{
this.offsetX += FlxG.keys.pressed.ALT ? 0.1 : (FlxG.keys.pressed.SHIFT ? 10.0 : 1.0);
}
if (FlxG.keys.justPressed.UP)
{
this.offsetY -= FlxG.keys.pressed.ALT ? 0.1 : (FlxG.keys.pressed.SHIFT ? 10.0 : 1.0);
}
if (FlxG.keys.justPressed.DOWN)
{
this.offsetY += FlxG.keys.pressed.ALT ? 0.1 : (FlxG.keys.pressed.SHIFT ? 10.0 : 1.0);
}
if (FlxG.keys.justPressed.SPACE)
{
currentState = (currentState == Idle ? TV : Idle);
}
}
} }
function onFinishAnim():Void function onFinishAnim():Void
@ -139,11 +169,15 @@ class DJBoyfriend extends FlxAtlasSprite
case "Boyfriend DJ watchin tv OG": case "Boyfriend DJ watchin tv OG":
var frame:Int = FlxG.random.bool(33) ? 112 : 166; var frame:Int = FlxG.random.bool(33) ? 112 : 166;
if (FlxG.random.bool(10))
// BF switches channels when the video ends, or at a 10% chance each time his idle loops.
if (FlxG.random.bool(5))
{ {
frame = 60; frame = 60;
// boyfriend switches channel code? // boyfriend switches channel code?
// runTvLogic();
} }
trace('Replay idle: ${frame}');
anim.play("Boyfriend DJ watchin tv OG", true, false, frame); anim.play("Boyfriend DJ watchin tv OG", true, false, frame);
// trace('Finished confirm'); // trace('Finished confirm');
} }
@ -152,24 +186,31 @@ class DJBoyfriend extends FlxAtlasSprite
public function resetAFKTimer():Void public function resetAFKTimer():Void
{ {
timeSinceSpook = 0; timeSinceSpook = 0;
gotSpooked = false;
} }
var offsetX:Float = 0.0;
var offsetY:Float = 0.0;
function setupAnimations():Void function setupAnimations():Void
{ {
// animation.addByPrefix('intro', "boyfriend dj intro", 24, false); // Intro
addOffset('boyfriend dj intro', 8, 3); addOffset('boyfriend dj intro', 8.0 - 1.3, 3.0 - 0.4);
// animation.addByPrefix('idle', "Boyfriend DJ0", 24, false); // Idle
addOffset('Boyfriend DJ', 0, 0); addOffset('Boyfriend DJ', 0, 0);
// animation.addByPrefix('confirm', "Boyfriend DJ confirm", 24, false); // Confirm
addOffset('Boyfriend DJ confirm', 0, 0); addOffset('Boyfriend DJ confirm', 0, 0);
// animation.addByPrefix('spook', "bf dj afk0", 24, false); // AFK: Spook
addOffset('bf dj afk', 0, 0); addOffset('bf dj afk', 649.5, 58.5);
// AFK: TV
addOffset('Boyfriend DJ watchin tv OG', 0, 0);
} }
var cartoonSnd:FlxStreamSound; var cartoonSnd:Null<FunkinSound> = null;
public var playingCartoon:Bool = false; public var playingCartoon:Bool = false;
@ -178,39 +219,47 @@ class DJBoyfriend extends FlxAtlasSprite
if (cartoonSnd == null) if (cartoonSnd == null)
{ {
// tv is OFF, but getting turned on // tv is OFF, but getting turned on
FlxG.sound.play(Paths.sound('tv_on')); // Eric got FUCKING TROLLED there is no `tv_on` or `channel_switch` sound!
// FunkinSound.playOnce(Paths.sound('tv_on'), 1.0, function() {
cartoonSnd = new FlxStreamSound(); // });
FlxG.sound.defaultSoundGroup.add(cartoonSnd); loadCartoon();
} }
else else
{ {
// plays it smidge after the click // plays it smidge after the click
new FlxTimer().start(0.1, function(_) { // new FlxTimer().start(0.1, function(_) {
FlxG.sound.play(Paths.sound('channel_switch')); // // FunkinSound.playOnce(Paths.sound('channel_switch'));
}); // });
} cartoonSnd.destroy();
// cartoonSnd.loadEmbedded(Paths.sound("cartoons/peck"));
// cartoonSnd.play();
loadCartoon(); loadCartoon();
} }
// loadCartoon();
}
function loadCartoon() function loadCartoon()
{ {
cartoonSnd.loadEmbedded(Paths.sound(getRandomFlashToon()), false, false, function() { cartoonSnd = FunkinSound.load(Paths.sound(getRandomFlashToon()), 1.0, false, true, true, function() {
anim.play("Boyfriend DJ watchin tv OG", true, false, 60); anim.play("Boyfriend DJ watchin tv OG", true, false, 60);
}); });
cartoonSnd.play(true, FlxG.random.float(0, cartoonSnd.length));
// Fade out music to 40% volume over 1 second.
// This helps make the TV a bit more audible.
FlxG.sound.music.fadeOut(1.0, 0.4);
// Play the cartoon at a random time between the start and 5 seconds from the end.
cartoonSnd.time = FlxG.random.float(0, Math.max(cartoonSnd.length - (5 * Constants.MS_PER_SEC), 0.0));
} }
var cartoonList:Array<String> = openfl.utils.Assets.list().filter(function(path) return path.startsWith("assets/sounds/cartoons/")); final cartoonList:Array<String> = openfl.utils.Assets.list().filter(function(path) return path.startsWith("assets/sounds/cartoons/"));
function getRandomFlashToon():String function getRandomFlashToon():String
{ {
var randomFile = FlxG.random.getObject(cartoonList); var randomFile = FlxG.random.getObject(cartoonList);
// Strip folder prefix
randomFile = randomFile.replace("assets/sounds/", ""); randomFile = randomFile.replace("assets/sounds/", "");
// Strip file extension
randomFile = randomFile.substring(0, randomFile.length - 4); randomFile = randomFile.substring(0, randomFile.length - 4);
return randomFile; return randomFile;
@ -244,11 +293,32 @@ class DJBoyfriend extends FlxAtlasSprite
var daOffset = animOffsets.get(AnimName); var daOffset = animOffsets.get(AnimName);
if (animOffsets.exists(AnimName)) if (animOffsets.exists(AnimName))
{ {
offset.set(daOffset[0], daOffset[1]); var xValue = daOffset[0];
var yValue = daOffset[1];
if (AnimName == "Boyfriend DJ watchin tv OG")
{
xValue += offsetX;
yValue += offsetY;
}
offset.set(xValue, yValue);
} }
else else
{
offset.set(0, 0); offset.set(0, 0);
} }
}
public override function destroy():Void
{
super.destroy();
if (cartoonSnd != null)
{
cartoonSnd.destroy();
cartoonSnd = null;
}
}
} }
enum DJBoyfriendState enum DJBoyfriendState

View file

@ -174,7 +174,11 @@ class FreeplayState extends MusicBeatSubState
isDebug = true; isDebug = true;
#end #end
FunkinSound.playMusic('freakyMenu'); FunkinSound.playMusic('freakyMenu',
{
overrideExisting: true,
restartTrack: false
});
// Add a null entry that represents the RANDOM option // Add a null entry that represents the RANDOM option
songs.push(null); songs.push(null);
@ -684,14 +688,6 @@ class FreeplayState extends MusicBeatSubState
if (FlxG.keys.justPressed.T) typing.hasFocus = true; if (FlxG.keys.justPressed.T) typing.hasFocus = true;
if (FlxG.sound.music != null)
{
if (FlxG.sound.music.volume < 0.7)
{
FlxG.sound.music.volume += 0.5 * elapsed;
}
}
lerpScore = MathUtil.coolLerp(lerpScore, intendedScore, 0.2); lerpScore = MathUtil.coolLerp(lerpScore, intendedScore, 0.2);
lerpCompletion = MathUtil.coolLerp(lerpCompletion, intendedCompletion, 0.9); lerpCompletion = MathUtil.coolLerp(lerpCompletion, intendedCompletion, 0.9);
@ -729,9 +725,9 @@ class FreeplayState extends MusicBeatSubState
{ {
if (busy) return; if (busy) return;
var upP:Bool = controls.UI_UP_P; var upP:Bool = controls.UI_UP_P && !FlxG.keys.pressed.CONTROL;
var downP:Bool = controls.UI_DOWN_P; var downP:Bool = controls.UI_DOWN_P && !FlxG.keys.pressed.CONTROL;
var accepted:Bool = controls.ACCEPT; var accepted:Bool = controls.ACCEPT && !FlxG.keys.pressed.CONTROL;
if (FlxG.onMobile) if (FlxG.onMobile)
{ {
@ -805,10 +801,8 @@ class FreeplayState extends MusicBeatSubState
} }
#end #end
if (controls.UI_UP || controls.UI_DOWN) if (!FlxG.keys.pressed.CONTROL && (controls.UI_UP || controls.UI_DOWN))
{ {
spamTimer += elapsed;
if (spamming) if (spamming)
{ {
if (spamTimer >= 0.07) if (spamTimer >= 0.07)
@ -825,7 +819,24 @@ class FreeplayState extends MusicBeatSubState
} }
} }
} }
else if (spamTimer >= 0.9) spamming = true; else if (spamTimer >= 0.9)
{
spamming = true;
}
else if (spamTimer <= 0)
{
if (controls.UI_UP)
{
changeSelection(-1);
}
else
{
changeSelection(1);
}
}
spamTimer += elapsed;
dj.resetAFKTimer();
} }
else else
{ {
@ -833,29 +844,18 @@ class FreeplayState extends MusicBeatSubState
spamTimer = 0; spamTimer = 0;
} }
if (upP)
{
dj.resetAFKTimer();
changeSelection(-1);
}
if (downP)
{
dj.resetAFKTimer();
changeSelection(1);
}
if (FlxG.mouse.wheel != 0) if (FlxG.mouse.wheel != 0)
{ {
dj.resetAFKTimer(); dj.resetAFKTimer();
changeSelection(-Math.round(FlxG.mouse.wheel / 4)); changeSelection(-Math.round(FlxG.mouse.wheel / 4));
} }
if (controls.UI_LEFT_P) if (controls.UI_LEFT_P && !FlxG.keys.pressed.CONTROL)
{ {
dj.resetAFKTimer(); dj.resetAFKTimer();
changeDiff(-1); changeDiff(-1);
} }
if (controls.UI_RIGHT_P) if (controls.UI_RIGHT_P && !FlxG.keys.pressed.CONTROL)
{ {
dj.resetAFKTimer(); dj.resetAFKTimer();
changeDiff(1); changeDiff(1);
@ -867,7 +867,7 @@ class FreeplayState extends MusicBeatSubState
FlxTimer.globalManager.clear(); FlxTimer.globalManager.clear();
dj.onIntroDone.removeAll(); dj.onIntroDone.removeAll();
FlxG.sound.play(Paths.sound('cancelMenu')); FunkinSound.playOnce(Paths.sound('cancelMenu'));
var longestTimer:Float = 0; var longestTimer:Float = 0;
@ -1013,7 +1013,14 @@ class FreeplayState extends MusicBeatSubState
// Set the difficulty star count on the right. // Set the difficulty star count on the right.
albumRoll.setDifficultyStars(daSong?.songRating); albumRoll.setDifficultyStars(daSong?.songRating);
albumRoll.albumId = daSong?.albumId ?? Constants.DEFAULT_ALBUM_ID;
// Set the album graphic and play the animation if relevant.
var newAlbumId:String = daSong?.albumId ?? Constants.DEFAULT_ALBUM_ID;
if (albumRoll.albumId != newAlbumId)
{
albumRoll.albumId = newAlbumId;
albumRoll.playIntro();
}
} }
// Clears the cache of songs, frees up memory, they' ll have to be loaded in later tho function clearDaCache(actualSongTho:String) // Clears the cache of songs, frees up memory, they' ll have to be loaded in later tho function clearDaCache(actualSongTho:String)
@ -1051,7 +1058,7 @@ class FreeplayState extends MusicBeatSubState
trace('No songs available!'); trace('No songs available!');
busy = false; busy = false;
letterSort.inputEnabled = true; letterSort.inputEnabled = true;
FlxG.sound.play(Paths.sound('cancelMenu')); FunkinSound.playOnce(Paths.sound('cancelMenu'));
return; return;
} }
@ -1084,7 +1091,7 @@ class FreeplayState extends MusicBeatSubState
PlayStatePlaylist.campaignId = cap.songData.levelId; PlayStatePlaylist.campaignId = cap.songData.levelId;
// Visual and audio effects. // Visual and audio effects.
FlxG.sound.play(Paths.sound('confirmMenu')); FunkinSound.playOnce(Paths.sound('confirmMenu'));
dj.confirm(); dj.confirm();
new FlxTimer().start(1, function(tmr:FlxTimer) { new FlxTimer().start(1, function(tmr:FlxTimer) {
@ -1126,8 +1133,7 @@ class FreeplayState extends MusicBeatSubState
function changeSelection(change:Int = 0):Void function changeSelection(change:Int = 0):Void
{ {
FlxG.sound.play(Paths.sound('scrollMenu'), 0.4); FunkinSound.playOnce(Paths.sound('scrollMenu'), 0.4);
// FlxG.sound.playMusic(Paths.inst(songs[curSelected].songName));
var prevSelected:Int = curSelected; var prevSelected:Int = curSelected;
@ -1170,15 +1176,25 @@ class FreeplayState extends MusicBeatSubState
{ {
if (curSelected == 0) if (curSelected == 0)
{ {
FlxG.sound.playMusic(Paths.music('freeplay/freeplayRandom'), 0); FunkinSound.playMusic('freeplayRandom',
{
startingVolume: 0.0,
overrideExisting: true,
restartTrack: true
});
FlxG.sound.music.fadeIn(2, 0, 0.8); FlxG.sound.music.fadeIn(2, 0, 0.8);
} }
else else
{ {
// TODO: Stream the instrumental of the selected song? // TODO: Stream the instrumental of the selected song?
if (prevSelected == 0) var didReplace:Bool = FunkinSound.playMusic('freakyMenu',
{
startingVolume: 0.0,
overrideExisting: true,
restartTrack: false
});
if (didReplace)
{ {
FunkinSound.playMusic('freakyMenu');
FlxG.sound.music.fadeIn(2, 0, 0.8); FlxG.sound.music.fadeIn(2, 0, 0.8);
} }
} }
@ -1214,8 +1230,8 @@ class DifficultySelector extends FlxSprite
override function update(elapsed:Float):Void override function update(elapsed:Float):Void
{ {
if (flipX && controls.UI_RIGHT_P) moveShitDown(); if (flipX && controls.UI_RIGHT_P && !FlxG.keys.pressed.CONTROL) moveShitDown();
if (!flipX && controls.UI_LEFT_P) moveShitDown(); if (!flipX && controls.UI_LEFT_P && !FlxG.keys.pressed.CONTROL) moveShitDown();
super.update(elapsed); super.update(elapsed);
} }

View file

@ -182,8 +182,6 @@ class SongMenuItem extends FlxSpriteGroup
{ {
var charPath:String = "freeplay/icons/"; var charPath:String = "freeplay/icons/";
trace(char);
// TODO: Put this in the character metadata where it belongs. // TODO: Put this in the character metadata where it belongs.
// TODO: Also, can use CharacterDataParser.getCharPixelIconAsset() // TODO: Also, can use CharacterDataParser.getCharPixelIconAsset()
switch (char) switch (char)

View file

@ -155,7 +155,11 @@ class MainMenuState extends MusicBeatState
function playMenuMusic():Void function playMenuMusic():Void
{ {
FunkinSound.playMusic('freakyMenu'); FunkinSound.playMusic('freakyMenu',
{
overrideExisting: true,
restartTrack: false
});
} }
function resetCamStuff() function resetCamStuff()
@ -321,7 +325,7 @@ class MainMenuState extends MusicBeatState
if (controls.BACK && menuItems.enabled && !menuItems.busy) if (controls.BACK && menuItems.enabled && !menuItems.busy)
{ {
FlxG.sound.play(Paths.sound('cancelMenu')); FunkinSound.playOnce(Paths.sound('cancelMenu'));
FlxG.switchState(() -> new TitleState()); FlxG.switchState(() -> new TitleState());
} }
} }

View file

@ -6,9 +6,11 @@ import flixel.FlxSubState;
import flixel.addons.transition.FlxTransitionableState; import flixel.addons.transition.FlxTransitionableState;
import flixel.group.FlxGroup; import flixel.group.FlxGroup;
import flixel.util.FlxSignal; import flixel.util.FlxSignal;
import funkin.audio.FunkinSound;
import funkin.ui.mainmenu.MainMenuState; import funkin.ui.mainmenu.MainMenuState;
import funkin.ui.MusicBeatState; import funkin.ui.MusicBeatState;
import funkin.util.WindowUtil; import funkin.util.WindowUtil;
import funkin.audio.FunkinSound;
import funkin.input.Controls; import funkin.input.Controls;
class OptionsState extends MusicBeatState class OptionsState extends MusicBeatState
@ -144,7 +146,7 @@ class Page extends FlxGroup
{ {
if (canExit && controls.BACK) if (canExit && controls.BACK)
{ {
FlxG.sound.play(Paths.sound('cancelMenu')); FunkinSound.playOnce(Paths.sound('cancelMenu'));
exit(); exit();
} }
} }

View file

@ -231,7 +231,11 @@ class StoryMenuState extends MusicBeatState
function playMenuMusic():Void function playMenuMusic():Void
{ {
FunkinSound.playMusic('freakyMenu'); FunkinSound.playMusic('freakyMenu',
{
overrideExisting: true,
restartTrack: false
});
} }
function updateData():Void function updateData():Void
@ -382,7 +386,7 @@ class StoryMenuState extends MusicBeatState
if (controls.BACK && !exitingMenu && !selectedLevel) if (controls.BACK && !exitingMenu && !selectedLevel)
{ {
FlxG.sound.play(Paths.sound('cancelMenu')); FunkinSound.playOnce(Paths.sound('cancelMenu'));
exitingMenu = true; exitingMenu = true;
FlxG.switchState(() -> new MainMenuState()); FlxG.switchState(() -> new MainMenuState());
} }
@ -434,6 +438,8 @@ class StoryMenuState extends MusicBeatState
} }
} }
FunkinSound.playOnce(Paths.sound('scrollMenu'), 0.4);
updateText(); updateText();
updateBackground(previousLevelId); updateBackground(previousLevelId);
updateProps(); updateProps();
@ -446,7 +452,11 @@ class StoryMenuState extends MusicBeatState
*/ */
function changeDifficulty(change:Int = 0):Void function changeDifficulty(change:Int = 0):Void
{ {
var difficultyList:Array<String> = currentLevel.getDifficulties(); // "For now, NO erect in story mode" -Dave
var difficultyList:Array<String> = Constants.DEFAULT_DIFFICULTY_LIST;
// Use this line to displays all difficulties
// var difficultyList:Array<String> = currentLevel.getDifficulties();
var currentIndex:Int = difficultyList.indexOf(currentDifficultyId); var currentIndex:Int = difficultyList.indexOf(currentDifficultyId);
currentIndex += change; currentIndex += change;
@ -473,6 +483,7 @@ class StoryMenuState extends MusicBeatState
if (hasChanged) if (hasChanged)
{ {
buildDifficultySprite(); buildDifficultySprite();
FunkinSound.playOnce(Paths.sound('scrollMenu'), 0.4);
// Disable the funny music thing for now. // Disable the funny music thing for now.
// funnyMusicThing(); // funnyMusicThing();
} }
@ -511,7 +522,7 @@ class StoryMenuState extends MusicBeatState
{ {
if (!currentLevel.isUnlocked()) if (!currentLevel.isUnlocked())
{ {
FlxG.sound.play(Paths.sound('cancelMenu')); FunkinSound.playOnce(Paths.sound('cancelMenu'));
return; return;
} }
@ -519,7 +530,7 @@ class StoryMenuState extends MusicBeatState
selectedLevel = true; selectedLevel = true;
FlxG.sound.play(Paths.sound('confirmMenu')); FunkinSound.playOnce(Paths.sound('confirmMenu'));
currentLevelTitle.isFlashing = true; currentLevelTitle.isFlashing = true;

View file

@ -22,7 +22,11 @@ class AttractState extends MusicBeatState
public override function create():Void public override function create():Void
{ {
// Pause existing music. // Pause existing music.
FlxG.sound.music.stop(); if (FlxG.sound.music != null)
{
FlxG.sound.music.destroy();
FlxG.sound.music = null;
}
#if html5 #if html5
playVideoHTML5(ATTRACT_VIDEO_PATH); playVideoHTML5(ATTRACT_VIDEO_PATH);

View file

@ -222,10 +222,14 @@ class TitleState extends MusicBeatState
{ {
var shouldFadeIn = (FlxG.sound.music == null); var shouldFadeIn = (FlxG.sound.music == null);
// Load music. Includes logic to handle BPM changes. // Load music. Includes logic to handle BPM changes.
FunkinSound.playMusic('freakyMenu', false, true); FunkinSound.playMusic('freakyMenu',
FlxG.sound.music.volume = 0; {
startingVolume: 0.0,
overrideExisting: true,
restartTrack: true
});
// Fade from 0.0 to 0.7 over 4 seconds // Fade from 0.0 to 0.7 over 4 seconds
if (shouldFadeIn) FlxG.sound.music.fadeIn(4, 0, 0.7); if (shouldFadeIn) FlxG.sound.music.fadeIn(4.0, 0.0, 0.7);
} }
function getIntroTextShit():Array<Array<String>> function getIntroTextShit():Array<Array<String>>
@ -323,7 +327,7 @@ class TitleState extends MusicBeatState
if (Date.now().getDay() == 5) NGio.unlockMedal(61034); if (Date.now().getDay() == 5) NGio.unlockMedal(61034);
titleText.animation.play('press'); titleText.animation.play('press');
FlxG.camera.flash(FlxColor.WHITE, 1); FlxG.camera.flash(FlxColor.WHITE, 1);
FlxG.sound.play(Paths.sound('confirmMenu'), 0.7); FunkinSound.playOnce(Paths.sound('confirmMenu'), 0.7);
transitioning = true; transitioning = true;
var targetState:NextState = () -> new MainMenuState(); var targetState:NextState = () -> new MainMenuState();
@ -338,7 +342,7 @@ class TitleState extends MusicBeatState
// ngSpr?? // ngSpr??
FlxG.switchState(targetState); FlxG.switchState(targetState);
}); });
// FlxG.sound.play(Paths.music('titleShoot'), 0.7); // FunkinSound.playOnce(Paths.music('titleShoot'), 0.7);
} }
if (pressedEnter && !skippedIntro && initialized) skipIntro(); if (pressedEnter && !skippedIntro && initialized) skipIntro();
@ -385,14 +389,12 @@ class TitleState extends MusicBeatState
{ {
cheatActive = true; cheatActive = true;
FlxG.sound.playMusic(Paths.music('tutorialTitle'), 1);
var spec:SpectogramSprite = new SpectogramSprite(FlxG.sound.music); var spec:SpectogramSprite = new SpectogramSprite(FlxG.sound.music);
add(spec); add(spec);
Conductor.instance.forceBPM(190); Conductor.instance.forceBPM(190);
FlxG.camera.flash(FlxColor.WHITE, 1); FlxG.camera.flash(FlxColor.WHITE, 1);
FlxG.sound.play(Paths.sound('confirmMenu'), 0.7); FunkinSound.playOnce(Paths.sound('confirmMenu'), 0.7);
} }
function createCoolText(textArray:Array<String>) function createCoolText(textArray:Array<String>)

View file

@ -171,7 +171,12 @@ class LoadingState extends MusicBeatState
function onLoad():Void function onLoad():Void
{ {
if (stopMusic && FlxG.sound.music != null) FlxG.sound.music.stop(); // Stop the instrumental.
if (stopMusic && FlxG.sound.music != null)
{
FlxG.sound.music.destroy();
FlxG.sound.music = null;
}
FlxG.switchState(target); FlxG.switchState(target);
} }
@ -200,7 +205,8 @@ class LoadingState extends MusicBeatState
// All assets preloaded, switch directly to play state (defualt on other targets). // All assets preloaded, switch directly to play state (defualt on other targets).
if (shouldStopMusic && FlxG.sound.music != null) if (shouldStopMusic && FlxG.sound.music != null)
{ {
FlxG.sound.music.stop(); FlxG.sound.music.destroy();
FlxG.sound.music = null;
} }
// Load and cache the song's charts. // Load and cache the song's charts.

View file

@ -18,6 +18,7 @@ import flixel.addons.transition.FlxTransitionableState;
import openfl.display.BitmapData; import openfl.display.BitmapData;
import funkin.ui.freeplay.FreeplayState; import funkin.ui.freeplay.FreeplayState;
import openfl.geom.Matrix; import openfl.geom.Matrix;
import funkin.audio.FunkinSound;
import openfl.display.Sprite; import openfl.display.Sprite;
import openfl.display.Bitmap; import openfl.display.Bitmap;
import flixel.FlxState; import flixel.FlxState;
@ -137,7 +138,7 @@ class StickerSubState extends MusicBeatSubState
new FlxTimer().start(sticker.timing, _ -> { new FlxTimer().start(sticker.timing, _ -> {
sticker.visible = false; sticker.visible = false;
var daSound:String = FlxG.random.getObject(sounds); var daSound:String = FlxG.random.getObject(sounds);
FlxG.sound.play(Paths.sound(daSound)); FunkinSound.playOnce(Paths.sound(daSound));
if (grpStickers == null || ind == grpStickers.members.length - 1) if (grpStickers == null || ind == grpStickers.members.length - 1)
{ {
@ -227,7 +228,7 @@ class StickerSubState extends MusicBeatSubState
sticker.visible = true; sticker.visible = true;
var daSound:String = FlxG.random.getObject(sounds); var daSound:String = FlxG.random.getObject(sounds);
FlxG.sound.play(Paths.sound(daSound)); FunkinSound.playOnce(Paths.sound(daSound));
var frameTimer:Int = FlxG.random.int(0, 2); var frameTimer:Int = FlxG.random.int(0, 2);

View file

@ -0,0 +1,994 @@
package funkin.ui.transition.preload;
import openfl.events.MouseEvent;
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.BlendMode;
import flash.display.Sprite;
import flash.Lib;
import flixel.system.FlxBasePreloader;
import funkin.modding.PolymodHandler;
import funkin.play.character.CharacterData.CharacterDataParser;
import funkin.util.MathUtil;
import lime.app.Future;
import lime.math.Rectangle;
import openfl.display.Sprite;
import openfl.text.TextField;
import openfl.text.TextFormat;
import openfl.text.TextFormatAlign;
using StringTools;
// Annotation embeds the asset in the executable for faster loading.
// Polymod can't override this, so we can't use this technique elsewhere.
@:bitmap("art/preloaderArt.png")
class LogoImage extends BitmapData {}
#if TOUCH_HERE_TO_PLAY
@:bitmap('art/touchHereToPlay.png')
class TouchHereToPlayImage extends BitmapData {}
#end
/**
* This preloader displays a logo while the game downloads assets.
*/
class FunkinPreloader extends FlxBasePreloader
{
/**
* The logo image width at the base resolution.
* Scaled up/down appropriately as needed.
*/
static final BASE_WIDTH:Float = 1280;
/**
* Margin at the sides and bottom, around the loading bar.
*/
static final BAR_PADDING:Float = 20;
static final BAR_HEIGHT:Int = 20;
/**
* Logo takes this long (in seconds) to fade in.
*/
static final LOGO_FADE_TIME:Float = 2.5;
// Ratio between window size and BASE_WIDTH
var ratio:Float = 0;
var currentState:FunkinPreloaderState = FunkinPreloaderState.NotStarted;
// private var downloadingAssetsStartTime:Float = -1;
private var downloadingAssetsPercent:Float = -1;
private var downloadingAssetsComplete:Bool = false;
private var preloadingPlayAssetsPercent:Float = -1;
private var preloadingPlayAssetsStartTime:Float = -1;
private var preloadingPlayAssetsComplete:Bool = false;
private var cachingGraphicsPercent:Float = -1;
private var cachingGraphicsStartTime:Float = -1;
private var cachingGraphicsComplete:Bool = false;
private var cachingAudioPercent:Float = -1;
private var cachingAudioStartTime:Float = -1;
private var cachingAudioComplete:Bool = false;
private var cachingDataPercent:Float = -1;
private var cachingDataStartTime:Float = -1;
private var cachingDataComplete:Bool = false;
private var parsingSpritesheetsPercent:Float = -1;
private var parsingSpritesheetsStartTime:Float = -1;
private var parsingSpritesheetsComplete:Bool = false;
private var parsingStagesPercent:Float = -1;
private var parsingStagesStartTime:Float = -1;
private var parsingStagesComplete:Bool = false;
private var parsingCharactersPercent:Float = -1;
private var parsingCharactersStartTime:Float = -1;
private var parsingCharactersComplete:Bool = false;
private var parsingSongsPercent:Float = -1;
private var parsingSongsStartTime:Float = -1;
private var parsingSongsComplete:Bool = false;
private var initializingScriptsPercent:Float = -1;
private var cachingCoreAssetsPercent:Float = -1;
/**
* The timestamp when the other steps completed and the `Finishing up` step started.
*/
private var completeTime:Float = -1;
// Graphics
var logo:Bitmap;
#if TOUCH_HERE_TO_PLAY
var touchHereToPlay:Bitmap;
#end
var progressBar:Bitmap;
var progressLeftText:TextField;
var progressRightText:TextField;
public function new()
{
super(Constants.PRELOADER_MIN_STAGE_TIME, Constants.SITE_LOCK);
// We can't even call trace() yet, until Flixel loads.
trace('Initializing custom preloader...');
this.siteLockTitleText = Constants.SITE_LOCK_TITLE;
this.siteLockBodyText = Constants.SITE_LOCK_DESC;
}
override function create():Void
{
// Nothing happens in the base preloader.
super.create();
// Background color.
Lib.current.stage.color = Constants.COLOR_PRELOADER_BG;
// Width and height of the preloader.
this._width = Lib.current.stage.stageWidth;
this._height = Lib.current.stage.stageHeight;
// Scale assets to the screen size.
ratio = this._width / BASE_WIDTH / 2.0;
// Create the logo.
logo = createBitmap(LogoImage, function(bmp:Bitmap) {
// Scale and center the logo.
// We have to do this inside the async call, after the image size is known.
bmp.scaleX = bmp.scaleY = ratio;
bmp.x = (this._width - bmp.width) / 2;
bmp.y = (this._height - bmp.height) / 2;
});
addChild(logo);
#if TOUCH_HERE_TO_PLAY
touchHereToPlay = createBitmap(TouchHereToPlayImage, function(bmp:Bitmap) {
// Scale and center the touch to start image.
// We have to do this inside the async call, after the image size is known.
bmp.scaleX = bmp.scaleY = ratio;
bmp.x = (this._width - bmp.width) / 2;
bmp.y = (this._height - bmp.height) / 2;
});
touchHereToPlay.alpha = 0.0;
addChild(touchHereToPlay);
#end
// Create the progress bar.
progressBar = new Bitmap(new BitmapData(1, BAR_HEIGHT, true, Constants.COLOR_PRELOADER_BAR));
progressBar.x = BAR_PADDING;
progressBar.y = this._height - BAR_PADDING - BAR_HEIGHT;
addChild(progressBar);
// Create the progress message.
progressLeftText = new TextField();
var progressLeftTextFormat = new TextFormat("VCR OSD Mono", 16, Constants.COLOR_PRELOADER_BAR, true);
progressLeftTextFormat.align = TextFormatAlign.LEFT;
progressLeftText.defaultTextFormat = progressLeftTextFormat;
progressLeftText.selectable = false;
progressLeftText.width = this._width - BAR_PADDING * 2;
progressLeftText.text = 'Downloading assets...';
progressLeftText.x = BAR_PADDING;
progressLeftText.y = this._height - BAR_PADDING - BAR_HEIGHT - 16 - 4;
addChild(progressLeftText);
// Create the progress %.
progressRightText = new TextField();
var progressRightTextFormat = new TextFormat("VCR OSD Mono", 16, Constants.COLOR_PRELOADER_BAR, true);
progressRightTextFormat.align = TextFormatAlign.RIGHT;
progressRightText.defaultTextFormat = progressRightTextFormat;
progressRightText.selectable = false;
progressRightText.width = this._width - BAR_PADDING * 2;
progressRightText.text = '0%';
progressRightText.x = BAR_PADDING;
progressRightText.y = this._height - BAR_PADDING - BAR_HEIGHT - 16 - 4;
addChild(progressRightText);
}
var lastElapsed:Float = 0.0;
override function update(percent:Float):Void
{
var elapsed:Float = (Date.now().getTime() - this._startTime) / 1000.0;
// trace('Time since last frame: ' + (lastElapsed - elapsed));
downloadingAssetsPercent = percent;
var loadPercent:Float = updateState(percent, elapsed);
updateGraphics(loadPercent, elapsed);
lastElapsed = elapsed;
}
function updateState(percent:Float, elapsed:Float):Float
{
switch (currentState)
{
case FunkinPreloaderState.NotStarted:
if (downloadingAssetsPercent > 0.0) currentState = FunkinPreloaderState.DownloadingAssets;
return percent;
case FunkinPreloaderState.DownloadingAssets:
// Sometimes percent doesn't go to 100%, it's a floating point error.
if (downloadingAssetsPercent >= 1.0
|| (elapsed > Constants.PRELOADER_MIN_STAGE_TIME
&& downloadingAssetsComplete)) currentState = FunkinPreloaderState.PreloadingPlayAssets;
return percent;
case FunkinPreloaderState.PreloadingPlayAssets:
if (preloadingPlayAssetsPercent < 0.0)
{
preloadingPlayAssetsStartTime = elapsed;
preloadingPlayAssetsPercent = 0.0;
// This is quick enough to do synchronously.
// Assets.initialize();
/*
// Make a future to retrieve the manifest
var future:Future<lime.utils.AssetLibrary> = Assets.preloadLibrary('gameplay');
future.onProgress((loaded:Int, total:Int) -> {
preloadingPlayAssetsPercent = loaded / total;
});
future.onComplete((library:lime.utils.AssetLibrary) -> {
});
*/
// TODO: Reimplement this.
preloadingPlayAssetsPercent = 1.0;
preloadingPlayAssetsComplete = true;
return 0.0;
}
else if (Constants.PRELOADER_MIN_STAGE_TIME > 0)
{
var elapsedPreloadingPlayAssets:Float = elapsed - preloadingPlayAssetsStartTime;
if (preloadingPlayAssetsComplete && elapsedPreloadingPlayAssets >= Constants.PRELOADER_MIN_STAGE_TIME)
{
currentState = FunkinPreloaderState.InitializingScripts;
return 0.0;
}
else
{
// We need to return SIMULATED progress here.
if (preloadingPlayAssetsPercent < (elapsedPreloadingPlayAssets / Constants.PRELOADER_MIN_STAGE_TIME)) return preloadingPlayAssetsPercent;
else
return elapsedPreloadingPlayAssets / Constants.PRELOADER_MIN_STAGE_TIME;
}
}
else
{
if (preloadingPlayAssetsComplete) currentState = FunkinPreloaderState.InitializingScripts;
}
return preloadingPlayAssetsPercent;
case FunkinPreloaderState.InitializingScripts:
if (initializingScriptsPercent < 0.0)
{
initializingScriptsPercent = 0.0;
/*
var future:Future<Array<String>> = []; // PolymodHandler.loadNoModsAsync();
future.onProgress((loaded:Int, total:Int) -> {
trace('PolymodHandler.loadNoModsAsync() progress: ' + loaded + '/' + total);
initializingScriptsPercent = loaded / total;
});
future.onComplete((result:Array<String>) -> {
trace('Completed initializing scripts: ' + result);
});
*/
initializingScriptsPercent = 1.0;
currentState = FunkinPreloaderState.CachingGraphics;
return 0.0;
}
return initializingScriptsPercent;
case CachingGraphics:
if (cachingGraphicsPercent < 0)
{
cachingGraphicsPercent = 0.0;
cachingGraphicsStartTime = elapsed;
/*
var assetsToCache:Array<String> = []; // Assets.listGraphics('core');
var future:Future<Array<String>> = []; // Assets.cacheAssets(assetsToCache);
future.onProgress((loaded:Int, total:Int) -> {
cachingGraphicsPercent = loaded / total;
});
future.onComplete((_result) -> {
trace('Completed caching graphics.');
});
*/
// TODO: Reimplement this.
cachingGraphicsPercent = 1.0;
cachingGraphicsComplete = true;
return 0.0;
}
else if (Constants.PRELOADER_MIN_STAGE_TIME > 0)
{
var elapsedCachingGraphics:Float = elapsed - cachingGraphicsStartTime;
if (cachingGraphicsComplete && elapsedCachingGraphics >= Constants.PRELOADER_MIN_STAGE_TIME)
{
currentState = FunkinPreloaderState.CachingAudio;
return 0.0;
}
else
{
if (cachingGraphicsPercent < (elapsedCachingGraphics / Constants.PRELOADER_MIN_STAGE_TIME))
{
// Return real progress if it's lower.
return cachingGraphicsPercent;
}
else
{
// Return simulated progress if it's higher.
return elapsedCachingGraphics / Constants.PRELOADER_MIN_STAGE_TIME;
}
}
}
else
{
if (cachingGraphicsComplete)
{
currentState = FunkinPreloaderState.CachingAudio;
return 0.0;
}
else
{
return cachingGraphicsPercent;
}
}
case CachingAudio:
if (cachingAudioPercent < 0)
{
cachingAudioPercent = 0.0;
cachingAudioStartTime = elapsed;
var assetsToCache:Array<String> = []; // Assets.listSound('core');
/*
var future:Future<Array<String>> = []; // Assets.cacheAssets(assetsToCache);
future.onProgress((loaded:Int, total:Int) -> {
cachingAudioPercent = loaded / total;
});
future.onComplete((_result) -> {
trace('Completed caching audio.');
});
*/
// TODO: Reimplement this.
cachingAudioPercent = 1.0;
cachingAudioComplete = true;
return 0.0;
}
else if (Constants.PRELOADER_MIN_STAGE_TIME > 0)
{
var elapsedCachingAudio:Float = elapsed - cachingAudioStartTime;
if (cachingAudioComplete && elapsedCachingAudio >= Constants.PRELOADER_MIN_STAGE_TIME)
{
currentState = FunkinPreloaderState.CachingData;
return 0.0;
}
else
{
// We need to return SIMULATED progress here.
if (cachingAudioPercent < (elapsedCachingAudio / Constants.PRELOADER_MIN_STAGE_TIME))
{
return cachingAudioPercent;
}
else
{
return elapsedCachingAudio / Constants.PRELOADER_MIN_STAGE_TIME;
}
}
}
else
{
if (cachingAudioComplete)
{
currentState = FunkinPreloaderState.CachingData;
return 0.0;
}
else
{
return cachingAudioPercent;
}
}
case CachingData:
if (cachingDataPercent < 0)
{
cachingDataPercent = 0.0;
cachingDataStartTime = elapsed;
var assetsToCache:Array<String> = [];
var sparrowFramesToCache:Array<String> = [];
// Core files
// assetsToCache = assetsToCache.concat(Assets.listText('core'));
// assetsToCache = assetsToCache.concat(Assets.listJSON('core'));
// Core spritesheets
// assetsToCache = assetsToCache.concat(Assets.listXML('core'));
// Gameplay files
// assetsToCache = assetsToCache.concat(Assets.listText('gameplay'));
// assetsToCache = assetsToCache.concat(Assets.listJSON('gameplay'));
// We're not caching gameplay spritesheets here because they're fetched on demand.
/*
var future:Future<Array<String>> = [];
// Assets.cacheAssets(assetsToCache, true);
future.onProgress((loaded:Int, total:Int) -> {
cachingDataPercent = loaded / total;
});
future.onComplete((_result) -> {
trace('Completed caching data.');
});
*/
cachingDataPercent = 1.0;
cachingDataComplete = true;
return 0.0;
}
else if (Constants.PRELOADER_MIN_STAGE_TIME > 0)
{
var elapsedCachingData:Float = elapsed - cachingDataStartTime;
if (cachingDataComplete && elapsedCachingData >= Constants.PRELOADER_MIN_STAGE_TIME)
{
currentState = FunkinPreloaderState.ParsingSpritesheets;
return 0.0;
}
else
{
// We need to return SIMULATED progress here.
if (cachingDataPercent < (elapsedCachingData / Constants.PRELOADER_MIN_STAGE_TIME)) return cachingDataPercent;
else
return elapsedCachingData / Constants.PRELOADER_MIN_STAGE_TIME;
}
}
else
{
if (cachingDataComplete)
{
currentState = FunkinPreloaderState.ParsingSpritesheets;
return 0.0;
}
}
return cachingDataPercent;
case ParsingSpritesheets:
if (parsingSpritesheetsPercent < 0)
{
parsingSpritesheetsPercent = 0.0;
parsingSpritesheetsStartTime = elapsed;
// Core spritesheets
var sparrowFramesToCache = []; // Assets.listXML('core').map((xml:String) -> xml.replace('.xml', '').replace('core:assets/core/', ''));
// We're not caching gameplay spritesheets here because they're fetched on demand.
/*
var future:Future<Array<String>> = []; // Assets.cacheSparrowFrames(sparrowFramesToCache, true);
future.onProgress((loaded:Int, total:Int) -> {
parsingSpritesheetsPercent = loaded / total;
});
future.onComplete((_result) -> {
trace('Completed parsing spritesheets.');
});
*/
parsingSpritesheetsPercent = 1.0;
parsingSpritesheetsComplete = true;
return 0.0;
}
else if (Constants.PRELOADER_MIN_STAGE_TIME > 0)
{
var elapsedParsingSpritesheets:Float = elapsed - parsingSpritesheetsStartTime;
if (parsingSpritesheetsComplete && elapsedParsingSpritesheets >= Constants.PRELOADER_MIN_STAGE_TIME)
{
currentState = FunkinPreloaderState.ParsingStages;
return 0.0;
}
else
{
// We need to return SIMULATED progress here.
if (parsingSpritesheetsPercent < (elapsedParsingSpritesheets / Constants.PRELOADER_MIN_STAGE_TIME)) return parsingSpritesheetsPercent;
else
return elapsedParsingSpritesheets / Constants.PRELOADER_MIN_STAGE_TIME;
}
}
else
{
if (parsingSpritesheetsComplete)
{
currentState = FunkinPreloaderState.ParsingStages;
return 0.0;
}
}
return parsingSpritesheetsPercent;
case ParsingStages:
if (parsingStagesPercent < 0)
{
parsingStagesPercent = 0.0;
parsingStagesStartTime = elapsed;
/*
// TODO: Reimplement this.
var future:Future<Array<String>> = []; // StageDataParser.loadStageCacheAsync();
future.onProgress((loaded:Int, total:Int) -> {
parsingStagesPercent = loaded / total;
});
future.onComplete((_result) -> {
trace('Completed parsing stages.');
});
*/
parsingStagesPercent = 1.0;
parsingStagesComplete = true;
return 0.0;
}
else if (Constants.PRELOADER_MIN_STAGE_TIME > 0)
{
var elapsedParsingStages:Float = elapsed - parsingStagesStartTime;
if (parsingStagesComplete && elapsedParsingStages >= Constants.PRELOADER_MIN_STAGE_TIME)
{
currentState = FunkinPreloaderState.ParsingCharacters;
return 0.0;
}
else
{
// We need to return SIMULATED progress here.
if (parsingStagesPercent < (elapsedParsingStages / Constants.PRELOADER_MIN_STAGE_TIME)) return parsingStagesPercent;
else
return elapsedParsingStages / Constants.PRELOADER_MIN_STAGE_TIME;
}
}
else
{
if (parsingStagesComplete)
{
currentState = FunkinPreloaderState.ParsingCharacters;
return 0.0;
}
}
return parsingStagesPercent;
case ParsingCharacters:
if (parsingCharactersPercent < 0)
{
parsingCharactersPercent = 0.0;
parsingCharactersStartTime = elapsed;
/*
// TODO: Reimplement this.
var future:Future<Array<String>> = []; // CharacterDataParser.loadCharacterCacheAsync();
future.onProgress((loaded:Int, total:Int) -> {
parsingCharactersPercent = loaded / total;
});
future.onComplete((_result) -> {
trace('Completed parsing characters.');
});
*/
parsingCharactersPercent = 1.0;
parsingCharactersComplete = true;
return 0.0;
}
else if (Constants.PRELOADER_MIN_STAGE_TIME > 0)
{
var elapsedParsingCharacters:Float = elapsed - parsingCharactersStartTime;
if (parsingCharactersComplete && elapsedParsingCharacters >= Constants.PRELOADER_MIN_STAGE_TIME)
{
currentState = FunkinPreloaderState.ParsingSongs;
return 0.0;
}
else
{
// We need to return SIMULATED progress here.
if (parsingCharactersPercent < (elapsedParsingCharacters / Constants.PRELOADER_MIN_STAGE_TIME)) return parsingCharactersPercent;
else
return elapsedParsingCharacters / Constants.PRELOADER_MIN_STAGE_TIME;
}
}
else
{
if (parsingStagesComplete)
{
currentState = FunkinPreloaderState.ParsingSongs;
return 0.0;
}
}
return parsingCharactersPercent;
case ParsingSongs:
if (parsingSongsPercent < 0)
{
parsingSongsPercent = 0.0;
parsingSongsStartTime = elapsed;
/*
// TODO: Reimplement this.
var future:Future<Array<String>> = ;
// SongDataParser.loadSongCacheAsync();
future.onProgress((loaded:Int, total:Int) -> {
parsingSongsPercent = loaded / total;
});
future.onComplete((_result) -> {
trace('Completed parsing songs.');
});
*/
parsingSongsPercent = 1.0;
parsingSongsComplete = true;
return 0.0;
}
else if (Constants.PRELOADER_MIN_STAGE_TIME > 0)
{
var elapsedParsingSongs:Float = elapsed - parsingSongsStartTime;
if (parsingSongsComplete && elapsedParsingSongs >= Constants.PRELOADER_MIN_STAGE_TIME)
{
currentState = FunkinPreloaderState.Complete;
return 0.0;
}
else
{
// We need to return SIMULATED progress here.
if (parsingSongsPercent < (elapsedParsingSongs / Constants.PRELOADER_MIN_STAGE_TIME))
{
return parsingSongsPercent;
}
else
{
return elapsedParsingSongs / Constants.PRELOADER_MIN_STAGE_TIME;
}
}
}
else
{
if (parsingSongsComplete)
{
currentState = FunkinPreloaderState.Complete;
return 0.0;
}
else
{
return parsingSongsPercent;
}
}
case FunkinPreloaderState.Complete:
if (completeTime < 0)
{
completeTime = elapsed;
}
return 1.0;
#if TOUCH_HERE_TO_PLAY
case FunkinPreloaderState.TouchHereToPlay:
if (completeTime < 0)
{
completeTime = elapsed;
}
if (touchHereToPlay.alpha < 1.0)
{
touchHereToPlay.alpha = 1.0;
addEventListener(MouseEvent.CLICK, onTouchHereToPlay);
}
return 1.0;
#end
default:
// Do nothing.
}
return 0.0;
}
#if TOUCH_HERE_TO_PLAY
function onTouchHereToPlay(e:MouseEvent):Void
{
removeEventListener(MouseEvent.CLICK, onTouchHereToPlay);
// This is the actual thing that makes the game load.
immediatelyStartGame();
}
#end
static final TOTAL_STEPS:Int = 11;
static final ELLIPSIS_TIME:Float = 0.5;
function updateGraphics(percent:Float, elapsed:Float):Void
{
// Render logo (including transitions)
if (completeTime > 0.0)
{
var elapsedFinished:Float = renderLogoFadeOut(elapsed);
// trace('Fading out logo... (' + elapsedFinished + 's)');
if (elapsedFinished > LOGO_FADE_TIME)
{
#if TOUCH_HERE_TO_PLAY
// The logo has faded out, but we're not quite done yet.
// In order to prevent autoplay issues, we need the user to click after the loading finishes.
currentState = FunkinPreloaderState.TouchHereToPlay;
#else
immediatelyStartGame();
#end
}
}
else
{
renderLogoFadeIn(elapsed);
}
// Render progress bar
var maxWidth = this._width - BAR_PADDING * 2;
var barWidth = maxWidth * percent;
progressBar.width = barWidth;
// Cycle ellipsis count to show loading
var ellipsisCount:Int = Std.int(elapsed / ELLIPSIS_TIME) % 3 + 1;
var ellipsis:String = '';
for (i in 0...ellipsisCount)
ellipsis += '.';
// Render status text
switch (currentState)
{
// case FunkinPreloaderState.NotStarted:
default:
updateProgressLeftText('Loading (0/$TOTAL_STEPS)$ellipsis');
case FunkinPreloaderState.DownloadingAssets:
updateProgressLeftText('Downloading assets (1/$TOTAL_STEPS)$ellipsis');
case FunkinPreloaderState.PreloadingPlayAssets:
updateProgressLeftText('Preloading assets (2/$TOTAL_STEPS)$ellipsis');
case FunkinPreloaderState.InitializingScripts:
updateProgressLeftText('Initializing scripts (3/$TOTAL_STEPS)$ellipsis');
case FunkinPreloaderState.CachingGraphics:
updateProgressLeftText('Caching graphics (4/$TOTAL_STEPS)$ellipsis');
case FunkinPreloaderState.CachingAudio:
updateProgressLeftText('Caching audio (5/$TOTAL_STEPS)$ellipsis');
case FunkinPreloaderState.CachingData:
updateProgressLeftText('Caching data (6/$TOTAL_STEPS)$ellipsis');
case FunkinPreloaderState.ParsingSpritesheets:
updateProgressLeftText('Parsing spritesheets (7/$TOTAL_STEPS)$ellipsis');
case FunkinPreloaderState.ParsingStages:
updateProgressLeftText('Parsing stages (8/$TOTAL_STEPS)$ellipsis');
case FunkinPreloaderState.ParsingCharacters:
updateProgressLeftText('Parsing characters (9/$TOTAL_STEPS)$ellipsis');
case FunkinPreloaderState.ParsingSongs:
updateProgressLeftText('Parsing songs (10/$TOTAL_STEPS)$ellipsis');
case FunkinPreloaderState.Complete:
updateProgressLeftText('Finishing up ($TOTAL_STEPS/$TOTAL_STEPS)$ellipsis');
#if TOUCH_HERE_TO_PLAY
case FunkinPreloaderState.TouchHereToPlay:
updateProgressLeftText(null);
#end
}
var percentage:Int = Math.floor(percent * 100);
trace('Preloader state: ' + currentState + ' (' + percentage + '%, ' + elapsed + 's)');
// Render percent text
progressRightText.text = '$percentage%';
super.update(percent);
}
function updateProgressLeftText(text:Null<String>):Void
{
if (progressLeftText != null)
{
if (text == null)
{
progressLeftText.alpha = 0.0;
}
else if (progressLeftText.text != text)
{
// We have to keep updating the text format, because the font can take a frame or two to load.
var progressLeftTextFormat = new TextFormat("VCR OSD Mono", 16, Constants.COLOR_PRELOADER_BAR, true);
progressLeftTextFormat.align = TextFormatAlign.LEFT;
progressLeftText.defaultTextFormat = progressLeftTextFormat;
progressLeftText.text = text;
}
}
}
function immediatelyStartGame():Void
{
_loaded = true;
}
/**
* Fade out the logo.
* @param elapsed Elapsed time since the preloader started.
* @return Elapsed time since the logo started fading out.
*/
function renderLogoFadeOut(elapsed:Float):Float
{
// Fade-out takes LOGO_FADE_TIME seconds.
var elapsedFinished = elapsed - completeTime;
logo.alpha = 1.0 - MathUtil.easeInOutCirc(elapsedFinished / LOGO_FADE_TIME);
logo.scaleX = (1.0 - MathUtil.easeInBack(elapsedFinished / LOGO_FADE_TIME)) * ratio;
logo.scaleY = (1.0 - MathUtil.easeInBack(elapsedFinished / LOGO_FADE_TIME)) * ratio;
logo.x = (this._width - logo.width) / 2;
logo.y = (this._height - logo.height) / 2;
// Fade out progress bar too.
progressBar.alpha = logo.alpha;
progressLeftText.alpha = logo.alpha;
progressRightText.alpha = logo.alpha;
return elapsedFinished;
}
function renderLogoFadeIn(elapsed:Float):Void
{
// Fade-in takes LOGO_FADE_TIME seconds.
logo.alpha = MathUtil.easeInOutCirc(elapsed / LOGO_FADE_TIME);
logo.scaleX = MathUtil.easeOutBack(elapsed / LOGO_FADE_TIME) * ratio;
logo.scaleY = MathUtil.easeOutBack(elapsed / LOGO_FADE_TIME) * ratio;
logo.x = (this._width - logo.width) / 2;
logo.y = (this._height - logo.height) / 2;
}
#if html5
// These fields only exist on Web builds.
/**
* Format the layout of the site lock screen.
*/
override function createSiteLockFailureScreen():Void
{
addChild(createSiteLockFailureBackground(Constants.COLOR_PRELOADER_LOCK_BG, Constants.COLOR_PRELOADER_LOCK_BG));
addChild(createSiteLockFailureIcon(Constants.COLOR_PRELOADER_LOCK_FG, 0.9));
addChild(createSiteLockFailureText(30));
}
/**
* Format the text of the site lock screen.
*/
override function adjustSiteLockTextFields(titleText:TextField, bodyText:TextField, hyperlinkText:TextField):Void
{
var titleFormat = titleText.defaultTextFormat;
titleFormat.align = TextFormatAlign.CENTER;
titleFormat.color = Constants.COLOR_PRELOADER_LOCK_FONT;
titleText.setTextFormat(titleFormat);
var bodyFormat = bodyText.defaultTextFormat;
bodyFormat.align = TextFormatAlign.CENTER;
bodyFormat.color = Constants.COLOR_PRELOADER_LOCK_FONT;
bodyText.setTextFormat(bodyFormat);
var hyperlinkFormat = hyperlinkText.defaultTextFormat;
hyperlinkFormat.align = TextFormatAlign.CENTER;
hyperlinkFormat.color = Constants.COLOR_PRELOADER_LOCK_LINK;
hyperlinkText.setTextFormat(hyperlinkFormat);
}
#end
override function destroy():Void
{
// Ensure the graphics are properly destroyed and GC'd.
removeChild(logo);
removeChild(progressBar);
logo = progressBar = null;
super.destroy();
}
override function onLoaded():Void
{
super.onLoaded();
// We're not ACTUALLY finished.
// This function gets called when the DownloadingAssets step is done.
// We need to wait for the other steps, then the logo to fade out.
_loaded = false;
downloadingAssetsComplete = true;
}
}
enum FunkinPreloaderState
{
/**
* The state before downloading has begun.
* Moves to either `DownloadingAssets` or `CachingGraphics` based on platform.
*/
NotStarted;
/**
* Downloading assets.
* On HTML5, Lime will do this for us, before calling `onLoaded`.
* On Desktop, this step will be completed immediately, and we'll go straight to `CachingGraphics`.
*/
DownloadingAssets;
/**
* Preloading play assets.
* Loads the `manifest.json` for the `gameplay` library.
* If we make the base preloader do this, it will download all the assets as well,
* so we have to do it ourselves.
*/
PreloadingPlayAssets;
/**
* Loading FireTongue, loading Polymod, parsing and instantiating module scripts.
*/
InitializingScripts;
/**
* Loading all graphics from the `core` library to the cache.
*/
CachingGraphics;
/**
* Loading all audio from the `core` library to the cache.
*/
CachingAudio;
/**
* Loading all data files from the `core` library to the cache.
*/
CachingData;
/**
* Parsing all XML files from the `core` library into FlxFramesCollections and caching them.
*/
ParsingSpritesheets;
/**
* Parsing stage data and scripts.
*/
ParsingStages;
/**
* Parsing character data and scripts.
*/
ParsingCharacters;
/**
* Parsing song data and scripts.
*/
ParsingSongs;
/**
* Finishing up.
*/
Complete;
#if TOUCH_HERE_TO_PLAY
/**
* Touch Here to Play is displayed.
*/
TouchHereToPlay;
#end
}

View file

@ -0,0 +1,17 @@
# funkin.ui.loading.preload
This package contains code powering the HTML5 preloader screen.
The preloader performs the following tasks:
- **Downloading assets**: Downloads the `core` asset library and loads its manifest
- **Preloading play assets**: Downloads the `gameplay` asset library (manifest only)
- **Initializing scripts**: Downloads and registers stage scripts, character scripts, song scripts, and module scripts.
- **Caching graphics**: Downloads all graphics from the `core` asset library, uploads them to the GPU, then dumps them from RAM. This prepares them to be used very quickly in-game.
- **Caching audio**: Downloads all audio files from the `core` asset library, and caches them. This prepares them to be used very quickly in-game.
- **Caching data**: Downloads and caches all TXT files, all JSON files (it also parses them), and XML files (from the `core` library only). This prepares them to be used in the next steps.
- **Parsing stages**: Parses all stage data and instantiates associated stage scripts. This prepares them to be used in-game.
- **Parsing characters**: Parses all character data and instantiates associated character scripts. This prepares them to be used in-game.
- **Parsing songs**: Parses all song data and instantiates associated song scripts. This prepares them to be used in-game.
- **Finishing up**: Waits for the screen to fade out. Then, it loads the first state of the app.
Due to the first few steps not being relevant on desktop, and due to this preloader being built in Lime rather than HaxeFlixel because of how Lime handles asset loading, this preloader is not used on desktop. The splash loader is used instead.

View file

@ -1,8 +1,9 @@
package funkin.util; package funkin.util;
import flixel.system.FlxBasePreloader;
import flixel.util.FlxColor; import flixel.util.FlxColor;
import lime.app.Application;
import funkin.data.song.SongData.SongTimeFormat; import funkin.data.song.SongData.SongTimeFormat;
import lime.app.Application;
/** /**
* A store of unchanging, globally relevant values. * A store of unchanging, globally relevant values.
@ -59,6 +60,16 @@ class Constants
*/ */
// ============================== // ==============================
/**
* Preloader sitelock.
* Matching is done by `FlxStringUtil.getDomain`, so any URL on the domain will work.
* The first link in this list is the one users will be redirected to if they try to access the game from a different URL.
*/
public static final SITE_LOCK:Array<String> = [
"https://www.newgrounds.com/portal/view/770371", // Newgrounds, baybee!
FlxBasePreloader.LOCAL // localhost for dev stuff
];
/** /**
* Link to download the game on Itch.io. * Link to download the game on Itch.io.
*/ */
@ -116,6 +127,44 @@ class Constants
0xFFCC1111 // right (3) 0xFFCC1111 // right (3)
]; ];
/**
* Color for the preloader background
*/
public static final COLOR_PRELOADER_BG:FlxColor = 0xFF000000;
/**
* Color for the preloader progress bar
*/
public static final COLOR_PRELOADER_BAR:FlxColor = 0xFF00FF00;
/**
* Color for the preloader site lock background
*/
public static final COLOR_PRELOADER_LOCK_BG:FlxColor = 0xFF1B1717;
/**
* Color for the preloader site lock foreground
*/
public static final COLOR_PRELOADER_LOCK_FG:FlxColor = 0xB96F10;
/**
* Color for the preloader site lock text
*/
public static final COLOR_PRELOADER_LOCK_FONT:FlxColor = 0xCCCCCC;
/**
* Color for the preloader site lock link
*/
public static final COLOR_PRELOADER_LOCK_LINK:FlxColor = 0xEEB211;
/**
* LANGUAGE
*/
// ==============================
public static final SITE_LOCK_TITLE:String = "You Loser!";
public static final SITE_LOCK_DESC:String = "This isn't Newgrounds!\nGo play Friday Night Funkin' on Newgrounds:";
/** /**
* GAME DEFAULTS * GAME DEFAULTS
*/ */
@ -157,6 +206,11 @@ class Constants
*/ */
public static final DEFAULT_VARIATION:String = 'default'; public static final DEFAULT_VARIATION:String = 'default';
/**
* Standard variations used by the game.
*/
public static final DEFAULT_VARIATION_LIST:Array<String> = ['default', 'erect', 'pico'];
/** /**
* The default intensity for camera zooms. * The default intensity for camera zooms.
*/ */
@ -286,6 +340,19 @@ class Constants
*/ */
public static final MP3_DELAY_MS:Float = 528 / 44100 * Constants.MS_PER_SEC; public static final MP3_DELAY_MS:Float = 528 / 44100 * Constants.MS_PER_SEC;
/**
* Each step of the preloader has to be on screen at least this long.
*
* 0 = The preloader immediately moves to the next step when it's ready.
* 1 = The preloader waits for 1 second before moving to the next step.
* The progress bare is automatically rescaled to match.
*/
#if debug
public static final PRELOADER_MIN_STAGE_TIME:Float = 1.0;
#else
public static final PRELOADER_MIN_STAGE_TIME:Float = 0.1;
#end
/** /**
* HEALTH VALUES * HEALTH VALUES
*/ */

View file

@ -19,6 +19,7 @@ class MathUtil
* *
* @return The interpolated value. * @return The interpolated value.
*/ */
@:deprecated('Use smoothLerp instead')
public static function coolLerp(base:Float, target:Float, ratio:Float):Float public static function coolLerp(base:Float, target:Float, ratio:Float):Float
{ {
return base + cameraLerp(ratio) * (target - base); return base + cameraLerp(ratio) * (target - base);
@ -47,6 +48,36 @@ class MathUtil
return Math.log(value) / Math.log(base); return Math.log(value) / Math.log(base);
} }
public static function easeInOutCirc(x:Float):Float
{
if (x <= 0.0) return 0.0;
if (x >= 1.0) return 1.0;
var result:Float = (x < 0.5) ? (1 - Math.sqrt(1 - 4 * x * x)) / 2 : (Math.sqrt(1 - 4 * (1 - x) * (1 - x)) + 1) / 2;
return (result == Math.NaN) ? 1.0 : result;
}
public static function easeInOutBack(x:Float, ?c:Float = 1.70158):Float
{
if (x <= 0.0) return 0.0;
if (x >= 1.0) return 1.0;
var result:Float = (x < 0.5) ? (2 * x * x * ((c + 1) * 2 * x - c)) / 2 : (1 - 2 * (1 - x) * (1 - x) * ((c + 1) * 2 * (1 - x) - c)) / 2;
return (result == Math.NaN) ? 1.0 : result;
}
public static function easeInBack(x:Float, ?c:Float = 1.70158):Float
{
if (x <= 0.0) return 0.0;
if (x >= 1.0) return 1.0;
return (1 + c) * x * x * x - c * x * x;
}
public static function easeOutBack(x:Float, ?c:Float = 1.70158):Float
{
if (x <= 0.0) return 0.0;
if (x >= 1.0) return 1.0;
return 1 + (c + 1) * Math.pow(x - 1, 3) + c * Math.pow(x - 1, 2);
}
/** /**
* Get the base-2 logarithm of a value. * Get the base-2 logarithm of a value.
* @param x value * @param x value

View file

@ -174,7 +174,7 @@ class ScreenshotPlugin extends FlxBasic
FlxTween.tween(flashSpr, {alpha: 0}, 0.15, {ease: FlxEase.quadOut, onComplete: _ -> FlxG.stage.removeChild(flashSpr)}); FlxTween.tween(flashSpr, {alpha: 0}, 0.15, {ease: FlxEase.quadOut, onComplete: _ -> FlxG.stage.removeChild(flashSpr)});
// Play a sound (auto-play is true). // Play a sound (auto-play is true).
FunkinSound.load(Paths.sound('screenshot'), 1.0, false, true, true); FunkinSound.playOnce(Paths.sound('screenshot'), 1.0);
} }
static final PREVIEW_INITIAL_DELAY = 0.25; // How long before the preview starts fading in. static final PREVIEW_INITIAL_DELAY = 0.25; // How long before the preview starts fading in.