Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
# Unreleased

- Speed up installed VPK indexing and primary animation graph lookup without changing asset validation or graph collision handling.
- Reuse the evaluated Blender scene for all character checks at a given frame and prepare cloth proxy skinning data once per rig.
- Reuse the checked shader inventory between models and carry verified map file identities from the export worker to Blender.
- Write sprite and trail particle curves in batches and keep visibility keys at lifetime transitions.

# 0.3.0b36 - Midtown from deadlockrigs 1.0.7

- Build maps with Sirsyorrz's deadlockrigs release 1.0.7 and the official Source 2 Viewer 21.1 release, both run unmodified. Map > Build from game downloads and checks them.
Expand Down
12 changes: 8 additions & 4 deletions agr/animation.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ def __init__(self, table: dict):
self.tick = -float('inf')
self.cached = None

def at(self, tick: int) -> tuple[dict, list[str]]:
def at(self, tick: int) -> tuple[dict, list[str], dict[int, list[str]]]:
if tick < self.tick:
raise AnimationError('Recipe input is not ordered by replay tick')
self.tick = tick
Expand All @@ -151,7 +151,11 @@ def at(self, tick: int) -> tuple[dict, list[str]]:
raise AnimationError('Animation task registry is empty or sparse')
assets = {r['name']: self.parse_asset(r)
for r in self.state.get('AnimAssetData', {}).values()}
self.cached = assets, [tasks[i]['name'] for i in range(len(tasks))]
graphs_by_id: dict[int, list[str]] = {}
for name in assets:
if name.endswith('.vnmgraph'):
graphs_by_id.setdefault(resource_id(name), []).append(name)
self.cached = assets, [tasks[i]['name'] for i in range(len(tasks))], graphs_by_id
return self.cached


Expand Down Expand Up @@ -538,9 +542,9 @@ def evaluate_segment(segment_path: Path, output: Path, assets: Path,
for row in selected_raw:
if row['demo_tick'] > desired[-1]:
break
recorded, registry = timeline.at(row['demo_tick'])
recorded, registry, graphs_by_id = timeline.at(row['demo_tick'])
primary = int(_field(row, 'm_primaryGraphId'))
matches = [g for g in recorded if g.endswith('.vnmgraph') and resource_id(g) == primary]
matches = graphs_by_id.get(primary, ())
if len(matches) != 1:
raise AnimationError(f'Asset pack has no graph/skeleton mapping for primary graph ID {primary}')
current = matches[0]
Expand Down
23 changes: 19 additions & 4 deletions agr/asset_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,9 +189,10 @@ def model(self, resource_path, provider):
# Material texture channels are discovered from compiled shader files,
# not just RERL dependencies. Without these, VRF can silently omit normal
# textures and mispack roughness while still producing a valid GLB.
shaders = sorted(p for p in provider.resources if p.endswith('.vcs'))
for path in shaders:
resolved = provider.resolve(path)
inventory = getattr(provider, 'compiled_shaders', None)
shaders = inventory() if inventory else tuple(
provider.resolve(path) for path in sorted(provider.resources) if path.endswith('.vcs'))
for resolved in shaders:
records[resolved.resource_path] = resolved
inputs = {p: r.sha256 for p, r in sorted(records.items())}
settings = {'format': 'glb', 'materials': True, 'rig': True,
Expand All @@ -204,7 +205,21 @@ def build(temp):
for p, resolved in records.items():
target = tree / p
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(resolved.local_path, target)
if p.endswith('.vcs'):
try:
shader = resolved.local_path.read_bytes()
except FileNotFoundError:
shader = None
if shader is None or hashlib.sha256(shader).hexdigest() != resolved.sha256:
refreshed = provider.resolve(p)
if refreshed.sha256 != resolved.sha256:
raise ConversionError(f'Game shader changed during model conversion: {p}')
shader = refreshed.local_path.read_bytes()
if hashlib.sha256(shader).hexdigest() != resolved.sha256:
raise ConversionError(f'Cached game shader changed during model conversion: {p}')
target.write_bytes(shader)
else:
shutil.copyfile(resolved.local_path, target)
gameinfo = tree / 'gameinfo.gi'
# VRF's --game loader does not expand this engine token for loose
# cache trees. An explicit private path works on both drive layouts.
Expand Down
5 changes: 3 additions & 2 deletions agr/blender_fe_proxy_bones.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ def bake_fe_proxy_bones(rig, definition, frames, fps, collection=None, *, unit_s
import bpy
import numpy as np
from mathutils import Matrix, Quaternion, Vector
from .fe_proxy_bones import proxy_bone_outputs, uniform_proxy_colliders, weighted_rigid_delta, skin_proxy_goals, project_proxy_rods
from .fe_proxy_bones import ProxyGoalSkinner, proxy_bone_outputs, uniform_proxy_colliders, weighted_rigid_delta, project_proxy_rods
from .cloth_proxy_settings import proxy_pin_weights
from .blender_fe_proxy import _capsule_mesh
from .blender_scene import _curve
Expand Down Expand Up @@ -78,11 +78,12 @@ def source_matrix(row):
pin=proxy.vertex_groups.new(name='AGR authored proxy goal pins')
for i,weight in enumerate(proxy_pin_weights(data,definition.get('blender_goal_pins','authored_strength'))):
if weight>0:pin.add([i],weight,'REPLACE')
skinner = ProxyGoalSkinner(data, rig.data.bones.keys(), unit_scale)
poses=[];worlds=[];goals=[]
for frame in frames:
scene.frame_set(frame);bpy.context.view_layer.update()
poses.append({bone.name:bone.matrix.copy() for bone in rig.pose.bones});worlds.append(rig.matrix_world.copy())
goals.append(skin_proxy_goals(data,poses[-1],unit_scale))
goals.append(skinner.evaluate(poses[-1]))
# Cloth pins follow exact DMX-inverse-bind skinning. The independently
# imported rig can relocate weapon bones, so its rest inverse is invalid
# for these source-space proxy vertices.
Expand Down
33 changes: 26 additions & 7 deletions agr/blender_scene.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,8 @@ def _init_blender():


def _action_channels(obj, name):
import bpy

action = bpy.data.actions.new(name)
obj.animation_data_create()
if hasattr(action, "slots"):
Expand All @@ -136,6 +138,8 @@ def _action_channels(obj, name):


def _curve(channels, obj, path, component, frames, values, constant=False, steps=None):
import numpy as np

curve = channels.new(path, index=component)
curve.keyframe_points.add(len(frames))
curve.keyframe_points.foreach_set("co", np.column_stack((frames, values)).astype(np.float32).ravel())
Expand Down Expand Up @@ -747,11 +751,11 @@ def _review_setup(scene, positions):
def build_scene(segment, assets, output, fps=64, partial=False, particle_runtime=None, shot_hero=None,
character_shader=None, character_only=False, allow_partial_lighting=False, external_map=None,
map_viewport_proxy=False, map_project_scene=None, pending_world_receivers=False,
shot_package=None, shot_reconstruction_map=None):
shot_package=None, shot_reconstruction_map=None, map_parent_receipt=None):
_init_blender()
if external_map is not None:
from agr.external_map import validate_map_library
library = validate_map_library(external_map)
library = validate_map_library(external_map, parent_receipt=map_parent_receipt)
if library.get('format') == 'renderlock-map-v2':
from agr.blender_map_scene import build_map_first
return build_map_first(build_scene, segment, assets, output, library=library,
Expand Down Expand Up @@ -1059,13 +1063,22 @@ def mark(name):
tick = marker.get("tick")
if tick is not None and data["start_tick"] <= tick <= data["end_tick"]:
scene.timeline_markers.new(str(marker.get("label", marker.get("name", "Replay event"))), frame=round(tick_frame(tick, data["start_tick"], data["tick_rate"], fps)))
for entry in report["entities"]:
root = bpy.data.objects[entry["root"]]
diagnostic_roots = [(entry, bpy.data.objects[entry["root"]])
for entry in report["entities"]]
for entry, _ in diagnostic_roots:
entry["transform_checks"] = []
for frame in sorted({1.0, scene["agr_end_frame_exact"], (1 + scene["agr_end_frame_exact"]) / 2}):
if diagnostic_roots:
end_frame = scene["agr_end_frame_exact"]
for frame in sorted({1.0, end_frame, (1 + end_frame) / 2}):
scene.frame_set(math.floor(frame), subframe=frame % 1)
evaluated = root.evaluated_get(bpy.context.evaluated_depsgraph_get())
entry["transform_checks"].append({"frame": frame, "location": list(evaluated.location), "rotation_euler_radians": list(evaluated.rotation_euler), "world_matrix": [list(row) for row in evaluated.matrix_world]})
depsgraph = bpy.context.evaluated_depsgraph_get()
for entry, root in diagnostic_roots:
evaluated = root.evaluated_get(depsgraph)
entry["transform_checks"].append({
"frame": frame, "location": list(evaluated.location),
"rotation_euler_radians": list(evaluated.rotation_euler),
"world_matrix": [list(row) for row in evaluated.matrix_world],
})
if poses_requested:
baked = sum(entry.get('pose', {}).get('status') == 'baked' for entry in report['entities'])
report['coverage']['skeletal_animation'] = {
Expand Down Expand Up @@ -1116,6 +1129,7 @@ def main(argv=None):
parser.add_argument('--external-map',type=Path)
parser.add_argument('--map-viewport-proxy',action='store_true')
parser.add_argument('--map-project-scene',type=Path,help=argparse.SUPPRESS)
parser.add_argument('--map-parent-receipt', nargs=2, help=argparse.SUPPRESS)
parser.add_argument('--map-texture-tier',choices=('auto','full','1024'),default='auto')
parser.add_argument('--map-crop-margin',type=float,default=120.0)
parser.add_argument('--shot-package', type=Path,
Expand All @@ -1132,10 +1146,15 @@ def main(argv=None):
from agr import blender_map_scene
blender_map_scene.MAP_OPTIONS.update(texture_tier=args.map_texture_tier,
crop_margin=args.map_crop_margin)
receipt = None
if args.external_map is not None and args.map_parent_receipt:
from agr.map_package import read_parent_receipt
receipt = read_parent_receipt(*args.map_parent_receipt)
attach_blender_log(args.output)
return build_scene(args.segment, args.assets, args.output, args.fps, args.partial,args.particle_runtime,
args.shot_hero,args.character_shader,args.character_only,args.partial_lighting,args.external_map,
args.map_viewport_proxy,args.map_project_scene,
map_parent_receipt=receipt,
shot_package=args.shot_package,
shot_reconstruction_map=(json.loads(args.shot_reconstruction_map.read_text(encoding='utf-8'))
if args.shot_reconstruction_map else None))
Expand Down
48 changes: 40 additions & 8 deletions agr/blender_simulated_effects.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,24 @@ def numeric(value):
raise ValueError('Invalid particle age or sprite sequence')


def _write_particle_curves(obj, facing_helper, frames, values, radii, boundaries):
from .blender_scene import _action_channels, _curve

_, channels = _action_channels(obj, obj.name + ' | particle samples')
for path, track in zip(('location', 'scale', 'rotation_quaternion', 'color'), zip(*values)):
for index, component in enumerate(zip(*track)):
_curve(channels, obj, path, index, frames, component)
if radii:
_curve(channels, obj, '["agr_trail_radius"]', 0, frames, radii)
for path in ('hide_render', 'hide_viewport'):
setattr(obj, path, True)
_curve(channels, obj, path, 0, (boundaries[0], frames[0], boundaries[1]), (1, 0, 1), constant=True)
if facing_helper is not None:
_, facing_channels = _action_channels(facing_helper, facing_helper.name + ' | particle samples')
for index, component in enumerate(zip(*(sample[0] for sample in values))):
_curve(facing_channels, facing_helper, 'location', index, frames, component)


def collect_system_samples(simulation):
"""Retain live array order and empty samples for whole-system renderers."""
systems = {}
Expand Down Expand Up @@ -854,6 +872,12 @@ def build_rope_layer(index,renderer):
rotation=obj.constraints.new('COPY_ROTATION');rotation.target=facing_helper
rotation.name='AGR camera facing before particle roll'
rotation.mix_mode='BEFORE';rotation.owner_space='WORLD';rotation.target_space='WORLD'
first=1+(samples[0][0]-simulation['start_tick'])*frame_step;last=1+(samples[-1][0]-simulation['start_tick'])*frame_step
# Keep the legacy insertion behavior when Blender can merge nearby
# float32 keys. Light data and node socket animations keep their own actions.
boundaries = (first-frame_step, last+frame_step)
bulk = not light and frame_step >= .02 and max(map(abs, boundaries)) < frame_step * 2**20
frames, values, radii = [], [], []
for tick,step,p in samples:
frame=1+(tick-simulation['start_tick'])*frame_step
obj.location=Vector(p['position'])*unit_scale
Expand Down Expand Up @@ -885,31 +909,39 @@ def build_rope_layer(index,renderer):
obj.rotation_quaternion=Vector((1,0,0)).rotation_difference(Vector(direction))
obj.location-=Vector(direction)*length*renderer.get('m_flForwardShift',0)*unit_scale
obj.scale=(max(1e-9,length*unit_scale),1,max(1e-9,radius*unit_scale))
obj['agr_trail_radius']=float(radius*unit_scale);obj.keyframe_insert('["agr_trail_radius"]',frame=frame)
obj['agr_trail_radius']=float(radius*unit_scale)
if bulk:radii.append(obj['agr_trail_radius'])
else:obj.keyframe_insert('["agr_trail_radius"]',frame=frame)
else:
radius=p['radius']*render_scalar(renderer.get('m_flRadiusScale'),context=context,default=1)*unit_scale
obj.scale=(radius,radius,radius)
if normal_aligned:
obj.rotation_quaternion=Vector((0,0,1)).rotation_difference(Vector(p['normal']).normalized())@Quaternion((0,0,1),p['rotation'][2])
else:
facing_helper.location=obj.location
facing_helper.keyframe_insert('location',frame=frame)
if not bulk:facing_helper.keyframe_insert('location',frame=frame)
obj.rotation_quaternion=Quaternion((0,0,1),p['rotation'][2])
if bulk:
frames.append(frame)
values.append((tuple(obj.location), tuple(obj.scale), tuple(obj.rotation_quaternion), tuple(obj.color)))
continue
for prop in ('location','scale','rotation_quaternion','color'):obj.keyframe_insert(prop,frame=frame)
obj.hide_render=False;obj.hide_viewport=False
obj.keyframe_insert('hide_render',frame=frame);obj.keyframe_insert('hide_viewport',frame=frame)
first=1+(samples[0][0]-simulation['start_tick'])*frame_step;last=1+(samples[-1][0]-simulation['start_tick'])*frame_step
# Samples are one replay tick apart, regardless of output FPS. A
# whole output-frame offset stretches low-FPS tails and clips high-FPS ones.
boundaries = (first-frame_step, last+frame_step)
for frame in boundaries:
obj.hide_render=True;obj.hide_viewport=True;obj.keyframe_insert('hide_render',frame=frame);obj.keyframe_insert('hide_viewport',frame=frame)
if bulk:
_write_particle_curves(obj, facing_helper, frames, values, radii, boundaries)
else:
for frame in boundaries:
obj.hide_render=True;obj.hide_viewport=True;obj.keyframe_insert('hide_render',frame=frame);obj.keyframe_insert('hide_viewport',frame=frame)
if light:
for frame in boundaries:data.energy=0;data.keyframe_insert('energy',frame=frame)
_linear(data)
if range_socket is not None:_linear(data.node_tree)
_linear(obj)
if facing_helper is not None:_linear(facing_helper)
if not bulk:
_linear(obj)
if facing_helper is not None:_linear(facing_helper)
if not light:
# The released renderer has literal/constant scalar support,
# not the development renderer's dynamic per-sample contexts.
Expand Down
4 changes: 4 additions & 0 deletions agr/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -831,6 +831,10 @@ def set_stage(name):
if external_map is not None:
command += ['--external-map', external_map['path']]
if external_map.get('format') == 'renderlock-map-v2':
from .map_package import write_parent_receipt
receipt_path = work / 'verified-map.json'
receipt_digest = write_parent_receipt(external_map, receipt_path)
command += ['--map-parent-receipt', str(receipt_path), receipt_digest]
command += ['--map-project-scene', str(output)]
# Defaults also cover callers that build the arguments themselves (the app window).
command += ['--map-texture-tier', getattr(args, 'map_texture_tier', None) or 'auto',
Expand Down
4 changes: 2 additions & 2 deletions agr/external_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def validate_map_blender(report, library=None):
raise ValueError('External map: choose Blender 5.2 LTS for the new prepared map workflow.')


def validate_map_library(path):
def validate_map_library(path, *, parent_receipt=None):
"""Require the supported unmodified download before expensive preparation."""
try:
path = Path(path).expanduser().resolve()
Expand All @@ -62,7 +62,7 @@ def validate_map_library(path):
except (ValueError, AttributeError):
prepared = False
if prepared:
return map_package.library_identity(path)
return map_package.library_identity(path, parent_receipt=parent_receipt)
before = path.stat()
sizes = {MAP_BLEND_BYTES, *(entry['bytes'] for entry in _LEGACY_MAPS.values())}
if path.suffix.lower() != '.blend' or not path.is_file() or before.st_size not in sizes:
Expand Down
Loading