visionsim.simulate.heatsim package

Submodules

visionsim.simulate.heatsim.adapter module

Map Blender scene geometry and Cycles bakes to thermal solve points.

The solver uses millimetres, so geometry, irradiance and density are converted at the boundary from metres, W/m² and kg/m³ respectively.

visionsim.simulate.heatsim.adapter.gather_meshes(scene: Any) → list[source]

Select visible, nonempty meshes enabled for thermal simulation.

Give linked duplicates independent mesh datablocks before writing UVs or attributes so one object’s thermal field cannot overwrite another’s.

visionsim.simulate.heatsim.adapter.resolve_material(obj: Any, defaults: dict) → dict[source]

Resolve per-object thermal parameters.

Priority: an explicitly set per-object value on obj.heat_sim_material (detected via _is_set()), else the global defaults dict. Because the PropertyGroup is registered on every object, only is_property_set can tell a user-authored override from the registered group default; without that gate the global --config.thermal.* knobs would be silently inert. SI units throughout (thermal_diffusivity in mm^2/s, density in kg/m^3, specific_heat in J/(kg.K)).

visionsim.simulate.heatsim.adapter.global_temperature_range(history: dict[str, Any], default_K: float) → tuple[float, float][source]

Robust global colormap range (tmin, tmax) in Kelvin over the solved scene.

Spans the final temperatures of every solved object, so the preview covers the actual data instead of a fixed 295-400 K band. To keep a few artifact-hot vertices from destroying the exposure, the bounds are the 1st and 99th percentiles of the pooled final-timestep temperatures rather than the raw min/max. The lower bound is floored at default_K — unsolved meshes are stamped at that temperature — and the span is widened to at least 1 K so a near-uniform field does not collapse to a single colour.

Parameters:
  • history – {obj_name: (timesteps, vertices) array} from solve_scene().

  • default_K – Default initial temperature stamped on unsolved meshes.

Returns:

(tmin, tmax) with tmax - tmin >= 1.0.

class visionsim.simulate.heatsim.adapter.AtlasPlan(layout: AtlasLayout, texels: dict[str, dict[str, ~numpy.ndarray]]=<factory>, density: float = 0.0, tile_min: int = 16, tile_max: int = 512, soft_max: int = 500000, digest: str = '', meshes: dict[str, ~typing.Any]=<factory>)[source]

Bases: object

The output of build_atlas_plan(): per-object texel tables ready for _combine()’s TEXEL branch, plus the shared tile layout and the allocator settings that produced it (kept around so solve_scene() can fold them into the solve cache key).

texels maps object name -> {"position_mm" (K,3), "normal" (K,3), "uv" (K,2), "xy" (K,2) int64, "face" (K,) int64, "face_material_index" (M,) int32}. "xy" is the tile-LOCAL integer texel coordinate (before the tile’s AtlasLayout offset is added) - write_atlas() uses it together with layout.tiles[name].offset to scatter this object’s solved texel temperatures into the shared atlas image. Only objects that made it all the way through selection, UV prep and rasterization appear here; every other sim object (excluded by atlas.select_for_atlas(), or rejected after a UV/vertex-count failure) is simply absent and keeps the per-vertex path in _combine.

meshes retains private modifier results. Install them with use_atlas_geometry() during baking, field writeback and rendering.

layout: AtlasLayout
texels: dict[str, dict[str, ndarray]]
density: float = 0.0
tile_min: int = 16
tile_max: int = 512
soft_max: int = 500000
digest: str = ''
meshes: dict[str, Any]
__init__(layout: AtlasLayout, texels: dict[str, dict[str, ~numpy.ndarray]]=<factory>, density: float = 0.0, tile_min: int = 16, tile_max: int = 512, soft_max: int = 500000, digest: str = '', meshes: dict[str, ~typing.Any]=<factory>) → None
visionsim.simulate.heatsim.adapter.use_atlas_geometry(scene: Any, plan: AtlasPlan | None)[source]

Use the same evaluated surfaces that own the plan’s bake and atlas UVs.

visionsim.simulate.heatsim.adapter.build_atlas_plan(scene: Any, sim_objects: list, cfg: dict) → AtlasPlan[source]

Unwrap final geometry so generated faces cannot reuse another surface’s UVs.

visionsim.simulate.heatsim.adapter.write_atlas(history: dict, atlas_plan: AtlasPlan, cache_root: Path, defaults: dict | None = None, assignment: Any | None = None) → Path[source]

Write the final-timestep texel temperatures to a 32-bit float EXR atlas image.

Scatters every atlas-participating object’s LAST solved timestep into the shared atlas array at its tile’s texels (_scatter_atlas_arrays()), push-out dilates across the invalid margin so render-time bilinear filtering never samples an untouched texel, and saves an RGBA float EXR to <cache_root>/atlas_<hash>/atlas_temperature.exr: R and B hold temperature in Kelvin, G holds the per-texel IR emissivity the gray-body shader reads (thermal_shader._build_emissivity_source_chain), and A is 1 where valid/dilated coverage exists, 0 elsewhere. <hash> covers the plan digest plus the participating object names and their solved values, so re-solving with different temperatures writes a new path rather than overwriting a cached atlas. The caller (blender.py) is expected to load and pack the result as the HeatSim_Temperature_Atlas Blender image before wiring the shader (thermal_shader) or rendering.

Parameters:
  • history – {obj_name: (timesteps, K) array} as returned by solve_scene() (called with this same atlas_plan); K must match each atlas object’s texel count for its temperatures to be scattered (a mismatch is logged and that object’s tile is left to dilation/zero).

  • atlas_plan – The plan from build_atlas_plan() that produced history’s TEXEL-mode objects.

  • cache_root – Root directory for thermal caches (same one passed to solve_scene()).

Returns:

Path to the written EXR file.

visionsim.simulate.heatsim.adapter.solve_scene(scene: Any, *, defaults: dict, solver_cfg: dict, cache_root: Path, assignment: Any | None = None, atlas_plan: AtlasPlan | None = None, source_digest: str | None = None, recompute: bool = False) → dict[source]

Cache-aware FEM heat solve for scene.

A validated cache hit returns the stored per-object history. Otherwise the scene is sampled, Cycles irradiance is baked, and the shared point-cloud system is integrated before its history is split by object.

When atlas_plan (from build_atlas_plan()) is supplied, its atlas-participating objects additionally get per-texel irradiance (_compute_texel_irradiance()) merged into the same flux_by_obj the per-vertex path already builds, and it is threaded through to _combine()’s TEXEL branch. atlas_plan=None uses evaluated mesh vertices throughout.

Returns {obj_name: (timesteps, vertices) ndarray}.

visionsim.simulate.heatsim.adapter.write_frame_attributes(scene: Any, history: dict, timestep: int, defaults: dict, assignment: Any | None = None, atlas_plan: AtlasPlan | None = None) → None[source]

Write per-vertex temperatures for the chosen timestep (use -1 for last).

For every simulated mesh (present in history) this writes a sim_temperature (FLOAT/POINT) attribute for that timestep plus a constant emissivity (FLOAT/POINT) attribute. An object with no entry in history – e.g. a DIRICHLET_SOURCE whose topology changes every frame, so it was never given a per-vertex field – gets a CONSTANT-fill sim_temperature/emissivity instead of being left absent (an absent sim_temperature makes the temperature AOV emit 0 K, see _write_constant_fill_attributes()). A per-vertex field whose count does not match the base mesh raises RuntimeError instead: writing it would render a plausible-looking but wrong field. The object also gets an OBJECT-level heatsim_default_temperature custom property so downstream rendering still has a sane fallback: defaults['initial_temperature_K'] (ambient) for FEM participants, or the object’s own dirichlet_temperature_K reservoir temperature for a DIRICHLET_SOURCE (e.g. a topology-changing hot liquid whose vertex count can’t be tracked per-frame) so it still renders hot instead of at ambient. This does NOT apply to atlas participants (see below) – they deliberately get no per-vertex attribute at all.

When assignment is supplied the emissivity attribute is resolved per vertex from the object’s material slots rather than stamped as one object-level constant, so per-slot emissivity reaches the gray-body radiance shader. In LWIR that difference (polished metal ~0.05 vs painted ~0.9) dominates how the rendered frame looks.

When atlas_plan is supplied (TEXEL render domain), objects present in atlas_plan.texels are atlas participants: their per-pixel signal comes from the rendered atlas image (write_atlas()) sampled by the shader, not from a per-vertex mesh attribute, so this function writes ONLY their heatsim_default_temperature fallback (used where the atlas mix factor is 0, e.g. margin the dilation never reached) and skips the sim_temperature/emissivity point-attribute write entirely – even if history[obj.name]’s texel count happens to equal the mesh’s vertex count. Every mesh also gets an explicit ATLAS_COVERAGE_PROP OBJECT-domain float (1.0 for atlas participants, 0.0 otherwise); the shader multiplies this into its atlas mix factor so a non-participant object can never pick up stray atlas coverage through the default (0,0,0) vector a missing HeatSim_Atlas_UV attribute produces. Non-atlas objects are written exactly as when atlas_plan=None.

visionsim.simulate.heatsim.atlas module

Pure geometry for thermal atlas selection, packing, rasterization and padding.

Sparse surfaces use covered texel centers as simulation points and render lookup addresses; dense surfaces can retain evaluated mesh vertices.

class visionsim.simulate.heatsim.atlas.TileSpec(obj_name: str, size: tuple[int, int], offset: tuple[int, int])[source]

Bases: object

One object’s placement in the shared atlas image.

obj_name: str
size: tuple[int, int]

(w, h) texels; both are multiples of 4 and in [tile_min, tile_max] (tiles are square).

offset: tuple[int, int]

(x, y) top-left corner of this tile in atlas pixels.

__init__(obj_name: str, size: tuple[int, int], offset: tuple[int, int]) → None
class visionsim.simulate.heatsim.atlas.AtlasLayout(atlas_size: tuple[int, int], tiles: dict[str, TileSpec], effective_density: float, rescaled: bool)[source]

Bases: object

The full result of allocate(): every tile’s placement plus the density actually used.

atlas_size: tuple[int, int]
tiles: dict[str, TileSpec]
effective_density: float

Equal to the requested density unless the soft-max safety valve rescaled it down.

rescaled: bool

True iff the soft-max safety valve engaged (see allocate()).

__init__(atlas_size: tuple[int, int], tiles: dict[str, TileSpec], effective_density: float, rescaled: bool) → None
visionsim.simulate.heatsim.atlas.surface_area_m2(verts_mm: ndarray, faces: ndarray) → float[source]

Total triangle surface area, converted from mm^2 (input units) to m^2.

visionsim.simulate.heatsim.atlas.select_for_atlas(n_verts: int, area_m2: float, density: float, *, writeback_possible: bool = True) → bool[source]

True iff this object should join the atlas rather than keep the per-vertex path.

Normally that’s a density call: native vertex density below the atlas target means the object’s own vertices are too sparse to sample it well, so it joins.

writeback_possible=False overrides the density rule unconditionally. It signals that the caller cannot write a per-vertex result back onto this object’s base mesh at all (its base and evaluated vertex counts differ, e.g. a Bevel/Subdivision/ Geometry-Nodes modifier) - the vertex path is not merely low-resolution here, it is structurally incapable of holding the solved field, so density is moot and the atlas (UV-addressed, not vertex-addressed) is the only path that can represent this object.

visionsim.simulate.heatsim.atlas.allocate(areas: dict[str, float], density: float, *, tile_min: int = 16, tile_max: int = 512, soft_max: int = 500000, retained_vertex_count: int = 0, padding: int = 2) → AtlasLayout[source]

Size and shelf-pack one atlas tile per object in areas.

Tile side is purely area-driven (ceil(sqrt(area_m2 * density)), rounded up to a multiple of 4, clamped to [tile_min, tile_max]) - never squeezed by a budget. soft_max is a warn-only safety valve: if sum(side^2) + retained_vertex_count exceeds it, density is rescaled uniformly (down) by (soft_max - retained_vertex_count) / tiles_total and tiles are resized at the new density; this is a single corrective pass, not an iterative solve, so clamping can still leave the total above soft_max - the valve’s job is to warn loudly and shrink, not to silently degrade below the warning, and not to guarantee an exact bound.

visionsim.simulate.heatsim.atlas.rasterize_tile(verts_mm: ndarray, faces: ndarray, loop_uv: ndarray, tile_size: tuple[int, int], *, reject_overlaps: bool = False) → dict[str, ndarray][source]

Rasterize triangles (given per-triangle-corner UVs already in tile-local [0,1] space).

Texel centers are tested at ((x+0.5)/W, (y+0.5)/H); a half-open (top-left) edge rule means abutting triangles never double-claim a boundary texel. Triangles are processed in faces order and earlier ones win: once a texel is covered it is never revisited. Zero-UV-area (degenerate) triangles are skipped and contribute no texels (and no NaNs). reject_overlaps rejects shared addresses with conflicting positions or normals.

Returns arrays for covered texels only: xy (K,2) int tile-local texel indices, position_mm (K,3) barycentric-interpolated 3D positions, normal (K,3) unit face normals, face (K,) int source-triangle index into faces.

visionsim.simulate.heatsim.atlas.dilate(image: ndarray, valid: ndarray, iterations: int = 4) → ndarray[source]

Push-out margin dilation: each invalid texel takes the mean of its valid 8-neighbors.

Repeated for iterations passes; a texel filled on one pass becomes a valid source for the next (so the filled region grows outward by up to one texel per pass), but once a texel is valid - originally or newly filled - its value is never touched again.

valid must be 2D ((H, W)) regardless of whether image is single- or multi-channel ((H, W) or (H, W, C)) - one validity bit per texel, not per channel.

visionsim.simulate.heatsim.cache module

visionsim.simulate.heatsim.cache.read_bake_uv(path: Path, signature: str, loop_count: int) → ndarray | None[source]

Read one validated layout for this geometry; reject damaged cache entries.

visionsim.simulate.heatsim.cache.publish_bake_uv(path: Path, signature: str, uv: ndarray) → ndarray[source]

Publish a complete layout once; every competing writer uses the winner.

Blender unwrapping can vary slightly between processes. Replacing an existing layout would change the sample addresses after another worker had solved them.

visionsim.simulate.heatsim.cache.cache_key(blend_path: Path, solver_cfg: dict, source_digest: str = '') → str[source]

Stable cache key from the blend identity and solver-relevant config.

Parameters:
  • blend_path – Path to the source blend file.

  • solver_cfg – Solver-relevant config values that affect the result.

Returns:

A short hex digest used as the cache subdirectory name.

visionsim.simulate.heatsim.cache.file_digest(path: Path) → str[source]
visionsim.simulate.heatsim.cache.source_identity(blend_data: Any) → str | None[source]

Identify an unmodified saved blend and its external image/library inputs.

Unsaved edits and unavailable inputs cannot be identified safely, so callers must bake and solve again in those cases.

visionsim.simulate.heatsim.cache.write_temperatures(cache_root: Path, key: str, per_object: dict[str, ndarray], meta: dict) → Path[source]

Write per-object temperature histories to <cache_root>/<key>/temperatures.npz.

Parameters:
  • cache_root – Root directory for thermal caches.

  • key – Cache key from cache_key().

  • expected_counts (dict[str, int] | None, optional) – Expected sample count per object; a mismatch invalidates the cache. Defaults to None.

  • per_object – Mapping of object name to a (timesteps, vertices) array.

  • meta – JSON-serializable metadata stored alongside the arrays.

Returns:

The path to the written .npz archive.

visionsim.simulate.heatsim.cache.read_temperatures(cache_root: Path, key: str, expected_counts: dict[str, int] | None = None) → dict[str, ndarray] | None[source]

Read per-object temperature histories, or return None on a cache miss.

Parameters:
  • cache_root – Root directory for thermal caches.

  • key – Cache key from cache_key().

  • expected_counts (dict[str, int] | None, optional) – Expected sample count per object; a mismatch invalidates the cache. Defaults to None.

Returns:

Mapping of object name to its history array, or None if absent.

visionsim.simulate.heatsim.geometry module

Private evaluated meshes shared by thermal baking, sampling and rendering.

visionsim.simulate.heatsim.geometry.evaluated_meshes(objects: list) → dict[str, Any][source]

Copy render-visible geometry and triangulate n-gons for thermal UV charts.

visionsim.simulate.heatsim.geometry.release_meshes(meshes: dict[str, Any]) → None[source]

Release snapshots once their render job is finished or preparation failed.

visionsim.simulate.heatsim.geometry.use_meshes(scene: Any, meshes: dict[str, Any])[source]

Temporarily install snapshots; never evaluate their modifiers a second time.

visionsim.simulate.heatsim.irradiance module

Cycles baking and sampling for absorbed thermal flux.

class visionsim.simulate.heatsim.irradiance.BakedFluxMap(pixels: ndarray, vertex_flux: ndarray, width: int, height: int)[source]

Bases: object

Container for baked flux data coming from an image texture.

pixels: ndarray
vertex_flux: ndarray
width: int
height: int
__init__(pixels: ndarray, vertex_flux: ndarray, width: int, height: int) → None
visionsim.simulate.heatsim.irradiance.prepare_object_bake_uv(obj: bpy.types.Object) → None[source]

Ensure BAKE_UV_LAYER_NAME exists on the object and is unwrapped for baking.

This mirrors the shared baking pipeline, but operates on a single object: - Create/activate BAKE_UV_LAYER_NAME - Generate and validate non-overlapping thermal UVs on a disposable copy

visionsim.simulate.heatsim.irradiance.is_bake_image(image, base_name: str, name_suffix: str) → bool[source]

Recognize a local, explicitly owned output rather than trusting its name.

visionsim.simulate.heatsim.irradiance.resolve_bake_image(base_name: str, name_suffix: str, preferred_name: str | None = None)[source]

Read an owned image by its recorded alias or logical key, without editing it.

visionsim.simulate.heatsim.irradiance.bake_vertex_albedo(scene, obj, texture_size: int) → ndarray[source]

Bake albedo and sample it on the evaluated mesh used by the heat solve.

visionsim.simulate.heatsim.irradiance.bake_albedo_map(scene, obj, texture_size: int) → BakedFluxMap | None[source]

Bake visible colour (COLOR pass), reading Base Color for known opaque surfaces.

visionsim.simulate.heatsim.irradiance.bake_irradiance_map(scene, obj, texture_size: int, samples: int | None = None) → BakedFluxMap | None[source]

Bake incident irradiance (DIFFUSE DIRECT+INDIRECT) for a single object.

Known opaque surfaces, including supported Add/Mix combinations, use a unit-white diffuse receiver only at the initial bake shading point (Ray Depth == 0). Subsequent hits, including self-reflections, use the authored shader. This avoids missing light on black or metallic receivers without whitening the scene’s indirect illumination. Transparent, subsurface and unrecognized surfaces retain the authored bake.

Cycles includes emissive geometry, indirect lighting and world illumination. vertex_flux is incident W/m²; the caller multiplies by 1 - albedo to obtain absorbed flux.

visionsim.simulate.heatsim.laplacian module

Robust point-cloud Laplacian and mass matrix for thermal samples.

visionsim.simulate.heatsim.laplacian.point_cloud_laplacian_and_mass(points: ndarray, mollify_factor: float = 1e-05, n_neighbors: int = 30)[source]

Build robust point-cloud Laplacian + diagonal lumped mass matrix.

Returns:

(L, M) as SciPy sparse matrices.

visionsim.simulate.heatsim.material_slots module

Temporary object material overrides that preserve authored slot assignments.

class visionsim.simulate.heatsim.material_slots.MaterialSlotState(materials: list[bpy.types.Material | None], data_materials: list[bpy.types.Material | None], object_materials: list[bpy.types.Material | None], links: list[str], active_index: int, bare_material_indices: list[int] | None)[source]

Bases: object

Keep effective, mesh and hidden object assignments alive during a bake.

materials: list[bpy.types.Material | None]
data_materials: list[bpy.types.Material | None]
object_materials: list[bpy.types.Material | None]
active_index: int
bare_material_indices: list[int] | None
__init__(materials: list[bpy.types.Material | None], data_materials: list[bpy.types.Material | None], object_materials: list[bpy.types.Material | None], links: list[str], active_index: int, bare_material_indices: list[int] | None) → None
visionsim.simulate.heatsim.material_slots.snapshot_material_slots(obj: bpy.types.Object) → MaterialSlotState[source]

Capture object overrides even when the slot currently uses its DATA link.

visionsim.simulate.heatsim.material_slots.set_material_override(obj: bpy.types.Object, index: int, material: bpy.types.Material) → None[source]

Use OBJECT links so a shared mesh’s DATA materials remain untouched.

visionsim.simulate.heatsim.material_slots.restore_material_slots(obj: bpy.types.Object, state: MaterialSlotState) → None[source]

Restore in place; rebuilding existing slots resets polygon material indices.

visionsim.simulate.heatsim.materials module

Thermal material properties: preset library, per-scene assignment, per-vertex resolution.

Three layers, one job: turn a Blender object’s material slots into the per-vertex (N,) arrays the FEM solver already accepts.

  1. PRESETS - a fixed library of named thermal materials.

  2. load_assignments() - parse a scene’s committed sidecar, which maps Blender material names onto those presets.

  3. resolve_vertex_materials() - walk mesh.polygons[].material_index and produce the per-vertex arrays.

Units are SI-with-mm-diffusivity, matching visionsim.simulate.heatsim.adapter: alpha_mm2_s mm^2/s, density_kg_m3 kg/m^3, specific_heat_J_kgK J/(kg.K), emissivity_ir dimensionless in [0, 1], temperatures in K.

There is deliberately no solar-absorptivity column: absorbed flux is already computed post-(1 - albedo) from Cycles bakes of the scene’s real textures, so a per-preset absorptivity would double-count.

Sidecars are authored offline as JSON and committed; this module reads them.

visionsim.simulate.heatsim.materials.MIN_DIRICHLET_K = 280.0

Below this a ‘heat source’ is really a cold sink; almost always an authoring slip.

visionsim.simulate.heatsim.materials.MAX_DIRICHLET_K = 500.0

Above this we are out of interior-scene territory (an oven element, not a room).

class visionsim.simulate.heatsim.materials.ThermalPreset(key: str, alpha_mm2_s: float, density_kg_m3: float, specific_heat_J_kgK: float, emissivity_ir: float, notes: str, specular_fraction_ir: float = 0.0, roughness_ir: float = 0.5)[source]

Bases: object

One named thermal material. Frozen so the shared library cannot be mutated.

key: str
alpha_mm2_s: float
density_kg_m3: float
specific_heat_J_kgK: float
emissivity_ir: float
notes: str
specular_fraction_ir: float = 0.0
roughness_ir: float = 0.5
__init__(key: str, alpha_mm2_s: float, density_kg_m3: float, specific_heat_J_kgK: float, emissivity_ir: float, notes: str, specular_fraction_ir: float = 0.0, roughness_ir: float = 0.5) → None
visionsim.simulate.heatsim.materials.PRESETS: dict[str, ThermalPreset] = {'aluminium': ThermalPreset(key='aluminium', alpha_mm2_s=97.0, density_kg_m3=2700.0, specific_heat_J_kgK=900.0, emissivity_ir=0.2, notes='Uncoated aluminium with a rough surface.', specular_fraction_ir=0.8, roughness_ir=0.35), 'aluminium_polished': ThermalPreset(key='aluminium_polished', alpha_mm2_s=97.0, density_kg_m3=2700.0, specific_heat_J_kgK=900.0, emissivity_ir=0.05, notes='Mirror-polished aluminium.', specular_fraction_ir=0.98, roughness_ir=0.08), 'asphalt': ThermalPreset(key='asphalt', alpha_mm2_s=0.33, density_kg_m3=1900.0, specific_heat_J_kgK=920.0, emissivity_ir=0.95, notes='Asphalt / bitumen with inert fill.', specular_fraction_ir=0.0, roughness_ir=0.5), 'brick': ThermalPreset(key='brick', alpha_mm2_s=0.59, density_kg_m3=1920.0, specific_heat_J_kgK=800.0, emissivity_ir=0.93, notes='Representative fired-clay brick.', specular_fraction_ir=0.0, roughness_ir=0.5), 'carpet': ThermalPreset(key='carpet', alpha_mm2_s=0.17, density_kg_m3=200.0, specific_heat_J_kgK=1300.0, emissivity_ir=0.9, notes='Approximate effective carpet properties.', specular_fraction_ir=0.0, roughness_ir=0.5), 'ceramic': ThermalPreset(key='ceramic', alpha_mm2_s=0.6, density_kg_m3=2300.0, specific_heat_J_kgK=850.0, emissivity_ir=0.93, notes='Approximate glazed ceramic: tile, sanitaryware, pottery.', specular_fraction_ir=0.0, roughness_ir=0.5), 'concrete': ThermalPreset(key='concrete', alpha_mm2_s=0.97, density_kg_m3=2240.0, specific_heat_J_kgK=900.0, emissivity_ir=0.92, notes='Representative sand/gravel or stone aggregate concrete.', specular_fraction_ir=0.0, roughness_ir=0.5), 'copper': ThermalPreset(key='copper', alpha_mm2_s=116.0, density_kg_m3=8960.0, specific_heat_J_kgK=385.0, emissivity_ir=0.65, notes='Oxidised copper.', specular_fraction_ir=0.5, roughness_ir=0.4), 'drywall': ThermalPreset(key='drywall', alpha_mm2_s=0.22, density_kg_m3=640.0, specific_heat_J_kgK=1150.0, emissivity_ir=0.9, notes='Representative gypsum plasterboard.', specular_fraction_ir=0.0, roughness_ir=0.5), 'fabric': ThermalPreset(key='fabric', alpha_mm2_s=0.09, density_kg_m3=300.0, specific_heat_J_kgK=1300.0, emissivity_ir=0.95, notes='Approximate textile properties; weave and fiber dependent.', specular_fraction_ir=0.0, roughness_ir=0.5), 'foliage': ThermalPreset(key='foliage', alpha_mm2_s=0.15, density_kg_m3=700.0, specific_heat_J_kgK=3000.0, emissivity_ir=0.96, notes='Approximate live foliage; artificial plants need their actual material.', specular_fraction_ir=0.0, roughness_ir=0.5), 'food': ThermalPreset(key='food', alpha_mm2_s=0.14, density_kg_m3=1000.0, specific_heat_J_kgK=3200.0, emissivity_ir=0.95, notes='Approximate unfrozen food; composition dependent.', specular_fraction_ir=0.0, roughness_ir=0.5), 'glass': ThermalPreset(key='glass', alpha_mm2_s=0.43, density_kg_m3=2500.0, specific_heat_J_kgK=880.0, emissivity_ir=0.84, notes='Uncoated soda-lime float glass. Opaque in LWIR.', specular_fraction_ir=0.95, roughness_ir=0.05), 'iron': ThermalPreset(key='iron', alpha_mm2_s=18.0, density_kg_m3=7200.0, specific_heat_J_kgK=450.0, emissivity_ir=0.31, notes='Approximate cast-iron properties; grade unspecified.', specular_fraction_ir=0.6, roughness_ir=0.4), 'leather': ThermalPreset(key='leather', alpha_mm2_s=0.11, density_kg_m3=900.0, specific_heat_J_kgK=1500.0, emissivity_ir=0.95, notes='Approximate natural leather; synthetic leather may differ.', specular_fraction_ir=0.0, roughness_ir=0.5), 'li_ion': ThermalPreset(key='li_ion', alpha_mm2_s=0.2, density_kg_m3=2500.0, specific_heat_J_kgK=1100.0, emissivity_ir=0.88, notes='Approximate cell bulk; scalar model ignores directional conduction.', specular_fraction_ir=0.0, roughness_ir=0.5), 'marble': ThermalPreset(key='marble', alpha_mm2_s=1.2, density_kg_m3=2700.0, specific_heat_J_kgK=880.0, emissivity_ir=0.94, notes='Approximate natural marble; other worktop materials may differ.', specular_fraction_ir=0.0, roughness_ir=0.5), 'metal_painted': ThermalPreset(key='metal_painted', alpha_mm2_s=15.4, density_kg_m3=7850.0, specific_heat_J_kgK=440.0, emissivity_ir=0.92, notes='Steel with nonmetallic paint; coating thermal mass neglected.', specular_fraction_ir=0.0, roughness_ir=0.5), 'paper': ThermalPreset(key='paper', alpha_mm2_s=0.13, density_kg_m3=700.0, specific_heat_J_kgK=1340.0, emissivity_ir=0.93, notes='Approximate paper/card; coatings and porosity may differ.', specular_fraction_ir=0.0, roughness_ir=0.5), 'plaster': ThermalPreset(key='plaster', alpha_mm2_s=0.31, density_kg_m3=1120.0, specific_heat_J_kgK=1090.0, emissivity_ir=0.91, notes='Gypsum plaster; not cement render.', specular_fraction_ir=0.0, roughness_ir=0.5), 'polystyrene': ThermalPreset(key='polystyrene', alpha_mm2_s=0.12, density_kg_m3=1050.0, specific_heat_J_kgK=1300.0, emissivity_ir=0.9, notes='Solid polystyrene; excludes expanded foam.', specular_fraction_ir=0.0, roughness_ir=0.5), 'porcelain': ThermalPreset(key='porcelain', alpha_mm2_s=0.7, density_kg_m3=2400.0, specific_heat_J_kgK=840.0, emissivity_ir=0.92, notes='Approximate vitrified porcelain: tableware, basins.', specular_fraction_ir=0.0, roughness_ir=0.5), 'pvc': ThermalPreset(key='pvc', alpha_mm2_s=0.17, density_kg_m3=1400.0, specific_heat_J_kgK=880.0, emissivity_ir=0.93, notes='Representative unplasticized PVC.', specular_fraction_ir=0.0, roughness_ir=0.5), 'rubber': ThermalPreset(key='rubber', alpha_mm2_s=0.1, density_kg_m3=1200.0, specific_heat_J_kgK=1400.0, emissivity_ir=0.94, notes='Approximate solid elastomer; formulation dependent.', specular_fraction_ir=0.0, roughness_ir=0.5), 'skin': ThermalPreset(key='skin', alpha_mm2_s=0.099, density_kg_m3=1109.0, specific_heat_J_kgK=3391.0, emissivity_ir=0.98, notes='Human skin. Pair with role=DIRICHLET_SOURCE at ~307 K.', specular_fraction_ir=0.0, roughness_ir=0.5), 'stainless_steel': ThermalPreset(key='stainless_steel', alpha_mm2_s=3.8, density_kg_m3=7900.0, specific_heat_J_kgK=500.0, emissivity_ir=0.16, notes='Grade 304 stainless with a buffed finish.', specular_fraction_ir=0.95, roughness_ir=0.18), 'steel': ThermalPreset(key='steel', alpha_mm2_s=15.4, density_kg_m3=7850.0, specific_heat_J_kgK=440.0, emissivity_ir=0.24, notes='Freshly rolled bare structural steel.', specular_fraction_ir=0.8, roughness_ir=0.3), 'tile_glazed': ThermalPreset(key='tile_glazed', alpha_mm2_s=0.7, density_kg_m3=2400.0, specific_heat_J_kgK=840.0, emissivity_ir=0.92, notes='Approximate glazed porcelain floor tile; finish dependent.', specular_fraction_ir=0.8, roughness_ir=0.2), 'water': ThermalPreset(key='water', alpha_mm2_s=0.146, density_kg_m3=997.0, specific_heat_J_kgK=4180.0, emissivity_ir=0.96, notes='Liquid water at 25 C; surface FEM ignores convection.', specular_fraction_ir=0.0, roughness_ir=0.5), 'wood': ThermalPreset(key='wood', alpha_mm2_s=0.15, density_kg_m3=700.0, specific_heat_J_kgK=1630.0, emissivity_ir=0.9, notes='Representative oak at 12% moisture; scalar approximation.', specular_fraction_ir=0.0, roughness_ir=0.5)}

The thermal preset library, keyed by preset name.

visionsim.simulate.heatsim.materials.preset_keys() → list[str][source]

Sorted preset keys. This is the closed enum the offline assignment tool chooses from.

class visionsim.simulate.heatsim.materials.MaterialEntry(preset: ThermalPreset | None, role: str, dirichlet_K: float | None, confidence: float, reason: str, specular_fraction_ir: float | None = None, roughness_ir: float | None = None)[source]

Bases: object

One material’s assignment. preset is None means ‘fall back to the globals’.

preset: ThermalPreset | None
role: str
dirichlet_K: float | None
confidence: float
reason: str
specular_fraction_ir: float | None = None
roughness_ir: float | None = None
__init__(preset: ThermalPreset | None, role: str, dirichlet_K: float | None, confidence: float, reason: str, specular_fraction_ir: float | None = None, roughness_ir: float | None = None) → None
class visionsim.simulate.heatsim.materials.SceneAssignment(scene: str, digest: str, default_preset: ThermalPreset | None, materials: dict[str, MaterialEntry])[source]

Bases: object

A scene’s sidecar, keyed by Blender material name.

scene: str
digest: str
default_preset: ThermalPreset | None
materials: dict[str, MaterialEntry]
entry_for(material_name: str, *, object_name: str | None = None) → MaterialEntry | None[source]

Prefer object_name::material_name over the shared material entry.

reflection_for(material_name: str, *, object_name: str | None = None) → tuple[float, float][source]

Render-only reflection controls, resolved per material slot.

__init__(scene: str, digest: str, default_preset: ThermalPreset | None, materials: dict[str, MaterialEntry]) → None
visionsim.simulate.heatsim.materials.load_assignments(path: Path) → SceneAssignment[source]

Parse and validate the sidecar at path.

Recoverable inconsistencies degrade to the global defaults with a warning: an unknown preset key, role, material field, or an out-of-band Dirichlet temperature. Structural problems raise: a bad schema version, a malformed block, or a non-numeric dirichlet_K/confidence.

visionsim.simulate.heatsim.materials.resolve_vertex_materials(obj: Any, assignment: SceneAssignment, fallback: dict[str, Any]) → dict[str, ndarray] | None[source]

Return per-vertex thermal arrays for obj, or None if slots cannot drive it.

Blender stores materials on faces; the solver wants one value per vertex. Almost every vertex is interior to a single material region, so the conversion is a lookup. At a seam - a vertex touching faces of two different materials - the rule differs by the kind of quantity:

  • Continuous (alpha, rho, c, eps, T0) -> area-weighted mean. A wood-to-metal joint really is a material gradient, so a blend is closer to reality than an arbitrary hard jump.

  • Categorical (pinned or not, and at what temperature) -> dominant incident material by area. A vertex cannot be “60% pinned”.

Both rules share one accumulation pass building face area per (vertex, slot); only the final reduction differs (weighted mean vs argmax). The cheaper alternative - “pinned if any touching face is a source” - is rejected because it leaks a lamp filament’s temperature outward into the surrounding glass shade.

Parameters:
  • obj – A Blender MESH object (or duck-typed stand-in) exposing data.vertices, data.polygons and material_slots.

  • assignment – The scene’s parsed sidecar.

  • fallback – The object-level resolution from adapter.resolve_material, used for unassigned slots and untouched vertices - so an explicitly authored heat_sim_material still wins where the sidecar is silent.

Returns:

{"t0", "alpha", "rho", "c", "eps", "dirichlet_mask"}, each (N,), or None when the object has no slots or no vertices (the caller then keeps its existing object-level path).

t0 is only meaningful where dirichlet_mask is True – there it holds the vertex’s exact reservoir temperature. Where dirichlet_mask is False it instead holds the same area-weighted mean as every other continuous field, which at a seam onto a Dirichlet slot blends in a slice of that reservoir’s temperature even though the vertex itself is not pinned. Callers must supply the ambient initial temperature themselves for unpinned vertices rather than using this array’s value wholesale (see adapter._combine, which does exactly that).

visionsim.simulate.heatsim.materials.resolve_face_materials(obj: Any, assignment: SceneAssignment, fallback: dict[str, Any], face_slots: ndarray) → dict[str, ndarray] | None[source]

Return per-FACE thermal arrays for obj, or None if slots cannot drive it.

The texel-sim analogue of resolve_vertex_materials(): a texel belongs to exactly one face, and a face belongs to exactly one material slot, so there is no seam to blend across - unlike the per-vertex path this is an exact lookup, never an area-weighted mean.

Parameters:
  • obj – A Blender MESH object (or duck-typed stand-in) exposing material_slots.

  • assignment – The scene’s parsed sidecar.

  • fallback – The object-level resolution from adapter.resolve_material, used for unassigned slots - so an explicitly authored heat_sim_material still wins where the sidecar is silent.

  • face_slots – (M,) int array of material_index per face. The caller is responsible for keeping face order consistent with whatever face indices it later uses to index into the result (e.g. atlas.rasterize_tile’s face output, which indexes into the same triangulated face array this was built from). An out-of-range index is clamped to the last slot, mirroring resolve_vertex_materials()’s material_index handling.

Returns:

{"t0", "alpha", "rho", "c", "eps", "dirichlet_mask"}, each (M,) where M = len(face_slots), or None when the object has no material slots.

t0 here is always the face’s exact assigned value (the reservoir temperature where dirichlet_mask is True, else the slot/object ambient) since there is no seam to blend across a whole face. A caller that wants the vertex path’s “an unpinned face starts at ambient regardless of a neighboring Dirichlet slot” convention gets that for free here already - there is no neighbor contribution to exclude. Callers combining this with an object-level Dirichlet override should still apply that themselves (see adapter._combine).

visionsim.simulate.heatsim.names module

Identifiers shared by thermal bake, atlas and shader stages.

visionsim.simulate.heatsim.physics module

Shared thermal model values and physical constants.

visionsim.simulate.heatsim.properties module

Per-object thermal material PropertyGroup for visionsim heat simulation.

Existing Blender object property names are retained so authored scenes load their material overrides.

class visionsim.simulate.heatsim.properties.HeatSimObjectMaterialProperties(*args: Any, **kwargs: Any)[source]

Bases: PropertyGroup

Per-object material + initial condition configuration for heat simulation.

Values are stored in SI units:

thermal_diffusivity_mm2_s: mm²/s density_kg_m3: kg/m³ specific_heat_J_kgK: J/(kg·K) initial_temperature_K: K

initial_temperature_K: FloatProperty(name='Initial Temp (K)', description='Initial temperature for this object (used if no per-vertex attribute override is provided)', default=ThermalConfig.initial_temperature_K, min=0.0)
thermal_diffusivity_mm2_s: FloatProperty(name='Thermal Diffusivity α (mm²/s)', description='Thermal diffusivity for this object in mm²/s (used if no per-vertex attribute override is provided). Note: your solver uses mm-units internally, so mm²/s is the natural unit here.', default=ThermalConfig.thermal_diffusivity_mm2_s, min=0.0)
density_kg_m3: FloatProperty(name='Density ρ (kg/m³)', description='Material density in kg/m^3 (used if no per-vertex attribute override is provided)', default=ThermalConfig.density_kg_m3, min=0.0)
specific_heat_J_kgK: FloatProperty(name='Specific Heat c (J/kgK)', description='Specific heat capacity in J/(kg*K) (used if no per-vertex attribute override is provided)', default=ThermalConfig.specific_heat_J_kgK, min=0.0)
emissivity: FloatProperty(name='Emissivity ε', description='Surface emissivity for thermal rendering and radiation calculations (0-1)', default=ThermalConfig.emissivity, min=0.0, max=1.0)
thermal_role: EnumProperty(name='Thermal Role', description='How this object participates in the FEM heat sim. FEM Participant (default): full transient FEM; topology must be stable. Dirichlet Source: vertex temperatures are pinned to a constant value every step.', items=['FEM_PARTICIPANT', 'FEM Participant', 'Full transient simulation; stable topology required', 'DIRICHLET_SOURCE', 'Dirichlet Source (constant T)', 'Vertex temperatures pinned; topology may change per frame'], default='FEM_PARTICIPANT')
dirichlet_temperature_K: FloatProperty(name='Dirichlet Temperature (K)', description="Constant temperature for this object's vertices when Thermal Role = Dirichlet Source. When set to 0 (or below), falls back to this object's Initial Temp.", default=0.0, min=0.0, soft_min=0.0, soft_max=2000.0)
visionsim.simulate.heatsim.properties.register() → None[source]

Register the per-object thermal material PropertyGroup on bpy.types.Object.

visionsim.simulate.heatsim.properties.unregister() → None[source]

Unregister the thermal material PropertyGroup.

visionsim.simulate.heatsim.solver module

Transient heat integration on a robust point-cloud Laplacian.

visionsim.simulate.heatsim.solver.scipy_to_torch_sparse(mat, device, dtype=torch.float32)[source]

Convert a SciPy sparse matrix to a torch.sparse_coo_tensor on a given device.

visionsim.simulate.heatsim.solver.sparse_diag(A)[source]

Extract the diagonal of a coalesced torch sparse COO tensor as a dense (N,) vector.

visionsim.simulate.heatsim.solver.pcg_solve(mv, b, Minv, x0=None, tol=1e-06, max_iter=200, rtol=0.0)[source]

Jacobi (diagonal) preconditioned Conjugate Gradient for SPD systems A x = b, where mv(x) computes A @ x and Minv is the (N,1) inverse-diagonal preconditioner.

class visionsim.simulate.heatsim.solver.HeatSimFEM(gen_params, sim_params, **kwargs)[source]

Bases: object

Memory-efficient heat simulation using torch sparse and CG. Sparse matrices are used and no dense system matrices are formed.

__init__(gen_params, sim_params, **kwargs) → None[source]
perform_gt_heat_simulation(verts_np, faces_np, boundary_faces_np, boundary_verts_mask_override=None, u0=None, irradiance_map=None, thermal_diffusivity_map=None, density_map=None, specific_heat_map=None, emissivity_map=None, steady_state: bool = False, tol_K_per_s: float = 0.0, store_only_final: bool = False)[source]

visionsim.simulate.heatsim.thermal_shader module

Thermal AOV + gray-body radiance shader support for visionsim.

Provides four entry points consumed by the thermal render pipeline:

visionsim.simulate.heatsim.thermal_shader.setup_temperature_aov(scene: Any, view_layer: Any) → str[source]

Register a temperature value AOV on view_layer and wire it into scene materials.

For every mesh material in the scene, appends an Attribute("sim_temperature") → ShaderNodeOutputAOV("temperature") chain so that Cycles writes raw temperature values into the AOV render pass.

Parameters:
  • scene – The Blender scene (bpy.types.Scene).

  • view_layer – The view layer on which to register the AOV (bpy.types.ViewLayer).

Returns:

The compositor socket name "temperature" — wire this to the CompositorNodeOutputFile input for the temperature render pass.

visionsim.simulate.heatsim.thermal_shader.enter_thermal_scene(scene: Any, *, radiance_scale: float, assignment: SceneAssignment | None = None) → dict[source]

Swap scene into thermal rendering state for a gray-body radiance pass.

Uses per-slot gray-body materials when an assignment is supplied, otherwise a uniform diffuse view-layer override. All thermal materials are opaque. Disables glossy filtering, smooth mesh shading and weighted normals to avoid losing reflected thermal energy near edges. Hides light objects and sets a uniform-background thermal world. Returns an opaque state dict; pass it to restore_scene() to undo all changes.

Parameters:
  • scene – The Blender scene.

  • radiance_scale – Multiplier applied after σ·T⁴; controls the brightness of the rendered radiance image relative to physical W/m² values.

  • assignment – Thermal sidecar providing per-material reflection controls.

Returns:

An opaque state dict for passing to restore_scene().

Note

Self-restoring: the state dict is populated as the scene is mutated, and any exception during setup triggers a full restore_scene() rollback before the error is re-raised. This guarantees the scene is never left half-swapped even though the caller has not yet received state.

visionsim.simulate.heatsim.thermal_shader.restore_scene(scene: Any, state: dict) → None[source]

Restore scene to the state captured by enter_thermal_scene().

Parameters:
visionsim.simulate.heatsim.thermal_shader.stamp_default_temperatures(scene: Any, *, default_K: float) → None[source]

Stamp the heatsim_default_temperature custom property on every mesh object.

The gray-body emission shader reads this as a fallback temperature wherever the per-vertex sim_temperature attribute is absent (objects not participating in the FEM solve, or fluid meshes regenerated each frame by Mantaflow). Cheap to call every frame.

Parameters:
  • scene – The Blender scene.

  • default_K – Fallback temperature in Kelvin to stamp on all mesh objects.

visionsim.simulate.heatsim.uv_utils module

Validate thermal UV layouts and preserve authored Blender UV state.

visionsim.simulate.heatsim.uv_utils.repair_bake_uv(mesh, object_name: str, source_mesh=None) → None[source]

Validate every generated layout; rechart only when it fails.

Relax connected charts first so thin faces can share bake pixels with their neighbors. If that makes the layout worse, retain the original charts and unfold only failing faces. Never accept a partial/overlapping map. The caller owns the Edit-mode context and restores scene selection settings.

visionsim.simulate.heatsim.uv_utils.get_uv_state(obj: bpy.types.Object) → tuple[str | None, str | None][source]

Return (active_uv_name, active_render_uv_name) for a mesh object.

visionsim.simulate.heatsim.uv_utils.set_uv_state(obj: bpy.types.Object, state: tuple[str | None, str | None]) → None[source]

Set active/render UV for a mesh object, if the UV names exist.

visionsim.simulate.heatsim.uv_utils.snapshot_uv_states(objects: Iterable[bpy.types.Object]) → list[tuple[bpy.types.Object, tuple[str | None, str | None]]][source]

Capture UV state for objects (only MESH objects with UV layers).

visionsim.simulate.heatsim.uv_utils.restore_uv_states(snapshot: list[tuple[bpy.types.Object, tuple[str | None, str | None]]]) → None[source]

Restore a previously-captured UV snapshot.

Module contents