-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBatchRender.py
1659 lines (1364 loc) · 69.6 KB
/
BatchRender.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import re
import tkinter as tk
from tkinter import ttk, filedialog
import subprocess
import threading
import time
import psutil
import os
import customtkinter
from CTkListbox import *
import tkinterDnD
from PIL import Image
import queue
from functools import partial
# Global variables
render_queue = queue.Queue()
current_render = None
stop_event = threading.Event()
pause_event = threading.Event()
current_render_item = None
# Initialize gsv_entries at the global level
command = ""
render_thread = None
progressbar = None
katana_bin = "katanaBin"
render_process = None
error_detected = False
stop_render_event = threading.Event()
initial_frame_rendering_detected = False
rendering_stopped = False
new_appearance_mode = "Dark"
# Flag for enabling or disabling reuse rendering process
# reuse_rendering_process_enabled = False
initial_calculation_done = False # Tracks if initial frame calculation phase is complete
manually_stopped = False
forgro_color="#1d1e1e"
gray_color= "gray"
gsv_entries = []
# Global variable to track enabled/disabled state of items
queue_item_states = []
# Initialize CustomTkinter
# customtkinter.set_ctk_parent_class(tkinterDnD.Tk)
# customtkinter.set_appearance_mode("Dark")
# customtkinter.set_default_color_theme("blue")
# Create main window
# width = 900
# height = 630
# root = customtkinter.CTk()
# root.geometry(f"{width}x{height}")
# root.title("Katana Batch Renderer")
# root.grid_rowconfigure(0, weight=1)
render_output_queue = queue.Queue()
# root.grid_columnconfigure(0, weight=1)
# root.grid_columnconfigure(1, weight=100)
# root.resizable(True, True)
# Global variables to track rendered frames
frame_range_list = []
completed_frames = set()
def parse_job_from_text(text):
"""Parses a job dictionary from the listbox item text."""
try:
parts = text.split(" | ")
katana_file = parts[0].split(". ")[1]
frame_range = parts[1].split(": ")[1]
return {"katana_file": katana_file, "frame_range": frame_range}
except Exception as e:
print(f"Error parsing job: {e}")
return None
def parse_frame_range(frame_range_str):
frames = set()
for part in frame_range_str.split(','):
if '-' in part:
start, end = map(int, part.split('-'))
frames.update(range(start, end + 1))
else:
frames.add(int(part))
return frames
def show_value(selected_option):
result_label.configure(state=tk.NORMAL) # Enable the CTkTextbox for editing
result_label.delete(1.0, tk.END) # Clear existing text
result_label.insert(tk.END, f"Selected Option: {selected_option}")
result_label.configure(state=tk.DISABLED)
# Draggable Treeview Class remains unchanged
class DraggableTreeview(ttk.Treeview):
def __init__(self, master, **kwargs):
super().__init__(master, **kwargs)
self.locked_indices = set() # Set of indices that are permanently locked (rendered)
self.currently_rendering_index = None # Index currently being rendered
self.bind('<ButtonPress-1>', self.on_drag_start)
self.bind('<B1-Motion>', self.on_drag_motion)
self.bind('<ButtonRelease-1>', self.on_drag_drop)
self.dragged_item = None
def on_drag_start(self, event):
item = self.identify_row(event.y)
if item:
tags = self.item(item, 'tags')
if 'rendering' in tags or 'rendered' in tags:
return 'break' # Prevent drag if item is rendering or rendered
current_index = self.index(item)
if current_index in self.locked_indices:
return 'break' # Prevent drag if item is locked
if self.currently_rendering_index is not None and current_index <= self.currently_rendering_index:
return 'break' # Prevent drag if item is before or currently rendering
self.dragged_item = item
self.selection_set(item)
def on_drag_motion(self, event):
if self.dragged_item:
item = self.identify_row(event.y)
if item and item != self.dragged_item:
target_index = self.index(item)
dragged_index = self.index(self.dragged_item)
if target_index in self.locked_indices:
return 'break'
if self.currently_rendering_index is not None and target_index <= self.currently_rendering_index:
return 'break'
self.move(self.dragged_item, '', target_index)
def on_drag_drop(self, event):
if self.dragged_item:
item = self.identify_row(event.y)
if item and item != self.dragged_item:
target_index = self.index(item)
dragged_index = self.index(self.dragged_item)
if target_index in self.locked_indices:
return 'break'
if self.currently_rendering_index is not None and target_index <= self.currently_rendering_index:
return 'break'
self.move(self.dragged_item, '', target_index)
self.dragged_item = None
update_row_numbers(self)
def update_row_numbers(tree):
items = tree.get_children()
for index, item in enumerate(items, start=1):
old_values = tree.item(item, "values")
# just update the #0 text to new index
tree.item(item, text=str(index), values=old_values)
# def on_render_button_click(tree):
# global render_thread
# render_thread = threading.Thread(target=lambda: render(tree))
# render_thread.start()
def disable_header_click(event):
region = event.widget.identify_region(event.x, event.y)
if region == "heading":
return "break"
def create_treeview(parent):
style = ttk.Style()
style.theme_use("default")
style.configure("Custom.Treeview.Heading",
background="#1d1e1e", # sets header background to gray
foreground="white", # sets header text color (adjust as needed)
font=("Arial", 16),
borderwidth=0,
relief="flat") # sets header font size to 16
style.map(
"Custom.Treeview.Heading",
background=[
("active", "#1d1e1e"), # same color as normal
("pressed", "#1d1e1e")
],
relief=[
("active", "flat"),
("pressed", "flat")
],
foreground=[
("active", "white"),
("pressed", "white")
]
)
# Configure a custom style named "Custom.Treeview"
style.configure(
"Custom.Treeview",
background="#2A2A2A", # dark gray background
fieldbackground="#2A2A2A", # same background color for fields
foreground="white", # white text
rowheight=25, # slightly taller rows
font=("Arial", 16),
borderwidth=0,
relief="flat"
# bigger font to match the UI
)
# Optionally, change the highlight color for selected rows:
style.map("Custom.Treeview",
background=[("selected", "#1A1A1A")])
tree = DraggableTreeview(
parent,
columns=("KatanaFile", "FrameRange", "RenderNode", "GSV", "Flags", "BatFile","Status", "KatanaFullPath", "BatFullPath", "Switch"),
style="Custom.Treeview"
)
# #0 column will show your "ID"
tree.heading("#0", text="ID", anchor="center")
tree.column("#0", width=40, anchor="center", stretch=False)
# 1) KatanaFile column
tree.heading("KatanaFile", text="Katana File", anchor="center")
tree.column("KatanaFile", width=180, anchor="center", stretch=True)
# 2) FrameRange column
tree.heading("FrameRange", text="Frame Range", anchor="center")
tree.column("FrameRange", width=150, anchor="center", stretch=True)
# 3) RenderNode column
tree.heading("RenderNode", text="Render Node", anchor="center")
tree.column("RenderNode", width=120, anchor="center", stretch=True)
# 4) GSV column
tree.heading("GSV", text="GSV", anchor="center")
tree.column("GSV", width=180, anchor="center", stretch=True)
tree.heading("Flags", text="Flags", anchor="center")
tree.column("Flags", width=150, anchor="center", stretch=True)
tree.heading("BatFile", text=".bat File", anchor="center")
tree.column("BatFile", width=150, anchor="center", stretch=True)
tree.heading("Status", text="Status", anchor="center")
tree.column("Status", width=150, anchor="center", stretch=True)
# Hidden column for full path
tree.column("KatanaFullPath", width=0, stretch=False)
tree.column("BatFullPath", width=0, stretch=False)
tree.column("Switch", width=0, stretch=False)
# No heading needed for "FullPath" if you don't want it visible:
# tree.heading("FullPath", text="Full Path") # optional
# 1) Configure tags for special text colors
# 'rendering' and 'rendered' both have gray text
tree.tag_configure("rendering", foreground="#888888") # or another shade of gray
tree.tag_configure("rendered", foreground="#888888")
tree.tag_configure("stopped", foreground="#888888")
# Expand in all directions
tree.grid(row=0, column=0, sticky="nsew")
root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)
return tree
# Queue management functions
def add_to_queue():
katana_file = entry_katana_file.get()
frame_range = entry_frame_range.get()
render_node = entry_render_node.get()
bat_file = entry_load_bat.get() # full path for the .bat file
flags_text = flags.get().strip()
if not katana_file or not frame_range:
log_debug("Please provide Katana File and Frame Range.\n")
return
# Display only the file name (last part) for both Katana and .bat file
katana_display = os.path.basename(katana_file)
bat_display = os.path.basename(bat_file) if bat_file else "Default"
# Gather GSV entries into one string
gsv_list = []
for gsv_name_entry, gsv_value_entry, _ in gsv_entries:
name = gsv_name_entry.get().strip()
value = gsv_value_entry.get().strip()
if name and value:
gsv_list.append(f"{name}={value}")
gsv_str = ", ".join(gsv_list)
# The switch value from your CTkSwitch (assumed to return 1 for on, 0 for off)
switch_value = switch.get()
job_index = len(queue_tree.get_children()) + 1
queue_tree.insert(
"",
"end",
text=str(job_index),
values=(katana_display, frame_range, render_node, gsv_str, flags_text, bat_display, "Queued", katana_file, bat_file, switch_value )
)
render_queue.put({
"katana_file": katana_file,
"frame_range": frame_range,
"render_node": render_node,
"gsv_entries": gsv_list,
"flags": flags_text,
"bat_file": bat_file,
"switch": switch_value
})
queue_item_states.append(True) # Add the job's state (True = enabled)
# Log that this item has been added.
log_debug(f"{katana_display} has been added to the queue.\n")
def remove_from_queue():
selected_item = queue_tree.selection()
if not selected_item:
log_debug("Please select a render from the queue to remove.\n")
return
for item in selected_item:
# Retrieve the Katana filename from this row
item_values = queue_tree.item(item, "values")
# item_values = (KatanaFile, FrameRange, RenderNode, GSV, FullPath)
katana_file = item_values[0] if item_values and len(item_values) > 0 else "Unknown"
# The displayed filename in your first column
log_debug(f"Removed from '{katana_file}' queue \n")
# Now actually remove it from the Treeview
queue_tree.delete(item)
# Optionally update render_queue here if needed # Update the UI to reflect the changes
# if not queue_listbox.curselection(): # Check if any item is selected
# result_label.insert(tk.END, "Please select an item from the queue to remove.\n")
# return
# selected_index = queue_listbox.curselection()[0]
# queue_items = list(render_queue.queue)
# if 0 <= selected_index < len(queue_items):
# del queue_items[selected_index]
# render_queue.queue.clear()
# for item in queue_items:
# render_queue.put(item)
# update_queue_display()
def clear_queue():
# Check if there are items in the Treeview
if not queue_tree.get_children():
log_debug("There is nothing to clear in the queue.\n")
return
for item in queue_tree.get_children():
queue_tree.delete(item)
while not render_queue.empty():
render_queue.get()
# Log that the queue has been cleared
log_debug("Queue has been cleared.\n")
def log_debug(message):
result_label.configure(state=tk.NORMAL)
result_label.delete(1.0, tk.END)
result_label.insert(tk.END, message)
result_label.configure(state=tk.DISABLED)
result_label.update_idletasks() # force update if needed
def render(tree):
global render_process, stop_render_event, pause_event, completed_frames,clear_queue_button,pause_button,current_render_item, manually_stopped
manually_stopped = False
while not stop_render_event.is_set():
items_to_render = [item for item in tree.get_children()
if not set(tree.item(item, "tags")).intersection({"rendered", "stopped"})]
if not items_to_render:
break # No more items to render
current_render_item = items_to_render[0]
current_index = tree.index(current_render_item)
# get item data
# item_values = tree.item(item_to_render, "values")
item_values = list(tree.item(current_render_item, "values"))
item_values[6] = "Currently Rendering"
# Update on main thread:
local_item = current_render_item
local_values = tuple(item_values)
root.after(0, lambda: update_item(local_item, local_values, ("rendered",), log_missing=False))
# item_values is something like: ("template.katana", "1-10", "myRenderNode", "varA=1,varB=2")
katana_full = item_values[7] # Full path
frame_range = item_values[1]
render_node = item_values[2]
flags_text = item_values[4]
switch_value = item_values[9] # hidden column
# Lock the current index for rendering
tree.currently_rendering_index = current_index
tree.locked_indices.add(current_index)
# # Mark the item as "rendering"
# tree.item(item_to_render, tags=('rendering',))
# Extract job details from the treeview row; only katana_file and frame_range are stored
# katana_file, frame_range = tree.item(item_to_render, 'values')[1:]
frame_list = parse_frame_range(frame_range)
# Build the render command using the old code’s logic
command = f'"{katana_bin}" --batch --katana-file="{katana_full}" -t {frame_range}'
if render_node.strip():
command += f' --render-node={render_node.strip()}'
if int(switch_value) == 1:
command += " --reuse-render-process"
if flags_text:
command += f" {flags_text}"
for gsv_name_entry, gsv_value_entry, _ in gsv_entries:
name = gsv_name_entry.get().strip()
value = gsv_value_entry.get().strip()
if name and value:
command += f' --var {name}={value}'
# Start the render process
try:
render_process = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True,
text=True
)
# Monitor the render process
while True:
if stop_render_event.is_set() or pause_event.is_set():
break
output = render_process.stdout.readline()
if output == '' and render_process.poll() is not None:
break # Process has finished
if output:
handle_stdout(output.strip())
render_process.wait()
except Exception as e:
log_debug(f"Error during rendering: {e}\n")
finally:
# Update status: if the render was stopped manually, mark as "Stopped Rendering",
# otherwise "Done Rendering".
if manually_stopped:
item_values[6] = "Stopped Rendering"
else:
item_values[6] = "Done Rendering"
# Mark the item as "rendered"
local_item = current_render_item # captured item id
local_values = tuple(item_values) # ensure it has the correct number of values (10 in this case)
root.after(0, lambda: update_item(local_item, local_values, ("rendered",), log_missing=False))
tree.locked_indices.add(current_index)
tree.currently_rendering_index = None
current_render_item = None
# if completed_frames >= parse_frame_range(frame_range):
# break
render_button.configure(state=tk.NORMAL)
stop_render_button.configure(state=tk.DISABLED)
progressbar.set(0)
progressbar.stop()
# Only log "Rendering Done!" if the rendering finished normally.
if not manually_stopped:
log_debug("Rendering Done!\n")
clear_queue_button.configure(state=tk.NORMAL)
pause_button.configure(state=tk.DISABLED)
def update_item(item, values, tag, log_missing=False):
if item in queue_tree.get_children():
try:
queue_tree.item(item, values=values, tags=tag)
except Exception as e:
log_debug(f"Error updating item: {e}\n")
else:
if log_missing:
log_debug("Item no longer exists in the tree.\n")
# Render management functions
def start_rendering():
global render_thread, render_process, stop_render_event, pause_event,clear_queue_button,pause_button, current_render_item
# Find only items that are not yet rendered or stopped.
valid_items = [item for item in queue_tree.get_children()
if not set(queue_tree.item(item, "tags")).intersection({"rendered", "stopped"})]
if not valid_items:
log_debug("Please add a render to the queue.\n")
return
if not queue_tree.get_children():
log_debug("Please add a render to the queue.\n")
return
if render_thread and render_thread.is_alive():
log_debug( "A render is already in progress.\n")
return
stop_render_event.clear()
pause_event.clear()
render_button.configure(state=tk.DISABLED)
stop_render_button.configure(state=tk.NORMAL)
pause_button.configure(state=tk.NORMAL)
clear_queue_button.configure(state=tk.DISABLED)
log_debug("Starting rendering...\n")
render_thread = threading.Thread(target=lambda: render(queue_tree))
render_thread.start()
def process_render(job):
global current_render, stop_event, pause_event
katana_file = job["katana_file"]
frame_range = job["frame_range"]
render_node = job["render_node"]
flags = job["flags"]
gsv_entries = job["gsv_entries"]
command = f'"{katana_bin}" --batch --katana-file="{katana_file}" -t {frame_range}'
if render_node:
command += f' --render-node={render_node}'
if switch.get() == 1: # If reuse render process is enabled
command += " --reuse-render-process"
if flags:
command += f" {flags}"
for name, value in gsv_entries:
if name and value:
command += f' --var {name}={value}'
try:
log_debug( f"Starting render: {katana_file}\n")
render_process = subprocess.Popen(
command,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
bufsize=1,
universal_newlines=True
)
if render_process:
threading.Thread(target=monitor_render_output, args=(render_process,)).start()
except Exception as e:
log_debug( f"Error during render: {e}\n")
finally:
# After finishing the render, clear the current render
current_render = None
# Update the queue display to reflect the completed render
# update_queue_display()
# Move to the next job if the queue is not empty and stop was not triggered
if not render_queue.empty() and not stop_event.is_set():
start_rendering()
def update_progress_from_process(process, progressbar):
try:
for line in iter(process.stdout.readline, b''):
update_progress(line, progressbar)
except Exception as e:
print(f"Error reading output: {e}")
finally:
process.stdout.close()
def render_frames_thread():
global render_process
global progressbar
global stop_render_event
# ... (Your existing rendering code)
try:
render_process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True,text=True, bufsize=1, universal_newlines=True)
for line in iter(render_process.stdout.readline, b''):
render_output_queue.put(line)
root.after(10, update_progress, line, progressbar)
render_thread = threading.Thread(target=monitor_render_output, args=(render_output_queue, progressbar, render_process.stdout))
render_thread.start()
# ... (Your existing code)
except Exception as e:
# print(f"Error starting rendering process: {e}")
result_label.configure(state=tk.NORMAL)
result_label.delete(1.0, tk.END)
result_label.insert(tk.END, f"Error: {e}")
result_label.configure(state=tk.DISABLED)
finally:
stop_render_event.set()
stop_render_button.configure(state=tk.DISABLED)
def monitor_render_output(process):
# def monitor_render_output(output_stream):
global render_process
global progressbar
global error_detected
global stop_render_event
global frame_range_list
global rendering_stopped, manually_stopped
error_detected = False
def read_output(pipe, output_func):
for line in iter(pipe.readline, ''):
output_func(line)
try:
for line in iter(process.stdout.readline, ''):
if stop_event.is_set(): # Check if stop event is triggered
break
if pause_event.is_set(): # Check if pause event is triggered
continue
handle_stdout(line)
handle_stderr(line)
check_frame_status(line)
process.stdout.close()
process.stderr.close()
except Exception as e:
result_label.configure(state=tk.NORMAL)
result_label.insert(tk.END, f"Error reading output: {e}\n")
result_label.configure(state=tk.DISABLED)
finally:
stop_event.set() # Signal that rendering has stopped
def read_output(pipe, output_func):
for line in iter(pipe.readline, ''):
output_func(line)
stdout_thread = threading.Thread(target=read_output, args=(process.stdout, handle_stdout))
stderr_thread = threading.Thread(target=read_output, args=(process.stderr, handle_stderr))
stdout_thread.start()
stderr_thread.start()
stdout_thread.join()
stderr_thread.join()
process.stdout.close()
process.stderr.close()
stop_render_event.set()
render_button.configure(state=tk.NORMAL)
stop_render_button.configure(state=tk.DISABLED)
result_label.configure(state=tk.NORMAL)
result_label.delete(1.0, tk.END)
progressbar.configure(mode="determinate") # Ensure it's determinate when complete
if manually_stopped:
result_label.delete(1.0, tk.END)
result_label.insert(tk.END, "Rendering Stopped")
progressbar.stop()
rendering_stopped = True
elif error_detected: # If an error was detected
result_label.delete(1.0, tk.END)
result_label.insert(tk.END, "Error Detected")
progressbar.set(0) # Set the progress to 100% (finished)
progressbar.stop()
else: # Render finished successfully
result_label.delete(1.0, tk.END)
result_label.insert(tk.END, "Rendering Completed")
progressbar.set(1) # Set the progress to 100% (finished)
progressbar.stop()
manually_stopped = False
# result_label.configure(state=tk.DISABLED)
# try:
# for line in iter(partial(output_stream.readline, 4096), ''):
# # print(line.strip()) # Debug: Print each line of output
# output_text.insert(tk.END, line)
# output_text.yview(tk.END)
# update_progress(line, progressbar)
# check_frame_completion(line)
# if completed_frames >= frame_range_list:
# stop_render_event.set()
# # Terminate the render process if it's still running
# if render_process and render_process.poll() is None:
# render_process.terminate()
# render_process.wait() # Wait for the process to finish
# render_button.configure(state=tk.NORMAL)
# stop_render_button.configure(state=tk.DISABLED)
# result_label.configure(state=tk.NORMAL) # Enable the CTkTextbox for editing
# result_label.delete(1.0, tk.END)
# result_label.insert(tk.END, "Rendering Done!")
# result_label.configure(state=tk.DISABLED) # Disable the CTkTextbox
# except Exception as e:
# print(f"Error reading output: {e}")
# finally:
# if not output_stream.closed:
# output_stream.close()
# # if completed_frames >= frame_range_list:
# stop_render_event.set()
# render_button.configure(state=tk.NORMAL)
# stop_render_button.configure(state=tk.DISABLED)
# result_label.configure(state=tk.NORMAL) # Enable the CTkTextbox for editing
# result_label.delete(1.0, tk.END)
# result_label.insert(tk.END, "Rendering Done!")
# result_label.configure(state=tk.DISABLED) # Disable the CTkTextbox
def handle_stdout(line):
output_text.insert(tk.END, line+ "\n")
output_text.yview(tk.END)
update_progress(line, progressbar)
check_frame_status(line)
global error_detected # We will track if an error occurred
# You can add logic here to search for specific error keywords in the stdout output
if check_error_in_line(line):
error_detected = True
log_debug("Error Detected\n")
else:
# Call a function to update progress bar if no error
update_progress(line, progressbar)
def handle_stderr(line):
output_text.insert(tk.END, line)
output_text.yview(tk.END)
global error_detected # We will track if an error occurred
# You can add logic here to handle errors from stderr as well
if check_error_in_line(line):
error_detected = True
log_debug("Error Detected\n")
else:
return
def check_error_in_line(line):
lower_line = line.lower()
if "[ERROR python.MainBatch]:" in lower_line or "attributeerror" in lower_line or "[error python.main]:" in lower_line or "Exiting with error code: -1" in lower_line or "(Error node: " in lower_line :
return True
return False
def check_frame_status(output_line):
# Check if a frame started rendering
global initial_frame_rendering_detected
global rendering_stopped
# if rendering_stopped:
# return # Stop checking the frames if rendering was stopped
# For reuse rendering, check if "Frame: X" pattern is in the output
if switch.get() == 1:
# Look for the actual frame rendering line "Frame: X" (where X is the frame number)
frame_match = re.search(r"Frame: (\d+)", output_line) or re.search(r"Rendering frame (\d+)", output_line)
if frame_match:
# Set the flag to True once we detect actual rendering frames
initial_frame_rendering_detected = True
# Get the frame number from the match
current_frame = int(frame_match.group(1))
# print(f"Rendering detected for frame: {current_frame}")
# Update the label to show the current frame being rendered
update_result_label(current_frame, is_completed=False)
return
# If we haven't seen "Frame: X", skip other processing
if not initial_frame_rendering_detected:
# print("Waiting for initial frame rendering to start...")
return
else:
frame_match = re.search(r"Frame: (\d+)", output_line)
if frame_match:
# Set the flag to True once we detect actual rendering frames
current_frame = int(frame_match.group(1)) # Assign current frame
# Update the label to show the current frame being rendered
update_result_label(current_frame, is_completed=False)
return
# Check for frame completion for both normal and reuse modes
complete_match = re.search(r"Frame (\d+) completed", output_line)
if complete_match:
frame = int(complete_match.group(1))
completed_frames.add(frame)
update_result_label(frame, is_completed=True)
def update_result_label(frame, is_completed):
"""Update the label to show either the currently rendering frame or completed frame."""
# Enable the result label (CTkTextbox) for updating
result_label.configure(state=tk.NORMAL)
katana_file = entry_katana_file.get()
# Clear any previous text
result_label.delete(1.0, tk.END)
katana_file_name = os.path.basename(katana_file)
# Display message based on rendering status
if is_completed:
result_label.configure(state=tk.NORMAL)
result_label.delete(1.0, tk.END)
completed_frames_str = ", ".join(map(str, sorted(completed_frames)))
result_label.insert(tk.END, f"Frame {completed_frames_str} completed for {katana_file_name}")
else:
result_label.configure(state=tk.NORMAL)
result_label.delete(1.0, tk.END)
result_label.insert(tk.END, f"Currently rendering frame {frame} for {katana_file_name}")
# Disable the result label to make it read-only
result_label.configure(state=tk.DISABLED)
def update_ui(output_queue):
try:
while True:
message = output_queue.get()
if not message:
break
output_text.insert(tk.END, message + "\n")
output_text.yview(tk.END) # Auto-scroll to the end
except Exception as e:
print(f"Error updating UI: {e}")
def update_output_text(line):
output_text.configure(state=tk.NORMAL)
output_text.insert(tk.END, line)
output_text.see(tk.END)
output_text.configure(state=tk.DISABLED)
output_text.update_idletasks()
# Add this function to update the progress bar based on the output
# Add this function to update the progress bar based on the output
def update_progress(output_line, progressbar):
# Arnold
# Search for the percentage in the output line
if "done -" in output_line and "%" in output_line:
try:
# Extract the percentage value
percentage = int(output_line.split("%")[0].split()[-1])
# Convert the percentage to a value between 0 and 1
progress = percentage / 100.0
# Update the progress bar
progressbar.configure(mode="determinate")
progressbar.stop()
progressbar.set(progress)
# print(f"Updated progress to {progress}")
except ValueError:
pass # Handle the case where the conversion to int fail
# 3Delight
# 2) Check for lines like "[INFO python.RenderLog]: 25%"
elif "[INFO python.RenderLog]:" in output_line and "%" in output_line:
try:
# Example line: "[INFO python.RenderLog]: 25%"
# Split on ']:', then strip, then remove '%'
parts = output_line.split("]:")
if len(parts) >= 2:
# e.g. parts[1] = " 25%"
percentage_str = parts[1].strip()
# Remove trailing '%'
if percentage_str.endswith("%"):
percentage_str = percentage_str[:-1].strip()
# Convert to int
percentage = int(percentage_str)
progress = percentage / 100.0
# Update the progress bar
progressbar.configure(mode="determinate")
progressbar.stop()
progressbar.set(progress)
except ValueError:
pass
#Redshift
# elif "Block" in output_line and "rendered by GPU" in output_line:
elif "Block" in output_line:
# try:
# Extract the percentage value
block_info = output_line.split("Block ")[1].split(" ")[0]
current_block, total_blocks = map(int, block_info.split('/'))
# Convert the percentage to a value between 0 and 1
percentage = (current_block / total_blocks) * 100
progress = percentage / 100.0
# Update the progress bar
progressbar.configure(mode="determinate")
progressbar.stop()
progressbar.set(progress)
# print(f"Updated progress to {progress}")
# except ValueError:
# pass # Handle the case where the conversion to int fail
# After completing a frame or when rendering starts, set progress to indeterminate
else:
# If rendering is still in progress (e.g., processing next frame)
progressbar.configure(mode="indeterminate") # Set to indeterminate mode
progressbar.start()
def _update_progress(output_line, progressbar):
# Search for the percentage in the output line
if "done -" in output_line and "%" in output_line:
try:
# Extract the percentage value
percentage = int(output_line.split("%")[0].split()[-1])
# Convert the percentage to a value between 0 and 1
progress = percentage / 100.0
# Update the progress bar
progressbar.set(progress)
# print(f"Updated progress to {progress}")
except ValueError:
pass # Handle the case where the conversion to int fails
def extract_progress_from_line(line):
# Add your logic to extract the progress value from the line
# For example, you might use regular expressions to find the progress value
# Customize this based on the format of your render output
progress_match = re.search(r"Progress: (\d+)%", line)
if progress_match:
return int(progress_match.group(1)) / 100.0
else:
return 0.0
def cleanup_on_close():
global render_process
if render_thread and render_thread.is_alive():
render_thread.join(timeout=0)
stop_render()
elif render_process and render_process.poll() is None:
stop_render()
if render_process:
try:
parent = psutil.Process(render_process.pid)
children = parent.children(recursive=True)
for child in children:
child.terminate()
parent.terminate()
parent.wait() # Wait for the parent process to finish
#result_label.configure(text="Batch rendering stopped.")
result_label.configure(state=tk.NORMAL) # Enable the CTkTextbox for editing
result_label.delete(1.0, tk.END) # Clear existing text
result_label.insert(tk.END, "Batch rendering stopped.")
result_label.configure(state=tk.DISABLED) # Disable the CTkTextbox
except Exception as e:
#result_label.configure(text=f"Error stopping render: {e}")
result_label.configure(state=tk.NORMAL) # Enable the CTkTextbox for editing
result_label.delete(1.0, tk.END) # Clear existing text
result_label.insert(tk.END, f"Error stopping render: {e}")
result_label.configure(state=tk.DISABLED) # Disable the CTkTextbox
# root.protocol("WM_DELETE_WINDOW", cleanup_on_close)
root.destroy()
def display_output(output_stream):
print("Displaying output")
for line in output_stream:
# Update the CTkText widget with the command output
root.after(10, output_text.insert, tk.END, line)
output_stream.close()
def stop_render():
global render_process, stop_render_event, rendering_stopped, manually_stopped,clear_queue_button, pause_button, current_render_item
manually_stopped = True
if current_render_item is not None:
item_values = list(queue_tree.item(current_render_item, "values"))