Remove redundant node lookups

This commit is contained in:
Luke Hubmayer-Werner 2020-05-02 16:09:51 +09:30
parent 2442d5b6bd
commit 8facf97440
4 changed files with 107 additions and 93 deletions

View File

@ -2,6 +2,10 @@
#extends Node2D
extends Control
var NoteHandlerPath := @'/root/main/NoteHandler'
onready var NoteHandler := get_node(NoteHandlerPath)
onready var ScoreText := $ScoreText
var song_defs = {}
var song_images = {}
var genres = {}
@ -21,17 +25,17 @@ var menu_mode_prev_fade_timer := 0.0
var menu_mode_prev_fade_timer_duration := 0.25
var currently_playing := false
var scorescreen_song_key := ""
var scorescreen_song_key := ''
var scorescreen_score_data := {}
var scorescreen_datetime := {}
var scorescreen_saved := false
var touch_rects = []
var TitleFont := preload("res://assets/MenuTitleFont.tres")
var GenreFont := preload("res://assets/MenuGenreFont.tres")
var ScoreFont := preload("res://assets/MenuScoreFont.tres")
var snd_interact := preload("res://assets/softclap.wav")
var TitleFont := preload('res://assets/MenuTitleFont.tres')
var GenreFont := preload('res://assets/MenuGenreFont.tres')
var ScoreFont := preload('res://assets/MenuScoreFont.tres')
var snd_interact := preload('res://assets/softclap.wav')
var userroot : String = FileLoader.userroot
@ -43,21 +47,21 @@ func scan_library():
func save_score():
var rootdir = userroot + "scores"
var rootdir = userroot + 'scores'
var dir = Directory.new()
var err = dir.make_dir_recursive(rootdir)
if err != OK:
print("An error occurred while trying to create the scores directory: ", err)
print('An error occurred while trying to create the scores directory: ', err)
return err
var data = {}
data.score_data = scorescreen_score_data
data.song_key = scorescreen_song_key
var json = JSON.print(data)
var file = File.new()
# var filename = rootdir + "/{year}{month}{day}T{hour}{minute}{second}.json".format(scorescreen_datetime)
# var filename = rootdir + '/{year}{month}{day}T{hour}{minute}{second}.json'.format(scorescreen_datetime)
# So uh. Can't zero-pad using the string.format() method. This sucks.
var dt = scorescreen_datetime
var filename = rootdir + "/%04d%02d%02dT%02d%02d%02d.json"%[dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second]
var filename = rootdir + '/%04d%02d%02dT%02d%02d%02d.json'%[dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second]
err = file.open(filename, File.WRITE)
if err != OK:
print(err)
@ -67,31 +71,31 @@ func save_score():
scorescreen_saved = true
func load_score(filename):
var rootdir = userroot + "scores"
var rootdir = userroot + 'scores'
var dir = Directory.new()
var err = dir.make_dir_recursive(rootdir)
if err != OK:
print("An error occurred while trying to create the scores directory: ", err)
print('An error occurred while trying to create the scores directory: ', err)
return err
var file = File.new()
err = file.open(rootdir + "/" + filename, File.READ)
err = file.open(rootdir + '/' + filename, File.READ)
if err != OK:
print("An error occurred while trying to access the chosen score file: ", err)
print('An error occurred while trying to access the chosen score file: ', err)
return err
var result_json = JSON.parse(file.get_as_text())
file.close()
if result_json.error != OK:
print("Error: ", result_json.error)
print("Error Line: ", result_json.error_line)
print("Error String: ", result_json.error_string)
print('Error: ', result_json.error)
print('Error Line: ', result_json.error_line)
print('Error String: ', result_json.error_string)
return result_json.error
var result = result_json.result
var data = {}
for key in result.score_data:
var value = {}
for k2 in result.score_data[key]:
if k2 == "MISS":
if k2 == 'MISS':
value[k2] = result.score_data[key][k2]
else:
value[int(k2)] = result.score_data[key][k2]
@ -102,11 +106,11 @@ func load_score(filename):
set_menu_mode(MenuMode.SCORE_SCREEN)
func _ready():
print("user:// root is: ", OS.get_user_data_dir())
print("Root for songs and scores is: ", userroot)
print('user:// root is: ', OS.get_user_data_dir())
print('Root for songs and scores is: ', userroot)
scan_library()
$"/root/main/NoteHandler".connect("finished_song", self, "finished_song")
# load_score("20191211T234131.json") # For testing purposes
NoteHandler.connect('finished_song', self, 'finished_song')
# load_score('20191211T234131.json') # For testing purposes
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
@ -122,11 +126,11 @@ func _process(delta):
menu_mode_prev_fade_timer = max(0.0, menu_mode_prev_fade_timer - delta)
update()
if (menu_mode == MenuMode.GAMEPLAY) and (menu_mode_prev_fade_timer <= 0.0) and not $"/root/main/NoteHandler".running:
if (menu_mode == MenuMode.GAMEPLAY) and (menu_mode_prev_fade_timer <= 0.0) and not NoteHandler.running:
var songslist = genres[genres.keys()[selected_genre]]
var song_key = songslist[selected_song % len(songslist)]
$"/root/main/NoteHandler".load_track(song_defs[song_key], selected_difficulty)
$"/root/main/NoteHandler".running = true
NoteHandler.load_track(song_defs[song_key], selected_difficulty)
NoteHandler.running = true
func draw_string_centered(font, position, string, color := Color.white):
draw_string(font, Vector2(position.x - font.get_string_size(string).x/2.0, position.y + font.get_ascent()), string, color)
@ -146,7 +150,7 @@ func draw_songtile(song_key, position, size, title_text:=false, difficulty=selec
func diffstr(difficulty: float):
# Convert .5 to +
return str(int(floor(difficulty))) + ("+" if fmod(difficulty, 1.0)>0.4 else "")
return str(int(floor(difficulty))) + ('+' if fmod(difficulty, 1.0)>0.4 else '')
func _draw_song_select(center: Vector2) -> Array:
@ -213,18 +217,18 @@ func _draw_chart_select(center: Vector2) -> Array:
var r = draw_songtile(song_key, Vector2(x, center.y), size, false, diff, (9 if diff == selected_difficulty else 3))
touchrects.append({rect=r, chart_idx=diff})
x += size + spacer_x
draw_string_centered(TitleFont, Vector2(center.x, center.y+size+64), song_defs[song_key]["title"], Color(0.95, 0.95, 1.0))
draw_string_centered(TitleFont, Vector2(center.x, center.y+size+64), song_defs[song_key]['title'], Color(0.95, 0.95, 1.0))
touchrects.append({rect=Rect2(center.x-450.0, center.y+310.0, 900.0, 300.0), chart_idx=-1})
# TODO: This is relatively expensive so we probably want to calculate this stuff once instead of every frame
var all_notes = FileLoader.SRT.load_file(song_defs[song_key].directory + "/" + song_defs[song_key].chart_filelist[selected_difficulty])
var all_notes = FileLoader.SRT.load_file(song_defs[song_key].directory + '/' + song_defs[song_key].chart_filelist[selected_difficulty])
var note_counts = {Note.NOTE_TAP: 0, Note.NOTE_HOLD: 0, Note.NOTE_STAR: 0}
for note in all_notes:
if note.type in note_counts:
note_counts[note.type] += 1
var notestrs = ["Taps:", "Holds:", "Slides:"]
var notestrs = ['Taps:', 'Holds:', 'Slides:']
var notetypes = [0, 1, 2]
for i in len(notestrs):
draw_string_centered(TitleFont, Vector2(center.x-50, center.y+size+128+i*50), notestrs[i], Color(0.95, 0.95, 1.0))
@ -248,17 +252,17 @@ func _draw_score_screen(center: Vector2) -> Array:
var y1 = y
var y2 = y + size + y_spacing*1.5
var tex_judgement_text = $"/root/main/NoteHandler".tex_judgement_text
var tex_judgement_text = NoteHandler.tex_judgement_text
var judgement_text_scale = 0.667
var judgement_text_width = 256 * judgement_text_scale
var judgement_text_height = 64 * judgement_text_scale
draw_songtile(song_key, Vector2(x_songtile-size/2.0, y), size, false, selected_difficulty, 3)
draw_string_centered(TitleFont, Vector2(x_songtile, y+size), song_defs[song_key]["title"], Color(0.95, 0.95, 1.0))
var notestrs = ["Taps:", "Holds Hit:", "Released:", "Stars:", "Slides:"]
draw_string_centered(TitleFont, Vector2(x_songtile, y+size), song_defs[song_key]['title'], Color(0.95, 0.95, 1.0))
var notestrs = ['Taps:', 'Holds Hit:', 'Released:', 'Stars:', 'Slides:']
var notetypes = [0, 1, -1, 2, -2]
var note_spacing = [0.0, 1.25, 2.25, 3.5, 4.5]
var judgestrs = Array(Rules.JUDGEMENT_STRINGS + ["Miss"])
var judgestrs = Array(Rules.JUDGEMENT_STRINGS + ['Miss'])
var judge_scores = [1.0, 0.9, 0.75, 0.5, 0.0]
var notetype_weights = [1.0, 1.0, 1.0, 1.0, 1.0]
var notecount_total = 0
@ -271,7 +275,7 @@ func _draw_score_screen(center: Vector2) -> Array:
# For each judgement type, print a column header
# draw_string_centered(TitleFont, Vector2(x2+x_spacing*(i+1), y2), judgestrs[i], Color(0.95, 0.95, 1.0))
draw_texture_rect_region(tex_judgement_text, Rect2(x2+x_spacing*(i+1)-judgement_text_width/2.0, y2, judgement_text_width, judgement_text_height), Rect2(0, 128*(i+3), 512, 128))
draw_string_centered(TitleFont, Vector2(x2+x_spacing*(len(judgestrs)+1), y2), "Score", Color(0.95, 0.95, 1.0))
draw_string_centered(TitleFont, Vector2(x2+x_spacing*(len(judgestrs)+1), y2), 'Score', Color(0.95, 0.95, 1.0))
for i in len(notestrs):
# For each note type, make a row and print scores
@ -286,19 +290,19 @@ func _draw_score_screen(center: Vector2) -> Array:
if j == 0:
score = scorescreen_score_data[idx][0]
elif j >= len(judgestrs)-1:
score = scorescreen_score_data[idx]["MISS"]
score = scorescreen_score_data[idx]['MISS']
else:
score = scorescreen_score_data[idx][j] + scorescreen_score_data[idx][-j]
notecount_early += scorescreen_score_data[idx][-j]
notecount_late += scorescreen_score_data[idx][j]
if (j >= len(judgestrs)-1) and (idx == -1):
draw_string_centered(TitleFont, Vector2(x2+x_spacing*(j+1), y_row), "^", Color(0.95, 0.95, 1.0))
draw_string_centered(TitleFont, Vector2(x2+x_spacing*(j+1), y_row), '^', Color(0.95, 0.95, 1.0))
else:
draw_string_centered(TitleFont, Vector2(x2+x_spacing*(j+1), y_row), str(score), Color(0.95, 0.95, 1.0))
notecount_total += score # Kinda redundant, will probably refactor eventually
note_count += score
note_score += score * judge_scores[j]
draw_string_centered(TitleFont, Vector2(x2+x_spacing*(len(judgestrs)+1), y_row), "%2.2f%%"%(note_score/max(note_count, 1)*100.0), Color(0.95, 0.95, 1.0))
draw_string_centered(TitleFont, Vector2(x2+x_spacing*(len(judgestrs)+1), y_row), '%2.2f%%'%(note_score/max(note_count, 1)*100.0), Color(0.95, 0.95, 1.0))
total_score += note_score * notetype_weights[i]
total_scoremax += note_count * notetype_weights[i]
@ -310,28 +314,28 @@ func _draw_score_screen(center: Vector2) -> Array:
else:
score_idx += 1
# draw_string_centered(ScoreFont, Vector2(x_score, y1), Rules.SCORE_STRINGS[score_idx], Color(1.0, 1.0, 1.0))
# draw_string_centered(TitleFont, Vector2(x_score, y1+y_spacing*3), "%2.3f%%"%(overall_score*100.0), Color(1.0, 1.0, 1.0))
$ScoreText.position = Vector2(x_score, y1)
$ScoreText.score = Rules.SCORE_STRINGS[score_idx]
$ScoreText.score_sub = "%2.3f%%"%(overall_score*100.0)
$ScoreText.update()
# draw_string_centered(TitleFont, Vector2(x_score, y1+y_spacing*3), '%2.3f%%'%(overall_score*100.0), Color(1.0, 1.0, 1.0))
ScoreText.position = Vector2(x_score, y1)
ScoreText.score = Rules.SCORE_STRINGS[score_idx]
ScoreText.score_sub = '%2.3f%%'%(overall_score*100.0)
ScoreText.update()
draw_string_centered(TitleFont, Vector2(x, y2+y_spacing*7), "Early : Late", Color(0.95, 0.95, 1.0))
draw_string_centered(TitleFont, Vector2(x, y2+y_spacing*8), "%3d%% : %3d%%"%[notecount_early*100/notecount_total, notecount_late*100/notecount_total], Color(0.95, 0.95, 1.0))
draw_string_centered(TitleFont, Vector2(x, y2+y_spacing*7), 'Early : Late', Color(0.95, 0.95, 1.0))
draw_string_centered(TitleFont, Vector2(x, y2+y_spacing*8), '%3d%% : %3d%%'%[notecount_early*100/notecount_total, notecount_late*100/notecount_total], Color(0.95, 0.95, 1.0))
var rect_songselect := Rect2(x-100.0, y+660.0, 400.0, 100.0)
draw_rect(rect_songselect, Color.red)
draw_string_centered(TitleFont, Vector2(x+100, y+680), "Song Select", Color(0.95, 0.95, 1.0))
draw_string_centered(TitleFont, Vector2(x+100, y+680), 'Song Select', Color(0.95, 0.95, 1.0))
touchrects.append({rect=rect_songselect, next_menu=MenuMode.SONG_SELECT})
var rect_save := Rect2(x-300.0, y+660.0, 180.0, 100.0)
if not scorescreen_saved:
draw_rect(rect_save, Color.blue)
draw_string_centered(TitleFont, Vector2(x-210, y+680), "Save", Color(0.95, 0.95, 1.0))
touchrects.append({rect=rect_save, action="save"})
draw_string_centered(TitleFont, Vector2(x-210, y+680), 'Save', Color(0.95, 0.95, 1.0))
touchrects.append({rect=rect_save, action='save'})
else:
draw_rect(rect_save, Color.darkgray)
draw_string_centered(TitleFont, Vector2(x-210, y+680), "Saved", Color(0.95, 0.95, 1.0))
draw_string_centered(TitleFont, Vector2(x-210, y+680), 'Saved', Color(0.95, 0.95, 1.0))
return touchrects
func _draw_gameplay(center: Vector2) -> Array:
@ -341,8 +345,8 @@ func _draw_gameplay(center: Vector2) -> Array:
var rect_songselect := Rect2(x-960.0, y+440.0, 100.0, 100.0)
draw_rect(rect_songselect, Color.red)
draw_string_centered(TitleFont, center+Vector2(-910, 470), "Stop", Color(0.95, 0.95, 1.0))
touchrects.append({rect=rect_songselect, action="stop"})
draw_string_centered(TitleFont, center+Vector2(-910, 470), 'Stop', Color(0.95, 0.95, 1.0))
touchrects.append({rect=rect_songselect, action='stop'})
return touchrects
@ -352,7 +356,7 @@ func _draw():
var outline_px = 3
var center = Vector2(540.0, 540.0-160.0) # Vector2(0.0, -160.0)
touch_rects = []
$ScoreText.hide()
ScoreText.hide()
for i in MenuMode:
touch_rects.append([])
@ -382,7 +386,7 @@ func _draw():
GameTheme.set_screen_filter_alpha(1.0 - progress)
MenuMode.SCORE_SCREEN:
_draw_score_screen(center_next)
$ScoreText.show()
ScoreText.show()
else:
match menu_mode:
MenuMode.SONG_SELECT:
@ -399,7 +403,7 @@ func _draw():
MenuMode.SCORE_SCREEN:
GameTheme.set_screen_filter_alpha(1.0)
touch_rects[menu_mode] = _draw_score_screen(center)
$ScoreText.show()
ScoreText.show()
func set_menu_mode(mode):
menu_mode_prev = menu_mode
@ -427,22 +431,22 @@ func touch_select_chart(touchdict):
SFXPlayer.play(SFXPlayer.Type.NON_POSITIONAL, self, snd_interact, -4.5)
func touch_gameplay(touchdict):
if touchdict.has("action"):
if touchdict.has('action'):
SFXPlayer.play(SFXPlayer.Type.NON_POSITIONAL, self, snd_interact, 0.0)
if touchdict.action == "stop":
$"/root/main/NoteHandler".stop()
if touchdict.action == 'stop':
NoteHandler.stop()
func touch_score_screen(touchdict):
if touchdict.has("next_menu"):
if touchdict.has('next_menu'):
SFXPlayer.play(SFXPlayer.Type.NON_POSITIONAL, self, snd_interact, 0.0)
set_menu_mode(touchdict.next_menu)
$ScoreText.score = ""
$ScoreText.score_sub = ""
ScoreText.score = ''
ScoreText.score_sub = ''
# TODO: time this to coincide with the menu going fully offscreen
$ScoreText.update()
elif touchdict.has("action"):
ScoreText.update()
elif touchdict.has('action'):
SFXPlayer.play(SFXPlayer.Type.NON_POSITIONAL, self, snd_interact, 0.0)
if touchdict.action == "save":
if touchdict.action == 'save':
save_score()
func finished_song(song_key, score_data):
@ -478,15 +482,15 @@ func _input(event):
touch_score_screen(d)
match menu_mode:
MenuMode.SONG_SELECT:
if event.is_action_pressed("ui_right"):
if event.is_action_pressed('ui_right'):
selected_song += 1
elif event.is_action_pressed("ui_left"):
elif event.is_action_pressed('ui_left'):
selected_song -= 1
elif event.is_action_pressed("ui_up"):
elif event.is_action_pressed('ui_up'):
selected_genre = int(max(0, selected_genre - 1))
elif event.is_action_pressed("ui_down"):
elif event.is_action_pressed('ui_down'):
selected_genre = int(min(1, selected_genre + 1))
elif event.is_action_pressed("ui_page_up"):
elif event.is_action_pressed('ui_page_up'):
selected_difficulty = int(max(0, selected_difficulty - 1))
elif event.is_action_pressed("ui_page_down"):
elif event.is_action_pressed('ui_page_down'):
selected_difficulty = int(min(4, selected_difficulty + 1))

View File

@ -12,6 +12,14 @@ var tex_judgement_text := preload('res://assets/text-4k.png')
var tex_slide_arrow := preload('res://assets/slide-arrow-4k.png')
var slide_trail_shadermaterial := preload('res://shaders/slidetrail.tres')
export var MusicPlayerPath := @'/root/main/music'
export var VideoPlayerPath := @'/root/main/video'
export var InputHandlerPath := @'/root/main/InputHandler'
onready var MusicPlayer := get_node(MusicPlayerPath)
onready var VideoPlayer := get_node(VideoPlayerPath)
onready var InputHandler := get_node(InputHandlerPath)
onready var Painter = $Painter
onready var SlideTrailHandler = $'Viewport/Center/SlideTrailHandler'
onready var JudgeText = $'Viewport/Center/JudgeText'
onready var notelines = $'Viewport/Center/notelines'
@ -372,10 +380,10 @@ func check_hold_release(col):
func button_released(col):
# We only care about hold release.
# For that particular case, we want both to be unheld.
if $'/root/main/InputHandler'.touchbuttons_pressed[col] == 0:
if InputHandler.touchbuttons_pressed[col] == 0:
check_hold_release(col)
func touchbutton_released(col):
if $'/root/main/InputHandler'.buttons_pressed[col] == 0:
if InputHandler.buttons_pressed[col] == 0:
check_hold_release(col)
#----------------------------------------------------------------------------------------------------------------------------------------------
@ -552,10 +560,10 @@ func _ready():
noteline_array_image.fill(Color(0.0, 0.0, 0.0))
# Format: first 15 rows are for hit events, last row is for releases only (no ring glow)
$'/root/main/InputHandler'.connect('button_pressed', self, 'button_pressed')
$'/root/main/InputHandler'.connect('touchbutton_pressed', self, 'touchbutton_pressed')
$'/root/main/InputHandler'.connect('button_released', self, 'button_released')
$'/root/main/InputHandler'.connect('touchbutton_released', self, 'touchbutton_released')
InputHandler.connect('button_pressed', self, 'button_pressed')
InputHandler.connect('touchbutton_pressed', self, 'touchbutton_pressed')
InputHandler.connect('button_released', self, 'button_released')
InputHandler.connect('touchbutton_released', self, 'touchbutton_released')
func load_track(data: Dictionary, difficulty_idx: int):
set_time(-3.0)
@ -570,9 +578,9 @@ func load_track(data: Dictionary, difficulty_idx: int):
var audiostream = FileLoader.load_ogg(data.directory + '/' + data.audio_filelist[0])
var videostream = load(data.directory + '/' + data.video_filelist[0])
$'/root/main/music'.set_stream(audiostream)
$'/root/main/video'.set_stream(videostream)
$'/root/main/video'.update_aspect_ratio(data.video_dimensions[0]/data.video_dimensions[1])
MusicPlayer.set_stream(audiostream)
VideoPlayer.set_stream(videostream)
VideoPlayer.update_aspect_ratio(data.video_dimensions[0]/data.video_dimensions[1])
# all_notes = FileLoader.Test.stress_pattern()
Note.process_note_list(all_notes)
@ -588,8 +596,8 @@ func load_track(data: Dictionary, difficulty_idx: int):
initialise_scores() # Remove old score
func stop():
$'/root/main/music'.stop()
$'/root/main/video'.stop()
MusicPlayer.stop()
VideoPlayer.stop()
# running = false
next_note_to_load = 1000000 # Hacky but whatever
@ -639,17 +647,15 @@ func _process(delta):
timer.start()
timer.connect('timeout', timer, 'queue_free')
# if (t_old < 0) and (t >= 0):
# get_node('/root/main/video').play()
var vt_delta := time - video_start_time()
if (0.0 <= vt_delta) and (vt_delta < 1.0) and not get_node('/root/main/video').is_playing():
get_node('/root/main/video').play()
get_node('/root/main/video').set_stream_position(vt_delta)
if (0.0 <= vt_delta) and (vt_delta < 1.0) and not VideoPlayer.is_playing():
VideoPlayer.play()
VideoPlayer.set_stream_position(vt_delta)
var at_delta := time - audio_start_time()
if (0.0 <= at_delta) and (at_delta < 1.0) and not get_node('/root/main/music').is_playing():
# get_node('/root/main/music').play()
# get_node('/root/main/music').seek(at_delta)
get_node('/root/main/music').play(at_delta)
if (0.0 <= at_delta) and (at_delta < 1.0) and not MusicPlayer.is_playing():
# MusicPlayer.play()
# MusicPlayer.seek(at_delta)
MusicPlayer.play(at_delta)
# Clean out expired notes
var miss_time: float = Rules.JUDGEMENT_TIMES_POST[-1] * bpm/60.0
@ -714,8 +720,8 @@ func _process(delta):
if (
next_note_to_load >= len(all_notes)
and not get_node('/root/main/video').is_playing()
and not get_node('/root/main/music').is_playing()
and not VideoPlayer.is_playing()
and not MusicPlayer.is_playing()
and active_notes.empty()
and active_judgement_texts.empty()
and slide_trail_mesh_instances.empty()
@ -727,4 +733,4 @@ func _process(delta):
# Redraw
meshinstance.material.set_shader_param('screen_size', get_viewport().get_size())
update()
$Painter.update()
Painter.update()

View File

@ -1,4 +1,6 @@
extends Node2D
onready var Viewport := get_node(@'../Viewport')
func _draw():
draw_texture_rect($"../Viewport".get_texture(), Rect2(-540, -540, 1080, 1080), false)
draw_texture_rect(Viewport.get_texture(), Rect2(-540, -540, 1080, 1080), false)

View File

@ -1,9 +1,11 @@
extends Node2D
onready var root := $'/root'
func _draw():
var screen_size = $"/root".get_visible_rect().size
var screen_size = root.get_visible_rect().size
var screen_height = max(screen_size.x, screen_size.y)
draw_rect(Rect2(-screen_height/2, -screen_height/2, screen_height, screen_height), GameTheme.screen_filter)
func _ready():
GameTheme.connect("screen_filter_changed", self, "update")
GameTheme.connect('screen_filter_changed', self, 'update')