Skip to content

Instantly share code, notes, and snippets.

@Shilo
Last active November 7, 2024 11:37
Show Gist options
  • Save Shilo/6a0fc903f79cb75686a1583a5ae7fe28 to your computer and use it in GitHub Desktop.
Save Shilo/6a0fc903f79cb75686a1583a5ae7fe28 to your computer and use it in GitHub Desktop.
Godot 4 tool to screenshot viewport when "screenshot" export boolean is pressed.
@tool
class_name ScreenshotViewportTool extends Node
@export var screenshot: bool:
set(__):
screenshot_viewport()
func screenshot_viewport(transparent_background: bool = false, hide_debug_colors: bool = false) -> void:
var time_string: String = Time.get_datetime_string_from_system().replace(":", "-").replace("T", "-")
var scene_file_name: String = self.get_owner().scene_file_path.get_file().get_basename()
var path := "res://" + scene_file_name + "-" + time_string + '-' + str(randi() % 8999 + 1000) + ".png"
var viewport := get_viewport()
var wait_post_frame: bool = false
if transparent_background:
viewport.transparent_bg = true
wait_post_frame = true
if hide_debug_colors and temp_hide_collision_shapes(self.get_owner()):
wait_post_frame = true
if wait_post_frame:
await RenderingServer.frame_post_draw
var error: Error = viewport.get_texture().get_image().save_png(path)
if transparent_background:
viewport.transparent_bg = false
if !error:
EditorInterface.get_resource_filesystem().scan()
print("Screenshot saved: ", path)
func temp_hide_collision_shapes(parent: Node = self):
var did_hide: bool = false
if parent is CollisionShape2D:
if temp_hide_collision_shape(parent):
did_hide = true
for child in parent.get_children():
if temp_hide_collision_shapes(child):
did_hide = true
if child is CollisionShape2D:
if temp_hide_collision_shape(child):
did_hide = true
return did_hide
func temp_hide_collision_shape(collision_shape: CollisionShape2D) -> bool:
if not collision_shape.visible:
return false
collision_shape.hide()
RenderingServer.frame_post_draw.connect(func():
collision_shape.show(),
CONNECT_ONE_SHOT
)
return true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment