Spaces:
Runtime error
Runtime error
File size: 26,830 Bytes
e6be672 | 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 | # Copyright (C) 2026 Mattia Zatelli
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
Visualize intent plugin — 3D visualization, color mapping, section boxes, camera controls.
Manages color mapping rules, section box clipping, 3D snapshot generation,
camera positioning, and element highlighting for the BIM viewer.
"""
import logging
import math
import uuid
from typing import Dict, Optional, List, Any
from datetime import datetime
from sqlalchemy.ext.asyncio import AsyncSession
from app.models import Project, Element
from app.schemas.intent import SingleQueryPlan, SingleQueryResult, MainIntent
from app.core.intent_system.base_plugin import BaseIntentPlugin
from app.core.intent_system.decorators import sub_intent
logger = logging.getLogger(__name__)
class VisualizeIntentPlugin(BaseIntentPlugin):
"""Plugin for the VISUALIZE intent — 3D visualization and color mapping."""
def __init__(self):
super().__init__()
self.intent_type = MainIntent.VISUALIZE
self.supported_sub_intents = [
"visualize.color_map",
"visualize.section_box",
"visualize.snapshot",
"visualize.camera",
"visualize.highlight",
]
# Color schemes
self.color_schemes = {
"by_type": {
"name": "By IFC Type",
"description": "Color elements by their IFC classification",
},
"by_level": {
"name": "By Level",
"description": "Color elements by building level/storey",
},
"by_material": {
"name": "By Material",
"description": "Color elements by material assignment",
},
"by_phase": {
"name": "By Phase",
"description": "Color by construction phase",
},
"by_status": {
"name": "By Status",
"description": "Color by element status/health",
},
"heatmap_area": {
"name": "Area Heatmap",
"description": "Heatmap based on element area",
},
"heatmap_volume": {
"name": "Volume Heatmap",
"description": "Heatmap based on element volume",
},
}
# Predefined color palettes
self.color_palettes = {
"default": {
"colors": [
"#3498db", "#e74c3c", "#2ecc71", "#f39c12",
"#9b59b6", "#1abc9c", "#34495e", "#e67e22",
],
"description": "Balanced color palette for general use",
},
"warm": {
"colors": [
"#ff6b6b", "#feca57", "#ee5a6f", "#ff7979",
"#fa8231", "#ff9ff3", "#ffd93d",
],
"description": "Warm color palette",
},
"cool": {
"colors": [
"#54a0ff", "#48dbfb", "#0abde3", "#00d2d3",
"#5f27cd", "#00a8ff", "#0097e6",
],
"description": "Cool color palette",
},
"earth": {
"colors": [
"#8b4513", "#d2691e", "#cd853f", "#daa520",
"#b8860b", "#a0522d", "#d2b48c",
],
"description": "Earth tones palette",
},
"pastel": {
"colors": [
"#ffeaa7", "#dfe6e9", "#fab1a0", "#74b9ff",
"#a29bfe", "#fd79a8", "#fdcb6e",
],
"description": "Soft pastel colors",
},
}
# Camera presets
self.camera_presets = {
"isometric": {
"name": "Isometric",
"angles": {"azimuth": 45, "elevation": 35},
},
"top": {
"name": "Top View",
"angles": {"azimuth": 0, "elevation": 90},
},
"front": {
"name": "Front View",
"angles": {"azimuth": 0, "elevation": 0},
},
"right": {
"name": "Right View",
"angles": {"azimuth": 90, "elevation": 0},
},
"perspective": {
"name": "Perspective",
"angles": {"azimuth": 30, "elevation": 25},
},
}
# Rendering presets
self.rendering_presets = {
"draft": {
"quality": "draft",
"shadows": False,
"ambient_occlusion": False,
"anti_aliasing": 1,
"render_time_estimate": "fast",
},
"standard": {
"quality": "standard",
"shadows": True,
"ambient_occlusion": False,
"anti_aliasing": 2,
"render_time_estimate": "medium",
},
"high": {
"quality": "high",
"shadows": True,
"ambient_occlusion": True,
"anti_aliasing": 4,
"render_time_estimate": "slow",
},
}
# ------------------------------------------------------------------
# Sub-intent handlers
# ------------------------------------------------------------------
@sub_intent("visualize.color_map")
async def handle_color_map(
self,
query_plan: SingleQueryPlan,
project: Project,
session: AsyncSession,
context: Optional[Dict] = None,
) -> SingleQueryResult:
"""Apply color mapping rules to elements."""
start_time = datetime.now()
# Get elements
query = await self.build_base_query(
session=session,
project=project,
filter_groups=query_plan.filter_groups,
scope=query_plan.scope,
)
result = await session.execute(query)
elements = result.scalars().all()
# Determine color scheme (default to by_type)
scheme = "by_type" # Could be extracted from filters/context
palette_name = "default"
# Generate color map
color_map = await self._generate_color_map(elements, scheme, palette_name)
explanation = (
f"Color map generated for {len(elements)} elements using '{scheme}' scheme. "
f"{color_map['unique_categories']} unique categories identified. "
f"Palette: {palette_name}."
)
return self.create_result(
query_plan=query_plan,
result_text=f"Color map: {len(elements)} elements, {color_map['unique_categories']} categories",
explanation=explanation,
result_data=color_map,
provenance=["database_query", "color_mapping"],
elements_processed=len(elements),
processing_time_ms=int(
(datetime.now() - start_time).total_seconds() * 1000
),
)
@sub_intent("visualize.section_box")
async def handle_section_box(
self,
query_plan: SingleQueryPlan,
project: Project,
session: AsyncSession,
context: Optional[Dict] = None,
) -> SingleQueryResult:
"""Define section box for 3D clipping."""
start_time = datetime.now()
# Get elements
query = await self.build_base_query(
session=session,
project=project,
filter_groups=query_plan.filter_groups,
scope=query_plan.scope,
)
result = await session.execute(query)
elements = result.scalars().all()
# Calculate section box bounds
section_box = await self._calculate_section_box(elements)
volume = (
section_box["dimensions"]["width"]
* section_box["dimensions"]["depth"]
* section_box["dimensions"]["height"]
)
explanation = (
f"Section box calculated for {len(elements)} elements. "
f"Dimensions: {section_box['dimensions']['width']:.1f} x "
f"{section_box['dimensions']['depth']:.1f} x "
f"{section_box['dimensions']['height']:.1f} m. "
f"Volume: {volume:.1f} m3."
)
return self.create_result(
query_plan=query_plan,
result_text=(
f"Section box: "
f"{section_box['dimensions']['width']:.1f}x"
f"{section_box['dimensions']['depth']:.1f}x"
f"{section_box['dimensions']['height']:.1f}m"
),
explanation=explanation,
result_data=section_box,
provenance=["database_query", "geometry_calculation"],
elements_processed=len(elements),
processing_time_ms=int(
(datetime.now() - start_time).total_seconds() * 1000
),
)
@sub_intent("visualize.snapshot")
async def handle_snapshot(
self,
query_plan: SingleQueryPlan,
project: Project,
session: AsyncSession,
context: Optional[Dict] = None,
) -> SingleQueryResult:
"""Generate 3D snapshot configuration."""
start_time = datetime.now()
# Get elements
query = await self.build_base_query(
session=session,
project=project,
filter_groups=query_plan.filter_groups,
scope=query_plan.scope,
)
result = await session.execute(query)
elements = result.scalars().all()
# Generate snapshot configuration
snapshot = await self._generate_snapshot_config(elements, project)
explanation = (
f"Snapshot configuration generated for {len(elements)} elements. "
f"Resolution: {snapshot['resolution']['width']}x{snapshot['resolution']['height']}. "
f"Camera preset: {snapshot['camera_preset']}. "
f"Rendering quality: {snapshot['rendering']['quality']}."
)
return self.create_result(
query_plan=query_plan,
result_text=(
f"Snapshot: {snapshot['resolution']['width']}x"
f"{snapshot['resolution']['height']} "
f"({snapshot['rendering']['quality']})"
),
explanation=explanation,
result_data=snapshot,
provenance=["database_query", "snapshot_generation"],
elements_processed=len(elements),
processing_time_ms=int(
(datetime.now() - start_time).total_seconds() * 1000
),
)
@sub_intent("visualize.camera")
async def handle_camera(
self,
query_plan: SingleQueryPlan,
project: Project,
session: AsyncSession,
context: Optional[Dict] = None,
) -> SingleQueryResult:
"""Calculate optimal camera positioning."""
start_time = datetime.now()
# Get elements
query = await self.build_base_query(
session=session,
project=project,
filter_groups=query_plan.filter_groups,
scope=query_plan.scope,
)
result = await session.execute(query)
elements = result.scalars().all()
# Calculate camera position
camera = await self._calculate_camera_position(elements, preset="isometric")
distance = self._calculate_distance(camera["position"], camera["target"])
explanation = (
f"Camera positioned for optimal view of {len(elements)} elements. "
f"Preset: {camera['preset']}. "
f"Distance from target: {distance:.1f}m. "
f"Field of view: {camera['fov']}."
)
return self.create_result(
query_plan=query_plan,
result_text=f"Camera: {camera['preset']} view, {distance:.1f}m from target",
explanation=explanation,
result_data=camera,
provenance=["database_query", "camera_calculation"],
elements_processed=len(elements),
processing_time_ms=int(
(datetime.now() - start_time).total_seconds() * 1000
),
)
@sub_intent("visualize.highlight")
async def handle_highlight(
self,
query_plan: SingleQueryPlan,
project: Project,
session: AsyncSession,
context: Optional[Dict] = None,
) -> SingleQueryResult:
"""Generate highlight configuration for specific elements."""
start_time = datetime.now()
# Get elements to highlight
query = await self.build_base_query(
session=session,
project=project,
filter_groups=query_plan.filter_groups,
scope=query_plan.scope,
)
result = await session.execute(query)
elements = result.scalars().all()
# Generate highlight configuration
highlight = await self._generate_highlight_config(elements)
explanation = (
f"Highlighting {len(elements)} elements. "
f"Highlight color: {highlight['highlight_color']}. "
f"Opacity: {highlight['opacity'] * 100}%. "
f"Outline: {'enabled' if highlight['outline'] else 'disabled'}."
)
return self.create_result(
query_plan=query_plan,
result_text=f"Highlighting {len(elements)} elements with {highlight['effect_type']} effect",
explanation=explanation,
result_data=highlight,
provenance=["database_query", "highlight_generation"],
elements_processed=len(elements),
processing_time_ms=int(
(datetime.now() - start_time).total_seconds() * 1000
),
)
# ------------------------------------------------------------------
# Helper methods
# ------------------------------------------------------------------
async def _generate_color_map(
self,
elements: List[Element],
scheme: str,
palette_name: str,
) -> Dict[str, Any]:
"""Generate color mapping for elements."""
palette = self.color_palettes.get(palette_name, self.color_palettes["default"])
colors = palette["colors"]
category_colors: Dict[str, str] = {}
element_colors: List[Dict[str, Any]] = []
category_counts: Dict[str, int] = {}
if scheme == "by_type":
# Group by IFC type
unique_types = sorted(set(e.ifc_type for e in elements if e.ifc_type))
for i, ifc_type in enumerate(unique_types):
category_colors[ifc_type] = colors[i % len(colors)]
category_counts[ifc_type] = sum(
1 for e in elements if e.ifc_type == ifc_type
)
for element in elements[:100]: # Sample first 100 for visualization
element_colors.append(
{
"element_id": element.ifc_global_id,
"element_name": element.name,
"category": element.ifc_type,
"color": category_colors.get(element.ifc_type, "#cccccc"),
}
)
elif scheme == "by_level":
# Group by level
unique_levels = sorted(
set(e.level_name for e in elements if e.level_name)
)
for i, level in enumerate(unique_levels):
category_colors[level] = colors[i % len(colors)]
category_counts[level] = sum(
1 for e in elements if e.level_name == level
)
for element in elements[:100]:
element_colors.append(
{
"element_id": element.ifc_global_id,
"element_name": element.name,
"category": element.level_name or "Unassigned",
"color": category_colors.get(element.level_name, "#cccccc"),
}
)
elif scheme == "by_material":
# Group by material
unique_materials = sorted(
set(e.material_name for e in elements if e.material_name)
)
for i, material in enumerate(unique_materials):
category_colors[material] = colors[i % len(colors)]
category_counts[material] = sum(
1 for e in elements if e.material_name == material
)
for element in elements[:100]:
element_colors.append(
{
"element_id": element.ifc_global_id,
"element_name": element.name,
"category": element.material_name or "No Material",
"color": category_colors.get(
element.material_name, "#cccccc"
),
}
)
elif scheme == "heatmap_area":
# Heatmap by area
areas = [float(e.area) for e in elements if e.area]
if areas:
min_area, max_area = min(areas), max(areas)
for element in elements[:100]:
if element.area:
normalized = (
(float(element.area) - min_area)
/ (max_area - min_area)
if max_area > min_area
else 0
)
color = self._get_heatmap_color(normalized)
else:
color = "#cccccc"
element_colors.append(
{
"element_id": element.ifc_global_id,
"element_name": element.name,
"value": float(element.area) if element.area else None,
"color": color,
}
)
return {
"project_id": elements[0].project_id if elements else None,
"scheme": scheme,
"scheme_name": self.color_schemes[scheme]["name"],
"palette": palette_name,
"palette_description": palette["description"],
"unique_categories": len(category_colors),
"category_colors": category_colors,
"category_counts": category_counts,
"element_colors": element_colors,
"total_elements": len(elements),
"sampled_elements": len(element_colors),
"legend": [
{
"category": cat,
"color": col,
"count": category_counts.get(cat, 0),
}
for cat, col in category_colors.items()
],
}
def _get_heatmap_color(self, value: float) -> str:
"""Get color for heatmap value (0-1). Blue (cold) to Red (hot) gradient."""
if value < 0.25:
return f"#00{int(value * 4 * 255):02x}ff" # Blue to cyan
elif value < 0.5:
return f"#00ff{int((0.5 - value) * 4 * 255):02x}" # Cyan to green
elif value < 0.75:
return f"#{int((value - 0.5) * 4 * 255):02x}ff00" # Green to yellow
else:
return f"#ff{int((1 - value) * 4 * 255):02x}00" # Yellow to red
async def _calculate_section_box(
self, elements: List[Element]
) -> Dict[str, Any]:
"""Calculate bounding box for section."""
# Mock calculation (in real implementation, would calculate from actual geometry)
min_coords = {"x": 0, "y": 0, "z": 0}
max_coords = {"x": 100, "y": 50, "z": 30}
center = {
"x": (min_coords["x"] + max_coords["x"]) / 2,
"y": (min_coords["y"] + max_coords["y"]) / 2,
"z": (min_coords["z"] + max_coords["z"]) / 2,
}
dimensions = {
"width": max_coords["x"] - min_coords["x"],
"depth": max_coords["y"] - min_coords["y"],
"height": max_coords["z"] - min_coords["z"],
}
return {
"min": min_coords,
"max": max_coords,
"center": center,
"dimensions": dimensions,
"clip_planes": [
{"normal": {"x": 1, "y": 0, "z": 0}, "distance": min_coords["x"], "enabled": True},
{"normal": {"x": -1, "y": 0, "z": 0}, "distance": -max_coords["x"], "enabled": True},
{"normal": {"x": 0, "y": 1, "z": 0}, "distance": min_coords["y"], "enabled": True},
{"normal": {"x": 0, "y": -1, "z": 0}, "distance": -max_coords["y"], "enabled": True},
{"normal": {"x": 0, "y": 0, "z": 1}, "distance": min_coords["z"], "enabled": True},
{"normal": {"x": 0, "y": 0, "z": -1}, "distance": -max_coords["z"], "enabled": True},
],
"element_count": len(elements),
}
async def _generate_snapshot_config(
self, elements: List[Element], project: Project
) -> Dict[str, Any]:
"""Generate snapshot configuration."""
camera_preset = "isometric"
rendering_preset = "standard"
camera = await self._calculate_camera_position(elements, camera_preset)
rendering = self.rendering_presets[rendering_preset]
return {
"project_id": project.id,
"project_name": project.name,
"camera_preset": camera_preset,
"camera": camera,
"resolution": {
"width": 1920,
"height": 1080,
"aspect_ratio": 16 / 9,
},
"format": "png",
"quality": 95,
"rendering": rendering,
"rendering_preset": rendering_preset,
"element_count": len(elements),
"background": {
"type": "gradient",
"top_color": "#e0f2f7",
"bottom_color": "#ffffff",
},
"lighting": {
"ambient": {"intensity": 0.3, "color": "#ffffff"},
"directional": [
{
"direction": {"x": 1, "y": 1, "z": -1},
"intensity": 0.7,
"color": "#ffffff",
},
],
},
"timestamp": datetime.now().isoformat(),
}
async def _calculate_camera_position(
self, elements: List[Element], preset: str = "isometric"
) -> Dict[str, Any]:
"""Calculate optimal camera position."""
# Calculate center of model (from section box)
section_box = await self._calculate_section_box(elements)
center = section_box["center"]
# Get preset angles
preset_config = self.camera_presets.get(
preset, self.camera_presets["isometric"]
)
azimuth = preset_config["angles"]["azimuth"]
elevation = preset_config["angles"]["elevation"]
# Calculate camera distance based on model size
max_dimension = max(
section_box["dimensions"]["width"],
section_box["dimensions"]["depth"],
section_box["dimensions"]["height"],
)
distance = max_dimension * 1.5 # 1.5x the largest dimension
# Calculate camera position from angles
azimuth_rad = math.radians(azimuth)
elevation_rad = math.radians(elevation)
position = {
"x": center["x"]
+ distance * math.cos(elevation_rad) * math.cos(azimuth_rad),
"y": center["y"]
+ distance * math.cos(elevation_rad) * math.sin(azimuth_rad),
"z": center["z"] + distance * math.sin(elevation_rad),
}
return {
"preset": preset,
"preset_name": preset_config["name"],
"position": position,
"target": center,
"up": {"x": 0, "y": 0, "z": 1}, # Z-up convention
"fov": 60, # Field of view in degrees
"near": 0.1, # Near clipping plane
"far": distance * 5, # Far clipping plane
"distance": distance,
"azimuth": azimuth,
"elevation": elevation,
}
def _calculate_distance(
self, pos1: Dict[str, float], pos2: Dict[str, float]
) -> float:
"""Calculate Euclidean distance between two points."""
return math.sqrt(
(pos1["x"] - pos2["x"]) ** 2
+ (pos1["y"] - pos2["y"]) ** 2
+ (pos1["z"] - pos2["z"]) ** 2
)
async def _generate_highlight_config(
self, elements: List[Element]
) -> Dict[str, Any]:
"""Generate highlight configuration for elements."""
highlighted_elements = []
for element in elements[:50]: # Sample first 50 for performance
highlighted_elements.append(
{
"element_id": element.ifc_global_id,
"element_name": element.name,
"element_type": element.ifc_type,
"level": element.level_name,
}
)
return {
"highlight_id": str(uuid.uuid4()),
"highlighted_elements": highlighted_elements,
"total_highlighted": len(elements),
"sampled_count": len(highlighted_elements),
"highlight_color": "#ff6b6b",
"opacity": 1.0,
"effect_type": "glow",
"outline": True,
"outline_width": 2,
"outline_color": "#ffffff",
"animation": {
"enabled": True,
"type": "pulse",
"duration": 1.5,
"loop": True,
},
"isolation": {
"isolate_highlighted": False,
"dim_others": True,
"dim_opacity": 0.3,
},
"timestamp": datetime.now().isoformat(),
}
|