extends Node3D ## Phone prototype: one physical task at a time; only heard facts persist. const Profile = preload("res://scripts/profile.gd") const Soundscape = preload("res://scripts/phone_soundscape.gd") const PhoneStage = preload("res://scripts/phone_stage.gd") const SAVE_PATH := "user://profile/phone_memory.cfg" const BG := Color("0b0a12") const CARD := Color("1c1826") const INK := Color("eee9dd") const MUTED := Color("a2afb9") const ACCENT := Color("c5addf") const RED := Color("db8b80") const GREEN := Color("9bc4b0") var story: Dictionary var facts: Dictionary = {} var endings: Dictionary = {} var completed := 0 var chapter := 1 var test_mode := false var qa_mode := false var running := false var impacted := false var elapsed := 0.0 var start_tick := 0 var place := "flat" var items: Dictionary = {} var done: Dictionary = {} var fired: Dictionary = {} var events: Array = [] var busy: Dictionary = {} var busy_start := 0.0 var busy_end := 0.0 var reply_at := 0.0 var replied := false var speech_until := 0.0 var outcome := "" var heard: Array[String] = [] var archive: Array = [] var voice_cache: Dictionary = {} var voice_levels: Dictionary = {} var voice_enabled := true var master_volume := 0.65 var ui: Control var overlay: Control var menu_screen := "" var menu_content: VBoxContainer var command_list: Container var transcript: VBoxContainer var transcript_scroll: ScrollContainer var journal: RichTextLabel var clock_label: Label var status_label: Label var objects_label: Label var task_label: Label var title_label: Label var phase_label: Label var busy_bar: ProgressBar var last_caption: Label var voice: AudioStreamPlayer var soundscape: Node var siren: AudioStreamPlayer var effect: AudioStreamPlayer var hum: AudioStreamPlayer var notification_sound: AudioStreamPlayer var notification_card: PanelContainer var notifications: Array = [] var notification_cursor := 0 var unread := 0 var toast_until := 0.0 var viewing_messages := false var stage: Control var dialing := false var dial_epoch := 0 var voice_meter: AudioEffectSpectrumAnalyzerInstance var caption_tween: Tween var screen_fade: ColorRect func _ready() -> void: story = JSON.parse_string(FileAccess.get_file_as_string("res://data/phone_story.json")) voice_levels = JSON.parse_string(FileAccess.get_file_as_string("res://data/voice_levels.json")) qa_mode = "--phone-qa" in OS.get_cmdline_user_args() if not qa_mode: var saved := Profile.read_profile(SAVE_PATH, story.facts, story.endings) facts = saved.facts endings = saved.endings completed = mini(saved.loops, 10) make_audio() make_ui() show_menu() if qa_mode: call_deferred("run_qa") func run_qa() -> void: var qa = load("res://scripts/phone_qa.gd").new() await qa.run(self) func style(color: Color, border: Color = Color.TRANSPARENT, radius: int = 16) -> StyleBoxFlat: var box := StyleBoxFlat.new() box.bg_color = color box.border_color = border box.set_border_width_all(1) box.set_corner_radius_all(radius) box.content_margin_left = 18 box.content_margin_right = 18 box.content_margin_top = 14 box.content_margin_bottom = 14 return box func label(text: String, size: int = 20, color: Color = INK) -> Label: var node := Label.new() node.text = text node.add_theme_font_size_override("font_size", size) node.add_theme_color_override("font_color", color) node.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART return node func button(text: String, id: String, callback: Callable) -> Button: var node := Button.new() node.text = text node.set_meta("action", id) node.custom_minimum_size.y = 48 node.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART node.add_theme_stylebox_override("normal", style(Color("282230"), Color("483e55"), 12)) node.add_theme_stylebox_override("hover", style(Color("3b2e46"), ACCENT, 12)) node.add_theme_stylebox_override("pressed", style(Color("51405d"), ACCENT, 12)) node.add_theme_stylebox_override("disabled", style(Color("1b252c"), Color("2b353d"), 10)) node.add_theme_color_override("font_color", INK) node.add_theme_color_override("font_hover_color", INK) node.add_theme_color_override("font_disabled_color", Color("65717b")) node.pressed.connect(callback) return node func column(parent: Node, width: float = 0) -> VBoxContainer: var box := VBoxContainer.new() box.add_theme_constant_override("separation", 12) box.size_flags_vertical = Control.SIZE_EXPAND_FILL box.custom_minimum_size.x = width parent.add_child(box) return box func panel(parent: Node, width: float = 0) -> VBoxContainer: var shell := PanelContainer.new() shell.custom_minimum_size.x = width shell.size_flags_vertical = Control.SIZE_EXPAND_FILL shell.add_theme_stylebox_override("panel", style(CARD)) parent.add_child(shell) return column(shell) func make_ui() -> void: var layer := CanvasLayer.new() add_child(layer) ui = Control.new() ui.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT) var theme := Theme.new() theme.default_font_size = 19 ui.theme = theme layer.add_child(ui) stage = PhoneStage.new() ui.add_child(stage) stage.build(self) refresh() func clear_children(parent: Node) -> void: for child in parent.get_children(): parent.remove_child(child) child.queue_free() func close_overlay() -> void: menu_screen = "" menu_content = null stage.set_menu_mode(false) viewing_messages = false stage.close_inbox() stage.center_region.modulate.a = 1.0 if is_instance_valid(overlay): overlay.get_parent().remove_child(overlay) overlay.queue_free() overlay = null func show_messages() -> void: close_overlay() viewing_messages = true unread = 0 notification_card.visible = false var box: VBoxContainer = stage.inbox() var back := button("‹ " + str(story.friend), "close_messages", func(): close_overlay() if impacted: show_ending()) back.add_theme_font_size_override("font_size",18) box.add_child(back) box.add_child(label("Мама · звонок продолжается" if running else "После звонка",12,ACCENT)) var scroll := ScrollContainer.new() scroll.custom_minimum_size = Vector2(0,350) scroll.size_flags_vertical = Control.SIZE_EXPAND_FILL scroll.horizontal_scroll_mode = ScrollContainer.SCROLL_MODE_DISABLED box.add_child(scroll) var messages := column(scroll) messages.size_flags_horizontal = Control.SIZE_EXPAND_FILL if notifications.is_empty(): messages.add_child(label("Пока нет сообщений.",15,MUTED)) for entry in notifications: var card := PanelContainer.new() var bubble := style(Color("373041"),Color.TRANSPARENT,13) bubble.content_margin_left = 10 bubble.content_margin_right = 10 bubble.content_margin_top = 10 bubble.content_margin_bottom = 10 card.add_theme_stylebox_override("panel",bubble) messages.add_child(card) var content := column(card) content.add_theme_constant_override("separation",6) content.add_child(label(entry.text,15)) content.add_child(label("%02d:%02d" % [int(entry.at)/60,int(entry.at)%60],11,ACCENT)) scroll_inbox_to_latest.call_deferred(scroll) func scroll_inbox_to_latest(scroll: ScrollContainer) -> void: await get_tree().process_frame if is_instance_valid(scroll): scroll.scroll_vertical = int(scroll.get_v_scroll_bar().max_value) func update_notifications(second: float) -> void: if not running and not impacted: return while notification_cursor < story.notifications.size(): var entry: Dictionary = story.notifications[notification_cursor] if second < float(entry.at): break notifications.append(entry.duplicate()) notification_cursor += 1 unread += 1 notification_sound.play() if viewing_messages: show_messages() else: show_notification(entry, second) if notification_card.visible and second >= toast_until: notification_card.visible = false func show_notification(entry: Dictionary, second: float) -> void: clear_children(notification_card) var content := column(notification_card) content.add_theme_constant_override("separation",5) var heading := HBoxContainer.new() content.add_child(heading) var sender := label(str(story.friend) + " · сейчас",13,Color("e7d5ed")) sender.size_flags_horizontal = Control.SIZE_EXPAND_FILL heading.add_child(sender) var dismiss := button("×", "dismiss_push", func(): notification_card.visible = false) dismiss.autowrap_mode = TextServer.AUTOWRAP_OFF dismiss.custom_minimum_size = Vector2(26,26) dismiss.add_theme_font_size_override("font_size",16) var empty := StyleBoxEmpty.new() for state in ["normal","hover","pressed"]: dismiss.add_theme_stylebox_override(state,empty) heading.add_child(dismiss) var message := button(entry.text,"open_push",show_messages) var message_size := ThemeDB.fallback_font.get_multiline_string_size(entry.text,HORIZONTAL_ALIGNMENT_LEFT,210,15) message.custom_minimum_size = Vector2(210,maxf(44,message_size.y)) message.alignment = HORIZONTAL_ALIGNMENT_LEFT message.add_theme_font_size_override("font_size",15) for state in ["normal","hover","pressed"]: message.add_theme_stylebox_override(state,empty) content.add_child(message) notification_card.visible = true notification_card.size = Vector2(234,0) notification_card.position.y = 30 var tween := create_tween() tween.tween_property(notification_card,"position:y",42.0,0.4).set_trans(Tween.TRANS_SINE).set_ease(Tween.EASE_OUT) fit_notification.call_deferred() toast_until = second + (12.0 if notification_cursor == 5 else 7.0) func fit_notification() -> void: await get_tree().process_frame await get_tree().process_frame notification_card.size = Vector2(234,notification_card.get_combined_minimum_size().y + 6) func modal() -> VBoxContainer: close_overlay() stage.center_region.modulate.a = 0.0 var holder := Control.new() holder.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT) holder.mouse_filter = Control.MOUSE_FILTER_IGNORE ui.add_child(holder) overlay = holder var region := MarginContainer.new() region.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT) region.offset_left = 348 region.offset_right = -300 region.offset_top = 80 region.offset_bottom = -24 region.mouse_filter = Control.MOUSE_FILTER_IGNORE holder.add_child(region) var center := CenterContainer.new() center.mouse_filter = Control.MOUSE_FILTER_IGNORE region.add_child(center) var shell := PanelContainer.new() shell.custom_minimum_size.x = 690 shell.add_theme_stylebox_override("panel",style(Color("1c1826"),Color("493d57"),24)) center.add_child(shell) return column(shell) func show_memory() -> void: var box := modal() box.add_child(label("Ты помнишь",30,ACCENT)) box.add_child(label("Вещи остаются у мамы. Между звонками — только память.",17,MUTED)) var text := RichTextLabel.new() text.custom_minimum_size = Vector2(640,410) text.add_theme_font_size_override("normal_font_size",20) text.text = journal.text box.add_child(text) box.add_child(button("Вернуться к звонку","close_memory",close_overlay)) func menu_page(page: String) -> VBoxContainer: close_overlay() menu_screen = page stage.set_menu_mode(true) var holder := MarginContainer.new() holder.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT) for edge in ["left","right","top","bottom"]: holder.add_theme_constant_override("margin_"+edge,32) ui.add_child(holder) overlay = holder var center := CenterContainer.new() holder.add_child(center) var box := column(center) box.custom_minimum_size.x = 620 box.add_theme_constant_override("separation",16) menu_content = box return box func menu_action(box: VBoxContainer, text: String, id: String, callback: Callable, primary: bool = false) -> void: var control := button(text,id,callback) control.custom_minimum_size.y = 54 control.mouse_default_cursor_shape = Control.CURSOR_POINTING_HAND control.add_theme_stylebox_override("normal",style(Color("2d2233") if primary else Color(0.065,0.055,0.08,0.85),Color("53405b") if primary else Color("2d2637"),14)) box.add_child(control) func return_to_call() -> void: close_overlay() if impacted: show_ending() func _unhandled_key_input(event: InputEvent) -> void: if not event is InputEventKey or not event.pressed or event.echo or event.keycode != KEY_ESCAPE: return get_viewport().set_input_as_handled() if dialing: return if not menu_screen.is_empty(): if menu_screen != "main": show_menu() elif running or impacted: return_to_call() elif viewing_messages: return_to_call() elif is_instance_valid(overlay) and running: close_overlay() else: show_menu() func show_menu() -> void: var box := menu_page("main") box.add_child(stage.centered("Не клади трубку",52,INK)) box.add_child(stage.centered("Девяносто секунд рядом с мамой.\nГолос, память и то, что удалось услышать.",19,MUTED)) var space := Control.new() space.custom_minimum_size.y = 12 box.add_child(space) if running or impacted: menu_action(box,"Вернуться к звонку" if running else "Итоги звонка","resume",return_to_call,true) else: menu_action(box,"Позвонить маме" if completed == 0 else "Продолжить · звонок %d" % mini(completed + 1, 10),"start",func(): dial_call(mini(completed+1,10),false),true) menu_action(box,"Проверка сцен","testing",show_test_menu) menu_action(box,"Звук и титры","settings",show_settings) menu_action(box,"Выйти из игры","quit",func(): get_tree().quit()) func show_settings() -> void: var box := menu_page("settings") box.add_child(stage.centered("Звук и титры",34,INK)) var enabled := CheckButton.new() enabled.text = "Озвучка реплик" enabled.button_pressed = voice_enabled enabled.toggled.connect(func(value): voice_enabled = value if not value: voice.stop()) box.add_child(enabled) box.add_child(label("Общая громкость", 20)) var slider := HSlider.new() slider.min_value = 0 slider.max_value = 1 slider.step = 0.05 slider.value = master_volume slider.value_changed.connect(func(value): master_volume = value AudioServer.set_bus_volume_db(0, linear_to_db(maxf(0.0001, value)))) box.add_child(slider) box.add_child(label("Фон и звуки окружения", 20)) var background := HSlider.new() background.name = "BackgroundVolume" background.min_value = 0 background.max_value = 1 background.step = 0.05 background.value = soundscape.volume background.value_changed.connect(soundscape.set_volume) box.add_child(background) box.add_child(label("Во время речи фон автоматически становится тише.", 16, MUTED)) menu_action(box,"Назад","back_menu",show_menu) func show_test_menu() -> void: var box := menu_page("testing") box.add_child(stage.centered("Проверка сцен",34,INK)) box.add_child(label("Отдельная сессия для тестирования. Основное сохранение не меняется.", 20, MUTED)) var choices := OptionButton.new() choices.custom_minimum_size.y = 48 for entry in story.chapters: choices.add_item("%02d · %s" % [entry.number, entry.title]) choices.set_meta("test_chapter", true) box.add_child(choices) var knowledge := OptionButton.new() knowledge.custom_minimum_size.y = 48 knowledge.add_item("Начать без знаний") knowledge.add_item("Использовать мою память") knowledge.add_item("Все знания для проверки маршрутов") knowledge.set_meta("test_knowledge", true) box.add_child(knowledge) menu_action(box,"Начать проверку","test_start",func(): dial_call(choices.selected+1,true,knowledge.selected),true) menu_action(box,"Назад","back_menu",show_menu) func dial_call(number: int, testing: bool, knowledge: int = 1, animate_in_qa: bool = false) -> void: if dialing: return if qa_mode and not animate_in_qa: begin_call(number,testing,knowledge) return dial_epoch += 1 var epoch := dial_epoch dialing = true running = false impacted = false close_overlay() voice.stop() effect.stop() siren.stop() hum.stop() soundscape.stop() stage.begin_dial() await get_tree().create_timer(2.4).timeout if epoch != dial_epoch: return begin_call(number,testing,knowledge) func begin_call(number: int, testing: bool, knowledge: int = 1) -> void: dial_epoch += 1 dialing = false # A test never writes the normal profile, including learned facts. if not qa_mode: var saved := Profile.read_profile(SAVE_PATH, story.facts, story.endings) facts = saved.facts endings = saved.endings completed = mini(saved.loops, 10) test_mode = testing if testing and knowledge == 0: facts = {} if testing and knowledge == 2: facts = {} for key in story.facts: facts[key] = true chapter = clampi(number, 1, 10) close_overlay() voice.stop() effect.stop() hum.stop() notification_sound.stop() notification_card.visible = false notifications.clear() notification_cursor = 0 unread = 0 siren.stop() soundscape.begin_call() screen_fade.color.a = 0 elapsed = 0 speech_until = 0 place = "flat" items = {} done = {} fired = {} busy = {} heard.clear() archive.clear() outcome = "" impacted = false running = true clear_children(transcript) start_tick = Time.get_ticks_msec() events = [] if chapter == 1: for beat in story.intro: events.append(beat.duplicate()) else: var entry: Dictionary = story.chapters[chapter - 1] var opening_at := voice_length("greeting") + 0.2 events.append({"at": opening_at, "line": entry.opening}) events.append({"at": opening_at + 0.3 + voice_length(entry.opening), "line": entry.reply}) say("greeting") refresh() func _process(_delta: float) -> void: soundscape.update_mix(_delta, voice_enabled and voice.playing) stage.update(_delta) if not running and not impacted: return var second := maxf(0, (Time.get_ticks_msec() - start_tick) / 1000.0) if running: elapsed = second advance() update_notifications(second) if impacted: screen_fade.color.a = lerpf(0.9,0.10,clampf((second-90.0)/1.8,0.0,1.0)) func advance() -> void: if not running: return # Resolve scheduled events chronologically, even if a frame spans several # boundaries. An action completed at 44 s still counts after a 46 s frame; # a laptop action completing at 46 s is cancelled by the 45 s power cut. var target := elapsed while running: var next_time := float(story.timeline.impact) var kind := "impact" for id in ["alarm", "power", "hum"]: if not fired.has(id) and float(story.timeline[id]) < next_time: next_time = story.timeline[id] kind = id if not events.is_empty() and float(events[0].at) < next_time: next_time = events[0].at kind = "dialogue" if not busy.is_empty(): if not replied and reply_at < next_time: next_time = reply_at kind = "reply" if busy_end < next_time: next_time = busy_end kind = "finish" if next_time > target: break elapsed = next_time soundscape.advance(elapsed, place) match kind: "impact": fired.impact = elapsed strike() return "alarm": fired.alarm = elapsed siren.volume_db = -70 siren.play() system_caption("На мамином конце слышна сирена.") "power": fired.power = elapsed system_caption("Свет в квартире погас. Щелчок — гул холодильника исчезает.") soundscape.power_cut(elapsed) if not busy.is_empty() and busy.get("power", false): busy = {} soundscape.cancel_task() say("late_mail") elif busy.is_empty(): say("power") refresh_commands() "hum": fired.hum = elapsed # The final reaction owns the rest of the call. Stop pending requests # before speaking, so neither a late reply nor a click can replace it. events.clear() busy = {} soundscape.cancel_task() hum.play() say("hum") refresh_commands() "dialogue": var event: Dictionary = events.pop_front() if busy.is_empty() and not fired.has("hum"): say(event.line) "reply": replied = true # Leave a clean breath before the fixed final line. Katya may be cut # short by that line, but do not begin a mother reply that cannot fit. if elapsed + voice_length(busy.response) + 0.2 <= float(story.timeline.hum): say(busy.response) else: # An unheard answer must not grant knowledge or items just before # the final reaction. That reaction will interrupt the request. busy_end = maxf(busy_end,float(story.timeline.hum)) "finish": finish_task() elapsed = target soundscape.advance(elapsed, place) refresh_live() func command_allowed(action: Dictionary) -> bool: if not running or chapter == 1 or fired.has("hum") or elapsed >= float(story.timeline.hum) or not busy.is_empty(): return false if action.get("once", false) and done.has(action.id): return false if action.has("places") and place not in action.places: return false if action.get("power", false) and elapsed >= float(story.timeline.power): return false for key in action.get("facts", []): if not facts.has(key): return false for key in action.get("unknown", []): if facts.has(key): return false for key in action.get("items", []): if not items.has(key): return false for key in action.get("missing", []): if items.has(key): return false return true func action_duration(action: Dictionary) -> float: var length := maxf(float(action.seconds), voice_length(action.request) + voice_length(action.response) + 0.35) if action.get("needs_light", false) and (elapsed >= float(story.timeline.power) or place in ["landing", "alcove"]) and not items.has("lamp"): length += 7 return length func choose_action(id: String) -> void: # Re-check state, time, and the visible control when a queued click arrives. if running: elapsed = (Time.get_ticks_msec() - start_tick) / 1000.0 if running: advance() if not can_respond(): return if is_instance_valid(overlay): return var control := action_button(id) if control == null or control.disabled: return var selected: Dictionary = {} for action in story.actions: if action.id == id: selected = action if id == "question": var entry: Dictionary = story.chapters[chapter - 1] selected = {"id": "question", "label": "Спросить маму", "seconds": 8, "request": entry.question, "response": entry.answer, "once": true} if selected.is_empty() or not command_allowed(selected): return events.clear() busy = selected.duplicate(true) busy_start = elapsed busy_end = elapsed + action_duration(selected) reply_at = maxf(elapsed + voice_length(selected.request) + 0.2, busy_end - voice_length(selected.response)) replied = false soundscape.schedule_task(id, elapsed + voice_length(selected.request) + 0.12, reply_at) say(selected.request) if selected.get("needs_light", false) and (elapsed >= float(story.timeline.power) or place in ["landing", "alcove"]) and not items.has("lamp"): system_caption("Без фонаря мама будет искать на ощупь. Это займёт дольше.") refresh_commands() func finish_task() -> void: var action := busy.duplicate(true) busy = {} soundscape.cancel_task() done[action.id] = true for key in action.get("learn", []): if not facts.has(key): facts[key] = true system_caption("Ты запомнила: " + str(story.facts[key])) for key in action.get("give", []): items[key] = true if action.has("move"): place = action.move if place == "alcove" and not items.has("connected"): system_caption("Голос рассыпается. Связь здесь слабее.") save_progress() refresh() func save_progress() -> void: if qa_mode or test_mode: return var result := Profile.write_profile(SAVE_PATH, facts, endings, completed) if result != OK: system_caption("Не удалось сохранить память на диске.") func strike() -> void: if impacted: return impacted = true running = false busy = {} events.clear() voice.stop() soundscape.stop() siren.stop() hum.stop() effect.stream = load("res://assets/audio/impact_cc0.wav") effect.play() outcome = "connected" if place == "alcove" and items.has("connected") else place endings[outcome] = true if not test_mode: completed = maxi(completed, chapter) save_progress() screen_fade.color = Color(0, 0, 0, 0.94) status_label.text = "Соединение прервано" refresh_commands() refresh_live() if menu_screen == "main": show_menu() if viewing_messages: show_messages() if qa_mode: return var epoch := start_tick await get_tree().create_timer(2.0).timeout if epoch != start_tick or not impacted: return screen_fade.color.a = 0.15 if outcome == "connected": say("after_alive") await get_tree().create_timer(voice_length("after_alive") + 1.0).timeout else: say("after_call") await get_tree().create_timer(voice_length("after_call") + 0.8).timeout if epoch == start_tick and impacted and not viewing_messages and menu_screen.is_empty(): show_ending() func show_ending() -> void: var entry: Dictionary = story.endings[outcome] var box := modal() box.add_child(label("ЗВОНОК ОБОРВАН · 01:30", 17, RED)) box.add_child(label(entry.title, 42)) box.add_child(label(entry.text, 23)) box.add_child(label("Знаний: %d / %d · Звонок: %d / 10" % [facts.size(), story.facts.size(), chapter], 18, MUTED)) if chapter == 10: box.add_child(label("Ты могла выбирать слова и действия.\nТы не могла остановить то, что происходило с домом.", 22, ACCENT)) box.add_child(button("Перезвонить · следующая итерация" if chapter < 10 else "Ещё один звонок", "next", func(): continue_call())) box.add_child(button("Повторить этот звонок", "retry", func(): continue_call(true))) box.add_child(button("Прочитать разговор", "transcript", show_transcript)) box.add_child(button("Сообщения от подруги", "ending_messages", show_messages)) box.add_child(button("В меню", "end_menu", show_menu)) func continue_call(retry: bool = false) -> void: # Test discoveries persist across test redials but never reach the disk save. var remembered := facts.duplicate() var number := chapter if retry else mini(chapter + 1, 10) var was_test := test_mode await dial_call(number, was_test) if was_test: facts = remembered refresh() func show_transcript() -> void: var box := modal() box.add_child(label("Последний разговор", 32)) var text := RichTextLabel.new() text.custom_minimum_size = Vector2(640, 430) text.add_theme_font_size_override("normal_font_size", 21) for entry in archive: text.append_text("%02d:%02d %s\n%s\n\n" % [int(entry.at) / 60, int(entry.at) % 60, entry.speaker, entry.text]) box.add_child(text) box.add_child(button("Назад", "back_ending", show_ending)) func refresh() -> void: if not is_instance_valid(journal): return var entry: Dictionary = story.chapters[chapter - 1] title_label.text = entry.title phase_label.text = ("ПРОВЕРКА · " if test_mode else "") + "ЗВОНОК %02d / 10" % chapter journal.text = "Пока только её голос." if facts.is_empty() else "" for key in story.facts: if facts.has(key): journal.append_text(str(story.facts[key]) + "\n\n") refresh_commands() refresh_live() func refresh_commands() -> void: if not is_instance_valid(command_list): return clear_children(command_list) if not running: var silence: Label = stage.centered("Линия молчит.",20,MUTED) silence.custom_minimum_size = Vector2(300,60) command_list.add_child(silence) return if fired.has("hum"): return if chapter == 1: var note: Label = stage.centered("Вы просто разговариваете.\nКажется, на всё ещё есть время.",19,Color("91839f")) note.custom_minimum_size = Vector2(400,85) command_list.add_child(note) return if not busy.is_empty(): return var entry: Dictionary = story.chapters[chapter - 1] if not done.has("question"): command_list.add_child(stage.chip("«"+str(story.lines[entry.question].text)+"»","question",func():choose_action("question"))) var names := {"look":"У входной двери", "keys_search":"Найти ключи", "keys_fast":"Ключи в куртке", "lamp_search":"Проверить фонарь", "lamp_fast":"Повернуть батарейку", "mail_hint":"Вспомнить письмо", "read_mail":"Прочитать почту", "safe":"Сейф · 0417", "front":"На площадку", "stairs":"Проверить лестницу", "side_try":"Боковая дверь", "side_open":"Ручку вверх и ключ", "inner":"Во внутренний коридор", "back":"Вернуться в квартиру", "neighbor":"Постучать соседке", "phone_test":"Проверить связь", "phone_shelf":"Телефон на полку", "speak_here":"Мам, я здесь", "speak_love":"Я люблю тебя"} for action in story.actions: if command_allowed(action): var id: String = action.id var caption := str(names.get(id,action.label)) var b: Button = stage.chip(caption,id,func():choose_action(id)) command_list.add_child(b) update_choice_state() func speech_finished() -> bool: return elapsed >= speech_until and (not voice_enabled or not voice.playing) func can_respond() -> bool: return running and chapter != 1 and not fired.has("hum") and busy.is_empty() and events.is_empty() and speech_finished() func update_choice_state() -> void: for child in command_list.get_children(): if child is Button: child.disabled = not can_respond() func refresh_live() -> void: if running and fired.has("alarm"): var rise := clampf((elapsed-float(story.timeline.alarm))/6.0,0.0,1.0) rise = rise*rise*(3.0-2.0*rise) siren.volume_db = linear_to_db(lerpf(db_to_linear(-70),db_to_linear(-8),rise)) status_label.text = "Плохая связь" if place == "alcove" and not items.has("connected") else "На линии" if not running: status_label.text = "Соединение прервано" if impacted else "Готова позвонить" var held: Array[String] = [] for key in items: held.append({"keys": "ключи", "lamp": "фонарь", "spare": "запасной ключ", "connected": "телефон на полке"}[key]) objects_label.text = "У мамы: " + (", ".join(held) if not held.is_empty() else "телефон") task_label.text = str(busy.label) if not busy.is_empty() else ("Дождись окончания реплики" if not can_respond() else "Что сказать маме?") if not running or fired.has("hum"): task_label.text = "" if chapter == 1: task_label.text = "" update_choice_state() busy_bar.visible = not busy.is_empty() if not busy.is_empty(): busy_bar.value = clampf((elapsed - busy_start) / (busy_end - busy_start) * 100, 0, 100) stage.refresh_call_display() func action_button(id: String, node: Node = null) -> Button: if node == null: node = ui if node is Button and node.is_visible_in_tree() and node.get_meta("action", "") == id: return node for child in node.get_children(): var found := action_button(id, child) if found != null: return found return null func voice_stream(id: String) -> AudioStream: if not voice_cache.has(id): var path := "res://assets/voice/%s.wav" % id if ResourceLoader.exists(path): voice_cache[id] = load(path) else: return null return voice_cache[id] func voice_length(id: String) -> float: var stream := voice_stream(id) return stream.get_length() if stream != null else maxf(2.0, str(story.lines[id].text).length() / 13.0) func say(id: String) -> void: if running and fired.has("hum") and id != "hum": return var entry: Dictionary = story.lines[id] heard.append(id) stage.speaker = entry.speaker speech_until = elapsed + voice_length(id) + 0.08 update_choice_state() add_caption(entry.speaker, entry.text) voice.stop() if id == "intro_04": soundscape.turn_tv_down() if id == "intro_06": soundscape.world_cue("footsteps", elapsed + voice_length(id) + 0.1) if voice_enabled: voice.bus = "Phone" if entry.speaker == "Мама" else "Dialogue" voice.stream = voice_stream(id) if voice.stream != null: soundscape.dialogue_started(float(voice_levels.get(id, -25.0)) - (3.0 if entry.speaker == "Мама" else 0.0)) voice.play() func system_caption(text: String) -> void: add_caption("", text) func add_caption(speaker: String, text: String) -> void: if caption_tween != null: caption_tween.kill() archive.append({"at":elapsed,"speaker":speaker,"text":text}) var content := VBoxContainer.new() content.add_theme_constant_override("separation",9) content.size_flags_horizontal = Control.SIZE_EXPAND_FILL transcript.add_child(content) if not speaker.is_empty(): var color := PhoneStage.PINK if speaker == "Катя" else PhoneStage.VIOLET content.add_child(stage.centered(speaker.to_upper(),12,color)) content.add_child(stage.centered(text,25 if not speaker.is_empty() else 15,INK if not speaker.is_empty() else MUTED)) # A new line takes focus; the complete conversation stays scrollable above it. for child in transcript.get_children(): child.modulate.a = 0.48 if child != content else 1.0 content.modulate.a = 0.0 caption_tween = content.create_tween() caption_tween.tween_property(content,"modulate:a",1.0,0.35) last_caption.text = "" call_deferred("scroll_to_latest") func scroll_to_latest() -> void: await get_tree().process_frame transcript_scroll.scroll_vertical = int(transcript_scroll.get_v_scroll_bar().max_value) func make_audio() -> void: voice = AudioStreamPlayer.new() soundscape = Soundscape.new() add_child(soundscape) soundscape.setup() siren = AudioStreamPlayer.new() effect = AudioStreamPlayer.new() hum = AudioStreamPlayer.new() notification_sound = AudioStreamPlayer.new() for player in [voice, siren, effect, hum, notification_sound]: add_child(player) for player in [siren, effect, hum]: player.bus = "SceneAudio" AudioServer.add_bus() var bus := AudioServer.bus_count - 1 AudioServer.set_bus_name(bus, "Dialogue") var spectrum := AudioEffectSpectrumAnalyzer.new() spectrum.buffer_length = 0.1 AudioServer.add_bus_effect(bus,spectrum) voice_meter = AudioServer.get_bus_effect_instance(bus,0) AudioServer.add_bus() bus = AudioServer.bus_count - 1 AudioServer.set_bus_name(bus, "Phone") AudioServer.set_bus_send(bus,"Dialogue") var high := AudioEffectHighPassFilter.new() high.cutoff_hz = 220 var low := AudioEffectLowPassFilter.new() low.cutoff_hz = 3600 AudioServer.add_bus_effect(bus, high) AudioServer.add_bus_effect(bus, low) voice.volume_db = -2 var alarm := load("res://assets/audio/siren_user.wav") as AudioStreamWAV alarm = alarm.duplicate() alarm.loop_mode = AudioStreamWAV.LOOP_FORWARD alarm.loop_end = int(alarm.get_length()*alarm.mix_rate) siren.stream = alarm siren.volume_db = -70 effect.volume_db = -12 hum.stream = load("res://assets/audio/approach.wav") hum.volume_db = -25 notification_sound.stream = load("res://assets/audio/click.wav") notification_sound.volume_db = -22 AudioServer.set_bus_volume_db(0, linear_to_db(master_volume))