ajout du plugin dialogical

This commit is contained in:
2026-01-10 13:00:58 +01:00
parent 8917a02a7b
commit c130c47042
884 changed files with 49385 additions and 0 deletions

View File

@@ -0,0 +1,397 @@
@tool
## Event that can play audio on a channel. The channel can be prededinfed
## (with default settings defined in the settings) or created on the spot.
## If no channel is given will play as a One-Shot SFX.
class_name DialogicAudioEvent
extends DialogicEvent
### Settings
## The file to play. If empty, the previous audio will be faded out.
var file_path := "":
set(value):
if file_path != value:
file_path = value
ui_update_needed.emit()
## The channel name to use. If none given plays as a One-Shot SFX.
var channel_name := "":
set(value):
if channel_name != channel_name_regex.sub(value, '', true):
channel_name = channel_name_regex.sub(value, '', true)
var defaults: Dictionary = DialogicUtil.get_audio_channel_defaults().get(channel_name, {})
if defaults:
fade_length = defaults.fade_length
volume = defaults.volume
audio_bus = defaults.audio_bus
loop = defaults.loop
ui_update_needed.emit()
## The length of the fade. If 0 it's an instant change.
var fade_length: float = 0.0
## The volume in decibel.
var volume: float = 0.0
## The audio bus the audio will be played on.
var audio_bus := ""
## If true, the audio will loop, otherwise only play once.
var loop := true
## Sync starting time with different channel (if playing audio on that channel)
var sync_channel := ""
## Helpers. Set automatically
var set_fade_length := false
var set_volume := false
var set_audio_bus := false
var set_loop := false
var set_sync_channel := false
var regex := RegEx.create_from_string(r'(?:audio)\s*(?<channel>[\w-]{2,}|[\w]*)?\s*(")?(?<file_path>(?(2)[^"\n]*|[^(: \n]*))(?(2)"|)(?:\s*\[(?<shortcode>.*)\])?')
var channel_name_regex := RegEx.create_from_string(r'(?<dash_only>^-$)|(?<invalid>[^\w-]{1})')
################################################################################
## EXECUTE
################################################################################
func _execute() -> void:
var audio_settings_overrides := {}
if set_audio_bus:
audio_settings_overrides["audio_bus"] = audio_bus
if set_volume:
audio_settings_overrides["volume"] = volume
if set_fade_length:
audio_settings_overrides["fade_length"] = fade_length
if set_loop:
audio_settings_overrides["loop"] = loop
audio_settings_overrides["sync_channel"] = sync_channel
dialogic.Audio.update_audio(channel_name, file_path, audio_settings_overrides)
finish()
################################################################################
## INITIALIZE
################################################################################
func _init() -> void:
event_name = "Audio"
set_default_color('Color7')
event_category = "Audio"
event_sorting_index = 2
func _get_icon() -> Resource:
return load(this_folder.path_join('icon_music.png'))
################################################################################
## SAVING/LOADING
################################################################################
func to_text () -> String:
var result_string := "audio "
if not channel_name.is_empty():
result_string += channel_name + " "
else:
loop = false
if not file_path.is_empty():
result_string += "\"" + file_path + "\""
else:
result_string += "-"
var shortcode := store_to_shortcode_parameters()
if not shortcode.is_empty():
result_string += " [" + shortcode + "]"
return result_string
func from_text(string:String) -> void:
# Pre Alpha 17 Conversion
if string.begins_with('[music'):
_music_from_text(string)
return
elif string.begins_with('[sound'):
_sound_from_text(string)
return
var result := regex.search(string)
channel_name = result.get_string('channel')
if result.get_string('file_path') == '-':
file_path = ""
else:
file_path = result.get_string('file_path')
if not result.get_string('shortcode'):
return
load_from_shortcode_parameters(result.get_string('shortcode'))
func get_shortcode_parameters() -> Dictionary:
return {
#param_name : property_info
"path" : {"property": "file_path", "default": "", "custom_stored":true, "ext_file":true},
"channel" : {"property": "channel_name", "default": "", "custom_stored":true},
"fade" : {"property": "fade_length", "default": 0.0},
"volume" : {"property": "volume", "default": 0.0},
"bus" : {"property": "audio_bus", "default": "",
"suggestions": DialogicUtil.get_audio_bus_suggestions},
"loop" : {"property": "loop", "default": true},
"sync" : {"property": "sync_channel", "default": "",
"suggestions": get_sync_audio_channel_suggestions},
}
## Returns a string with all the shortcode parameters.
func store_to_shortcode_parameters(params:Dictionary = {}) -> String:
if params.is_empty():
params = get_shortcode_parameters()
var custom_defaults: Dictionary = DialogicUtil.get_custom_event_defaults(event_name)
var channel_defaults := DialogicUtil.get_audio_channel_defaults()
var result_string := ""
for parameter in params.keys():
var parameter_info: Dictionary = params[parameter]
var value: Variant = get(parameter_info.property)
var default_value: Variant = custom_defaults.get(parameter_info.property, parameter_info.default)
if parameter_info.get('custom_stored', false):
continue
if "set_" + parameter_info.property in self and not get("set_" + parameter_info.property):
continue
if channel_name in channel_defaults.keys():
default_value = channel_defaults[channel_name].get(parameter_info.property, default_value)
if typeof(value) == typeof(default_value) and value == default_value:
if not "set_" + parameter_info.property in self or not get("set_" + parameter_info.property):
continue
result_string += " " + parameter + '="' + value_to_string(value, parameter_info.get("suggestions", Callable())) + '"'
return result_string.strip_edges()
func is_valid_event(string:String) -> bool:
if string.begins_with("audio"):
return true
# Pre Alpha 17 Converter
if string.strip_edges().begins_with('[music '):
return true
if string.strip_edges().begins_with('[sound '):
return true
return false
#region PreAlpha17 Conversion
func _music_from_text(string:String) -> void:
var data := parse_shortcode_parameters(string)
if data.has('channel') and data['channel'].to_int() > 0:
channel_name = 'music' + str(data['channel'].to_int() + 1)
else:
channel_name = 'music'
# Reapply original defaults as setting channel name may have overridden them
fade_length = 0.0
volume = 0.0
audio_bus = ''
loop = true
# Apply any custom event defaults
for default_prop in DialogicUtil.get_custom_event_defaults('music'):
if default_prop in self:
set(default_prop, DialogicUtil.get_custom_event_defaults('music')[default_prop])
# Apply shortcodes that exist
if data.has('path'):
file_path = data['path']
if data.has('fade'):
set_fade_length = true
fade_length = data['fade'].to_float()
if data.has('volume'):
set_volume = true
volume = data['volume'].to_float()
if data.has('bus'):
set_audio_bus = true
audio_bus = data['bus']
if data.has('loop'):
set_loop = true
loop = str_to_var(data['loop'])
update_text_version()
func _sound_from_text(string:String) -> void:
var data := parse_shortcode_parameters(string)
channel_name = ''
# Reapply original defaults as setting channel name may have overridden them
fade_length = 0.0
volume = 0.0
audio_bus = ''
loop = false
# Apply any custom event defaults
for default_prop in DialogicUtil.get_custom_event_defaults('sound'):
if default_prop in self:
set(default_prop, DialogicUtil.get_custom_event_defaults('sound')[default_prop])
# Apply shortcodes that exist
if data.has('path'):
file_path = data['path']
if data.has('volume'):
set_volume = true
volume = data['volume'].to_float()
if data.has('bus'):
set_audio_bus = true
audio_bus = data['bus']
if data.has('loop'):
set_loop = true
loop = str_to_var(data['loop'])
update_text_version()
#endregion
################################################################################
## EDITOR REPRESENTATION
################################################################################
func build_event_editor() -> void:
add_header_edit('file_path', ValueType.FILE, {
'left_text' : 'Play',
'file_filter' : "*.mp3, *.ogg, *.wav; Supported Audio Files",
'placeholder' : "Nothing",
'editor_icon' : ["AudioStreamMP3", "EditorIcons"]})
add_header_edit('file_path', ValueType.AUDIO_PREVIEW)
add_header_edit('channel_name', ValueType.DYNAMIC_OPTIONS, {
'left_text' :"on",
"right_text" : "channel.",
'placeholder' : '(One-Shot SFX)',
'mode' : 3,
'suggestions_func' : get_audio_channel_suggestions,
'validation_func' : DialogicUtil.validate_audio_channel_name,
'tooltip' : 'Use an existing channel or type the name for a new channel.',
})
add_header_button('', _open_audio_settings, 'Edit Audio Channels',
editor_node.get_theme_icon("ExternalLink", "EditorIcons"))
add_body_edit("set_fade_length", ValueType.BOOL_BUTTON,{
"editor_icon" : ["FadeCross", "EditorIcons"],
"tooltip" : "Overwrite Fade Length"
},"!channel_name.is_empty() and has_channel_defaults()")
add_body_edit('fade_length', ValueType.NUMBER, {'left_text':'Fade Time:'},
'!channel_name.is_empty() and (not has_channel_defaults() or set_fade_length)')
add_body_edit("set_volume", ValueType.BOOL_BUTTON,{
"editor_icon" : ["AudioStreamPlayer", "EditorIcons"],
"tooltip" : "Overwrite Volume"
},"!file_path.is_empty() and has_channel_defaults()")
add_body_edit('volume', ValueType.NUMBER, {'left_text':'Volume:', 'mode':2},
'!file_path.is_empty() and (not has_channel_defaults() or set_volume)')
add_body_edit("set_audio_bus", ValueType.BOOL_BUTTON,{
"editor_icon" : ["AudioBusBypass", "EditorIcons"],
"tooltip" : "Overwrite Audio Bus"
},"!file_path.is_empty() and has_channel_defaults()")
add_body_edit('audio_bus', ValueType.DYNAMIC_OPTIONS, {
'left_text':'Audio Bus:',
'placeholder' : 'Master',
'mode' : 2,
'suggestions_func' : DialogicUtil.get_audio_bus_suggestions,
}, '!file_path.is_empty() and (not has_channel_defaults() or set_audio_bus)')
add_body_edit("set_loop", ValueType.BOOL_BUTTON,{
"editor_icon" : ["Loop", "EditorIcons"],
"tooltip" : "Overwrite Loop"
},"!channel_name.is_empty() and !file_path.is_empty() and has_channel_defaults()")
add_body_edit('loop', ValueType.BOOL, {'left_text':'Loop:'},
'!channel_name.is_empty() and !file_path.is_empty() and (not has_channel_defaults() or set_loop)')
add_body_line_break("!channel_name.is_empty() and !file_path.is_empty()")
add_body_edit("set_sync_channel", ValueType.BOOL_BUTTON,{
"editor_icon" : ["TransitionSync", "EditorIcons"],
"tooltip" : "Enable Syncing"
},"!channel_name.is_empty() and !file_path.is_empty()")
add_body_edit('sync_channel', ValueType.DYNAMIC_OPTIONS, {
'left_text' :'Sync with:',
'placeholder' : '(No Sync)',
'mode' : 3,
'suggestions_func' : get_sync_audio_channel_suggestions,
'validation_func' : DialogicUtil.validate_audio_channel_name,
'tooltip' : "Use an existing channel or type the name for a new channel. If channel doesn't exist, this setting will be ignored.",
}, '!channel_name.is_empty() and !file_path.is_empty() and set_sync_channel')
## Used by the button on the visual event
func _open_audio_settings() -> void:
var editor_manager := editor_node.find_parent('EditorsManager')
if editor_manager:
editor_manager.open_editor(editor_manager.editors['Settings']['node'], true, "Audio")
## Helper for the visibility conditions
func has_channel_defaults() -> bool:
var defaults := DialogicUtil.get_audio_channel_defaults()
return defaults.has(channel_name)
func get_audio_channel_suggestions(filter:String) -> Dictionary:
var suggestions := {}
suggestions["(One-Shot SFX)"] = {
"value":"",
"tooltip": "Used for one shot sounds effects. Plays each sound in its own AudioStreamPlayer.",
"editor_icon": ["GuiRadioUnchecked", "EditorIcons"]
}
# TODO use .merged after dropping 4.2 support
suggestions.merge(DialogicUtil.get_audio_channel_suggestions(filter))
return suggestions
func get_sync_audio_channel_suggestions(filter:="") -> Dictionary:
return DialogicUtil.get_audio_channel_suggestions(filter)
####################### CODE COMPLETION ########################################
################################################################################
func _get_code_completion(CodeCompletionHelper:Node, TextNode:TextEdit, line:String, word:String, symbol:String) -> void:
var line_until: String = CodeCompletionHelper.get_line_untill_caret(line)
if symbol == ' ':
if line_until.count(' ') == 1:
TextNode.add_code_completion_option(CodeEdit.KIND_MEMBER, "One-Shot SFX", ' ', event_color.lerp(TextNode.syntax_highlighter.normal_color, 0.6))
for i in DialogicUtil.get_audio_channel_suggestions(""):
TextNode.add_code_completion_option(CodeEdit.KIND_MEMBER, i, i, event_color.lerp(TextNode.syntax_highlighter.normal_color, 0.6), null, " ")
elif line_until.count(" ") == 2:
TextNode.add_code_completion_option(CodeEdit.KIND_MEMBER, '"', '"', event_color.lerp(TextNode.syntax_highlighter.normal_color, 0.6))
if symbol == "[" or (symbol == " " and line.count("[")):
for i in ["fade", "volume", "bus", "loop", "sync"]:
if not i+"=" in line:
TextNode.add_code_completion_option(CodeEdit.KIND_MEMBER, i, i+'="', event_color.lerp(TextNode.syntax_highlighter.normal_color, 0.6))
if (symbol == '"' or symbol == "=") and line.count("["):
CodeCompletionHelper.suggest_shortcode_values(TextNode, self, line, word)
func _get_start_code_completion(_CodeCompletionHelper:Node, TextNode:TextEdit) -> void:
TextNode.add_code_completion_option(CodeEdit.KIND_PLAIN_TEXT, 'audio', 'audio ', event_color.lerp(TextNode.syntax_highlighter.normal_color, 0.3))
#################### SYNTAX HIGHLIGHTING #######################################
################################################################################
func _get_syntax_highlighting(Highlighter:SyntaxHighlighter, dict:Dictionary, line:String) -> Dictionary:
var result := regex.search(line)
dict[result.get_start()] = {"color":event_color.lerp(Highlighter.normal_color, 0.3)}
dict[result.get_start("channel")] = {"color":event_color.lerp(Highlighter.normal_color, 0.8)}
dict[result.get_start("file_path")] = {"color":event_color.lerp(Highlighter.string_color, 0.8)}
if result.get_string("shortcode"):
dict[result.get_start("shortcode")-1] = {"color":Highlighter.normal_color}
dict = Highlighter.color_shortcode_content(dict, line, result.get_start("shortcode"), 0, event_color)
return dict

View File

@@ -0,0 +1 @@
uid://8p4qchmcuj68

Binary file not shown.

After

Width:  |  Height:  |  Size: 552 B

View File

@@ -0,0 +1,40 @@
[remap]
importer="texture"
type="CompressedTexture2D"
uid="uid://buvpjsvdt4evk"
path="res://.godot/imported/icon_music.png-ffc971ba1265164a55f745186974be5f.ctex"
metadata={
"vram_texture": false
}
[deps]
source_file="res://addons/dialogic/Modules/Audio/icon_music.png"
dest_files=["res://.godot/imported/icon_music.png-ffc971ba1265164a55f745186974be5f.ctex"]
[params]
compress/mode=0
compress/high_quality=false
compress/lossy_quality=0.7
compress/uastc_level=0
compress/rdo_quality_loss=0.0
compress/hdr_compression=1
compress/normal_map=0
compress/channel_pack=0
mipmaps/generate=false
mipmaps/limit=-1
roughness/mode=0
roughness/src_normal=""
process/channel_remap/red=0
process/channel_remap/green=1
process/channel_remap/blue=2
process/channel_remap/alpha=3
process/fix_alpha_border=true
process/premult_alpha=false
process/normal_map_invert_y=false
process/hdr_as_srgb=false
process/hdr_clamp_exposure=false
process/size_limit=0
detect_3d/compress_to=1

Binary file not shown.

After

Width:  |  Height:  |  Size: 524 B

View File

@@ -0,0 +1,40 @@
[remap]
importer="texture"
type="CompressedTexture2D"
uid="uid://d3ookrkto0yh6"
path="res://.godot/imported/icon_sound.png-7a1a8a5533773d97969b6311b6a9133f.ctex"
metadata={
"vram_texture": false
}
[deps]
source_file="res://addons/dialogic/Modules/Audio/icon_sound.png"
dest_files=["res://.godot/imported/icon_sound.png-7a1a8a5533773d97969b6311b6a9133f.ctex"]
[params]
compress/mode=0
compress/high_quality=false
compress/lossy_quality=0.7
compress/uastc_level=0
compress/rdo_quality_loss=0.0
compress/hdr_compression=1
compress/normal_map=0
compress/channel_pack=0
mipmaps/generate=false
mipmaps/limit=-1
roughness/mode=0
roughness/src_normal=""
process/channel_remap/red=0
process/channel_remap/green=1
process/channel_remap/blue=2
process/channel_remap/alpha=3
process/fix_alpha_border=true
process/premult_alpha=false
process/normal_map_invert_y=false
process/hdr_as_srgb=false
process/hdr_clamp_exposure=false
process/size_limit=0
detect_3d/compress_to=1

View File

@@ -0,0 +1,14 @@
@tool
extends DialogicIndexer
func _get_events() -> Array:
return [this_folder.path_join('event_audio.gd')]
func _get_subsystems() -> Array:
return [{'name':'Audio', 'script':this_folder.path_join('subsystem_audio.gd')}]
func _get_settings_pages() -> Array:
return [this_folder.path_join('settings_audio.tscn')]

View File

@@ -0,0 +1 @@
uid://dk46l1toqeswc

View File

@@ -0,0 +1,241 @@
@tool
extends DialogicSettingsPage
## Settings page that contains settings for the audio subsystem
const TYPE_SOUND_AUDIO_BUS := "dialogic/audio/type_sound_bus"
const CHANNEL_DEFAULTS := "dialogic/audio/channel_defaults"
var channel_defaults := {}
var _revalidate_channel_names := false
func _ready() -> void:
%TypeSoundBus.item_selected.connect(_on_type_sound_bus_item_selected)
$Panel.add_theme_stylebox_override('panel', get_theme_stylebox("Background", "EditorStyles"))
func _refresh() -> void:
%TypeSoundBus.clear()
var idx := 0
for i in range(AudioServer.bus_count):
%TypeSoundBus.add_item(AudioServer.get_bus_name(i))
if AudioServer.get_bus_name(i) == ProjectSettings.get_setting(TYPE_SOUND_AUDIO_BUS, ""):
idx = i
%TypeSoundBus.select(idx)
load_channel_defaults(DialogicUtil.get_audio_channel_defaults())
func _about_to_close() -> void:
save_channel_defaults()
## TYPE SOUND AUDIO BUS
func _on_type_sound_bus_item_selected(index:int) -> void:
ProjectSettings.set_setting(TYPE_SOUND_AUDIO_BUS, %TypeSoundBus.get_item_text(index))
ProjectSettings.save()
#region AUDIO CHANNELS
################################################################################
func load_channel_defaults(dictionary:Dictionary) -> void:
channel_defaults.clear()
for i in %AudioChannelDefaults.get_children():
i.queue_free()
var column_names := [
"Channel Name",
"Volume",
"Audio Bus",
"Fade",
"Loop",
""
]
for column in column_names:
var label := Label.new()
label.text = column
label.theme_type_variation = 'DialogicHintText2'
%AudioChannelDefaults.add_child(label)
var channel_names := dictionary.keys()
channel_names.sort()
for channel_name in channel_names:
add_channel_defaults(
channel_name,
dictionary[channel_name].volume,
dictionary[channel_name].audio_bus,
dictionary[channel_name].fade_length,
dictionary[channel_name].loop)
await get_tree().process_frame
_revalidate_channel_names = true
revalidate_channel_names.call_deferred()
func save_channel_defaults() -> void:
var dictionary := {}
for i in channel_defaults:
if is_instance_valid(channel_defaults[i].channel_name):
var channel_name := ""
if not channel_defaults[i].channel_name is Label:
if channel_defaults[i].channel_name.current_value.is_empty():
continue
channel_name = channel_defaults[i].channel_name.current_value
#channel_name = DialogicUtil.channel_name_regex.sub(channel_name, '', true)
if channel_name.is_empty():
dictionary[channel_name] = {
'volume': channel_defaults[i].volume.get_value(),
'audio_bus': channel_defaults[i].audio_bus.current_value,
'fade_length': 0.0,
'loop': false,
}
else:
dictionary[channel_name] = {
'volume': channel_defaults[i].volume.get_value(),
'audio_bus': channel_defaults[i].audio_bus.current_value,
'fade_length': channel_defaults[i].fade_length.get_value(),
'loop': channel_defaults[i].loop.button_pressed,
}
ProjectSettings.set_setting(CHANNEL_DEFAULTS, dictionary)
ProjectSettings.save()
func _on_add_channel_defaults_pressed() -> void:
var added_node := add_channel_defaults('new_channel_name', 0.0, '', 0.0, true)
if added_node:
added_node.take_autofocus()
_revalidate_channel_names = true
revalidate_channel_names.call_deferred()
func add_channel_defaults(channel_name: String, volume: float, audio_bus: String, fade_length: float, loop: bool) -> Control:
var info := {}
for i in %AudioChannelDefaultRow.get_children():
var x := i.duplicate()
%AudioChannelDefaults.add_child(x)
info[i.name] = x
if channel_name.is_empty():
var channel_label := Label.new()
channel_label.text = &"One-Shot SFX"
channel_label.size_flags_horizontal = Control.SIZE_EXPAND_FILL
%AudioChannelDefaults.add_child(channel_label)
%AudioChannelDefaults.move_child(channel_label, info.channel_name.get_index())
info.channel_name.queue_free()
info.channel_name = channel_label
var HintTooltip := preload("res://addons/dialogic/Editor/Common/hint_tooltip_icon.tscn")
var fade_hint := HintTooltip.instantiate()
fade_hint.hint_text = "Fading is disabled for this channel."
%AudioChannelDefaults.add_child(fade_hint)
%AudioChannelDefaults.move_child(fade_hint, info.fade_length.get_index())
info.fade_length.queue_free()
info.fade_length = fade_hint
var loop_hint := HintTooltip.instantiate()
loop_hint.hint_text = "Looping is disabled for this channel."
%AudioChannelDefaults.add_child(loop_hint)
%AudioChannelDefaults.move_child(loop_hint, info.loop.get_index())
info.loop.queue_free()
info.loop = loop_hint
info.delete.disabled = true
else:
info.channel_name.suggestions_func = get_audio_channel_suggestions
info.channel_name.validation_func = validate_channel_names.bind(info.channel_name)
info.channel_name.set_value(channel_name)
info.fade_length.set_value(fade_length)
info.loop.set_pressed_no_signal(loop)
info.audio_bus.suggestions_func = DialogicUtil.get_audio_bus_suggestions
info.audio_bus.set_value(audio_bus)
info.delete.icon = get_theme_icon(&"Remove", &"EditorIcons")
channel_defaults[len(channel_defaults)] = info
return info['channel_name']
func _on_remove_channel_defaults_pressed(index: int) -> void:
for key in channel_defaults[index]:
channel_defaults[index][key].queue_free()
channel_defaults.erase(index)
func get_audio_channel_suggestions(search_text:String) -> Dictionary:
var suggestions := DialogicUtil.get_audio_channel_suggestions(search_text)
for i in channel_defaults.values():
if i.channel_name is DialogicVisualEditorField:
suggestions.erase(i.channel_name.current_value)
for key in suggestions.keys():
suggestions[key].erase('tooltip')
suggestions[key]['editor_icon'] = ["AudioStreamPlayer", "EditorIcons"]
return suggestions
func revalidate_channel_names() -> void:
_revalidate_channel_names = false
for i in channel_defaults:
if (is_instance_valid(channel_defaults[i].channel_name)
and not channel_defaults[i].channel_name is Label):
channel_defaults[i].channel_name.validate()
func validate_channel_names(search_text: String, field_node: Control) -> Dictionary:
var channel_cache = {}
var result := {}
var tooltips := []
if search_text.is_empty():
result['error_tooltip'] = 'Must not be empty.'
return result
if field_node:
channel_cache[search_text] = [field_node]
if field_node.current_value != search_text:
_revalidate_channel_names = true
revalidate_channel_names.call_deferred()
# Collect all channel names entered
for i in channel_defaults:
if (is_instance_valid(channel_defaults[i].channel_name)
and not channel_defaults[i].channel_name is Label
and channel_defaults[i].channel_name != field_node):
var text := channel_defaults[i].channel_name.current_value as String
if not channel_cache.has(text):
channel_cache[text] = []
channel_cache[text].append(channel_defaults[i].channel_name)
# Check for duplicate names
if channel_cache.has(search_text) and channel_cache[search_text].size() > 1:
tooltips.append("Duplicate channel name.")
# Check for invalid characters
result = DialogicUtil.validate_audio_channel_name(search_text)
if result:
tooltips.append(result.error_tooltip)
result.error_tooltip = "\n".join(tooltips)
elif not tooltips.is_empty():
result['error_tooltip'] = "\n".join(tooltips)
return result
#endregion

View File

@@ -0,0 +1 @@
uid://cqyhm6offcitc

View File

@@ -0,0 +1,113 @@
[gd_scene load_steps=6 format=3 uid="uid://c2qgetjc3mfo3"]
[ext_resource type="Script" uid="uid://cqyhm6offcitc" path="res://addons/dialogic/Modules/Audio/settings_audio.gd" id="1_2iyyr"]
[ext_resource type="PackedScene" uid="uid://dbpkta2tjsqim" path="res://addons/dialogic/Editor/Common/hint_tooltip_icon.tscn" id="2_o1ban"]
[ext_resource type="PackedScene" uid="uid://dpwhshre1n4t6" path="res://addons/dialogic/Editor/Events/Fields/field_options_dynamic.tscn" id="3_bx557"]
[ext_resource type="PackedScene" uid="uid://kdpp3mibml33" path="res://addons/dialogic/Editor/Events/Fields/field_number.tscn" id="4_xfyvc"]
[sub_resource type="StyleBoxFlat" id="StyleBoxFlat_m57ns"]
content_margin_left = 4.0
content_margin_top = 4.0
content_margin_right = 4.0
content_margin_bottom = 4.0
bg_color = Color(1, 0.365, 0.365, 1)
draw_center = false
border_width_left = 2
border_width_top = 2
border_width_right = 2
border_width_bottom = 2
corner_detail = 1
[node name="Audio" type="VBoxContainer"]
offset_right = 121.0
offset_bottom = 58.0
script = ExtResource("1_2iyyr")
[node name="TypingSoundsTitle" type="Label" parent="."]
layout_mode = 2
theme_type_variation = &"DialogicSettingsSection"
text = "Typing Sounds"
[node name="HBoxContainer2" type="HBoxContainer" parent="."]
layout_mode = 2
[node name="Label" type="Label" parent="HBoxContainer2"]
layout_mode = 2
text = "Audio Bus"
[node name="HintTooltip" parent="HBoxContainer2" instance=ExtResource("2_o1ban")]
layout_mode = 2
texture = null
hint_text = "The default audio bus used by TypeSound nodes."
[node name="TypeSoundBus" type="OptionButton" parent="HBoxContainer2"]
unique_name_in_owner = true
layout_mode = 2
[node name="HBoxContainer3" type="HBoxContainer" parent="."]
layout_mode = 2
[node name="Label" type="Label" parent="HBoxContainer3"]
layout_mode = 2
theme_type_variation = &"DialogicSettingsSection"
text = "Audio Channel Defaults"
[node name="HintTooltip" parent="HBoxContainer3" instance=ExtResource("2_o1ban")]
layout_mode = 2
texture = null
hint_text = "Default settings for named audio channels."
[node name="Panel" type="PanelContainer" parent="."]
layout_mode = 2
theme_override_styles/panel = SubResource("StyleBoxFlat_m57ns")
[node name="VBox" type="VBoxContainer" parent="Panel"]
layout_mode = 2
[node name="AudioChannelDefaults" type="GridContainer" parent="Panel/VBox"]
unique_name_in_owner = true
layout_mode = 2
size_flags_horizontal = 3
columns = 6
[node name="AudioChannelDefaultRow" type="HBoxContainer" parent="Panel/VBox"]
unique_name_in_owner = true
visible = false
layout_mode = 2
[node name="channel_name" parent="Panel/VBox/AudioChannelDefaultRow" instance=ExtResource("3_bx557")]
layout_mode = 2
size_flags_horizontal = 3
placeholder_text = "Enter Channel Name"
mode = 3
[node name="volume" parent="Panel/VBox/AudioChannelDefaultRow" instance=ExtResource("4_xfyvc")]
layout_mode = 2
mode = 2
min = -80.0
max = 6.0
suffix = "dB"
[node name="audio_bus" parent="Panel/VBox/AudioChannelDefaultRow" instance=ExtResource("3_bx557")]
layout_mode = 2
placeholder_text = "Master"
mode = 2
[node name="fade_length" parent="Panel/VBox/AudioChannelDefaultRow" instance=ExtResource("4_xfyvc")]
layout_mode = 2
mode = 0
enforce_step = false
min = 0.0
[node name="loop" type="CheckButton" parent="Panel/VBox/AudioChannelDefaultRow"]
layout_mode = 2
[node name="delete" type="Button" parent="Panel/VBox/AudioChannelDefaultRow"]
layout_mode = 2
[node name="Add" type="Button" parent="Panel/VBox"]
layout_mode = 2
size_flags_vertical = 4
text = "Add channel"
[connection signal="pressed" from="Panel/VBox/Add" to="." method="_on_add_channel_defaults_pressed"]

View File

@@ -0,0 +1,284 @@
extends DialogicSubsystem
## Subsystem for managing background audio and one-shot sound effects.
##
## This subsystem has many different helper methods for managing audio
## in your timeline.
## For instance, you can listen to audio changes via [signal audio_started].
## Whenever a new audio event is started, this signal is emitted and
## contains a dictionary with the following keys: [br]
## [br]
## Key | Value Type | Value [br]
## ----------- | ------------- | ----- [br]
## `path` | [type String] | The path to the audio resource file. [br]
## `channel` | [type String] | The channel name to play the audio on. [br]
## `volume` | [type float] | The volume in `db` of the audio resource that will be set to the [AudioStreamPlayer]. [br]
## `audio_bus` | [type String] | The audio bus name that the [AudioStreamPlayer] will use. [br]
## `loop` | [type bool] | Whether the audio resource will loop or not once it finishes playing. [br]
signal audio_started(info: Dictionary)
## Audio node for holding audio players
var audio_node := Node.new()
## Sound node for holding sound players
var one_shot_audio_node := Node.new()
## Dictionary with info of all current audio channels
var current_audio_channels: Dictionary = {}
#region STATE
####################################################################################################
## Clears the state on this subsystem and stops all audio.
func clear_game_state(_clear_flag := DialogicGameHandler.ClearFlags.FULL_CLEAR) -> void:
stop_all_channels()
stop_all_one_shot_sounds()
## Loads the state on this subsystem from the current state info.
func load_game_state(load_flag:=LoadFlags.FULL_LOAD) -> void:
if load_flag == LoadFlags.ONLY_DNODES:
return
# Pre Alpha 17 Converter
_convert_state_info()
var info: Dictionary = dialogic.current_state_info.get("audio", {})
for channel_name in info.keys():
if info[channel_name].path.is_empty():
update_audio(channel_name)
else:
update_audio(channel_name, info[channel_name].path, info[channel_name].settings_overrides)
## Pauses playing audio.
func pause() -> void:
for child in audio_node.get_children():
child.stream_paused = true
for child in one_shot_audio_node.get_children():
child.stream_paused = true
## Resumes playing audio.
func resume() -> void:
for child in audio_node.get_children():
child.stream_paused = false
for child in one_shot_audio_node.get_children():
child.stream_paused = false
func _on_dialogic_timeline_ended() -> void:
if not dialogic.Styles.get_layout_node():
clear_game_state()
#endregion
#region MAIN METHODS
####################################################################################################
func _ready() -> void:
dialogic.timeline_ended.connect(_on_dialogic_timeline_ended)
audio_node.name = "Audio"
add_child(audio_node)
one_shot_audio_node.name = "OneShotAudios"
add_child(one_shot_audio_node)
## Plays the given file (or nothing) on the given channel.
## No channel given defaults to the "One-Shot SFX" channel,
## which does not save audio but can have multiple audios playing simultaneously.
func update_audio(channel_name:= "", path := "", settings_overrides := {}) -> void:
#volume := 0.0, audio_bus := "", fade_time := 0.0, loop := true, sync_channel := "") -> void:
if not is_channel_playing(channel_name) and path.is_empty():
return
## Determine audio settings
## TODO use .merged after dropping 4.2 support
var audio_settings: Dictionary = DialogicUtil.get_audio_channel_defaults().get(channel_name, {})
audio_settings.merge(
{"volume":0, "audio_bus":"", "fade_length":0.0, "loop":true, "sync_channel":""}
)
audio_settings.merge(settings_overrides, true)
## Handle previous audio on channel
if is_channel_playing(channel_name):
var prev_audio_node: AudioStreamPlayer = current_audio_channels[channel_name]
prev_audio_node.name += "_Prev"
if audio_settings.fade_length > 0.0:
var fade_out_tween: Tween = create_tween()
fade_out_tween.tween_method(
interpolate_volume_linearly.bind(prev_audio_node),
db_to_linear(prev_audio_node.volume_db),
0.0,
audio_settings.fade_length)
fade_out_tween.tween_callback(prev_audio_node.queue_free)
else:
prev_audio_node.queue_free()
## Set state
if not dialogic.current_state_info.has('audio'):
dialogic.current_state_info['audio'] = {}
if not path:
dialogic.current_state_info['audio'].erase(channel_name)
return
dialogic.current_state_info['audio'][channel_name] = {'path':path, 'settings_overrides':settings_overrides}
audio_started.emit(dialogic.current_state_info['audio'][channel_name])
var new_player := AudioStreamPlayer.new()
if channel_name:
new_player.name = channel_name.validate_node_name()
audio_node.add_child(new_player)
else:
new_player.name = "OneShotSFX"
one_shot_audio_node.add_child(new_player)
var file := load(path)
if file == null:
printerr("[Dialogic] Audio file \"%s\" failed to load." % path)
return
new_player.stream = load(path)
## Apply audio settings
## Volume & Fade
if audio_settings.fade_length > 0.0:
new_player.volume_db = linear_to_db(0.0)
var fade_in_tween := create_tween()
fade_in_tween.tween_method(
interpolate_volume_linearly.bind(new_player),
0.0,
db_to_linear(audio_settings.volume),
audio_settings.fade_length)
else:
new_player.volume_db = audio_settings.volume
## Audio Bus
new_player.bus = audio_settings.audio_bus
## Loop
if "loop" in new_player.stream:
new_player.stream.loop = audio_settings.loop
elif "loop_mode" in new_player.stream:
if audio_settings.loop:
new_player.stream.loop_mode = AudioStreamWAV.LOOP_FORWARD
new_player.stream.loop_begin = 0
new_player.stream.loop_end = new_player.stream.mix_rate * new_player.stream.get_length()
else:
new_player.stream.loop_mode = AudioStreamWAV.LOOP_DISABLED
## Sync & start player
if audio_settings.sync_channel and is_channel_playing(audio_settings.sync_channel):
var play_position: float = current_audio_channels[audio_settings.sync_channel].get_playback_position()
new_player.play(play_position)
# TODO Remove this once https://github.com/godotengine/godot/issues/18878 is fixed
if new_player.stream is AudioStreamWAV and new_player.stream.format == AudioStreamWAV.FORMAT_IMA_ADPCM:
printerr("[Dialogic] WAV files using Ima-ADPCM compression cannot be synced. Reimport the file using a different compression mode.")
dialogic.print_debug_moment()
else:
new_player.play()
new_player.finished.connect(_on_audio_finished.bind(new_player, channel_name, path))
if channel_name:
current_audio_channels[channel_name] = new_player
## Returns `true` if any audio is playing on the given [param channel_name].
func is_channel_playing(channel_name: String) -> bool:
return (current_audio_channels.has(channel_name)
and is_instance_valid(current_audio_channels[channel_name])
and current_audio_channels[channel_name].is_playing())
## Stops audio on all channels.
func stop_all_channels(fade := 0.0) -> void:
for channel_name in current_audio_channels.keys():
update_audio(channel_name, '', {"fade_length":fade})
### Stops all one-shot sounds.
func stop_all_one_shot_sounds() -> void:
for i in one_shot_audio_node.get_children():
i.queue_free()
## Converts a linear loudness value to decibel and sets that volume to
## the given [param node].
func interpolate_volume_linearly(value: float, node: AudioStreamPlayer) -> void:
node.volume_db = linear_to_db(value)
## Returns whether the currently playing audio resource is the same as this
## event's [param resource_path], for [param channel_name].
func is_channel_playing_file(file_path: String, channel_name: String) -> bool:
return (is_channel_playing(channel_name)
and current_audio_channels[channel_name].stream.resource_path == file_path)
## Returns `true` if any channel is playing.
func is_any_channel_playing() -> bool:
for channel in current_audio_channels:
if is_channel_playing(channel):
return true
return false
func _on_audio_finished(player: AudioStreamPlayer, channel_name: String, path: String) -> void:
if current_audio_channels.has(channel_name) and current_audio_channels[channel_name] == player:
current_audio_channels.erase(channel_name)
player.queue_free()
if dialogic.current_state_info.get('audio', {}).get(channel_name, {}).get('path', '') == path:
dialogic.current_state_info['audio'].erase(channel_name)
#endregion
#region Pre Alpha 17 Conversion
func _convert_state_info() -> void:
var info: Dictionary = dialogic.current_state_info.get("music", {})
if info.is_empty():
return
var new_info := {}
if info.has("path"):
# Pre Alpha 16 Save Data Conversion
new_info['music'] = {
"path":info.path,
"settings_overrides": {
"volume":info.volume,
"audio_bus":info.audio_bus,
"loop":info.loop}
}
else:
# Pre Alpha 17 Save Data Conversion
for channel_id in info.keys():
if info[channel_id].is_empty():
continue
var channel_name = "music"
if channel_id > 0:
channel_name += str(channel_id + 1)
new_info[channel_name] = {
"path": info[channel_id].path,
"settings_overrides":{
'volume': info[channel_id].volume,
'audio_bus': info[channel_id].audio_bus,
'loop': info[channel_id].loop,
}
}
dialogic.current_state_info['audio'] = new_info
dialogic.current_state_info.erase('music')
#endregion

View File

@@ -0,0 +1 @@
uid://do8vgqtp35d6w