diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a7dde5..49e044b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,36 @@ All notable changes to this project are documented in this file. This project adheres to Semantic Versioning (`MAJOR.MINOR.PATCH`). +## [1.7.14] - 2026-10-31 + +### Piece-by-Piece Semantic Drawing Isolation, Timeline Stability Shield & Native Security Engine + +This release introduces an authentic whiteboard drawing experience by ensuring every distinct piece and object is drawn 100% completely before moving to the next, fixes timeline scene block shrinkage and playhead desynchronization upon deleting items, hardens project archive security against Zip-Slip attacks, and adds rich interactive visual demonstrations to project documentation. + +#### Core Drawing Experience & Whiteboard Engine (تجربة رسم السبورة البيضاء الواقعية) +* **Piece-by-Piece Object Isolation (رسم كل عنصر وتلوينه 100% أولاً):** + - **Solid Reveal Algorithm:** Eliminated unnatural vertical slab slicing where multiple objects on screen were partially filled at the same time. The drawing hand now completes each semantic object (e.g. Laptop, then Arduino, then Arrows, then LEDs) 100% before lifting off the canvas and transitioning to the next item. + - **Clean Outline Algorithm:** Isolated independent vector contours and shapes so that outlines for each object are drawn continuously without erratic jumping back and forth across the canvas. Added smooth in-air flight paths between distinct pieces. + - **Professional CAD Assembly:** Restructured structural CAD rendering so that each mechanical object completes all its assembly phases (outer chassis, primary components, connectors, and fine traces) in sequence before moving to other canvas elements. + - **Organic Sketch Algorithm:** Grouped independent visual clusters to ensure artistic sketches are rendered object by object with natural, continuous hand motions. + - **Natural Hand Velocity:** Fixed excessive hand speed during fill operations, ensuring consistent drawing speeds and natural transitions between visual elements. + +#### Timeline & Canvas Stability (استقرار شريط التايم لاين والمشاهد) +* **Scene Duration Shrinkage Elimination:** Fixed an issue where deleting an image or text element caused the scene timeline block to shrink to half a second (0.5s), causing text clipping (`Sc...`). Empty scenes now maintain a clean, stable 2.0-second baseline duration. +* **Automatic Playhead & Timer Resynchronization:** When all items in a scene are deleted, the red playhead line and digital timer automatically return to the start of the scene (`00:00.0 / 00:02.0`) instead of remaining frozen at the end of the deleted media. +* **Timeline Block Drag Constraints:** Enforced a minimum duration of 2.0 seconds when resizing scene blocks directly on the timeline, preventing accidental collapsing of scenes. +* **Preservation of User-Defined Durations:** Manually customized scene durations set via right-click are now preserved even after items are removed or modified. + +#### Security & System Protection (محرك الأمان وحماية النظام) +* **Fast In-Memory Protection:** Integrated ultra-fast in-memory validation that prevents application freezing or lag while checking file paths and inputs. +* **Project Archive Shield (Zip-Slip Protection):** Added security safeguards against malicious or corrupted `.dmproj` archives, preventing files from being written outside the project directory. +* **Windows Reserved Name Guard:** Added automatic filtering for reserved Windows system names (`CON`, `PRN`, `AUX`, `NUL`, `COM1-9`, `LPT1-9`) to prevent OS-level deadlocks. + +#### Visual Documentation & Demos (التوثيق المرئي والعروض التوضيحية) +* **Live Studio Demonstrations:** Embedded high-resolution animated demonstrations (GIFs) in the project documentation showcasing the full Whiteboard Studio workflow and the natural physics handwriting engine. + +--- + ## [1.7.13] - 2026-10-28 ### Robust Playback Crash Shield, Natural Click-Based Text Placement, Transit Hand Isolation & Core Stability diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0d123de..f2e71b4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -4,7 +4,7 @@ Thank you for your interest in contributing to DrawMotion. We are building an op --- -## Recent Architectural Updates & Solved Issues (v1.7.13) +## Recent Architectural Updates & Solved Issues (v1.7.14) To help contributors understand the current state of the application and recent developments, here is an overview of the latest bug fixes and functional enhancements: diff --git a/README.md b/README.md index 19d5dc6..27f35d3 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ ### The Open-Source Vector Animation & Whiteboard Studio Powered by Python & Qt [![Microsoft Store](https://img.shields.io/badge/Microsoft%20Store-Available%20Now-0078D4?style=for-the-badge&logo=microsoft-store&logoColor=white)](https://apps.microsoft.com/detail/9NMVGFL73RH4) -[![Latest Release](https://img.shields.io/badge/Release-v1.7.11-2ea44f?style=for-the-badge&logo=github)](https://github.com/DMotionX/DrawMotion/releases) +[![Latest Release](https://img.shields.io/badge/Release-v1.7.14-2ea44f?style=for-the-badge&logo=github)](https://github.com/DMotionX/DrawMotion/releases) [![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg?style=for-the-badge)](LICENSE)
@@ -41,6 +41,23 @@ DrawMotion Studio running in Ultra-Dark Mode — featuring the dynamic vector canvas, multi-track timeline, audio waveform sync, and precision properties inspector.

+### 🎬 Live Demonstrations & Animation Showcase + + + + + + +
+ Whiteboard Drawing & Canvas Studio
+ فيديو توضيحي لاستوديو الرسم والتحريك

+ DrawMotion Whiteboard Studio Demo +
+ Natural Physics Handwriting Engine
+ عرض توضيحي لمحرك الكتابة باليد والمحاكاة الحركية

+ DrawMotion Handwriting Engine Demo +
+ --- diff --git a/build_assets/msstore/AppxManifest.xml b/build_assets/msstore/AppxManifest.xml index 8936b3c..c843631 100644 --- a/build_assets/msstore/AppxManifest.xml +++ b/build_assets/msstore/AppxManifest.xml @@ -5,7 +5,7 @@ + Version="1.7.14.0" /> DrawMotion DrawMotion diff --git a/build_assets/setup_script.iss b/build_assets/setup_script.iss index c0581dd..f7f04f6 100644 --- a/build_assets/setup_script.iss +++ b/build_assets/setup_script.iss @@ -1,7 +1,7 @@ [Setup] SourceDir=.. AppName=DrawMotion -AppVersion=1.7.13 +AppVersion=1.7.14 AppPublisher=DrawMotion Team (Mohamed Fadl) AppPublisherURL=https://github.com/DMotionX/DrawMotion AppSupportURL=https://drawmotion-web.vercel.app/ diff --git a/build_assets/setup_script_github.iss b/build_assets/setup_script_github.iss index c0581dd..f7f04f6 100644 --- a/build_assets/setup_script_github.iss +++ b/build_assets/setup_script_github.iss @@ -1,7 +1,7 @@ [Setup] SourceDir=.. AppName=DrawMotion -AppVersion=1.7.13 +AppVersion=1.7.14 AppPublisher=DrawMotion Team (Mohamed Fadl) AppPublisherURL=https://github.com/DMotionX/DrawMotion AppSupportURL=https://drawmotion-web.vercel.app/ diff --git a/components/canvas/workspace.py b/components/canvas/workspace.py index 7d420a9..cd9caa4 100644 --- a/components/canvas/workspace.py +++ b/components/canvas/workspace.py @@ -383,7 +383,9 @@ def set_scene_duration_and_scale(self, board, new_dur): Sets the scene duration and scales all animated items inside it so their total duration matches the new scene duration. """ + new_dur = max(2.0, float(new_dur)) board.duration = new_dur + board.user_defined_duration = new_dur scene_items = [item for item in self.user_items if item.parentItem() == board] anim_items = [item for item in scene_items if hasattr(item, '_anim_duration')] @@ -466,11 +468,21 @@ def calculate_times(): if action['type'] == 'draw' and action['item']: action['item'].anim_delay = action['start'] - if respect_board_duration: - actual_dur = max(0.5, getattr(board, 'duration', total_items_duration)) - else: - actual_dur = max(0.5, total_items_duration) + DEFAULT_SCENE_DUR = 2.0 + if not anim_items: + # Empty scene (all items removed or fresh): restore/maintain default 2.0s + user_dur = getattr(board, 'user_defined_duration', None) + if user_dur is not None and user_dur >= DEFAULT_SCENE_DUR: + actual_dur = user_dur + else: + actual_dur = DEFAULT_SCENE_DUR board.duration = actual_dur + else: + if respect_board_duration: + actual_dur = max(DEFAULT_SCENE_DUR, getattr(board, 'duration', total_items_duration)) + else: + actual_dur = max(DEFAULT_SCENE_DUR, total_items_duration) + board.duration = actual_dur new_scene_windows.append({ 'scene_index': i, @@ -1041,15 +1053,26 @@ def delete_item(self, item): if item in self.user_items: self.user_items.remove(item) self.scene.removeItem(item) - self.animator_engine.hand_item.hide() - self.items_changed.emit(self.user_items) + if hasattr(self, 'animator_engine') and self.animator_engine: + if hasattr(self.animator_engine, 'hand_item') and self.animator_engine.hand_item: + self.animator_engine.hand_item.hide() + if hasattr(self.animator_engine, 'writing_hand_item') and self.animator_engine.writing_hand_item: + self.animator_engine.writing_hand_item.hide() + + # If all items are deleted, stop any ongoing playback and reset playhead to 0 + if not self.user_items: + if hasattr(self, 'animator_engine') and self.animator_engine: + self.animator_engine.stop() + if hasattr(self, 'animation_progress'): + self.animation_progress.emit(0.0) # Redistribute time among remaining items - self.distribute_global_time() + self.distribute_global_time(respect_board_duration=False) # Immediately resync the animator engine queue to match the remaining items - items_to_animate = self.user_items - self.animator_engine.sync_queue(items_to_animate) + items_to_animate = list(self.user_items) + if hasattr(self, 'animator_engine') and self.animator_engine: + self.animator_engine.sync_queue(items_to_animate, force_recompile=True) self.items_changed.emit(items_to_animate) diff --git a/components/splash/splash_view.py b/components/splash/splash_view.py index ac53c0c..d3389f2 100644 --- a/components/splash/splash_view.py +++ b/components/splash/splash_view.py @@ -6,7 +6,7 @@ """ import os import sys -from PySide6.QtCore import Qt, QPropertyAnimation, QEasingCurve, QSize +from PySide6.QtCore import Qt, QPropertyAnimation, QEasingCurve, QSize, QTimer from PySide6.QtGui import QIcon, QPixmap, QColor from PySide6.QtWidgets import ( QWidget, QFrame, QVBoxLayout, QHBoxLayout, QLabel, @@ -21,7 +21,7 @@ class InteractiveSplashScreen(QWidget): Studio-grade floating reload and splash screen. Guarantees instant (<50ms) visual response upon launching DrawMotion. """ - def __init__(self, version: str = "v1.7.13", parent=None): + def __init__(self, version: str = "v1.7.14", parent=None): super().__init__(parent) self.version = version self._target_window = None @@ -180,6 +180,15 @@ def finish_smoothly(self, target_window: QWidget = None) -> None: except Exception: pass + # Check if running in headless / offscreen mode (e.g., automated CI test runners) + is_offscreen = ( + os.environ.get("QT_QPA_PLATFORM") == "offscreen" or + (QApplication.instance() and getattr(QApplication.instance(), "platformName", lambda: "")() == "offscreen") + ) + if is_offscreen: + self._on_fade_finished() + return + # Smooth fade-out animation over the already-rendered target window self._fade_anim = QPropertyAnimation(self, b"windowOpacity") self._fade_anim.setDuration(250) @@ -191,6 +200,11 @@ def finish_smoothly(self, target_window: QWidget = None) -> None: def _on_fade_finished(self): """Finalizes transition and cleans up splash resources.""" + if hasattr(self, "_fade_anim") and self._fade_anim: + try: + self._fade_anim.stop() + except Exception: + pass if self._target_window is not None: try: self._target_window.raise_() @@ -198,4 +212,4 @@ def _on_fade_finished(self): except Exception: pass self.close() - self.deleteLater() + QTimer.singleShot(0, self.deleteLater) diff --git a/components/timeline/layers/scenes_layer.py b/components/timeline/layers/scenes_layer.py index 7feb14b..088a7f1 100644 --- a/components/timeline/layers/scenes_layer.py +++ b/components/timeline/layers/scenes_layer.py @@ -135,7 +135,7 @@ def _populate_track(self): if t_type and t_type != "None": t_dur = getattr(prev_board, 'transition_duration', 1.0) current_time += t_dur - base_dur = getattr(board, 'duration', 8.0) + base_dur = getattr(board, 'duration', 2.0) items = [i for i in self._workspace.user_items if i.parentItem() == board] # Find the actual compiled end time for this scene from the scheduler @@ -152,9 +152,9 @@ def _populate_track(self): if items: # Dynamically stretch the scene duration to fit all items - dur = max(base_dur, max_item_dur) + dur = max(2.0, base_dur, max_item_dur) else: - dur = base_dur + dur = max(2.0, base_dur) is_active = (i == self._workspace.current_scene_index) if self._workspace else False blocks.append({'start': current_time, 'duration': dur, diff --git a/components/timeline/panel.py b/components/timeline/panel.py index 850d9ae..39164be 100644 --- a/components/timeline/panel.py +++ b/components/timeline/panel.py @@ -346,18 +346,35 @@ def _on_focus_mode_toggled(self, is_focused): def set_workspace(self, workspace): self.workspace = workspace + def compute_total_project_duration(self) -> float: + total_time = 0.0 + if self.workspace: + if hasattr(self.workspace, 'artboards') and self.workspace.artboards: + cur_t = 0.0 + for i, b in enumerate(self.workspace.artboards): + if cur_t > 0 and i > 0: + prev_b = self.workspace.artboards[i - 1] + t_type = getattr(prev_b, 'transition_type', None) + if t_type and t_type != "None": + cur_t += getattr(prev_b, 'transition_duration', 1.0) + cur_t += getattr(b, 'duration', 2.0) + total_time = cur_t + if hasattr(self.workspace, 'animator_engine'): + schedule = getattr(self.workspace.animator_engine, 'schedule', None) + if schedule: + sched_max = max((a.get('end', 0.0) for a in schedule), default=0.0) + total_time = max(total_time, sched_max) + return max(2.0, total_time) + def set_playhead_progress(self, current_time_sec): + self._last_progress_time = current_time_sec x_pos = int(current_time_sec * PIXELS_PER_SECOND) self.playhead_line.move(x_pos, 0) self.playhead_line.setFixedHeight(self._tracks_container.height()) self.playhead_line.raise_() # Update Digital Timer - total_time = 0.0 - if self.workspace and hasattr(self.workspace, 'animator_engine'): - schedule = self.workspace.animator_engine.schedule - if schedule: - total_time = max(a['end'] for a in schedule) + total_time = self.compute_total_project_duration() def fmt(t): m = int(t // 60) @@ -414,9 +431,15 @@ def update_timeline(self, items=None): t_idx = self._tracks_layout.count() - 1 self._tracks_layout.insertWidget(t_idx, row.track_widget()) - # Keep playhead on top + # Keep playhead on top and synchronize with project duration if hasattr(self, 'playhead_line'): self.playhead_line.raise_() + total_dur = self.compute_total_project_duration() + current_t = getattr(self, '_last_progress_time', 0.0) + if current_t > total_dur: + current_t = 0.0 if not (self.workspace and self.workspace.user_items) else total_dur + self._last_progress_time = current_t + self.set_playhead_progress(current_t) self._left_layout.invalidate() self._tracks_layout.invalidate() diff --git a/components/widgets/timeline_track.py b/components/widgets/timeline_track.py index 24991df..64f4832 100644 --- a/components/widgets/timeline_track.py +++ b/components/widgets/timeline_track.py @@ -292,8 +292,8 @@ def mouseMoveEvent(self, event: QMouseEvent): self.setCursor(Qt.CursorShape.SizeAllCursor) # Cursor for moving elif getattr(self, '_resizing', False): dx = event.globalPosition().x() - self._drag_start_x - new_width = max(10, self._original_width + dx) - new_duration = new_width / self.pixels_per_second + min_dur = 2.0 if self.data.get('is_scene_block') else 0.5 + new_duration = max(min_dur, (self._original_width + dx) / self.pixels_per_second) self.duration = new_duration self._update_width() diff --git a/core/drawing_engine/algorithms/clean_outline/algorithm.py b/core/drawing_engine/algorithms/clean_outline/algorithm.py index 09d40b3..fc48b12 100644 --- a/core/drawing_engine/algorithms/clean_outline/algorithm.py +++ b/core/drawing_engine/algorithms/clean_outline/algorithm.py @@ -1,41 +1,80 @@ +# Copyright (c) 2026 Mohamed Fadl & DrawMotion Team +# SPDX-License-Identifier: GPL-3.0-or-later + import cv2 import numpy as np -from PySide6.QtCore import QPointF -from PySide6.QtGui import QImage -from typing import List, Dict, Any import math +import copy +from typing import List, Dict, Any +from PySide6.QtCore import QPointF, Qt +from PySide6.QtGui import QImage from ..base_algorithm import BaseDrawingAlgorithm -from .human_fill_generator import generate_human_islands + +_CLEAN_OUTLINE_CACHE = {} class CleanOutlineAlgorithm(BaseDrawingAlgorithm): """ - Professional style: Draws perfect centerlines with a thick, smooth brush to completely fill the ink. - Longest paths are drawn first (like a professional architect). + Clean Outline Drawing Algorithm. + Reveals crisp vector outline contours and concentric architectural fills strictly + piece-by-piece: each discrete object (e.g. Laptop, Arduino, LED) is 100% completed + before the hand lifts in the air to draw the next piece. """ - + def generate_plan(self, qimage: QImage, duration: float, **kwargs) -> List[Dict[str, Any]]: rtl = kwargs.get("rtl", False) - mask = self._get_ink_mask(qimage) - h, w = mask.shape + duration = max(0.5, float(duration or 8.0)) + cache_key = (id(qimage), rtl, duration) + + if cache_key in _CLEAN_OUTLINE_CACHE: + return copy.deepcopy(_CLEAN_OUTLINE_CACHE[cache_key]) + + w_orig, h_orig = qimage.width(), qimage.height() + if w_orig <= 0 or h_orig <= 0: + return [] + + # Safe pre-scale for very large images to prevent RAM pressure max_dim = 1600.0 scale = 1.0 - - if w > max_dim or h > max_dim: - scale = max_dim / max(w, h) - new_w = int(w * scale) - new_h = int(h * scale) - mask = cv2.resize(mask, (new_w, new_h), interpolation=cv2.INTER_AREA) - - raw_islands = generate_human_islands(mask, scale) + if w_orig > max_dim or h_orig > max_dim: + scale = max_dim / max(w_orig, h_orig) + w_scaled = int(w_orig * scale) + h_scaled = int(h_orig * scale) + work_qimg = qimage.scaled(w_scaled, h_scaled, Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation) + else: + work_qimg = qimage + + mask = self._get_ink_mask(work_qimg) + if cv2.countNonZero(mask) == 0: + return [] + + h, w = mask.shape + kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) + dilated = cv2.dilate(mask, kernel, iterations=1) + + num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(dilated, connectivity=8) + if num_labels <= 1: + return [] + + raw_islands = [] + for i in range(1, num_labels): + x, y, cw, ch, area = stats[i] + if area > 10: + raw_islands.append({ + "rect": (int(x), int(y), int(cw), int(ch)), + "label": int(i), + "centroid": (float(centroids[i][0]), float(centroids[i][1])), + "area": float(area), + "fused_labels": [int(i)] + }) + if not raw_islands: return [] - + # 1. Spatial Proximity & Containment Fusion (Union-Find) - # Guarantees inner details (eyes, nose, mouth, diacritics) are fused into their parent - # contour, completely eliminating blank facial patches and delayed pop-ins. + # Keeps large standalone objects (> 8000 scaled px) strictly isolated as separate pieces n = len(raw_islands) parent_uf = list(range(n)) - + def find_uf(k): while parent_uf[k] != k: parent_uf[k] = parent_uf[parent_uf[k]] @@ -51,13 +90,32 @@ def union_uf(a, b): c_x, c_y, c_w, c_h = child["rect"] c_area = child["area"] c_cx, c_cy = child["centroid"] - - if c_area > 8000.0: + + # Geometric containment: if child is strictly inside another island's bounding box, + # it is part of that same piece (e.g. screen inside laptop, IC inside circuit board) + contained_in = None + min_enclosing_area = float('inf') + for i, p_candidate in enumerate(raw_islands): + if i == j: + continue + p_x, p_y, p_w, p_h = p_candidate["rect"] + p_area = p_candidate["area"] + if (p_x - 8 <= c_x and p_y - 8 <= c_y and + c_x + c_w <= p_x + p_w + 8 and c_y + c_h <= p_y + p_h + 8): + if p_area < min_enclosing_area: + min_enclosing_area = p_area + contained_in = i + + if contained_in is not None: + union_uf(j, contained_in) + continue + + if c_area > 8000.0 * (scale ** 2): continue - + best_parent_idx = None best_parent_area = float('inf') - + for i, p_candidate in enumerate(raw_islands): if i == j: continue @@ -65,15 +123,15 @@ def union_uf(a, b): p_area = p_candidate["area"] if p_area < 1.8 * c_area: continue - - margin_x = 20.0 - margin_y = 26.0 + + margin_x = 18.0 + margin_y = 24.0 if (p_x - margin_x <= c_cx <= p_x + p_w + margin_x and p_y - margin_y <= c_cy <= p_y + p_h + margin_y): if p_area < best_parent_area: best_parent_area = p_area best_parent_idx = i - + if best_parent_idx is not None: union_uf(j, best_parent_idx) @@ -87,112 +145,196 @@ def union_uf(a, b): merged_islands = [] for r, group in groups.items(): rep = max(group, key=lambda it: it["area"]) - all_x = [isl["rect"][0] for isl in group] - all_y = [isl["rect"][1] for isl in group] - all_x2 = [isl["rect"][0] + isl["rect"][2] for isl in group] - all_y2 = [isl["rect"][1] + isl["rect"][3] for isl in group] + all_labels = [it["label"] for it in group] + all_x = [stats[lbl][0] for lbl in all_labels] + all_y = [stats[lbl][1] for lbl in all_labels] + all_x2 = [stats[lbl][0] + stats[lbl][2] for lbl in all_labels] + all_y2 = [stats[lbl][1] + stats[lbl][3] for lbl in all_labels] bx, by = min(all_x), min(all_y) bw = max(all_x2) - bx bh = max(all_y2) - by - - all_paths = [] - for isl in group: - all_paths.extend(isl["paths"]) - + merged_islands.append({ - "rect": (bx, by, bw, bh), - "label": rep["label"], - "centroid": rep["centroid"], - "area": sum(isl["area"] for isl in group), - "paths": all_paths + "rect": (int(bx), int(by), int(bw), int(bh)), + "label": int(rep["label"]), + "centroid": (float(rep["centroid"][0]), float(rep["centroid"][1])), + "area": float(sum(it["area"] for it in group)), + "fused_labels": all_labels }) - # 2. Sort islands naturally into reading lines (RTL / LTR) + # 2. Sort islands naturally into visual reading lines (RTL / LTR) islands = BaseDrawingAlgorithm.cluster_islands_into_lines( merged_islands, rtl=rtl, sort_mode="right_to_left" if rtl else "left_to_right" ) - - timed_segments = [] - accumulated_time = 0.0 - total_area = sum(island["area"] for island in islands) or 1.0 - - # Pen width guarantees 100% overlap between 5x5 kernel erosion concentric rings + + erosion_k = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)) step_canvas = 3.0 / scale - pen_width = max(24.0, step_canvas * 2.5) - + pen_width = max(20.0, step_canvas * 2.5) + + raw_units = [] + # 3. Process each island: generate clean outline & concentric contour paths for island in islands: - island_area = island["area"] - island_duration = duration * (island_area / total_area) - - path_data = [] - for pts in island["paths"]: - length = self._calculate_length(pts) - path_data.append({"pts": pts, "length": max(1.0, length)}) - - if not path_data: + target_labels = island.get("fused_labels", [island["label"]]) + bx, by, bw, bh = island["rect"] + sub_labels = labels[by:by+bh, bx:bx+bw] + sub_mask = np.isin(sub_labels, target_labels).astype(np.uint8) * 255 + + fill_paths = [] + max_iter = 80 + while cv2.countNonZero(sub_mask) > 0 and max_iter > 0: + max_iter -= 1 + contours, _ = cv2.findContours(sub_mask, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) + if not contours: + break + + for contour in contours: + if len(contour) < 3: + px = float(contour[0][0][0] + bx) / scale + py = float(contour[0][0][1] + by) / scale + fill_paths.append([QPointF(px, py), QPointF(px + 1.0, py)]) + continue + + epsilon = 0.003 * cv2.arcLength(contour, True) + approx = cv2.approxPolyDP(contour, epsilon, True) + if len(approx) < 3: + approx = contour + + ring_pts = [QPointF(float(pt[0][0] + bx) / scale, float(pt[0][1] + by) / scale) for pt in approx] + if ring_pts: + ring_pts.append(ring_pts[0]) + fill_paths.append(ring_pts) + + prev_nz = cv2.countNonZero(sub_mask) + sub_mask = cv2.erode(sub_mask, erosion_k, iterations=1) + if cv2.countNonZero(sub_mask) == prev_nz: + M = cv2.moments(sub_mask) + if M["m00"] > 0: + cx_sub = float(M["m10"] / M["m00"] + bx) / scale + cy_sub = float(M["m01"] / M["m00"] + by) / scale + fill_paths.append([QPointF(cx_sub, cy_sub), QPointF(cx_sub + 1.0, cy_sub)]) + break + + if not fill_paths: continue - - # Outermost ring / contour drawn first, followed by continuous nearest-neighbor inner rings - if len(path_data) > 1: - path_data.sort(key=lambda item: -item["length"]) - sorted_paths = [path_data.pop(0)] - - while path_data: - last_pt = sorted_paths[-1]["pts"][-1] - best_idx = 0 - best_dist = float('inf') - best_needs_reverse = False - - for i, item in enumerate(path_data): - start_pt = item["pts"][0] - end_pt = item["pts"][-1] - d_start = (start_pt.x() - last_pt.x())**2 + (start_pt.y() - last_pt.y())**2 - d_end = (end_pt.x() - last_pt.x())**2 + (end_pt.y() - last_pt.y())**2 - - if d_start < best_dist: - best_dist = d_start - best_idx = i - best_needs_reverse = False - - if d_end < best_dist: - best_dist = d_end - best_idx = i - best_needs_reverse = True - - next_item = path_data.pop(best_idx) - if best_needs_reverse: - next_item["pts"].reverse() - sorted_paths.append(next_item) - - path_data = sorted_paths - - total_island_length = sum(item["length"] for item in path_data) or 1.0 - - for item in path_data: - seg_share = item["length"] / total_island_length - seg_duration = island_duration * seg_share - - timed_segments.append({ - "type": "stroke", - "points": item["pts"], - "duration": seg_duration, - "start_time": accumulated_time, - "end_time": accumulated_time + seg_duration, - "width": pen_width, - "opacity": 1.0 - }) - accumulated_time += seg_duration - - # Normalize timeline smoothly to requested duration - if timed_segments and accumulated_time > 0: - scale_time = duration / accumulated_time - cur_t = 0.0 - for seg in timed_segments: - seg["duration"] *= scale_time - seg["start_time"] = cur_t - cur_t += seg["duration"] - seg["end_time"] = cur_t - + + # Sort paths within this island: longest outline first, then nearest-neighbor inner rings + path_data = [{"pts": p, "length": max(1.0, self._calculate_length(p))} for p in fill_paths] + path_data.sort(key=lambda it: -it["length"]) + sorted_paths = [path_data.pop(0)] + + while path_data: + last_pt = sorted_paths[-1]["pts"][-1] + best_idx = 0 + best_dist = float("inf") + best_needs_rev = False + + for idx, item in enumerate(path_data): + p_st = item["pts"][0] + p_en = item["pts"][-1] + d_st = (p_st.x() - last_pt.x())**2 + (p_st.y() - last_pt.y())**2 + d_en = (p_en.x() - last_pt.x())**2 + (p_en.y() - last_pt.y())**2 + if d_st < best_dist: + best_dist = d_st + best_idx = idx + best_needs_rev = False + if d_en < best_dist: + best_dist = d_en + best_idx = idx + best_needs_rev = True + + next_it = path_data.pop(best_idx) + if best_needs_rev: + next_it["pts"].reverse() + sorted_paths.append(next_it) + + # Sub-strokes with in-air travels inside this piece + sub_strokes = [] + for item in sorted_paths: + if sub_strokes: + last_p = sub_strokes[-1]["points"][-1] + first_p = item["pts"][0] + dist = math.hypot(first_p.x() - last_p.x(), first_p.y() - last_p.y()) + if dist > 15.0: + sub_strokes.append({"type": "travel", "points": [last_p, first_p]}) + sub_strokes.append({"type": "stroke", "points": item["pts"]}) + + raw_units.append({ + "island": island, + "sub_strokes": sub_strokes + }) + + if not raw_units: + return [] + + # 4. Assemble timed segments with in-air travels between distinct pieces + total_stroke_len = sum( + sum(self._calculate_length(s["points"]) for s in u["sub_strokes"] if s["type"] == "stroke") + for u in raw_units + ) or 1.0 + + timed_segments: List[Dict[str, Any]] = [] + cur_time = 0.0 + + for u in raw_units: + sub_strokes = u["sub_strokes"] + + # In-air travel flight between distinct pieces + if timed_segments: + last_p = timed_segments[-1]["points"][-1] + first_p = sub_strokes[0]["points"][0] + dist = math.hypot(first_p.x() - last_p.x(), first_p.y() - last_p.y()) + if dist > 8.0: + flight_dur = min(0.18, max(0.04, dist / 2400.0)) + timed_segments.append({ + "type": "travel", + "points": [last_p, first_p], + "duration": flight_dur, + "start_time": cur_time, + "end_time": cur_time + flight_dur, + "width": 0.0, + "opacity": 0.0 + }) + cur_time += flight_dur + + # Draw all strokes of this piece COMPLETELY before ever leaving it + for s in sub_strokes: + length = self._calculate_length(s["points"]) + if s["type"] == "travel": + dur = min(0.12, max(0.02, length / 2400.0)) + timed_segments.append({ + "type": "travel", + "points": s["points"], + "duration": dur, + "start_time": cur_time, + "end_time": cur_time + dur, + "width": 0.0, + "opacity": 0.0 + }) + cur_time += dur + else: + seg_dur = duration * (length / total_stroke_len) + timed_segments.append({ + "type": "stroke", + "points": s["points"], + "duration": seg_dur, + "start_time": cur_time, + "end_time": cur_time + seg_dur, + "width": pen_width, + "opacity": 1.0 + }) + cur_time += seg_dur + + # 5. Timeline normalization to match duration strictly + if timed_segments and cur_time > 0: + scale_t = duration / cur_time + t = 0.0 + for s in timed_segments: + s["duration"] *= scale_t + s["start_time"] = t + t += s["duration"] + s["end_time"] = t + + _CLEAN_OUTLINE_CACHE[cache_key] = copy.deepcopy(timed_segments) return timed_segments def _calculate_length(self, points: List[QPointF]) -> float: @@ -202,3 +344,4 @@ def _calculate_length(self, points: List[QPointF]) -> float: dy = points[i].y() - points[i-1].y() length += math.hypot(dx, dy) return length + diff --git a/core/drawing_engine/algorithms/hatch_shading/algorithm.py b/core/drawing_engine/algorithms/hatch_shading/algorithm.py index 45dfba7..6c93b40 100644 --- a/core/drawing_engine/algorithms/hatch_shading/algorithm.py +++ b/core/drawing_engine/algorithms/hatch_shading/algorithm.py @@ -22,154 +22,87 @@ def generate_plan(self, qimage: QImage, duration: float, **kwargs) -> List[Dict[ mask = self._get_ink_mask(qimage) scale = 1.0 - islands = generate_smart_educational_paths(mask, scale) + islands = generate_smart_educational_paths(mask, scale, rtl=rtl) if not islands: return [] - is_zoned = any("zone" in isl for isl in islands) - if is_zoned: - timed_segments = [] - current_time = 0.0 - - for isl in islands: - target_zone_duration = duration * isl.get("weight", 0.33) - paths = isl.get("paths", []) - if not paths: - continue - - zone_segments = [] - zone_accum = 0.0 - - # Sort paths within this zone continuously - ordered_paths = self._sort_paths_continuous(paths) - - path_data = [] - for pts in ordered_paths: - if not pts: - continue - uniform_pts = self._resample_path_uniform(pts, step_dist=8.0) - length = self._calculate_length(uniform_pts) - if length > 0 or isl.get("is_dot", False): - path_data.append({"pts": uniform_pts, "length": max(2.0, length)}) - - if not path_data: - continue - - total_zone_length = sum(item["length"] for item in path_data) or 1.0 - stroke_w = isl.get("stroke_width", 16.0) - - for item in path_data: - seg_dur = max(0.005, target_zone_duration * (item["length"] / total_zone_length)) - - if zone_segments or timed_segments: - last_pt = zone_segments[-1]["points"][-1] if zone_segments else timed_segments[-1]["points"][-1] - st_pt = item["pts"][0] - dist = math.hypot(st_pt.x() - last_pt.x(), st_pt.y() - last_pt.y()) - if dist > 8.0: - travel_dur = min(0.12, max(0.035, dist / 2000.0)) - zone_segments.append({ - "type": "travel", - "points": [last_pt, st_pt], - "duration": travel_dur, - "start_time": zone_accum, - "end_time": zone_accum + travel_dur, - "width": 0.0, - "opacity": 0.0 - }) - zone_accum += travel_dur - - zone_segments.append({ - "type": "stroke", - "points": item["pts"], - "duration": seg_dur, - "start_time": zone_accum, - "end_time": zone_accum + seg_dur, - "width": stroke_w, - "opacity": 1.0 - }) - zone_accum += seg_dur - - if zone_segments and zone_accum > 0: - scale_f = target_zone_duration / zone_accum - for seg in zone_segments: - seg["duration"] *= scale_f - seg["start_time"] = current_time - current_time += seg["duration"] - seg["end_time"] = current_time - timed_segments.append(seg) - - return timed_segments - - # Fallback line clustering - ordered_islands = self._cluster_islands_pedagogical(islands, rtl=rtl) - if not ordered_islands: - return [] - - for isl in ordered_islands: + for isl in islands: isl["total_length"] = sum( - self._calculate_length(pts) for pts in isl["paths"] if pts + self._calculate_length(pts) for pts in isl.get("paths", []) if pts ) or 1.0 - - total_all_length = sum(isl["total_length"] for isl in ordered_islands) or 1.0 - + + total_all_length = sum(isl["total_length"] for isl in islands) or 1.0 + timed_segments = [] - accumulated_time = 0.0 + current_time = 0.0 - for island in ordered_islands: - island_length = island["total_length"] - island_duration = duration * (island_length / total_all_length) + for isl in islands: + target_mod_duration = max(0.05, duration * (isl["total_length"] / total_all_length)) + paths = isl.get("paths", []) + if not paths: + continue + mod_segments = [] + mod_accum = 0.0 + stroke_w = isl.get("stroke_width", 16.0) + path_data = [] - for pts in island["paths"]: + for pts in paths: if not pts: continue uniform_pts = self._resample_path_uniform(pts, step_dist=8.0) length = self._calculate_length(uniform_pts) - if length > 0 or island.get("is_dot", False): + if length > 0 or isl.get("is_dot", False): path_data.append({"pts": uniform_pts, "length": max(2.0, length)}) if not path_data: continue - total_island_length = sum(item["length"] for item in path_data) or 1.0 + total_mod_len = sum(item["length"] for item in path_data) or 1.0 for item in path_data: - seg_share = item["length"] / total_island_length - seg_duration = max(0.015, island_duration * seg_share) + seg_dur = max(0.005, target_mod_duration * (item["length"] / total_mod_len)) - if timed_segments: - last_pt = timed_segments[-1]["points"][-1] - cur_start = item["pts"][0] - dx = cur_start.x() - last_pt.x() - dy = cur_start.y() - last_pt.y() - air_dist = math.hypot(dx, dy) - if air_dist > 12.0: - travel_dur = min(0.12, max(0.035, air_dist / 1400.0)) - timed_segments.append({ + # In-air travel flight between consecutive strokes and between discrete modules + if mod_segments or timed_segments: + last_pt = mod_segments[-1]["points"][-1] if mod_segments else timed_segments[-1]["points"][-1] + st_pt = item["pts"][0] + dist = math.hypot(st_pt.x() - last_pt.x(), st_pt.y() - last_pt.y()) + if dist > 8.0: + travel_dur = min(0.12, max(0.035, dist / 2000.0)) + mod_segments.append({ "type": "travel", - "points": [last_pt, cur_start], + "points": [last_pt, st_pt], "duration": travel_dur, - "start_time": accumulated_time, - "end_time": accumulated_time + travel_dur, + "start_time": mod_accum, + "end_time": mod_accum + travel_dur, "width": 0.0, "opacity": 0.0 }) - accumulated_time += travel_dur - - dynamic_width = max(18.0, min(24.0, 18.0 + item["length"] / 120.0)) - timed_segments.append({ + mod_accum += travel_dur + + mod_segments.append({ "type": "stroke", "points": item["pts"], - "duration": seg_duration, - "start_time": accumulated_time, - "end_time": accumulated_time + seg_duration, - "width": dynamic_width, + "duration": seg_dur, + "start_time": mod_accum, + "end_time": mod_accum + seg_dur, + "width": stroke_w, "opacity": 1.0 }) - accumulated_time += seg_duration + mod_accum += seg_dur + + if mod_segments and mod_accum > 0: + scale_f = target_mod_duration / mod_accum + for seg in mod_segments: + seg["duration"] *= scale_f + seg["start_time"] = current_time + current_time += seg["duration"] + seg["end_time"] = current_time + timed_segments.append(seg) - if timed_segments and accumulated_time > 0: - scale_time = duration / accumulated_time + if timed_segments and current_time > 0: + scale_time = duration / current_time cur_t = 0.0 for seg in timed_segments: seg["duration"] *= scale_time diff --git a/core/drawing_engine/algorithms/hatch_shading/smart_education_generator.py b/core/drawing_engine/algorithms/hatch_shading/smart_education_generator.py index 5636c9b..81b90b5 100644 --- a/core/drawing_engine/algorithms/hatch_shading/smart_education_generator.py +++ b/core/drawing_engine/algorithms/hatch_shading/smart_education_generator.py @@ -1,3 +1,5 @@ +# Copyright (c) 2026 Mohamed Fadl & DrawMotion Team +# SPDX-License-Identifier: GPL-3.0-or-later import cv2 import numpy as np from PySide6.QtCore import QPointF @@ -46,12 +48,15 @@ def map_pt(px, py): return paths -def generate_smart_educational_paths(mask: np.ndarray, scale: float = 1.0) -> List[Dict[str, Any]]: +def generate_smart_educational_paths(mask: np.ndarray, scale: float = 1.0, rtl: bool = False) -> List[Dict[str, Any]]: """ - Smart Educational Flow (Pedagogical Concept Zoning): - - Divides visual space into 3 Pedagogical Concept Zones (Top, Center, Bottom). - - Teaches and draws each zone completely (outlines + bold chisel-tip marker fills) - before lifting the pen in a deliberate in-air travel flight to the next concept zone. + Smart Educational Flow (Semantic Component-First Whiteboard Flow): + - Identifies discrete semantic modules (e.g. Arduino board, sensors, ICs, diagram boxes, characters) + and isolates interconnecting wire/bus networks. + - Eliminates arbitrary horizontal Y-band slicing. + - Each module is drawn completely: Outer Frame -> Internal Features -> Solid Chisel Fills + before lifting the pen in a deliberate in-air travel flight to the next module. + - Interconnecting wires, arrows, and final annotations are drawn in the finale to link the modules. - Zero blanket sweeps across empty white space. - Zero pop-in, 100% steady progressive reveal. """ @@ -76,33 +81,117 @@ def map_pt(px, py): y_indices, _ = np.where(work_mask > 0) if len(y_indices) == 0: return [] - y_min, y_max = int(np.min(y_indices)), int(np.max(y_indices)) - total_h = max(1, y_max - y_min) - - z1_y = y_min + int(0.35 * total_h) - z2_y = y_min + int(0.70 * total_h) - - zone_defs = [ - ("Zone 1: Header & Power Unit", y_min, z1_y, 0.30, 16.0), - ("Zone 2: Core Processing & Logic", z1_y, z2_y, 0.45, 16.0), - ("Zone 3: Interface & Peripheral Ports", z2_y, y_max + 1, 0.25, 14.0) - ] - + from ..base_algorithm import BaseDrawingAlgorithm filter_w = 14.0 * map_scale fill_step = max(8, int(14.0 * map_scale)) + + # 1. Separate Macro-Bodies from Thin Interconnecting Wires (e.g. 1-3px wires connecting modules) + body_k = cv2.getStructuringElement(cv2.MORPH_RECT, (4, 4)) + opened_bodies = cv2.morphologyEx(work_mask, cv2.MORPH_OPEN, body_k) - islands = [] + total_ink = cv2.countNonZero(work_mask) + opened_ink = cv2.countNonZero(opened_bodies) - for z_idx, (z_name, z_start_y, z_end_y, z_weight, stroke_w) in enumerate(zone_defs): - z_mask = np.zeros_like(work_mask) - z_mask[z_start_y:z_end_y, :] = work_mask[z_start_y:z_end_y, :] - if cv2.countNonZero(z_mask) == 0: - continue - - contours, hierarchy = cv2.findContours(z_mask, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) - z_paths = [] - z_cnts = [] + # If opening destroyed almost everything (e.g. pure single-pixel line art), fallback to work_mask directly + if opened_ink < total_ink * 0.15: + working_bodies = work_mask + wires_mask = np.zeros_like(work_mask) + else: + working_bodies = opened_bodies + wires_mask = cv2.bitwise_and(work_mask, cv2.bitwise_not(opened_bodies)) + + # 2. Connected Component Analysis on working_bodies + n_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(working_bodies, connectivity=8) + + raw_bodies = [] + for i in range(1, n_labels): + bx, by, bw, bh, area = stats[i] + if area >= 25: + raw_bodies.append({ + "id": i, + "rect": (bx, by, bw, bh), + "area": area, + "centroid": (float(centroids[i][0]), float(centroids[i][1])), + "mask": (labels == i) + }) + + if not raw_bodies: + raw_bodies.append({ + "id": 1, + "rect": (0, 0, work_mask.shape[1], work_mask.shape[0]), + "area": total_ink, + "centroid": (work_mask.shape[1] / 2.0, work_mask.shape[0] / 2.0), + "mask": (work_mask > 0) + }) + + # 3. Spatial Proximity & Containment Fusion (Union-Find) + # Merges chips, pins, inner features, and closely clustered sub-elements into semantic modules + n = len(raw_bodies) + parent = list(range(n)) + def find(i): + while parent[i] != i: + parent[i] = parent[parent[i]] + i = parent[i] + return i + def union(i, j): + ri, rj = find(i), find(j) + if ri != rj: + parent[ri] = rj + + for i in range(n): + bi = raw_bodies[i]["rect"] + for j in range(i + 1, n): + bj = raw_bodies[j]["rect"] + # Two bodies belong to same module if their bounding boxes are within 18px of each other + margin = 18 + ov_x = max(0, min(bi[0] + bi[2] + margin, bj[0] + bj[2] + margin) - max(bi[0] - margin, bj[0] - margin)) + ov_y = max(0, min(bi[1] + bi[3] + margin, bj[1] + bj[3] + margin) - max(bi[1] - margin, bj[1] - margin)) + if ov_x > 0 and ov_y > 0: + union(i, j) + + groups = {} + for i in range(n): + r = find(i) + if r not in groups: + groups[r] = [] + groups[r].append(raw_bodies[i]) + + # 4. Build Modules and Extract Hierarchical Strokes + modules = [] + + for mod_idx, (r, body_list) in enumerate(groups.items()): + mod_mask = np.zeros_like(work_mask) + min_x = min(b["rect"][0] for b in body_list) + min_y = min(b["rect"][1] for b in body_list) + max_x = max(b["rect"][0] + b["rect"][2] for b in body_list) + max_y = max(b["rect"][1] + b["rect"][3] for b in body_list) + + # Include original ink pixels in the module bounding box (captures inner text/labels) + pad = 4 + px1, py1 = max(0, min_x - pad), max(0, min_y - pad) + px2, py2 = min(work_mask.shape[1], max_x + pad), min(work_mask.shape[0], max_y + pad) + + for b in body_list: + mod_mask[b["mask"]] = 255 + mod_mask[py1:py2, px1:px2] = cv2.bitwise_or(mod_mask[py1:py2, px1:px2], work_mask[py1:py2, px1:px2]) + + # Prevent stealing pixels from disjoint modules + for other_r, other_bodies in groups.items(): + if other_r != r: + for ob in other_bodies: + ox, oy, ow, oh = ob["rect"] + if ox > max_x + 12 or ox + ow < min_x - 12 or oy > max_y + 12 or oy + oh < min_y - 12: + mod_mask[ob["mask"]] = 0 + + # Hierarchical Path Generation for this Module: + # Layer 1: Outlines (top-level contours) + # Layer 2: Internal Details (nested contours) + # Layer 3: Chisel Pocket Fills + contours, hierarchy = cv2.findContours(mod_mask, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) + outer_paths = [] + inner_paths = [] + mod_cnts = [] for i, c in enumerate(contours): arc = cv2.arcLength(c, True) @@ -121,37 +210,82 @@ def map_pt(px, py): pts = [QPointF(*map_pt(cx - 1.5, cy)), QPointF(*map_pt(cx + 1.5, cy))] if pts: - z_paths.append(pts) - z_cnts.append(c) - - # Localized solid pocket fills within this concept zone - canvas_z = np.zeros_like(z_mask) - if z_cnts: - cv2.drawContours(canvas_z, z_cnts, -1, 255, max(8, int(14 * map_scale))) + is_outer = (hierarchy is not None and hierarchy[0][i][3] == -1) + if is_outer: + outer_paths.append(pts) + else: + inner_paths.append(pts) + mod_cnts.append(c) + + # Chisel Pocket Fills + fill_paths = [] + canvas_mod = np.zeros_like(mod_mask) + if mod_cnts: + cv2.drawContours(canvas_mod, mod_cnts, -1, 255, max(8, int(14 * map_scale))) - unrev_z = (z_mask > 0) & (canvas_z == 0) - n_u, l_u, s_u, _ = cv2.connectedComponentsWithStats(unrev_z.astype(np.uint8) * 255) + unrev_mod = (mod_mask > 0) & (canvas_mod == 0) + n_u, l_u, s_u, _ = cv2.connectedComponentsWithStats(unrev_mod.astype(np.uint8) * 255) for u in range(1, n_u): if s_u[u, cv2.CC_STAT_AREA] >= 25: pocket = (l_u == u).astype(np.uint8) * 255 pocket_fills = generate_clean_chisel_fills(pocket, step=fill_step, map_scale=map_scale, scale=scale) - z_paths.extend(pocket_fills) - + fill_paths.extend(pocket_fills) + + # Combine hierarchically: Outlines -> Inner details -> Chisel fills + all_mod_paths = outer_paths + inner_paths + fill_paths clean_paths = BaseDrawingAlgorithm.filter_non_overlapping_strokes( - z_paths, z_mask, stroke_width=filter_w, max_overlap_ratio=0.88 - ) if z_paths else [] - + all_mod_paths, mod_mask, stroke_width=filter_w, max_overlap_ratio=0.88 + ) if all_mod_paths else [] + if clean_paths: - islands.append({ - "name": z_name, + total_mod_area = sum(b["area"] for b in body_list) + modules.append({ + "name": f"Module {mod_idx + 1}", "paths": clean_paths, - "weight": z_weight, - "stroke_width": stroke_w, - "zone": z_idx + 1, - "rect": (0, z_start_y / (map_scale * scale), w / scale, (z_end_y - z_start_y) / (map_scale * scale)), - "centroid": (w / (2 * scale), (z_start_y + z_end_y) / (2 * map_scale * scale)), - "area": float(len(clean_paths) * 100), - "is_dot": False + "stroke_width": 16.0, + "rect": (min_x / (map_scale * scale), min_y / (map_scale * scale), + (max_x - min_x) / (map_scale * scale), (max_y - min_y) / (map_scale * scale)), + "centroid": ((min_x + max_x) / (2 * map_scale * scale), (min_y + max_y) / (2 * map_scale * scale)), + "area": float(total_mod_area), + "is_wires": False }) - - return islands + + # 5. Extract Interconnecting Wires & Lines (Lines linking different modules) + if cv2.countNonZero(wires_mask) > 40: + wires_clean = wires_mask.copy() + for m in modules: + rx, ry, rw, rh = m["rect"] + mx1, my1 = int(rx * map_scale * scale), int(ry * map_scale * scale) + mx2, my2 = int((rx + rw) * map_scale * scale), int((ry + rh) * map_scale * scale) + wires_clean[my1:my2, mx1:mx2] = 0 + + if cv2.countNonZero(wires_clean) >= 30: + wire_cnts, _ = cv2.findContours(wires_clean, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) + wire_paths = [] + for c in wire_cnts: + if cv2.arcLength(c, False) >= 8: + pts = [QPointF(*map_pt(pt[0][0], pt[0][1])) for pt in c] + wire_paths.append(pts) + if wire_paths: + modules.append({ + "name": "Interconnecting Wires & Links", + "paths": wire_paths, + "stroke_width": 12.0, + "rect": (0, 0, w / scale, h / scale), + "centroid": (w / (2 * scale), h / (2 * scale)), + "area": float(cv2.countNonZero(wires_clean)), + "is_wires": True + }) + + # 6. Pedagogical Ordering of Modules: + # Separate wire module (to always draw last) from main bodies + main_modules = [m for m in modules if not m.get("is_wires", False)] + wire_modules = [m for m in modules if m.get("is_wires", False)] + + # Sort main modules along reading flow (RTL / LTR) + if rtl: + main_modules.sort(key=lambda m: -m["rect"][0]) + else: + main_modules.sort(key=lambda m: m["rect"][0]) + + return main_modules + wire_modules diff --git a/core/drawing_engine/algorithms/organic_sketch/algorithm.py b/core/drawing_engine/algorithms/organic_sketch/algorithm.py index 7f9877a..29c94f8 100644 --- a/core/drawing_engine/algorithms/organic_sketch/algorithm.py +++ b/core/drawing_engine/algorithms/organic_sketch/algorithm.py @@ -1,190 +1,374 @@ +# Copyright (c) 2026 Mohamed Fadl & DrawMotion Team +# SPDX-License-Identifier: GPL-3.0-or-later + import cv2 import numpy as np -import random import math -from PySide6.QtCore import QPointF -from PySide6.QtGui import QImage +import copy from typing import List, Dict, Any +from PySide6.QtCore import QPointF, Qt +from PySide6.QtGui import QImage from ..base_algorithm import BaseDrawingAlgorithm -from .scribble_generator import generate_scribble_islands +from .scribble_generator import generate_clean_diagonal_shades + +_ORGANIC_SKETCH_CACHE = {} class OrganicSketchAlgorithm(BaseDrawingAlgorithm): """ Organic Sketch (Freehand Charcoal / Pencil Artist Flow): - - 3 Artistic Construction Phases: - 1. Phase 1: Gestural Perspective Rough-in (15% duration) -> rapid axis guide curves. - 2. Phase 2: Organic Freehand Contours (45% duration) -> expressive silhouettes & line-work. - 3. Phase 3: Slanted 45° Pencil Cross-Hatching (40% duration) -> localized shading on shadows. - - Zero Retrace & Zero Blanket Sweeps: No rubbing over white background. - - Zero Early Completion: Ink reveals steadily from 0.0s until 8.0s. + Strictly follows the human whiteboarding principle: + «Draw one discrete visual piece, complete it 100% via 3 artistic sketch phases, + then lift the hand in an in-air travel flight and enter the next piece». + + 3 Artistic Construction Phases (Executed Per-Piece): + 1. Phase 1: Localized Gestural Rough-in (Quick axis/proportion guide curve within the piece) + 2. Phase 2: Organic Freehand Contours (Expressive silhouettes & line-work of the piece) + 3. Phase 3: Slanted 45° Pencil Cross-Hatching (Diagonal pencil shading on solid/shadow pockets) + + Key Invariants: + - Strictly Piece-by-Piece: Discrete visual pieces (e.g. Laptop, Arduino, LED) + are never drawn concurrently; each piece reaches 100% completion before moving on. + - Zero Retrace & Zero Blanket Sweeps: Shading restricted to unrevealed ink pockets. + - Natural Hand Velocity & Exact Duration: Smooth progress from 0.0s to duration. """ - + def generate_plan(self, qimage: QImage, duration: float, **kwargs) -> List[Dict[str, Any]]: rtl = kwargs.get("rtl", False) - mask = self._get_ink_mask(qimage) + duration = max(0.5, float(duration or 8.0)) + cache_key = (id(qimage), rtl, duration) + + if cache_key in _ORGANIC_SKETCH_CACHE: + return copy.deepcopy(_ORGANIC_SKETCH_CACHE[cache_key]) + + w_orig, h_orig = qimage.width(), qimage.height() + if w_orig <= 0 or h_orig <= 0: + return [] + + # Safe pre-scale for very large images to prevent RAM pressure + max_dim = 1600.0 scale = 1.0 - - islands = generate_scribble_islands(mask, scale) - if not islands: + if w_orig > max_dim or h_orig > max_dim: + scale = max_dim / max(w_orig, h_orig) + w_scaled = int(w_orig * scale) + h_scaled = int(h_orig * scale) + work_qimg = qimage.scaled(w_scaled, h_scaled, Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation) + else: + work_qimg = qimage + + mask = self._get_ink_mask(work_qimg) + if cv2.countNonZero(mask) == 0: return [] - - is_phased = any("phase" in isl for isl in islands) - if is_phased: - timed_segments = [] - current_time = 0.0 - - for isl in islands: - target_phase_duration = duration * isl.get("weight", 0.33) - paths = isl.get("paths", []) - if not paths: + + h, w = mask.shape + kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) + dilated = cv2.dilate(mask, kernel, iterations=1) + + num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(dilated, connectivity=8) + if num_labels <= 1: + return [] + + raw_islands = [] + for i in range(1, num_labels): + x, y, cw, ch, area = stats[i] + if area > 10: + raw_islands.append({ + "rect": (int(x), int(y), int(cw), int(ch)), + "label": int(i), + "centroid": (float(centroids[i][0]), float(centroids[i][1])), + "area": float(area), + "fused_labels": [int(i)] + }) + + if not raw_islands: + return [] + + # 1. Containment & Spatial Proximity Fusion (Union-Find) + # Keeps large standalone objects (> 8000 scaled px) strictly isolated as separate pieces + n = len(raw_islands) + parent_uf = list(range(n)) + + def find_uf(k): + while parent_uf[k] != k: + parent_uf[k] = parent_uf[parent_uf[k]] + k = parent_uf[k] + return k + + def union_uf(a, b): + ra, rb = find_uf(a), find_uf(b) + if ra != rb: + parent_uf[ra] = rb + + for j, child in enumerate(raw_islands): + c_x, c_y, c_w, c_h = child["rect"] + c_area = child["area"] + c_cx, c_cy = child["centroid"] + + # Geometric containment: if child is strictly inside another island's bounding box, + # it is part of that same piece (e.g. screen inside laptop, IC inside circuit board) + contained_in = None + min_enclosing_area = float('inf') + for i, p_candidate in enumerate(raw_islands): + if i == j: continue - - phase_segments = [] - phase_accum = 0.0 - - ordered_paths = self._sort_paths_continuous(paths) - - path_data = [] - for pts in ordered_paths: - if not pts: - continue - uniform_pts = self._resample_path_uniform(pts, step_dist=8.0) - length = self._calculate_length(uniform_pts) - if length > 0 or isl.get("is_dot", False): - path_data.append({"pts": uniform_pts, "length": max(2.0, length)}) - - if not path_data: + p_x, p_y, p_w, p_h = p_candidate["rect"] + p_area = p_candidate["area"] + if (p_x - 8 <= c_x and p_y - 8 <= c_y and + c_x + c_w <= p_x + p_w + 8 and c_y + c_h <= p_y + p_h + 8): + if p_area < min_enclosing_area: + min_enclosing_area = p_area + contained_in = i + + if contained_in is not None: + union_uf(j, contained_in) + continue + + if c_area > 8000.0 * (scale ** 2): + continue + + best_parent_idx = None + best_parent_area = float('inf') + + for i, p_candidate in enumerate(raw_islands): + if i == j: + continue + p_x, p_y, p_w, p_h = p_candidate["rect"] + p_area = p_candidate["area"] + if p_area < 1.8 * c_area: + continue + + margin_x = 18.0 + margin_y = 24.0 + if (p_x - margin_x <= c_cx <= p_x + p_w + margin_x and + p_y - margin_y <= c_cy <= p_y + p_h + margin_y): + if p_area < best_parent_area: + best_parent_area = p_area + best_parent_idx = i + + if best_parent_idx is not None: + union_uf(j, best_parent_idx) + + groups = {} + for j in range(n): + r = find_uf(j) + if r not in groups: + groups[r] = [] + groups[r].append(raw_islands[j]) + + merged_islands = [] + for r, group in groups.items(): + rep = max(group, key=lambda it: it["area"]) + all_labels = [it["label"] for it in group] + all_x = [stats[lbl][0] for lbl in all_labels] + all_y = [stats[lbl][1] for lbl in all_labels] + all_x2 = [stats[lbl][0] + stats[lbl][2] for lbl in all_labels] + all_y2 = [stats[lbl][1] + stats[lbl][3] for lbl in all_labels] + bx, by = min(all_x), min(all_y) + bw = max(all_x2) - bx + bh = max(all_y2) - by + + merged_islands.append({ + "rect": (int(bx), int(by), int(bw), int(bh)), + "label": int(rep["label"]), + "centroid": (float(rep["centroid"][0]), float(rep["centroid"][1])), + "area": float(sum(it["area"] for it in group)), + "fused_labels": all_labels + }) + + # 2. Sort islands naturally into visual reading lines (RTL / LTR) + islands = BaseDrawingAlgorithm.cluster_islands_into_lines( + merged_islands, rtl=rtl, sort_mode="right_to_left" if rtl else "left_to_right" + ) + + raw_piece_units = [] + # 3. Process each island independently with 3-phase organic sketch flow + for island in islands: + target_labels = island.get("fused_labels", [island["label"]]) + bx, by, bw, bh = island["rect"] + sub_labels = labels[by:by+bh, bx:bx+bw] + sub_mask = np.isin(sub_labels, target_labels).astype(np.uint8) * 255 + + if cv2.countNonZero(sub_mask) == 0: + continue + + # Phase 1: Localized gestural guide curve within this piece + gestural_paths = [] + if bw >= 20 and bh >= 20: + if rtl: + p_st = QPointF(float(bx + bw - 10) / scale, float(by + 10) / scale) + p_mid = QPointF(float(bx + bw / 2) / scale, float(by + bh / 2) / scale) + p_en = QPointF(float(bx + 10) / scale, float(by + bh - 10) / scale) + else: + p_st = QPointF(float(bx + 10) / scale, float(by + 10) / scale) + p_mid = QPointF(float(bx + bw / 2) / scale, float(by + bh / 2) / scale) + p_en = QPointF(float(bx + bw - 10) / scale, float(by + bh - 10) / scale) + gestural_paths.append([p_st, p_mid, p_en]) + + # Phase 2: Organic freehand contours of this piece + contours, hierarchy = cv2.findContours(sub_mask, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) + contour_paths = [] + contour_cnts = [] + if contours: + for i, c in enumerate(contours): + arc = cv2.arcLength(c, True) + if arc >= 6: + approx = cv2.approxPolyDP(c, 0.002 * arc, True) + if len(approx) >= 3: + pts = [QPointF(float(pt[0][0] + bx) / scale, float(pt[0][1] + by) / scale) for pt in approx] + pts.append(pts[0]) + else: + pts = [QPointF(float(pt[0][0] + bx) / scale, float(pt[0][1] + by) / scale) for pt in c] + if len(pts) >= 2: + pts.append(pts[0]) + else: + cx_c = float(np.mean(c[:, 0, 0])) + cy_c = float(np.mean(c[:, 0, 1])) + pts = [ + QPointF(float(cx_c - 1.5 + bx) / scale, float(cy_c + by) / scale), + QPointF(float(cx_c + 1.5 + bx) / scale, float(cy_c + by) / scale) + ] + if pts: + contour_paths.append(pts) + contour_cnts.append(c) + + # Phase 3: Slanted 45° pencil shading on solid/shadow pockets + canvas_sub = np.zeros(sub_mask.shape, dtype=np.uint8) + if contour_cnts: + cv2.drawContours(canvas_sub, contour_cnts, -1, 255, 12) + + unrevealed = (sub_mask > 0) & (canvas_sub == 0) + n_u, l_u, s_u, _ = cv2.connectedComponentsWithStats(unrevealed.astype(np.uint8) * 255) + hatch_step = max(8, int(12.0 * scale)) + hatch_paths = [] + for u in range(1, n_u): + if s_u[u, cv2.CC_STAT_AREA] >= 25: + pocket = (l_u == u).astype(np.uint8) * 255 + diag_shades = generate_clean_diagonal_shades(pocket, step=hatch_step, map_scale=1.0, scale=scale) + for stroke in diag_shades: + hatch_paths.append([QPointF(p.x() + float(bx) / scale, p.y() + float(by) / scale) for p in stroke]) + + # Build sub-strokes for this piece following Phase 1 -> Phase 2 -> Phase 3 + piece_sub_strokes = [] + phases = [ + ("Phase 1: Gesture", gestural_paths, 9.0), + ("Phase 2: Contours", contour_paths, 14.0), + ("Phase 3: Hatching", hatch_paths, 11.0), + ] + + for phase_name, p_paths, stroke_w in phases: + if not p_paths: continue - - total_phase_length = sum(item["length"] for item in path_data) or 1.0 - stroke_w = isl.get("stroke_width", 14.0) - - for item in path_data: - seg_dur = max(0.005, target_phase_duration * (item["length"] / total_phase_length)) - - if phase_segments or timed_segments: - last_pt = phase_segments[-1]["points"][-1] if phase_segments else timed_segments[-1]["points"][-1] - st_pt = item["pts"][0] - dist = math.hypot(st_pt.x() - last_pt.x(), st_pt.y() - last_pt.y()) - if dist > 8.0: - travel_dur = min(0.08, max(0.02, dist / 2200.0)) - phase_segments.append({ + start_pt = piece_sub_strokes[-1]["points"][-1] if piece_sub_strokes else None + ordered = self._sort_paths_continuous(p_paths, rtl=rtl, start_near=start_pt) + for pts in ordered: + if piece_sub_strokes: + last_p = piece_sub_strokes[-1]["points"][-1] + first_p = pts[0] + dist = math.hypot(first_p.x() - last_p.x(), first_p.y() - last_p.y()) + if dist > 15.0: + piece_sub_strokes.append({ "type": "travel", - "points": [last_pt, st_pt], - "duration": travel_dur, - "start_time": phase_accum, - "end_time": phase_accum + travel_dur, - "width": 0.0, - "opacity": 0.0 + "points": [last_p, first_p] }) - phase_accum += travel_dur - - phase_segments.append({ + piece_sub_strokes.append({ "type": "stroke", - "points": item["pts"], + "points": pts, + "width": stroke_w + }) + + if piece_sub_strokes: + raw_piece_units.append({ + "island": island, + "sub_strokes": piece_sub_strokes + }) + + if not raw_piece_units: + return [] + + # 4. Assemble timed segments across all pieces + total_stroke_len = sum( + sum(self._calculate_length(s["points"]) for s in u["sub_strokes"] if s["type"] == "stroke") + for u in raw_piece_units + ) or 1.0 + + timed_segments: List[Dict[str, Any]] = [] + cur_time = 0.0 + + for u in raw_piece_units: + sub_strokes = u["sub_strokes"] + + # In-air travel flight between distinct pieces + if timed_segments: + last_p = timed_segments[-1]["points"][-1] + first_p = sub_strokes[0]["points"][0] + dist = math.hypot(first_p.x() - last_p.x(), first_p.y() - last_p.y()) + if dist > 8.0: + flight_dur = min(0.20, max(0.04, dist / 2400.0)) + timed_segments.append({ + "type": "travel", + "points": [last_p, first_p], + "duration": flight_dur, + "start_time": cur_time, + "end_time": cur_time + flight_dur, + "width": 0.0, + "opacity": 0.0 + }) + cur_time += flight_dur + + # Draw all strokes of this piece COMPLETELY before ever leaving it + for s in sub_strokes: + length = self._calculate_length(s["points"]) + if s["type"] == "travel": + dur = min(0.12, max(0.02, length / 2400.0)) + timed_segments.append({ + "type": "travel", + "points": s["points"], + "duration": dur, + "start_time": cur_time, + "end_time": cur_time + dur, + "width": 0.0, + "opacity": 0.0 + }) + cur_time += dur + else: + seg_dur = duration * (length / total_stroke_len) + timed_segments.append({ + "type": "stroke", + "points": s["points"], "duration": seg_dur, - "start_time": phase_accum, - "end_time": phase_accum + seg_dur, - "width": stroke_w, + "start_time": cur_time, + "end_time": cur_time + seg_dur, + "width": s.get("width", 14.0), "opacity": 1.0 }) - phase_accum += seg_dur - - if phase_segments and phase_accum > 0: - scale_f = target_phase_duration / phase_accum - for seg in phase_segments: - seg["duration"] *= scale_f - seg["start_time"] = current_time - current_time += seg["duration"] - seg["end_time"] = current_time - timed_segments.append(seg) - - return timed_segments - - # Fallback ordering - ordered_islands = self._order_islands_artistic_flow(islands, rtl=rtl) - if not ordered_islands: - return [] + cur_time += seg_dur - for isl in ordered_islands: - isl["total_length"] = sum( - self._calculate_length(pts) for pts in isl["paths"] if pts - ) or 1.0 - - total_all_length = sum(isl["total_length"] for isl in ordered_islands) or 1.0 - - timed_segments = [] - accumulated_time = 0.0 - - for island in ordered_islands: - island_length = island["total_length"] - island_duration = duration * (island_length / total_all_length) - - path_data = [] - for pts in island["paths"]: - if not pts: - continue - uniform_pts = self._resample_path_uniform(pts, step_dist=8.0) - length = self._calculate_length(uniform_pts) - if length > 0 or island.get("is_dot", False): - path_data.append({"pts": uniform_pts, "length": max(2.0, length)}) - - if not path_data: - continue - - total_island_length = sum(item["length"] for item in path_data) or 1.0 - - for item in path_data: - seg_share = item["length"] / total_island_length - seg_duration = max(0.015, island_duration * seg_share) - - if timed_segments: - last_pt = timed_segments[-1]["points"][-1] - cur_start = item["pts"][0] - dx = cur_start.x() - last_pt.x() - dy = cur_start.y() - last_pt.y() - air_dist = math.hypot(dx, dy) - if air_dist > 12.0: - travel_dur = min(0.12, max(0.035, air_dist / 1400.0)) - timed_segments.append({ - "type": "travel", - "points": [last_pt, cur_start], - "duration": travel_dur, - "start_time": accumulated_time, - "end_time": accumulated_time + travel_dur, - "width": 0.0, - "opacity": 0.0 - }) - accumulated_time += travel_dur - - dynamic_width = max(18.0, min(24.0, 18.0 + item["length"] / 100.0)) - timed_segments.append({ - "type": "stroke", - "points": item["pts"], - "duration": seg_duration, - "start_time": accumulated_time, - "end_time": accumulated_time + seg_duration, - "width": dynamic_width, - "opacity": 1.0 - }) - accumulated_time += seg_duration - - if timed_segments and accumulated_time > 0: - scale_time = duration / accumulated_time - cur_t = 0.0 - for seg in timed_segments: - seg["duration"] *= scale_time - seg["start_time"] = cur_t - cur_t += seg["duration"] - seg["end_time"] = cur_t - + # 5. Timeline normalization to match duration strictly + if timed_segments and cur_time > 0: + scale_t = duration / cur_time + t = 0.0 + for s in timed_segments: + s["duration"] *= scale_t + s["start_time"] = t + t += s["duration"] + s["end_time"] = t + + _ORGANIC_SKETCH_CACHE[cache_key] = copy.deepcopy(timed_segments) return timed_segments - def _sort_paths_continuous(self, paths: List[List[QPointF]]) -> List[List[QPointF]]: + def _sort_paths_continuous(self, paths: List[List[QPointF]], rtl: bool = False, start_near: QPointF = None) -> List[List[QPointF]]: if len(paths) <= 1: return paths remaining = list(paths) - sorted_p = [remaining.pop(0)] + if start_near is not None: + best_init_idx = min(range(len(remaining)), key=lambda i: min( + (p.x() - start_near.x())**2 + (p.y() - start_near.y())**2 for p in remaining[i] + )) + elif rtl: + best_init_idx = max(range(len(remaining)), key=lambda i: max(p.x() for p in remaining[i])) + else: + best_init_idx = min(range(len(remaining)), key=lambda i: min(p.x() for p in remaining[i])) + + sorted_p = [remaining.pop(best_init_idx)] while remaining: last_pt = sorted_p[-1][-1] best_idx, best_dist, best_rev = 0, float('inf'), False @@ -202,9 +386,6 @@ def _sort_paths_continuous(self, paths: List[List[QPointF]]) -> List[List[QPoint sorted_p.append(nx) return sorted_p - def _order_islands_artistic_flow(self, islands: List[Dict[str, Any]], rtl: bool = False) -> List[Dict[str, Any]]: - return list(islands) - def _calculate_length(self, points: List[QPointF]) -> float: length = 0.0 for i in range(1, len(points)): @@ -212,31 +393,3 @@ def _calculate_length(self, points: List[QPointF]) -> float: dy = points[i].y() - points[i-1].y() length += math.hypot(dx, dy) return length - - def _resample_path_uniform(self, points: List[QPointF], step_dist: float = 8.0) -> List[QPointF]: - if len(points) < 2: - return points - new_pts = [points[0]] - accum_dist = 0.0 - for i in range(1, len(points)): - p0 = points[i-1] - p1 = points[i] - dx = p1.x() - p0.x() - dy = p1.y() - p0.y() - seg_dist = math.hypot(dx, dy) - if seg_dist < 1e-4: - continue - curr_p = p0 - while accum_dist + seg_dist >= step_dist: - needed = step_dist - accum_dist - t = needed / seg_dist - new_p = QPointF(curr_p.x() + (p1.x() - curr_p.x()) * t, - curr_p.y() + (p1.y() - curr_p.y()) * t) - new_pts.append(new_p) - seg_dist -= needed - curr_p = new_p - accum_dist = 0.0 - accum_dist += seg_dist - if math.hypot(points[-1].x() - new_pts[-1].x(), points[-1].y() - new_pts[-1].y()) > 1.0: - new_pts.append(points[-1]) - return new_pts diff --git a/core/drawing_engine/algorithms/professional/algorithm.py b/core/drawing_engine/algorithms/professional/algorithm.py index fa935d8..e6f8514 100644 --- a/core/drawing_engine/algorithms/professional/algorithm.py +++ b/core/drawing_engine/algorithms/professional/algorithm.py @@ -1,207 +1,391 @@ -from PySide6.QtCore import QPointF -from PySide6.QtGui import QImage -from typing import List, Dict, Any +# Copyright (c) 2026 Mohamed Fadl & DrawMotion Team +# SPDX-License-Identifier: GPL-3.0-or-later + +import cv2 +import numpy as np import math +import copy +from typing import List, Dict, Any +from PySide6.QtCore import QPointF, Qt +from PySide6.QtGui import QImage from ..base_algorithm import BaseDrawingAlgorithm -from .professional_generator import generate_professional_paths +from .professional_generator import generate_clean_localized_fills + +_PROFESSIONAL_CACHE = {} class ProfessionalAlgorithm(BaseDrawingAlgorithm): """ Professional Vector Drawing (CAD Structural Hierarchy & Whiteboard Flow): - - 4-Tier CAD Structural Assembly: - 1. Tier 1: External Chassis & Primary Silhouettes (25% duration) - 2. Tier 2: Major IC Units, Ports & Localized Solid Fills (25% duration) - 3. Tier 3: Discrete Components, Pins, & Sockets (25% duration) - 4. Tier 4: Fine Copper Traces, Vias, & Silkscreen Labels (25% duration) - - Zero Retrace & Zero Blanket Sweeps: No rubbing over white background. - - Zero Early Completion: Ink reveals steadily from 0.0s until 8.0s. + Strictly follows the human whiteboarding principle: + «Draw one discrete visual piece, complete it 100% via 4-tier CAD structural assembly, + then lift the hand in an in-air travel flight and enter the next piece». + + 4-Tier CAD Structural Assembly (Executed Per-Piece): + 1. Tier 1: External Chassis & Primary Silhouette (Board outline, outer frames) + 2. Tier 2: Major Functional Units & IC Bodies (Chips, ports + localized solid pocket fills) + 3. Tier 3: Discrete Components & Pins (Headers, capacitors, resistors + small fills) + 4. Tier 4: Fine Details & Silkscreen (Copper traces, vias, text labels) + + Key Invariants: + - Strictly Piece-by-Piece: Discrete semantic objects (e.g. Laptop, Arduino, LED) + are never drawn concurrently; each piece reaches 100% completion before moving on. + - Zero Retrace & Zero Blanket Sweeps: Localized fills only in unrevealed solid pockets. + - Natural Hand Velocity & Exact Duration: Smooth progress from 0.0s to duration. """ - + def generate_plan(self, qimage: QImage, duration: float, **kwargs) -> List[Dict[str, Any]]: rtl = kwargs.get("rtl", False) - mask = self._get_ink_mask(qimage) + duration = max(0.5, float(duration or 8.0)) + cache_key = (id(qimage), rtl, duration) + + if cache_key in _PROFESSIONAL_CACHE: + return copy.deepcopy(_PROFESSIONAL_CACHE[cache_key]) + + w_orig, h_orig = qimage.width(), qimage.height() + if w_orig <= 0 or h_orig <= 0: + return [] + + # Safe pre-scale for very large images to prevent RAM pressure + max_dim = 1600.0 scale = 1.0 - - islands = generate_professional_paths(mask, scale) - if not islands: + if w_orig > max_dim or h_orig > max_dim: + scale = max_dim / max(w_orig, h_orig) + w_scaled = int(w_orig * scale) + h_scaled = int(h_orig * scale) + work_qimg = qimage.scaled(w_scaled, h_scaled, Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation) + else: + work_qimg = qimage + + mask = self._get_ink_mask(work_qimg) + if cv2.countNonZero(mask) == 0: + return [] + + h, w = mask.shape + kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) + dilated = cv2.dilate(mask, kernel, iterations=1) + + num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(dilated, connectivity=8) + if num_labels <= 1: + return [] + + raw_islands = [] + for i in range(1, num_labels): + x, y, cw, ch, area = stats[i] + if area > 10: + raw_islands.append({ + "rect": (int(x), int(y), int(cw), int(ch)), + "label": int(i), + "centroid": (float(centroids[i][0]), float(centroids[i][1])), + "area": float(area), + "fused_labels": [int(i)] + }) + + if not raw_islands: return [] - - # Check if islands are already structured into architectural tiers - is_tiered = any("tier" in isl for isl in islands) - if is_tiered: - timed_segments = [] - current_time = 0.0 - - for isl in islands: - target_tier_duration = duration * isl.get("weight", 0.25) - paths = isl.get("paths", []) - if not paths: + + # 1. Containment & Spatial Fusion (Union-Find) + # Keeps large standalone objects (> 8000 scaled px) strictly isolated as separate pieces + n = len(raw_islands) + parent_uf = list(range(n)) + + def find_uf(k): + while parent_uf[k] != k: + parent_uf[k] = parent_uf[parent_uf[k]] + k = parent_uf[k] + return k + + def union_uf(a, b): + ra, rb = find_uf(a), find_uf(b) + if ra != rb: + parent_uf[ra] = rb + + for j, child in enumerate(raw_islands): + c_x, c_y, c_w, c_h = child["rect"] + c_area = child["area"] + c_cx, c_cy = child["centroid"] + + # Geometric containment: if child is strictly inside another island's bounding box, + # it is part of that same piece (e.g. screen inside laptop, IC inside circuit board) + contained_in = None + min_enclosing_area = float('inf') + for i, p_candidate in enumerate(raw_islands): + if i == j: continue - - tier_segments = [] - tier_accum = 0.0 - - # Order paths continuously using spatial nearest-neighbor - ordered_paths = self._sort_paths_continuous(paths) - - path_data = [] - for pts in ordered_paths: + p_x, p_y, p_w, p_h = p_candidate["rect"] + p_area = p_candidate["area"] + if (p_x - 8 <= c_x and p_y - 8 <= c_y and + c_x + c_w <= p_x + p_w + 8 and c_y + c_h <= p_y + p_h + 8): + if p_area < min_enclosing_area: + min_enclosing_area = p_area + contained_in = i + + if contained_in is not None: + union_uf(j, contained_in) + continue + + if c_area > 8000.0 * (scale ** 2): + continue + + best_parent_idx = None + best_parent_area = float('inf') + + for i, p_candidate in enumerate(raw_islands): + if i == j: + continue + p_x, p_y, p_w, p_h = p_candidate["rect"] + p_area = p_candidate["area"] + if p_area < 1.8 * c_area: + continue + + margin_x = 18.0 + margin_y = 24.0 + if (p_x - margin_x <= c_cx <= p_x + p_w + margin_x and + p_y - margin_y <= c_cy <= p_y + p_h + margin_y): + if p_area < best_parent_area: + best_parent_area = p_area + best_parent_idx = i + + if best_parent_idx is not None: + union_uf(j, best_parent_idx) + + groups = {} + for j in range(n): + r = find_uf(j) + if r not in groups: + groups[r] = [] + groups[r].append(raw_islands[j]) + + merged_islands = [] + for r, group in groups.items(): + rep = max(group, key=lambda it: it["area"]) + all_labels = [it["label"] for it in group] + all_x = [stats[lbl][0] for lbl in all_labels] + all_y = [stats[lbl][1] for lbl in all_labels] + all_x2 = [stats[lbl][0] + stats[lbl][2] for lbl in all_labels] + all_y2 = [stats[lbl][1] + stats[lbl][3] for lbl in all_labels] + bx, by = min(all_x), min(all_y) + bw = max(all_x2) - bx + bh = max(all_y2) - by + + merged_islands.append({ + "rect": (int(bx), int(by), int(bw), int(bh)), + "label": int(rep["label"]), + "centroid": (float(rep["centroid"][0]), float(rep["centroid"][1])), + "area": float(sum(it["area"] for it in group)), + "fused_labels": all_labels + }) + + # 2. Sort islands naturally into visual reading lines (RTL / LTR) + islands = BaseDrawingAlgorithm.cluster_islands_into_lines( + merged_islands, rtl=rtl, sort_mode="right_to_left" if rtl else "left_to_right" + ) + + raw_piece_units = [] + # 3. For each piece: generate 4-tier CAD structural paths + for island in islands: + target_labels = island.get("fused_labels", [island["label"]]) + bx, by, bw, bh = island["rect"] + sub_labels = labels[by:by+bh, bx:bx+bw] + sub_mask = np.isin(sub_labels, target_labels).astype(np.uint8) * 255 + + if cv2.countNonZero(sub_mask) == 0: + continue + + contours, hierarchy = cv2.findContours(sub_mask, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) + t1_paths, t2_paths, t3_paths, t4_paths = [], [], [], [] + t1_cnts, t2_cnts, t3_cnts, t4_cnts = [], [], [], [] + + if contours: + for i, c in enumerate(contours): + arc = cv2.arcLength(c, True) + c_area = cv2.contourArea(c) + parent = hierarchy[0][i][3] if hierarchy is not None else -1 + + if arc >= 6: + epsilon = 0.002 * arc + approx = cv2.approxPolyDP(c, epsilon, True) + if len(approx) >= 3: + pts = [QPointF(float(pt[0][0] + bx) / scale, float(pt[0][1] + by) / scale) for pt in approx] + pts.append(pts[0]) + else: + pts = [QPointF(float(pt[0][0] + bx) / scale, float(pt[0][1] + by) / scale) for pt in c] + if len(pts) >= 2: + pts.append(pts[0]) + else: + cx = float(np.mean(c[:, 0, 0])) + cy = float(np.mean(c[:, 0, 1])) + p1 = QPointF(float(cx - 1.5 + bx) / scale, float(cy + by) / scale) + p2 = QPointF(float(cx + 1.5 + bx) / scale, float(cy + by) / scale) + pts = [p1, p2] + if not pts: continue - uniform_pts = self._resample_path_uniform(pts, step_dist=8.0) - length = self._calculate_length(uniform_pts) - if length > 0 or isl.get("is_dot", False): - path_data.append({"pts": uniform_pts, "length": max(2.0, length)}) - - if not path_data: + + # Tier Classification + if arc >= 140 or (parent == -1 and c_area >= 400): + t1_paths.append(pts) + t1_cnts.append(c) + elif arc >= 40 or c_area >= 60: + t2_paths.append(pts) + t2_cnts.append(c) + elif arc >= 16 or c_area >= 15: + t3_paths.append(pts) + t3_cnts.append(c) + else: + t4_paths.append(pts) + t4_cnts.append(c) + + # Ensure at least one primary contour in Tier 1 if available + if not t1_paths and t2_paths: + t1_paths.append(t2_paths.pop(0)) + + # Localized solid pocket fills within this piece + canvas_sub = np.zeros(sub_mask.shape, dtype=np.uint8) + all_cnts = t1_cnts + t2_cnts + t3_cnts + t4_cnts + if all_cnts: + cv2.drawContours(canvas_sub, all_cnts, -1, 255, 12) + + unrevealed = (sub_mask > 0) & (canvas_sub == 0) + n_u, l_u, s_u, _ = cv2.connectedComponentsWithStats(unrevealed.astype(np.uint8) * 255) + fill_step = max(6, int(12.0 * scale)) + for u in range(1, n_u): + u_area = s_u[u, cv2.CC_STAT_AREA] + if u_area < 25: continue - - total_tier_length = sum(item["length"] for item in path_data) or 1.0 - stroke_w = isl.get("stroke_width", 14.0) - - for item in path_data: - seg_dur = max(0.005, target_tier_duration * (item["length"] / total_tier_length)) - - # In-air travel flight - if tier_segments or timed_segments: - last_pt = tier_segments[-1]["points"][-1] if tier_segments else timed_segments[-1]["points"][-1] - st_pt = item["pts"][0] - dist = math.hypot(st_pt.x() - last_pt.x(), st_pt.y() - last_pt.y()) - if dist > 8.0: - travel_dur = min(0.06, max(0.015, dist / 2500.0)) - tier_segments.append({ + pocket = (l_u == u).astype(np.uint8) * 255 + pocket_fills = generate_clean_localized_fills(pocket, step=fill_step, map_scale=1.0, scale=scale) + offset_fills = [] + for stroke in pocket_fills: + offset_fills.append([QPointF(p.x() + float(bx) / scale, p.y() + float(by) / scale) for p in stroke]) + if u_area >= 500: + t2_paths.extend(offset_fills) + else: + t3_paths.extend(offset_fills) + + # Build ordered sub-strokes for this piece following 4-tier CAD order + piece_sub_strokes = [] + tiers = [ + ("Tier 1: Chassis", t1_paths, 14.0), + ("Tier 2: ICs & Pockets", t2_paths, 13.0), + ("Tier 3: Pins & Elements", t3_paths, 10.0), + ("Tier 4: Details & Traces", t4_paths, 8.0), + ] + + for tier_name, tier_paths, stroke_w in tiers: + if not tier_paths: + continue + start_pt = piece_sub_strokes[-1]["points"][-1] if piece_sub_strokes else None + ordered = self._sort_paths_continuous(tier_paths, rtl=rtl, start_near=start_pt) + for pts in ordered: + if piece_sub_strokes: + last_p = piece_sub_strokes[-1]["points"][-1] + first_p = pts[0] + dist = math.hypot(first_p.x() - last_p.x(), first_p.y() - last_p.y()) + if dist > 15.0: + piece_sub_strokes.append({ "type": "travel", - "points": [last_pt, st_pt], - "duration": travel_dur, - "start_time": tier_accum, - "end_time": tier_accum + travel_dur, - "width": 0.0, - "opacity": 0.0 + "points": [last_p, first_p] }) - tier_accum += travel_dur - - tier_segments.append({ + piece_sub_strokes.append({ "type": "stroke", - "points": item["pts"], - "duration": seg_dur, - "start_time": tier_accum, - "end_time": tier_accum + seg_dur, - "width": stroke_w, - "opacity": 1.0 + "points": pts, + "width": stroke_w }) - tier_accum += seg_dur - - # Normalize THIS TIER to EXACTLY target_tier_duration! - if tier_segments and tier_accum > 0: - scale_f = target_tier_duration / tier_accum - for seg in tier_segments: - seg["duration"] *= scale_f - seg["start_time"] = current_time - current_time += seg["duration"] - seg["end_time"] = current_time - timed_segments.append(seg) - - return timed_segments - - # Fallback Semantic Clustering for non-tiered inputs - cluster_objects = self._cluster_into_semantic_objects(islands, rtl=rtl) - if not cluster_objects: + + if piece_sub_strokes: + raw_piece_units.append({ + "island": island, + "sub_strokes": piece_sub_strokes + }) + + if not raw_piece_units: return [] - - num_blocks = len(cluster_objects) - total_sqrt_area = sum(math.sqrt(max(100.0, obj["w"] * obj["h"])) for obj in cluster_objects) or 1.0 - - for obj in cluster_objects: - obj["total_length"] = sum( - sum(self._calculate_length(pts) for pts in isl["paths"] if pts) - for isl in obj["islands"] - ) or 1.0 - - total_all_length = sum(obj["total_length"] for obj in cluster_objects) or 1.0 - - for obj in cluster_objects: - area_factor = math.sqrt(max(100.0, obj["w"] * obj["h"])) / total_sqrt_area - length_factor = obj["total_length"] / total_all_length - uniform_factor = 1.0 / num_blocks - weight = 0.40 * area_factor + 0.45 * length_factor + 0.15 * uniform_factor - obj["duration"] = duration * weight - - timed_segments = [] - accumulated_time = 0.0 - - for obj in cluster_objects: - block_duration = obj["duration"] - block_total_len = obj["total_length"] - - for island in obj["islands"]: - island_length = sum(self._calculate_length(pts) for pts in island["paths"] if pts) - island_duration = block_duration * (island_length / block_total_len) - - path_data = [] - for pts in island["paths"]: - if not pts: - continue - uniform_pts = self._resample_path_uniform(pts, step_dist=8.0) - length = self._calculate_length(uniform_pts) - if length > 0 or island.get("is_dot", False): - path_data.append({"pts": uniform_pts, "length": max(2.0, length)}) - - if not path_data: - continue - - total_island_length = sum(item["length"] for item in path_data) or 1.0 - stroke_w = island.get("stroke_width", 14.0) - - for item in path_data: - seg_share = item["length"] / total_island_length - seg_duration = max(0.015, island_duration * seg_share) - - if timed_segments: - last_pt = timed_segments[-1]["points"][-1] - cur_start = item["pts"][0] - dx = cur_start.x() - last_pt.x() - dy = cur_start.y() - last_pt.y() - air_dist = math.hypot(dx, dy) - if air_dist > 12.0: - travel_dur = min(0.12, max(0.035, air_dist / 1400.0)) - timed_segments.append({ - "type": "travel", - "points": [last_pt, cur_start], - "duration": travel_dur, - "start_time": accumulated_time, - "end_time": accumulated_time + travel_dur, - "width": 0.0, - "opacity": 0.0 - }) - accumulated_time += travel_dur + # 4. Assemble timed segments with in-air travels between distinct pieces + total_stroke_len = sum( + sum(self._calculate_length(s["points"]) for s in u["sub_strokes"] if s["type"] == "stroke") + for u in raw_piece_units + ) or 1.0 + + timed_segments: List[Dict[str, Any]] = [] + cur_time = 0.0 + + for u in raw_piece_units: + sub_strokes = u["sub_strokes"] + + # In-air travel flight between distinct pieces + if timed_segments: + last_p = timed_segments[-1]["points"][-1] + first_p = sub_strokes[0]["points"][0] + dist = math.hypot(first_p.x() - last_p.x(), first_p.y() - last_p.y()) + if dist > 8.0: + flight_dur = min(0.20, max(0.04, dist / 2400.0)) + timed_segments.append({ + "type": "travel", + "points": [last_p, first_p], + "duration": flight_dur, + "start_time": cur_time, + "end_time": cur_time + flight_dur, + "width": 0.0, + "opacity": 0.0 + }) + cur_time += flight_dur + + # Draw all strokes of this piece COMPLETELY before ever leaving it + for s in sub_strokes: + length = self._calculate_length(s["points"]) + if s["type"] == "travel": + dur = min(0.12, max(0.02, length / 2400.0)) + timed_segments.append({ + "type": "travel", + "points": s["points"], + "duration": dur, + "start_time": cur_time, + "end_time": cur_time + dur, + "width": 0.0, + "opacity": 0.0 + }) + cur_time += dur + else: + seg_dur = duration * (length / total_stroke_len) timed_segments.append({ "type": "stroke", - "points": item["pts"], - "duration": seg_duration, - "start_time": accumulated_time, - "end_time": accumulated_time + seg_duration, - "width": stroke_w, + "points": s["points"], + "duration": seg_dur, + "start_time": cur_time, + "end_time": cur_time + seg_dur, + "width": s.get("width", 14.0), "opacity": 1.0 }) - accumulated_time += seg_duration - - if timed_segments and accumulated_time > 0: - scale_time = duration / accumulated_time - cur_t = 0.0 - for seg in timed_segments: - seg["duration"] *= scale_time - seg["start_time"] = cur_t - cur_t += seg["duration"] - seg["end_time"] = cur_t - + cur_time += seg_dur + + # 5. Timeline normalization to match duration strictly + if timed_segments and cur_time > 0: + scale_t = duration / cur_time + t = 0.0 + for s in timed_segments: + s["duration"] *= scale_t + s["start_time"] = t + t += s["duration"] + s["end_time"] = t + + _PROFESSIONAL_CACHE[cache_key] = copy.deepcopy(timed_segments) return timed_segments - def _sort_paths_continuous(self, paths: List[List[QPointF]]) -> List[List[QPointF]]: + def _sort_paths_continuous(self, paths: List[List[QPointF]], rtl: bool = False, start_near: QPointF = None) -> List[List[QPointF]]: if len(paths) <= 1: return paths remaining = list(paths) - sorted_p = [remaining.pop(0)] + if start_near is not None: + best_init_idx = min(range(len(remaining)), key=lambda i: min( + (p.x() - start_near.x())**2 + (p.y() - start_near.y())**2 for p in remaining[i] + )) + elif rtl: + best_init_idx = max(range(len(remaining)), key=lambda i: max(p.x() for p in remaining[i])) + else: + best_init_idx = min(range(len(remaining)), key=lambda i: min(p.x() for p in remaining[i])) + + sorted_p = [remaining.pop(best_init_idx)] while remaining: last_pt = sorted_p[-1][-1] best_idx, best_dist, best_rev = 0, float('inf'), False @@ -219,11 +403,6 @@ def _sort_paths_continuous(self, paths: List[List[QPointF]]) -> List[List[QPoint sorted_p.append(nx) return sorted_p - def _cluster_into_semantic_objects(self, islands: List[Dict[str, Any]], rtl: bool = False) -> List[Dict[str, Any]]: - cluster_objects = BaseDrawingAlgorithm.cluster_into_semantic_objects(islands, rtl=rtl) - text_blocks, heroes, accents = BaseDrawingAlgorithm.categorize_semantic_objects(cluster_objects, rtl=rtl) - return heroes + accents + text_blocks - def _calculate_length(self, points: List[QPointF]) -> float: length = 0.0 for i in range(1, len(points)): @@ -231,31 +410,3 @@ def _calculate_length(self, points: List[QPointF]) -> float: dy = points[i].y() - points[i-1].y() length += math.hypot(dx, dy) return length - - def _resample_path_uniform(self, points: List[QPointF], step_dist: float = 8.0) -> List[QPointF]: - if len(points) < 2: - return points - new_pts = [points[0]] - accum_dist = 0.0 - for i in range(1, len(points)): - p0 = points[i-1] - p1 = points[i] - dx = p1.x() - p0.x() - dy = p1.y() - p0.y() - seg_dist = math.hypot(dx, dy) - if seg_dist < 1e-4: - continue - curr_p = p0 - while accum_dist + seg_dist >= step_dist: - needed = step_dist - accum_dist - t = needed / seg_dist - new_p = QPointF(curr_p.x() + (p1.x() - curr_p.x()) * t, - curr_p.y() + (p1.y() - curr_p.y()) * t) - new_pts.append(new_p) - seg_dist -= needed - curr_p = new_p - accum_dist = 0.0 - accum_dist += seg_dist - if math.hypot(points[-1].x() - new_pts[-1].x(), points[-1].y() - new_pts[-1].y()) > 1.0: - new_pts.append(points[-1]) - return new_pts diff --git a/core/drawing_engine/algorithms/solid_reveal/algorithm.py b/core/drawing_engine/algorithms/solid_reveal/algorithm.py index e12891b..7773c9d 100644 --- a/core/drawing_engine/algorithms/solid_reveal/algorithm.py +++ b/core/drawing_engine/algorithms/solid_reveal/algorithm.py @@ -1,47 +1,69 @@ +# Copyright (c) 2026 Mohamed Fadl & DrawMotion Team +# SPDX-License-Identifier: GPL-3.0-or-later + import cv2 import numpy as np +import math +import copy +from typing import List, Dict, Any from PySide6.QtCore import QPointF from PySide6.QtGui import QImage -from typing import List, Dict, Any from ..base_algorithm import BaseDrawingAlgorithm -import copy _SOLID_CACHE = {} class SolidRevealAlgorithm(BaseDrawingAlgorithm): """ - Algorithm for solid mask shading. - Divides the image into completely independent ink islands, - and shades them one by one using an organic grid path. - """ + Solid Reveal Drawing Algorithm. + Strictly follows the human whiteboarding principle: + «Draw one discrete visual piece, complete it 100%, then lift the hand and enter the next piece». + Key Mechanics: + 1. Island Isolation: Large standalone objects (e.g. Laptop, Arduino, LED) remain strictly + independent islands; small features (dots, accents, keys) fuse into their parent island. + 2. Line & Direction Sorting: Islands are clustered into visual lines and sorted strictly + according to reading direction (RTL / LTR). + 3. Organic Continuous Sweep: Each island is shaded completely in a smooth nearest-neighbor + organic sweep with zero mechanical horizontal slab slicing (no fax/printer vertical scans). + 4. In-Air Travel Flights: Explicit in-air travel flights with width=0.0 and opacity=0.0 + are emitted when lifting the hand between distinct islands or distant sub-features. + 5. Calibrated Velocity: Smooth, calm, natural hand velocity across the full duration. + """ + def generate_plan(self, qimage: QImage, duration: float, **kwargs) -> List[Dict[str, Any]]: rtl = kwargs.get("rtl", False) + duration = max(0.5, float(duration or 8.0)) cache_key = (id(qimage), rtl, duration) - + if cache_key in _SOLID_CACHE: return copy.deepcopy(_SOLID_CACHE[cache_key]) - + w, h = qimage.width(), qimage.height() + if w <= 0 or h <= 0: + return [] + ptr = qimage.constBits() arr = np.frombuffer(ptr, np.uint8).reshape((h, w, 4)).copy() - - # Only process pixels with alpha > 10 + + # Quick validation: check alpha channel alpha = arr[:, :, 3] - valid_mask = alpha > 10 - - if not np.any(valid_mask): + if not np.any(alpha > 10): return [] - + mask = self._get_ink_mask(qimage) + if cv2.countNonZero(mask) == 0: + return [] + h, w = mask.shape - + # 1. Connect anti-aliased pixels to form solid islands kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) dilated = cv2.dilate(mask, kernel, iterations=1) - + num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(dilated, connectivity=8) - + if num_labels <= 1: + return [] + raw_islands = [] for i in range(1, num_labels): x, y, cw, ch, area = stats[i] @@ -53,16 +75,16 @@ def generate_plan(self, qimage: QImage, duration: float, **kwargs) -> List[Dict[ "area": float(area), "fused_labels": [int(i)] }) - + if not raw_islands: return [] - # 2. Transitive Spatial Proximity & Containment Fusion (Union-Find) - # Prevents dropped child components when fusions are multi-level (A -> B -> C), - # guaranteeing 100% complete ink coverage with zero missing facial features or word fragments. + # 2. Containment & Proximity Fusion (Union-Find) + # Allows small inner features/dots to fuse with their parent, while large standalone + # objects (> 8000px) remain STRICTLY isolated components so they are drawn one by one. n = len(raw_islands) parent_uf = list(range(n)) - + def find_uf(k): while parent_uf[k] != k: parent_uf[k] = parent_uf[parent_uf[k]] @@ -78,14 +100,14 @@ def union_uf(a, b): c_x, c_y, c_w, c_h = child["rect"] c_area = child["area"] c_cx, c_cy = child["centroid"] - - # Skip large standalone objects + + # Large standalone objects are NEVER merged together into a mega-block if c_area > 8000.0: continue - + best_parent_idx = None best_parent_area = float('inf') - + for i, p_candidate in enumerate(raw_islands): if i == j: continue @@ -93,8 +115,8 @@ def union_uf(a, b): p_area = p_candidate["area"] if p_area < 1.8 * c_area: continue - - # Check spatial containment or immediate proximity (e.g. face details / dots) + + # Check spatial containment or immediate proximity (e.g. face details / dots / keys) margin_x = 18.0 margin_y = 24.0 if (p_x - margin_x <= c_cx <= p_x + p_w + margin_x and @@ -102,7 +124,7 @@ def union_uf(a, b): if p_area < best_parent_area: best_parent_area = p_area best_parent_idx = i - + if best_parent_idx is not None: union_uf(j, best_parent_idx) @@ -117,7 +139,7 @@ def union_uf(a, b): for r, group in groups.items(): rep = max(group, key=lambda it: it["area"]) all_labels = [it["label"] for it in group] - + all_x = [stats[lbl][0] for lbl in all_labels] all_y = [stats[lbl][1] for lbl in all_labels] all_x2 = [stats[lbl][0] + stats[lbl][2] for lbl in all_labels] @@ -125,7 +147,7 @@ def union_uf(a, b): bx, by = min(all_x), min(all_y) bw = max(all_x2) - bx bh = max(all_y2) - by - + merged_islands.append({ "rect": (int(bx), int(by), int(bw), int(bh)), "label": int(rep["label"]), @@ -134,23 +156,23 @@ def union_uf(a, b): "fused_labels": all_labels }) - # 3. Sort islands naturally into reading lines (RTL / LTR) + # 3. Sort islands naturally into visual reading lines (RTL / LTR) islands = BaseDrawingAlgorithm.cluster_islands_into_lines( merged_islands, rtl=rtl, sort_mode="right_to_left" if rtl else "left_to_right" ) - + grid_size = 15 - band_height = 100 - segments = [] - - # 4. Generate smooth organic scribble path for each island + brush_w = grid_size * 2.2 + raw_island_units = [] + + # 4. Generate continuous organic scribble path for each island INDEPENDENTLY for island in islands: target_labels = island.get("fused_labels", [island["label"]]) bx, by, bw, bh = island["rect"] - + sub_labels = labels[by:by+bh, bx:bx+bw] sub_mask = np.isin(sub_labels, target_labels) - + blocks = [] for r_rel in range(0, bh, grid_size): for c_rel in range(0, bw, grid_size): @@ -158,95 +180,128 @@ def union_uf(a, b): c_end = min(c_rel + grid_size, bw) if np.any(sub_mask[r_rel:r_end, c_rel:c_end]): blocks.append((bx + c_rel + grid_size // 2, by + r_rel + grid_size // 2)) - + if not blocks: continue - - if bh <= 160: - # Small or medium island: single continuous organic TSP sweep - if rtl and blocks: - start_idx = max(range(len(blocks)), key=lambda i: blocks[i][0] - blocks[i][1]) - else: - start_idx = min(range(len(blocks)), key=lambda i: blocks[i][0] + blocks[i][1]) - - path = [blocks.pop(start_idx)] - while blocks: - curr = path[-1] - arr = np.array(blocks) - dists = (arr[:, 0] - curr[0])**2 + (arr[:, 1] - curr[1])**2 - min_idx = np.argmin(dists) - path.append(blocks.pop(min_idx)) + + # Start point determined strictly by reading direction corner + if rtl: + start_idx = max(range(len(blocks)), key=lambda i: blocks[i][0] - blocks[i][1]) else: - # Tall macro-island: Banded vertical sweep - # Ensures face and upper features are 100% completed before descending down - bands = [] - y_start = by - while y_start < by + bh: - y_end = y_start + band_height - band_blocks = [b for b in blocks if y_start <= b[1] < y_end] - if band_blocks: - bands.append(band_blocks) - y_start = y_end - - path = [] - last_pt = None - for band in bands: - if not band: - continue - if last_pt is None: - if rtl: - start_idx = max(range(len(band)), key=lambda i: band[i][0] - band[i][1]) - else: - start_idx = min(range(len(band)), key=lambda i: band[i][0] + band[i][1]) - curr = band.pop(start_idx) - else: - arr = np.array(band) - dists = (arr[:, 0] - last_pt[0])**2 + (arr[:, 1] - last_pt[1])**2 - min_idx = np.argmin(dists) - curr = band.pop(min_idx) - - path.append(curr) - while band: - curr = path[-1] - arr = np.array(band) - dists = (arr[:, 0] - curr[0])**2 + (arr[:, 1] - curr[1])**2 - min_idx = np.argmin(dists) - path.append(band.pop(min_idx)) - last_pt = path[-1] - + start_idx = min(range(len(blocks)), key=lambda i: blocks[i][0] + blocks[i][1]) + + # Continuous organic nearest-neighbor TSP path across the entire island + # Eliminates 100px horizontal slab slicing (no vertical fax machine scans) + path = [blocks.pop(start_idx)] + while blocks: + curr = path[-1] + arr = np.array(blocks) + dists = (arr[:, 0] - curr[0])**2 + (arr[:, 1] - curr[1])**2 + min_idx = np.argmin(dists) + path.append(blocks.pop(min_idx)) + pts = [QPointF(float(p[0]), float(p[1])) for p in path] if len(pts) == 1: pts.append(QPointF(pts[0].x() + 1.0, pts[0].y())) - - length = self._calculate_length(pts) - segments.append({ - "type": "stroke", - "points": pts, - "length": length, - "width": grid_size * 2.2, - "opacity": 1.0 - }) - - # 5. Assign timestamps - total_length = sum(seg["length"] for seg in segments) or 1.0 - accumulated_time = 0.0 - - timed_segments = [] - for seg in segments: - seg_share = seg["length"] / total_length - seg_duration = duration * seg_share - - timed_segments.append({ - "type": seg["type"], - "points": seg["points"], - "duration": seg_duration, - "start_time": accumulated_time, - "end_time": accumulated_time + seg_duration, - "width": seg["width"], - "opacity": seg["opacity"] + + # Check for sub-jumps within this island (e.g. disjoint features inside the fused island) + sub_strokes = [] + cur_sub = [pts[0]] + for i in range(1, len(pts)): + d = math.hypot(pts[i].x() - pts[i-1].x(), pts[i].y() - pts[i-1].y()) + if d > 45.0: + if len(cur_sub) == 1: + cur_sub.append(QPointF(cur_sub[0].x() + 1.0, cur_sub[0].y())) + sub_strokes.append({"type": "stroke", "points": cur_sub}) + sub_strokes.append({"type": "travel", "points": [cur_sub[-1], pts[i]]}) + cur_sub = [pts[i]] + else: + cur_sub.append(pts[i]) + + if len(cur_sub) == 1: + cur_sub.append(QPointF(cur_sub[0].x() + 1.0, cur_sub[0].y())) + sub_strokes.append({"type": "stroke", "points": cur_sub}) + + raw_island_units.append({ + "island": island, + "sub_strokes": sub_strokes }) - accumulated_time += seg_duration - + + if not raw_island_units: + return [] + + # 5. Calculate physical lengths and assemble sequential timed plan + total_stroke_len = 0.0 + for unit in raw_island_units: + for s in unit["sub_strokes"]: + s["length"] = max(1.0, self._calculate_length(s["points"])) + if s["type"] == "stroke": + total_stroke_len += s["length"] + + total_stroke_len = max(1.0, total_stroke_len) + timed_segments: List[Dict[str, Any]] = [] + cur_time = 0.0 + + for unit in raw_island_units: + sub_strokes = unit["sub_strokes"] + + # In-air travel flight between distinct islands + if timed_segments: + last_pt = timed_segments[-1]["points"][-1] + next_pt = sub_strokes[0]["points"][0] + dist = math.hypot(next_pt.x() - last_pt.x(), next_pt.y() - last_pt.y()) + if dist > 8.0: + flight_dur = min(0.18, max(0.04, dist / 2400.0)) + timed_segments.append({ + "type": "travel", + "points": [last_pt, next_pt], + "duration": flight_dur, + "start_time": cur_time, + "end_time": cur_time + flight_dur, + "width": 0.0, + "opacity": 0.0 + }) + cur_time += flight_dur + + # Draw all strokes of this island COMPLETELY before ever leaving it + for s in sub_strokes: + if s["type"] == "travel": + p0, p1 = s["points"][0], s["points"][1] + dist = math.hypot(p1.x() - p0.x(), p1.y() - p0.y()) + dur = min(0.12, max(0.03, dist / 2400.0)) + timed_segments.append({ + "type": "travel", + "points": s["points"], + "duration": dur, + "start_time": cur_time, + "end_time": cur_time + dur, + "width": 0.0, + "opacity": 0.0 + }) + cur_time += dur + else: + seg_dur = duration * (s["length"] / total_stroke_len) + timed_segments.append({ + "type": "stroke", + "points": s["points"], + "duration": seg_dur, + "start_time": cur_time, + "end_time": cur_time + seg_dur, + "width": brush_w, + "opacity": 1.0 + }) + cur_time += seg_dur + + # Final timeline synchronization to exactly match duration + if timed_segments and cur_time > 0: + scale_time = duration / cur_time + t = 0.0 + for seg in timed_segments: + seg["duration"] *= scale_time + seg["start_time"] = t + t += seg["duration"] + seg["end_time"] = t + _SOLID_CACHE[cache_key] = copy.deepcopy(timed_segments) return timed_segments @@ -258,3 +313,4 @@ def _calculate_length(self, points: List[QPointF]) -> float: dy = points[i].y() - points[i-1].y() length += math.hypot(dx, dy) return length + diff --git a/core/security_engine/bin/scanner.exe b/core/security_engine/bin/scanner.exe index 521bb04..3b018b0 100644 Binary files a/core/security_engine/bin/scanner.exe and b/core/security_engine/bin/scanner.exe differ diff --git a/core/security_engine/scanner_interface.py b/core/security_engine/scanner_interface.py index f3c9c22..9fd1369 100644 --- a/core/security_engine/scanner_interface.py +++ b/core/security_engine/scanner_interface.py @@ -1,15 +1,37 @@ +# Copyright (c) 2026 Mohamed Fadl & DrawMotion Team +# SPDX-License-Identifier: GPL-3.0-or-later import os +import sys import subprocess import logging +import unicodedata +import zipfile +from typing import Optional class SecurityEngine: """ - Decoupled Security Interface. - Communicates with the external standalone Blackbox (scanner.exe) - to validate user inputs against malicious injections. + Decoupled Zero-Risk Security Interface for DrawMotion. + Provides multi-layered protection: + 1. Ultra-fast, zero-overhead In-Memory Unicode input sanitization (Zero False Positives). + 2. Native OS validation via compiled Rust blackbox (scanner.exe) on Windows. + 3. Defensive Path Traversal & Windows Reserved Name shielding. + 4. Project Archive (Zip Slip / Zip Bomb) integrity verification. """ _instance = None + # Windows reserved device names that cause OS hangs or filesystem corruption + RESERVED_NAMES = { + "CON", "PRN", "AUX", "NUL", + "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", + "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", + "COM¹", "COM²", "COM³", "LPT¹", "LPT²", "LPT³" + } + + # Strict forbidden characters for file and folder names across Windows and POSIX + FORBIDDEN_CHARS = { + ';', '&', '|', '>', '<', '`', '$', '{', '}', '\\', '/', ':', '*', '?', '"', '\0' + } + def __init__(self): self.logger = logging.getLogger("SecurityEngine") self._scanner_path = self._resolve_scanner_path() @@ -20,70 +42,232 @@ def get_instance(cls): cls._instance = SecurityEngine() return cls._instance - def _resolve_scanner_path(self): + def _resolve_scanner_path(self) -> Optional[str]: """ Dynamically resolves the path to scanner.exe. - Works seamlessly in both Dev Mode and Nuitka Build Mode. + Works seamlessly in both Dev Mode and Nuitka / PyInstaller Build Mode. """ - # Base directory of this file - base_dir = os.path.dirname(os.path.abspath(__file__)) - - # Look for the binary in the expected bin/ directory - scanner_exe = os.path.join(base_dir, "bin", "scanner.exe") - - if os.path.exists(scanner_exe): - return scanner_exe + try: + # Base directory of this file + base_dir = os.path.dirname(os.path.abspath(__file__)) - self.logger.warning(f"Security Scanner not found at {scanner_exe}. System is operating using Fallback protection.") - return None + # Look for the binary in the expected bin/ directory + scanner_exe = os.path.join(base_dir, "bin", "scanner.exe") + + if os.path.exists(scanner_exe) and os.name == 'nt': + return scanner_exe + + # In Nuitka standalone builds, check application root + if getattr(sys, "frozen", False): + app_root = os.path.dirname(sys.executable) + candidate = os.path.join(app_root, "core", "security_engine", "bin", "scanner.exe") + if os.path.exists(candidate) and os.name == 'nt': + return candidate + + return None + except Exception as e: + self.logger.warning(f"Could not resolve scanner binary path: {e}") + return None + + @staticmethod + def _is_safe_char(c: str) -> bool: + """ + Validates individual character using the exact same rules as the Rust scanner: + - ASCII alphanumeric or general alphanumeric unicode (letters/digits in all languages) + - Safe punctuation: . _ - ( ) and space + - Arabic Unicode blocks: Primary, Supplement, Extended-A, Presentation-A, Presentation-B + """ + if c.isalnum() or c in {'.', '_', '-', ' ', '(', ')'}: + return True + + code = ord(c) + if ( + (0x0600 <= code <= 0x06FF) or # Arabic Primary + (0x0750 <= code <= 0x077F) or # Arabic Supplement + (0x08A0 <= code <= 0x08FF) or # Arabic Extended-A + (0xFB50 <= code <= 0xFDFF) or # Arabic Presentation Forms-A + (0xFE70 <= code <= 0xFEFF) # Arabic Presentation Forms-B + ): + return True + + return False + + def validate_in_memory(self, user_input: str) -> bool: + """ + Performs ultra-fast in-memory validation (< 0.05ms) with zero OS overhead. + Matches the strict security criteria of the Rust binary. + """ + if not user_input or not isinstance(user_input, str): + return False + + trimmed = user_input.strip() + if not trimmed: + return False + + # 1. Null-byte rejection + if '\0' in user_input: + self.logger.warning("Security Engine blocked input containing null bytes.") + return False + + # 2. Strong Unicode normalization (NFKC) + normalized = unicodedata.normalize('NFKC', trimmed) + upper = normalized.upper() + lower = normalized.lower() + + # 3. Path Traversal Check (relative path traversal) + if ".." in lower: + self.logger.warning(f"Security Engine blocked Path Traversal attempt: {user_input}") + return False + + # 4. Check for Reserved Windows Device Names + base_name = upper.split('.')[0].strip() + if upper in self.RESERVED_NAMES or base_name in self.RESERVED_NAMES: + self.logger.warning(f"Security Engine blocked Reserved Windows Name: {user_input}") + return False + + # 5. Fast check for shell / filesystem injection characters + for ch in normalized: + if ch in self.FORBIDDEN_CHARS: + self.logger.warning(f"Security Engine blocked forbidden character '{ch}' in: {user_input}") + return False + if not self._is_safe_char(ch): + self.logger.warning(f"Security Engine blocked non-allowlisted character '{ch}' in: {user_input}") + return False + + return True def is_safe_input(self, user_input: str) -> bool: """ - Validates the input string. + Validates user input string (e.g. folder name, project title). Returns True if safe, False if potentially malicious. + Guarantees 100% backwards compatibility and zero crash risk. """ - if not user_input or not user_input.strip(): + try: + # Step 1: Instant In-Memory validation + if not self.validate_in_memory(user_input): + return False + + # Step 2: Native external scanner validation if on Windows and binary exists + if self._scanner_path and os.name == 'nt': + try: + kwargs = { + "creationflags": subprocess.CREATE_NO_WINDOW + } + result = subprocess.run( + [self._scanner_path, user_input], + capture_output=True, + text=True, + timeout=1.5, + **kwargs + ) + if result.returncode != 0: + self.logger.warning(f"Rust Security Scanner blocked input: {user_input}") + return False + except subprocess.TimeoutExpired: + self.logger.error("Rust Security Scanner timed out, relying on in-memory validation.") + except Exception as e: + self.logger.warning(f"Rust Security Scanner invocation failed: {e}") + + return True + except Exception as e: + self.logger.error(f"Unexpected error in is_safe_input: {e}", exc_info=True) + # Fail-safe: if something unexpected crashed, reject input to maintain security return False - # Phase 1: Call external Rust/C# scanner if available - if self._scanner_path: - try: - # We pass the input securely via args. - # Avoid shell=True to prevent shell injection vulnerabilities. - kwargs = {} - if os.name == 'nt': - kwargs['creationflags'] = subprocess.CREATE_NO_WINDOW - - result = subprocess.run( - [self._scanner_path, user_input], - capture_output=True, - text=True, - timeout=2.0, - **kwargs - ) + def is_safe_path(self, target_path: str, base_dir: Optional[str] = None) -> bool: + """ + Guarantees that target_path does not escape base_dir via directory traversal. + """ + try: + if not target_path or '\0' in target_path: + return False - # Assume scanner returns exit code 0 for safe, non-zero for threat - if result.returncode == 0: - return True - else: - self.logger.warning(f"Security Engine blocked malicious input: {user_input}") + abs_target = os.path.abspath(os.path.normpath(target_path)) + + if base_dir: + abs_base = os.path.abspath(os.path.normpath(base_dir)) + # Ensure abs_target starts with abs_base directory + common = os.path.commonpath([abs_base, abs_target]) + if common != abs_base: + self.logger.warning(f"Path escape attempt blocked: {target_path} outside {base_dir}") return False - except subprocess.TimeoutExpired: - self.logger.error("Security Scanner timed out.") - return False - except Exception as e: - self.logger.error(f"Security Scanner execution failed: {e}") - # Fail-safe: Block if scanner crashes to prevent bypass + return True + except Exception as e: + self.logger.error(f"Error checking path safety: {e}") + return False + + def is_safe_project_archive( + self, + zip_path: str, + max_files: int = 10000, + max_uncompressed_bytes: int = 500 * 1024 * 1024 + ) -> bool: + """ + Validates .drawmotion project archive before extraction. + Prevents Zip Slip (directory traversal in archive members) and Zip Bomb attacks. + """ + try: + if not os.path.isfile(zip_path): return False - # Phase 2: Fallback (Basic Regex/Filter) if scanner.exe is missing - # This guarantees the app doesn't crash but still provides minimal protection - # Block common shell injection characters - forbidden_chars = [';', '&', '|', '>', '<', '`', '$', '(', ')', '{', '}', '\\', 'rm -rf'] - for char in forbidden_chars: - if char in user_input: - self.logger.warning(f"Fallback Security blocked malicious input: {user_input}") - return False + total_uncompressed = 0 + file_count = 0 + + with zipfile.ZipFile(zip_path, 'r') as zf: + for info in zf.infolist(): + file_count += 1 + if file_count > max_files: + self.logger.warning(f"Zip archive exceeded max file count limit: {zip_path}") + return False + + total_uncompressed += info.file_size + if total_uncompressed > max_uncompressed_bytes: + self.logger.warning(f"Zip archive exceeded uncompressed size limit: {zip_path}") + return False + + # Check for Zip Slip directory traversal + member_name = info.filename + if member_name.startswith(('/', '\\')) or (len(member_name) > 1 and member_name[1] == ':'): + self.logger.warning(f"Zip Slip absolute path blocked: {member_name}") + return False + + normalized = os.path.normpath(member_name) + if normalized.startswith("..") or ".." in normalized.split(os.sep): + self.logger.warning(f"Zip Slip relative traversal blocked: {member_name}") + return False + + return True + except zipfile.BadZipFile: + self.logger.warning(f"Corrupt or invalid zip archive: {zip_path}") + return False + except Exception as e: + self.logger.error(f"Error validating project archive: {e}") + return False + + def sanitize_file_name(self, raw_name: str, default: str = "project") -> str: + """ + Sanitizes a raw input string into a safe file/folder name. + """ + try: + if not raw_name or not isinstance(raw_name, str): + return default - return True + normalized = unicodedata.normalize('NFKC', raw_name).strip() + safe_chars = [] + + for ch in normalized: + if self._is_safe_char(ch) and ch not in self.FORBIDDEN_CHARS: + safe_chars.append(ch) + else: + safe_chars.append('_') + + clean_name = "".join(safe_chars).strip('. ') + clean_upper = clean_name.upper().split('.')[0] + + if not clean_name or clean_upper in self.RESERVED_NAMES: + return f"{default}_safe" + + return clean_name + except Exception: + return default diff --git a/core/security_engine/scanner_src/src/validators/string.rs b/core/security_engine/scanner_src/src/validators/string.rs index 56a2901..c34ef32 100644 --- a/core/security_engine/scanner_src/src/validators/string.rs +++ b/core/security_engine/scanner_src/src/validators/string.rs @@ -3,8 +3,12 @@ use crate::error::ScannerError; pub fn is_safe_char(c: char) -> bool { c.is_ascii_alphanumeric() - || matches!(c, '.' | '_' | '-' | ' ') - || ('\u{0600}'..='\u{06FF}').contains(&c) // Arabic block + || matches!(c, '.' | '_' | '-' | ' ' | '(' | ')') + || ('\u{0600}'..='\u{06FF}').contains(&c) // Arabic primary + || ('\u{0750}'..='\u{077F}').contains(&c) // Arabic Supplement + || ('\u{08A0}'..='\u{08FF}').contains(&c) // Arabic Extended-A + || ('\u{FB50}'..='\u{FDFF}').contains(&c) // Arabic Presentation Forms-A + || ('\u{FE70}'..='\u{FEFF}').contains(&c) // Arabic Presentation Forms-B } pub fn validate_input_string(raw_input: &str) -> Result<(), ScannerError> { diff --git a/core/serialization/serializer.py b/core/serialization/serializer.py index 0b02ea5..b123336 100644 --- a/core/serialization/serializer.py +++ b/core/serialization/serializer.py @@ -7,7 +7,7 @@ from PySide6.QtCore import QPointF SCHEMA_VERSION = 1 -APP_VERSION = "1.7.13" # Current target version +APP_VERSION = "1.7.14" # Current target version class SerializerEngine: """ diff --git a/core/settings_manager.py b/core/settings_manager.py index 408440d..906366a 100644 --- a/core/settings_manager.py +++ b/core/settings_manager.py @@ -18,7 +18,7 @@ class SettingsManager(QObject): DEFAULT_SETTINGS = { # Project Settings "canvas_size": "16:9", - "default_scene_duration": 8.0, + "default_scene_duration": 2.0, "auto_save_enabled": False, "auto_save_interval": 5, # minutes "default_project_path": os.path.normpath(os.path.expanduser("~/Documents/DrawMotion/Projects")), diff --git a/core/updater.py b/core/updater.py index 11641a7..bdc19b0 100644 --- a/core/updater.py +++ b/core/updater.py @@ -9,7 +9,7 @@ from utils.theme import THEME_COLORS # Current application version -CURRENT_VERSION = "1.7.13" +CURRENT_VERSION = "1.7.14" # Official public open-source repository GITHUB_REPO = "DMotionX/DrawMotion" diff --git a/docs/README.md b/docs/README.md index 1ff999b..1467fd7 100644 --- a/docs/README.md +++ b/docs/README.md @@ -4,6 +4,14 @@ This directory contains the engineering specifications, architectural models, an --- +## 🎬 Visual Showcase & Demonstrations + +| Whiteboard Drawing & Canvas Studio | Natural Physics Handwriting Engine | +| :---: | :---: | +| ![Whiteboard Studio Demo](video/فيديو%20توضيحي%20اول.gif) | ![Handwriting Engine Demo](video/عرض%20توصيحي%20لمحرك%20الكتابة.gif) | + +--- + ## Architecture and System Design * [Core Engineering Principles](architecture/core_principles.md): Single Source of Truth (SSOT), memory-safe data serialization, and decoupling patterns. diff --git "a/docs/video/\330\271\330\261\330\266 \330\252\331\210\330\265\331\212\330\255\331\212 \331\204\331\205\330\255\330\261\331\203 \330\247\331\204\331\203\330\252\330\247\330\250\330\251.gif" "b/docs/video/\330\271\330\261\330\266 \330\252\331\210\330\265\331\212\330\255\331\212 \331\204\331\205\330\255\330\261\331\203 \330\247\331\204\331\203\330\252\330\247\330\250\330\251.gif" new file mode 100644 index 0000000..ba233b5 Binary files /dev/null and "b/docs/video/\330\271\330\261\330\266 \330\252\331\210\330\265\331\212\330\255\331\212 \331\204\331\205\330\255\330\261\331\203 \330\247\331\204\331\203\330\252\330\247\330\250\330\251.gif" differ diff --git "a/docs/video/\331\201\331\212\330\257\331\212\331\210 \330\252\331\210\330\266\331\212\330\255\331\212 \330\247\331\210\331\204.gif" "b/docs/video/\331\201\331\212\330\257\331\212\331\210 \330\252\331\210\330\266\331\212\330\255\331\212 \330\247\331\210\331\204.gif" new file mode 100644 index 0000000..6009107 Binary files /dev/null and "b/docs/video/\331\201\331\212\330\257\331\212\331\210 \330\252\331\210\330\266\331\212\330\255\331\212 \330\247\331\210\331\204.gif" differ diff --git a/graphics/animated_image_item.py b/graphics/animated_image_item.py index dea7076..bb3381b 100644 --- a/graphics/animated_image_item.py +++ b/graphics/animated_image_item.py @@ -54,7 +54,7 @@ def run(self): # Modern vector algorithms (Professional, Sketch, Educational, etc.) already manage intentional strokes # and explicit in-air travel flights. Preserving them eliminates white gaps and chopped lines. if segment.get("type") in ["stroke", "travel"] or self.style_name in [ - "Professional", "Sketch", "Educational", "Organic Sketch", "Hatch Shading", + "Solid Reveal", "Professional", "Sketch", "Educational", "Organic Sketch", "Hatch Shading", "Clean Outline", "Line Art (Skeleton)", "Blueprint Drafting", "Engraving Hatch", "Ribbon Flow" ]: new_seg = dict(segment) diff --git a/graphics/artboard_item.py b/graphics/artboard_item.py index cdc4e45..0b4648e 100644 --- a/graphics/artboard_item.py +++ b/graphics/artboard_item.py @@ -25,7 +25,8 @@ def __init__(self, rect: QRectF, parent=None): # Solid white fill so it looks like a distinct "page" or "scene" self.setBrush(QBrush(QColor(255, 255, 255))) - self.duration = 8.0 # Default scene duration in seconds + self.duration = 2.0 # Default scene duration in seconds (standard across DrawMotion) + self.user_defined_duration = None # Preserves manual custom duration if set by user self.scene_index = 1 self.total_scenes = 1 @@ -82,6 +83,7 @@ def add_ratio_action(title, w, h): # Fallback if workspace method not found self.duration = new_dur + self.user_defined_duration = new_dur self._recalculate_scene_times() def _recalculate_scene_times(self): @@ -91,7 +93,7 @@ def _recalculate_scene_times(self): if views: workspace = views[0].parent() if hasattr(workspace, 'distribute_global_time'): - workspace.distribute_global_time() + workspace.distribute_global_time(respect_board_duration=True) def _set_aspect_ratio(self, w, h): self.setRect(self.rect().x(), self.rect().y(), w, h) diff --git a/tests/test_clean_outline_algorithm.py b/tests/test_clean_outline_algorithm.py new file mode 100644 index 0000000..dff1998 --- /dev/null +++ b/tests/test_clean_outline_algorithm.py @@ -0,0 +1,152 @@ +# Copyright (c) 2026 Mohamed Fadl & DrawMotion Team +# SPDX-License-Identifier: GPL-3.0-or-later + +import cv2 +import numpy as np +import pytest +from PySide6.QtGui import QImage +from PySide6.QtWidgets import QApplication +from core.drawing_engine.algorithms.factory import AlgorithmFactory +from core.drawing_engine.algorithms.clean_outline.algorithm import CleanOutlineAlgorithm + +@pytest.fixture(scope="module") +def qapp(): + app = QApplication.instance() + if not app: + app = QApplication([]) + return app + +def make_test_multicomponent_qimage(w=1000, h=600): + """ + Creates a synthetic multi-component image with two tall solid objects: + - Component 1 (Left): x in [100, 400], y in [150, 500] + - Component 2 (Right): x in [700, 950], y in [150, 450] + """ + canvas = np.full((h, w, 3), 255, dtype=np.uint8) + cv2.rectangle(canvas, (100, 150), (400, 500), (0, 0, 0), -1) + cv2.rectangle(canvas, (700, 150), (950, 450), (0, 0, 0), -1) + rgba = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGBA) + return QImage(rgba.data, w, h, w * 4, QImage.Format.Format_RGBA8888) + +def make_connected_wire_qimage(w=1200, h=500): + """ + Creates two standalone devices connected by a wire: + - Laptop on left (area > 8000) + - Thin cable touching both + - Arduino on right (area > 8000) + """ + canvas = np.full((h, w, 3), 255, dtype=np.uint8) + cv2.rectangle(canvas, (100, 100), (350, 400), (0, 0, 0), -1) + cv2.line(canvas, (350, 250), (600, 250), (0, 0, 0), 4) + cv2.rectangle(canvas, (600, 100), (850, 400), (0, 0, 0), -1) + rgba = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGBA) + return QImage(rgba.data, w, h, w * 4, QImage.Format.Format_RGBA8888) + +def test_clean_outline_instantiation(qapp): + algo = AlgorithmFactory.get_algorithm("Clean Outline") + assert isinstance(algo, CleanOutlineAlgorithm) + +def test_clean_outline_transparent_image(qapp): + algo = CleanOutlineAlgorithm() + transparent = QImage(200, 200, QImage.Format.Format_RGBA8888) + transparent.fill(0) + plan = algo.generate_plan(transparent, duration=5.0) + assert plan == [] + +def test_clean_outline_piece_by_piece_strict_sequence(qapp): + """ + Verifies that the left object finishes 100% completely before the hand + lifts and moves to draw the right object. + """ + qimg = make_test_multicomponent_qimage() + algo = CleanOutlineAlgorithm() + plan = algo.generate_plan(qimg, duration=8.0, rtl=False) + assert len(plan) > 0 + + strokes = [s for s in plan if s.get("type") == "stroke"] + assert len(strokes) >= 2 + + comp1_strokes = [s for s in strokes if s["points"][0].x() < 500] + comp2_strokes = [s for s in strokes if s["points"][0].x() > 600] + + assert len(comp1_strokes) > 0, "Component 1 must have strokes" + assert len(comp2_strokes) > 0, "Component 2 must have strokes" + + comp1_end = max(s["end_time"] for s in comp1_strokes) + comp2_start = min(s["start_time"] for s in comp2_strokes) + + assert comp1_end <= comp2_start + 1e-4, ( + f"Clean Outline: Component 1 must complete (end={comp1_end:.2f}s) " + f"before Component 2 starts (start={comp2_start:.2f}s)!" + ) + +def test_clean_outline_connected_wire_keeps_pieces_isolated(qapp): + """ + Verifies that when two large devices are connected by a wire, + they are drawn piece-by-piece rather than interleaved. + """ + qimg = make_connected_wire_qimage() + algo = CleanOutlineAlgorithm() + plan = algo.generate_plan(qimg, duration=8.0, rtl=False) + strokes = [s for s in plan if s.get("type") == "stroke"] + + laptop_strokes = [s for s in strokes if s["points"][0].x() <= 360] + arduino_strokes = [s for s in strokes if s["points"][0].x() >= 600] + + assert len(laptop_strokes) > 0, "Laptop must have strokes" + assert len(arduino_strokes) > 0, "Arduino must have strokes" + + laptop_end = max(s["end_time"] for s in laptop_strokes) + arduino_start = min(s["start_time"] for s in arduino_strokes) + + assert laptop_end <= arduino_start + 1e-4, ( + f"Clean Outline: Laptop must finish (end={laptop_end:.2f}s) " + f"before Arduino starts (start={arduino_start:.2f}s)!" + ) + +def test_clean_outline_in_air_travel_flights(qapp): + """ + Verifies that clean in-air travel flights (width=0, opacity=0) occur between pieces. + """ + qimg = make_test_multicomponent_qimage() + algo = CleanOutlineAlgorithm() + plan = algo.generate_plan(qimg, duration=8.0, rtl=False) + + travels = [s for s in plan if s.get("type") == "travel"] + assert len(travels) > 0, "Clean outline must have in-air travel flights between pieces" + for trav in travels: + assert trav["width"] == 0.0 + assert trav["opacity"] == 0.0 + +def test_clean_outline_rtl_reading_progression(qapp): + """ + Verifies that RTL mode draws from right to left (Component 2 before Component 1). + """ + qimg = make_test_multicomponent_qimage() + algo = CleanOutlineAlgorithm() + plan_rtl = algo.generate_plan(qimg, duration=8.0, rtl=True) + strokes_rtl = [s for s in plan_rtl if s.get("type") == "stroke"] + + comp1_strokes = [s for s in strokes_rtl if s["points"][0].x() < 500] + comp2_strokes = [s for s in strokes_rtl if s["points"][0].x() > 600] + + comp2_end = max(s["end_time"] for s in comp2_strokes) + comp1_start = min(s["start_time"] for s in comp1_strokes) + + assert comp2_end <= comp1_start + 1e-4, ( + f"RTL Clean Outline: Component 2 must complete (end={comp2_end:.2f}s) " + f"before Component 1 starts (start={comp1_start:.2f}s)!" + ) + +def test_clean_outline_exact_timeline_duration(qapp): + """ + Verifies that total timeline starts at 0.0 and ends exactly at duration with zero drift. + """ + qimg = make_test_multicomponent_qimage() + algo = CleanOutlineAlgorithm() + target_dur = 7.5 + plan = algo.generate_plan(qimg, duration=target_dur) + + assert len(plan) > 0 + assert abs(plan[0]["start_time"] - 0.0) < 1e-5 + assert abs(plan[-1]["end_time"] - target_dur) < 1e-4 diff --git a/tests/test_educational_algorithm.py b/tests/test_educational_algorithm.py new file mode 100644 index 0000000..ec80afd --- /dev/null +++ b/tests/test_educational_algorithm.py @@ -0,0 +1,100 @@ +# Copyright (c) 2026 Mohamed Fadl & DrawMotion Team +# SPDX-License-Identifier: GPL-3.0-or-later +import cv2 +import numpy as np +import pytest +from PySide6.QtGui import QImage +from PySide6.QtWidgets import QApplication +from core.drawing_engine.algorithms.factory import AlgorithmFactory +from core.drawing_engine.algorithms.hatch_shading.smart_education_generator import generate_smart_educational_paths + +@pytest.fixture(scope="module") +def qapp(): + app = QApplication.instance() + if not app: + app = QApplication([]) + return app + +def make_test_schematic_qimage(w=1000, h=600): + """Creates a synthetic multi-component schematic with Arduino, Sensor, and connecting wires on white background.""" + canvas = np.full((h, w, 3), 255, dtype=np.uint8) + + # Component 1: Arduino on the left (x: 100..400, y: 150..500) + cv2.rectangle(canvas, (100, 150), (400, 500), (0, 0, 0), 3) + cv2.rectangle(canvas, (200, 250), (300, 380), (0, 0, 0), -1) # MCU chip + cv2.rectangle(canvas, (120, 160), (380, 180), (0, 0, 0), -1) # Header pins + + # Component 2: Sensor on the right (x: 700..950, y: 150..350) + cv2.rectangle(canvas, (700, 150), (950, 350), (0, 0, 0), 3) + cv2.circle(canvas, (825, 250), 40, (0, 0, 0), 3) + + # Connecting wire between Arduino and Sensor + cv2.line(canvas, (380, 170), (550, 170), (0, 0, 0), 2) + cv2.line(canvas, (550, 170), (550, 220), (0, 0, 0), 2) + cv2.line(canvas, (550, 220), (700, 220), (0, 0, 0), 2) + + rgba = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGBA) + return QImage(rgba.data, w, h, w * 4, QImage.Format.Format_RGBA8888) + +def test_educational_algorithm_instantiation(qapp): + algo = AlgorithmFactory.get_algorithm("Educational") + assert algo is not None + +def test_educational_module_decomposition(qapp): + """Verifies that the generator decomposes multi-object schematics into distinct modules rather than slicing horizontally.""" + qimg = make_test_schematic_qimage() + algo = AlgorithmFactory.get_algorithm("Educational") + mask = algo._get_ink_mask(qimg) + + modules = generate_smart_educational_paths(mask, scale=1.0, rtl=False) + assert len(modules) >= 2, f"Expected at least 2 distinct modules + wires, got {len(modules)}" + + # Find main body modules (excluding the final wires) + body_modules = [m for m in modules if not m.get("is_wires", False)] + assert len(body_modules) >= 2, "Expected at least 2 main body modules (Arduino and Sensor)" + + # Check that Arduino and Sensor modules have distinct horizontal centers + centers_x = [m["centroid"][0] for m in body_modules] + assert max(centers_x) - min(centers_x) > 200, "Modules should have well-separated horizontal centers" + +def test_educational_plan_generation_timing_and_travels(qapp): + """Verifies plan generation, steady reveal timing, and in-air travel flights between modules.""" + qimg = make_test_schematic_qimage() + algo = AlgorithmFactory.get_algorithm("Educational") + + duration = 6.0 + plan = algo.generate_plan(qimg, duration=duration, rtl=False) + assert len(plan) > 0, "Plan should contain timed segments" + + # Verify timing monotonicity and bounds + for i in range(len(plan)): + assert plan[i]["start_time"] >= 0.0 + assert plan[i]["end_time"] <= duration + 0.05 + assert plan[i]["duration"] > 0.0 + if i > 0: + assert plan[i]["start_time"] >= plan[i-1]["start_time"] - 1e-4 + + # Verify in-air travel flights exist + travel_segments = [seg for seg in plan if seg.get("type") == "travel"] + assert len(travel_segments) > 0, "Educational flow must include prominent in-air travel flights" + for trav in travel_segments: + assert trav["width"] == 0.0 + assert trav["opacity"] == 0.0 + +def test_educational_direction_rtl_vs_ltr(qapp): + """Verifies that in LTR the left component is drawn first, and in RTL the right component is drawn first.""" + qimg = make_test_schematic_qimage() + algo = AlgorithmFactory.get_algorithm("Educational") + + plan_ltr = algo.generate_plan(qimg, duration=6.0, rtl=False) + plan_rtl = algo.generate_plan(qimg, duration=6.0, rtl=True) + + # First stroke start X in LTR vs RTL + first_stroke_ltr = next(s for s in plan_ltr if s.get("type") == "stroke") + first_stroke_rtl = next(s for s in plan_rtl if s.get("type") == "stroke") + + ltr_start_x = first_stroke_ltr["points"][0].x() + rtl_start_x = first_stroke_rtl["points"][0].x() + + assert ltr_start_x < 500, f"LTR should start on left Arduino, got x={ltr_start_x}" + assert rtl_start_x > 600, f"RTL should start on right Sensor, got x={rtl_start_x}" diff --git a/tests/test_interactive_splash.py b/tests/test_interactive_splash.py index c93eadc..746ab52 100644 --- a/tests/test_interactive_splash.py +++ b/tests/test_interactive_splash.py @@ -12,17 +12,17 @@ def qapp(): return app def test_interactive_splash_initialization(qapp): - splash = InteractiveSplashScreen(version="v1.7.13") + splash = InteractiveSplashScreen(version="v1.7.14") assert splash is not None - assert splash.version == "v1.7.13" + assert splash.version == "v1.7.14" assert splash.title_label.text() == "DRAWMOTION" assert splash.subtitle_label.text() == "ANIMATION STUDIO" - assert splash.version_badge.text() == "v1.7.13" + assert splash.version_badge.text() == "v1.7.14" assert splash.progress_bar.value() == 0 splash.close() def test_interactive_splash_progress_updates(qapp): - splash = InteractiveSplashScreen(version="v1.7.13") + splash = InteractiveSplashScreen(version="v1.7.14") splash.show() splash.set_progress(25, "Verifying health...") @@ -45,11 +45,11 @@ def test_interactive_splash_progress_updates(qapp): def test_interactive_splash_finish_smoothly(qapp, qtbot): dummy_window = QWidget() - splash = InteractiveSplashScreen(version="v1.7.13") + splash = InteractiveSplashScreen(version="v1.7.14") splash.show() splash.finish_smoothly(dummy_window) - # Wait for the 250ms animation and deletion to complete - qtbot.wait(350) + # Wait for the transition to complete and target window to become visible + qtbot.waitUntil(lambda: dummy_window.isVisible(), timeout=1000) assert dummy_window.isVisible() dummy_window.close() diff --git a/tests/test_organic_sketch_algorithm.py b/tests/test_organic_sketch_algorithm.py new file mode 100644 index 0000000..46f5adf --- /dev/null +++ b/tests/test_organic_sketch_algorithm.py @@ -0,0 +1,180 @@ +# Copyright (c) 2026 Mohamed Fadl & DrawMotion Team +# SPDX-License-Identifier: GPL-3.0-or-later + +import cv2 +import numpy as np +import pytest +from PySide6.QtGui import QImage +from PySide6.QtWidgets import QApplication +from core.drawing_engine.algorithms.factory import AlgorithmFactory +from core.drawing_engine.algorithms.organic_sketch.algorithm import OrganicSketchAlgorithm + +@pytest.fixture(scope="module") +def qapp(): + app = QApplication.instance() + if not app: + app = QApplication([]) + return app + +def make_test_multicomponent_qimage(w=1000, h=600): + """ + Creates a synthetic multi-component sketch image: + - Component 1 (Left): frame at [100..400, 150..500], screen fill at [150..350, 200..450] + - Component 2 (Right): frame at [700..950, 150..450], circular chip at (825, 300) + """ + canvas = np.full((h, w, 3), 255, dtype=np.uint8) + # Component 1 + cv2.rectangle(canvas, (100, 150), (400, 500), (0, 0, 0), 4) + cv2.rectangle(canvas, (150, 200), (350, 450), (0, 0, 0), -1) + + # Component 2 + cv2.rectangle(canvas, (700, 150), (950, 450), (0, 0, 0), 4) + cv2.circle(canvas, (825, 300), 50, (0, 0, 0), -1) + + rgba = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGBA) + return QImage(rgba.data, w, h, w * 4, QImage.Format.Format_RGBA8888) + +def make_connected_wire_qimage(w=1200, h=500): + """ + Creates two standalone devices connected by a wire: + - Laptop on left (area > 8000) + - Thin cable touching both + - Arduino on right (area > 8000) + """ + canvas = np.full((h, w, 3), 255, dtype=np.uint8) + cv2.rectangle(canvas, (100, 100), (350, 400), (0, 0, 0), -1) + cv2.line(canvas, (350, 250), (600, 250), (0, 0, 0), 4) + cv2.rectangle(canvas, (600, 100), (850, 400), (0, 0, 0), -1) + rgba = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGBA) + return QImage(rgba.data, w, h, w * 4, QImage.Format.Format_RGBA8888) + +def test_organic_sketch_instantiation(qapp): + algo1 = AlgorithmFactory.get_algorithm("Organic Sketch") + assert isinstance(algo1, OrganicSketchAlgorithm) + + algo2 = AlgorithmFactory.get_algorithm("Sketch") + assert isinstance(algo2, OrganicSketchAlgorithm) + +def test_organic_sketch_transparent_image(qapp): + algo = OrganicSketchAlgorithm() + transparent = QImage(200, 200, QImage.Format.Format_RGBA8888) + transparent.fill(0) + plan = algo.generate_plan(transparent, duration=5.0) + assert plan == [] + +def test_organic_sketch_piece_by_piece_strict_sequence(qapp): + """ + Verifies that the left object finishes 100% completely before the hand + lifts and moves to draw the right object in Organic Sketch mode. + """ + qimg = make_test_multicomponent_qimage() + algo = OrganicSketchAlgorithm() + plan = algo.generate_plan(qimg, duration=8.0, rtl=False) + assert len(plan) > 0 + + strokes = [s for s in plan if s.get("type") == "stroke"] + assert len(strokes) >= 2 + + comp1_strokes = [s for s in strokes if s["points"][0].x() < 500] + comp2_strokes = [s for s in strokes if s["points"][0].x() > 600] + + assert len(comp1_strokes) > 0, "Component 1 must have strokes" + assert len(comp2_strokes) > 0, "Component 2 must have strokes" + + comp1_end = max(s["end_time"] for s in comp1_strokes) + comp2_start = min(s["start_time"] for s in comp2_strokes) + + assert comp1_end <= comp2_start + 1e-4, ( + f"Organic Sketch: Component 1 must complete (end={comp1_end:.2f}s) " + f"before Component 2 starts (start={comp2_start:.2f}s)!" + ) + +def test_organic_sketch_artistic_phases_within_piece(qapp): + """ + Verifies that within a piece, the artistic sketch hierarchy is respected: + Light gestural rough-in guide curve is drawn first, followed by contours and cross-hatching. + """ + qimg = make_test_multicomponent_qimage() + algo = OrganicSketchAlgorithm() + plan = algo.generate_plan(qimg, duration=8.0, rtl=False) + strokes = [s for s in plan if s.get("type") == "stroke"] + + comp1_strokes = [s for s in strokes if s["points"][0].x() < 500] + assert len(comp1_strokes) >= 3 + + # First stroke of Component 1 is the Phase 1 gestural rough-in guide curve (lighter width ~9.0) + first_stroke = comp1_strokes[0] + assert first_stroke["width"] <= 10.0, ( + f"Expected Phase 1 gestural rough-in stroke width <= 10.0, got {first_stroke['width']}" + ) + +def test_organic_sketch_connected_wire_keeps_pieces_isolated(qapp): + """ + Verifies that when two large devices are connected by a wire in Organic Sketch mode, + they are drawn strictly piece-by-piece rather than interleaved. + """ + qimg = make_connected_wire_qimage() + algo = OrganicSketchAlgorithm() + plan = algo.generate_plan(qimg, duration=8.0, rtl=False) + strokes = [s for s in plan if s.get("type") == "stroke"] + + laptop_strokes = [s for s in strokes if s["points"][0].x() <= 360] + arduino_strokes = [s for s in strokes if s["points"][0].x() >= 600] + + assert len(laptop_strokes) > 0, "Laptop must have strokes" + assert len(arduino_strokes) > 0, "Arduino must have strokes" + + laptop_end = max(s["end_time"] for s in laptop_strokes) + arduino_start = min(s["start_time"] for s in arduino_strokes) + + assert laptop_end <= arduino_start + 1e-4, ( + f"Organic Sketch: Laptop must finish (end={laptop_end:.2f}s) " + f"before Arduino starts (start={arduino_start:.2f}s)!" + ) + +def test_organic_sketch_in_air_travel_flights(qapp): + """ + Verifies that in-air travel flights (width=0, opacity=0) occur between pieces. + """ + qimg = make_test_multicomponent_qimage() + algo = OrganicSketchAlgorithm() + plan = algo.generate_plan(qimg, duration=8.0, rtl=False) + + travels = [s for s in plan if s.get("type") == "travel"] + assert len(travels) > 0, "Organic Sketch must have in-air travel flights between pieces" + for trav in travels: + assert trav["width"] == 0.0 + assert trav["opacity"] == 0.0 + +def test_organic_sketch_rtl_reading_progression(qapp): + """ + Verifies that RTL mode draws from right to left (Component 2 before Component 1). + """ + qimg = make_test_multicomponent_qimage() + algo = OrganicSketchAlgorithm() + plan_rtl = algo.generate_plan(qimg, duration=8.0, rtl=True) + strokes_rtl = [s for s in plan_rtl if s.get("type") == "stroke"] + + comp1_strokes = [s for s in strokes_rtl if s["points"][0].x() < 500] + comp2_strokes = [s for s in strokes_rtl if s["points"][0].x() > 600] + + comp2_end = max(s["end_time"] for s in comp2_strokes) + comp1_start = min(s["start_time"] for s in comp1_strokes) + + assert comp2_end <= comp1_start + 1e-4, ( + f"RTL Organic Sketch: Component 2 must complete (end={comp2_end:.2f}s) " + f"before Component 1 starts (start={comp1_start:.2f}s)!" + ) + +def test_organic_sketch_exact_timeline_duration(qapp): + """ + Verifies that total timeline starts at 0.0 and ends exactly at duration with zero drift. + """ + qimg = make_test_multicomponent_qimage() + algo = OrganicSketchAlgorithm() + target_dur = 8.0 + plan = algo.generate_plan(qimg, duration=target_dur) + + assert len(plan) > 0 + assert abs(plan[0]["start_time"] - 0.0) < 1e-5 + assert abs(plan[-1]["end_time"] - target_dur) < 1e-4 diff --git a/tests/test_professional_algorithm.py b/tests/test_professional_algorithm.py new file mode 100644 index 0000000..16ac958 --- /dev/null +++ b/tests/test_professional_algorithm.py @@ -0,0 +1,177 @@ +# Copyright (c) 2026 Mohamed Fadl & DrawMotion Team +# SPDX-License-Identifier: GPL-3.0-or-later + +import cv2 +import numpy as np +import pytest +from PySide6.QtGui import QImage +from PySide6.QtWidgets import QApplication +from core.drawing_engine.algorithms.factory import AlgorithmFactory +from core.drawing_engine.algorithms.professional.algorithm import ProfessionalAlgorithm + +@pytest.fixture(scope="module") +def qapp(): + app = QApplication.instance() + if not app: + app = QApplication([]) + return app + +def make_test_multicomponent_qimage(w=1000, h=600): + """ + Creates a synthetic multi-component engineering drawing: + - Component 1 (Left, Laptop/Device): frame at [100..400, 150..500], screen fill at [150..350, 200..450] + - Component 2 (Right, Arduino/MCU): frame at [700..950, 150..450], circular chip at (825, 300) + """ + canvas = np.full((h, w, 3), 255, dtype=np.uint8) + # Component 1 + cv2.rectangle(canvas, (100, 150), (400, 500), (0, 0, 0), 4) + cv2.rectangle(canvas, (150, 200), (350, 450), (0, 0, 0), -1) + + # Component 2 + cv2.rectangle(canvas, (700, 150), (950, 450), (0, 0, 0), 4) + cv2.circle(canvas, (825, 300), 50, (0, 0, 0), -1) + + rgba = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGBA) + return QImage(rgba.data, w, h, w * 4, QImage.Format.Format_RGBA8888) + +def make_connected_wire_qimage(w=1200, h=500): + """ + Creates two standalone devices connected by a wire: + - Laptop on left (area > 8000) + - Thin cable touching both + - Arduino on right (area > 8000) + """ + canvas = np.full((h, w, 3), 255, dtype=np.uint8) + cv2.rectangle(canvas, (100, 100), (350, 400), (0, 0, 0), -1) + cv2.line(canvas, (350, 250), (600, 250), (0, 0, 0), 4) + cv2.rectangle(canvas, (600, 100), (850, 400), (0, 0, 0), -1) + rgba = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGBA) + return QImage(rgba.data, w, h, w * 4, QImage.Format.Format_RGBA8888) + +def test_professional_instantiation(qapp): + algo = AlgorithmFactory.get_algorithm("Professional") + assert isinstance(algo, ProfessionalAlgorithm) + +def test_professional_transparent_image(qapp): + algo = ProfessionalAlgorithm() + transparent = QImage(200, 200, QImage.Format.Format_RGBA8888) + transparent.fill(0) + plan = algo.generate_plan(transparent, duration=5.0) + assert plan == [] + +def test_professional_piece_by_piece_strict_sequence(qapp): + """ + Verifies that the left object finishes 100% completely before the hand + lifts and moves to draw the right object in Professional mode. + """ + qimg = make_test_multicomponent_qimage() + algo = ProfessionalAlgorithm() + plan = algo.generate_plan(qimg, duration=8.0, rtl=False) + assert len(plan) > 0 + + strokes = [s for s in plan if s.get("type") == "stroke"] + assert len(strokes) >= 2 + + comp1_strokes = [s for s in strokes if s["points"][0].x() < 500] + comp2_strokes = [s for s in strokes if s["points"][0].x() > 600] + + assert len(comp1_strokes) > 0, "Component 1 must have strokes" + assert len(comp2_strokes) > 0, "Component 2 must have strokes" + + comp1_end = max(s["end_time"] for s in comp1_strokes) + comp2_start = min(s["start_time"] for s in comp2_strokes) + + assert comp1_end <= comp2_start + 1e-4, ( + f"Professional: Component 1 must complete (end={comp1_end:.2f}s) " + f"before Component 2 starts (start={comp2_start:.2f}s)!" + ) + +def test_professional_cad_tier_hierarchy_within_piece(qapp): + """ + Verifies that within a piece, the CAD structural hierarchy is respected: + Outer chassis contour (Tier 1, width=14.0) is drawn before internal pocket fills / small details. + """ + qimg = make_test_multicomponent_qimage() + algo = ProfessionalAlgorithm() + plan = algo.generate_plan(qimg, duration=8.0, rtl=False) + strokes = [s for s in plan if s.get("type") == "stroke"] + + comp1_strokes = [s for s in strokes if s["points"][0].x() < 500] + assert len(comp1_strokes) >= 2 + + # First stroke of Component 1 should be Tier 1 (chassis outline, width ~14.0) + first_stroke = comp1_strokes[0] + assert first_stroke["width"] >= 13.0, ( + f"Expected Tier 1 chassis stroke width >= 13.0, got {first_stroke['width']}" + ) + +def test_professional_connected_wire_keeps_pieces_isolated(qapp): + """ + Verifies that when two large devices are connected by a wire in Professional mode, + they are drawn strictly piece-by-piece rather than interleaved. + """ + qimg = make_connected_wire_qimage() + algo = ProfessionalAlgorithm() + plan = algo.generate_plan(qimg, duration=8.0, rtl=False) + strokes = [s for s in plan if s.get("type") == "stroke"] + + laptop_strokes = [s for s in strokes if s["points"][0].x() <= 360] + arduino_strokes = [s for s in strokes if s["points"][0].x() >= 600] + + assert len(laptop_strokes) > 0, "Laptop must have strokes" + assert len(arduino_strokes) > 0, "Arduino must have strokes" + + laptop_end = max(s["end_time"] for s in laptop_strokes) + arduino_start = min(s["start_time"] for s in arduino_strokes) + + assert laptop_end <= arduino_start + 1e-4, ( + f"Professional: Laptop must finish (end={laptop_end:.2f}s) " + f"before Arduino starts (start={arduino_start:.2f}s)!" + ) + +def test_professional_in_air_travel_flights(qapp): + """ + Verifies that in-air travel flights (width=0, opacity=0) occur between pieces. + """ + qimg = make_test_multicomponent_qimage() + algo = ProfessionalAlgorithm() + plan = algo.generate_plan(qimg, duration=8.0, rtl=False) + + travels = [s for s in plan if s.get("type") == "travel"] + assert len(travels) > 0, "Professional must have in-air travel flights between pieces" + for trav in travels: + assert trav["width"] == 0.0 + assert trav["opacity"] == 0.0 + +def test_professional_rtl_reading_progression(qapp): + """ + Verifies that RTL mode draws from right to left (Component 2 before Component 1). + """ + qimg = make_test_multicomponent_qimage() + algo = ProfessionalAlgorithm() + plan_rtl = algo.generate_plan(qimg, duration=8.0, rtl=True) + strokes_rtl = [s for s in plan_rtl if s.get("type") == "stroke"] + + comp1_strokes = [s for s in strokes_rtl if s["points"][0].x() < 500] + comp2_strokes = [s for s in strokes_rtl if s["points"][0].x() > 600] + + comp2_end = max(s["end_time"] for s in comp2_strokes) + comp1_start = min(s["start_time"] for s in comp1_strokes) + + assert comp2_end <= comp1_start + 1e-4, ( + f"RTL Professional: Component 2 must complete (end={comp2_end:.2f}s) " + f"before Component 1 starts (start={comp1_start:.2f}s)!" + ) + +def test_professional_exact_timeline_duration(qapp): + """ + Verifies that total timeline starts at 0.0 and ends exactly at duration with zero drift. + """ + qimg = make_test_multicomponent_qimage() + algo = ProfessionalAlgorithm() + target_dur = 8.0 + plan = algo.generate_plan(qimg, duration=target_dur) + + assert len(plan) > 0 + assert abs(plan[0]["start_time"] - 0.0) < 1e-5 + assert abs(plan[-1]["end_time"] - target_dur) < 1e-4 diff --git a/tests/test_scene_duration_stability.py b/tests/test_scene_duration_stability.py new file mode 100644 index 0000000..2a1bf6c --- /dev/null +++ b/tests/test_scene_duration_stability.py @@ -0,0 +1,102 @@ +import pytest +from PySide6.QtCore import QRectF +from PySide6.QtWidgets import QApplication + +from graphics.artboard_item import SceneArtboardItem +from components.canvas.workspace import CanvasWorkspace + + +@pytest.fixture(scope="module") +def qapp(): + app = QApplication.instance() + if not app: + app = QApplication([]) + return app + + +def test_artboard_initial_duration(qapp): + """Artboard must be created with default duration of 2.0s, not 8.0s or 0.5s.""" + board = SceneArtboardItem(QRectF(0, 0, 1920, 1080)) + assert board.duration == 2.0 + assert board.user_defined_duration is None + + +def test_scene_duration_restore_to_2s_after_item_deletion(qapp): + """ + Core bug fix verification: + Adding an item expands scene duration. + Deleting the item must restore scene duration to 2.0s, never shrinking to 0.5s! + """ + workspace = CanvasWorkspace() + assert len(workspace.artboards) >= 1 + board = workspace.artboards[0] + + # 1. Fresh scene must be 2.0s + assert board.duration == 2.0 + + # 2. Mock animated item with 8.0s duration + class MockAnimItem: + def __init__(self, parent): + self._parent = parent + self._anim_duration = 8.0 + self.anim_duration = 8.0 + self.anim_delay = 0.0 + self.zValue = lambda: 0 + + def parentItem(self): + return self._parent + + mock_item = MockAnimItem(board) + workspace.user_items.append(mock_item) + + # Distribute time with item present + workspace.distribute_global_time(respect_board_duration=False) + assert board.duration == 8.0 + + # 3. Delete item (simulate user pressing Delete key) + workspace.user_items.remove(mock_item) + workspace.distribute_global_time(respect_board_duration=False) + + # Must restore to 2.0s, NOT 0.5s! + assert board.duration == 2.0, f"Expected 2.0s, but got {board.duration}s (corrupted shrinkage bug!)" + + +def test_user_defined_duration_preserved_on_deletion(qapp): + """ + If user manually set custom scene duration (e.g. 10.0s), + deleting items should respect the user-defined duration. + """ + workspace = CanvasWorkspace() + board = workspace.artboards[0] + + # User customizes duration to 10.0s + workspace.set_scene_duration_and_scale(board, 10.0) + assert board.duration == 10.0 + assert board.user_defined_duration == 10.0 + + # Distribute time with no items + workspace.distribute_global_time(respect_board_duration=False) + assert board.duration == 10.0 + + +def test_timeline_panel_total_project_duration_and_clamping(qapp): + """ + Timeline panel compute_total_project_duration must correctly return + at least 2.0s for empty scenes and clamp playhead progress properly. + """ + from components.timeline.panel import TimelinePanel + workspace = CanvasWorkspace() + panel = TimelinePanel() + panel.set_workspace(workspace) + + # For empty workspace with 1 board (2.0s), total project duration is 2.0s + total = panel.compute_total_project_duration() + assert total == 2.0 + + # Set playhead at 8.0s + panel.set_playhead_progress(8.0) + assert panel._last_progress_time == 8.0 + + # Calling update_timeline must clamp playhead back to 0.0 (or total project duration) + panel.update_timeline() + assert panel._last_progress_time <= 2.0 diff --git a/tests/test_security_engine.py b/tests/test_security_engine.py new file mode 100644 index 0000000..81de0f2 --- /dev/null +++ b/tests/test_security_engine.py @@ -0,0 +1,126 @@ +# Copyright (c) 2026 Mohamed Fadl & DrawMotion Team +# SPDX-License-Identifier: GPL-3.0-or-later +import os +import tempfile +import zipfile +import time +import pytest +from core.security_engine import SecurityEngine + +@pytest.fixture(scope="module") +def engine(): + return SecurityEngine.get_instance() + +def test_security_engine_singleton(): + e1 = SecurityEngine.get_instance() + e2 = SecurityEngine.get_instance() + assert e1 is e2 + +def test_safe_legitimate_inputs(engine): + """Verifies that legitimate user project and folder names are accepted with ZERO false positives.""" + valid_names = [ + "Project 1", + "My_Animation_2026", + "DrawMotion Demo-Test", + "مشروع الأردوينو", + "الدرس الأول (المقدمة)", + "Arduino Project (V2.1)", + "رسم كرتوني ممتع (نسخة 1)", + "مَشْرُوعٌ_تَعْلِيمِيّ", + "Test (Final) - 2026_01", + "Chapter 1.Introduction" + ] + for name in valid_names: + assert engine.is_safe_input(name) is True, f"Legitimate name should be accepted: {name}" + +def test_malicious_inputs_blocked(engine): + """Verifies that malicious injections, shell characters, and path traversal are strictly blocked.""" + malicious_inputs = [ + "", + " ", + "../../Windows", + "..\\..\\system32", + "safe_prefix/../../evil", + "; rm -rf /", + "test & calc.exe", + "file | whoami", + "test`id`", + "test$HOME", + "