Compare commits

...

99 Commits

Author SHA1 Message Date
f9cac02e06 Add file headers 2026-02-20 09:28:23 -07:00
05d35bbd86 Add GPLv3 license 2026-02-20 09:28:11 -07:00
2fb602c238 fix: Correct 2D axis label Y-position and set color to white
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-18 17:47:08 -07:00
48b547f4da feat: Add X, Y, Z labels to ViewCube axes
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-18 17:44:09 -07:00
c0cb427cf1 Fix: Apply consistent Z-up to Y-up transformations for camera
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-18 17:11:21 -07:00
380c333002 fix: Align YZ plane angle reference to positive Y-axis
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-18 17:04:37 -07:00
d3f0216053 fix: Correct XY/XZ plane snapping and snap indicator drawing
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-18 16:59:35 -07:00
8ccc5e48e9 fix: Correct Z-up plane mapping for drawing tools on XY and XZ planes
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-18 16:56:23 -07:00
2f9e3fdbd6 refactor: Adjust XY and YZ selection plane positions and hit areas
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-18 16:47:16 -07:00
d0e85129bf fix: Correct XY and XZ plane geometry and hit-testing
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-18 15:57:01 -07:00
471e7f2d9c fix: Align sketch grid with Z-up coordinate system
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-18 15:48:56 -07:00
1436d30963 feat: Implement Z-up coordinate system for camera and sketches
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-18 15:45:57 -07:00
3506696624 feat: Display camera info in debug window
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-18 14:58:37 -07:00
45a00b845b feat: Add debug window; accessible via Help menu and DEBUG env var
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-18 14:54:57 -07:00
2b9b54d5a5 build: Auto-generate resources.qrc from icons and shaders
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-18 13:07:49 -07:00
2333a7cdb5 fix: Emulate middle click with left + right mouse button for camera controls
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 17:29:58 -07:00
8a75dab453 Add README with build instructions 2026-02-17 17:28:32 -07:00
6396e49f9b refactor: Revert home button color inversion logic
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 17:28:25 -07:00
22efad4684 style: Adjust ViewCube home button position 2026-02-17 17:28:25 -07:00
d40ae7e670 refactor: DRY home button rect calculation in ViewCube
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 17:28:25 -07:00
2fb73d91ef feat: Invert home button icon color to white
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 17:28:25 -07:00
a6d46a8280 refactor: Update ViewCube home button icon and position 2026-02-17 17:28:12 -07:00
c28c080009 feat: Add animated home button to view cube to reset camera
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 16:56:25 -07:00
405e151f12 style: Increase default view cube opacity 2026-02-17 16:56:22 -07:00
5e20822df4 feat: Add translucent view cube with hover opacity effect
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 16:49:49 -07:00
34ecee0fa2 fix: Scale view cube size by device pixel ratio
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 16:44:54 -07:00
7010d221d0 fix: Correct OpenGL viewport scaling on high-DPI displays
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 16:42:01 -07:00
d43b49a12f fix: Reset dimension properties when defining new circle
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 15:42:19 -07:00
2407957fb6 fix: Clear CircleTool dimension properties on activation
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 15:35:11 -07:00
8a90b17b1f fix: Adjust v-axis for XY and XZ sketch planes to match preview
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 15:30:56 -07:00
e8aef2427b fix: Correct CircleTool XY/XZ plane drawing logic
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 15:27:04 -07:00
2ab4bbf805 fix: Calculate circle radius from point distance
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 15:20:17 -07:00
7f6c01c8a0 feat: Implement circle drawing tool
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 15:15:24 -07:00
4b0a903052 feat: Implement CircleTool with diameter input and preview
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 15:08:57 -07:00
37399bd7c1 feat: Add CircleTool 2026-02-17 15:08:55 -07:00
9d9c658cda fix: Correct QString to const char* for Qt property methods
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 15:00:08 -07:00
e1327b2caa Refactor: Abstract dimension input and finalize creation logic to SketchTool
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 14:58:02 -07:00
d66f7aaf56 fix: Calculate shortest path for camera rotations
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 14:47:56 -07:00
64b48c7ed1 feat: Add limits for camera and pivot point distances
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 14:41:55 -07:00
7ce318b402 fix: Restore camera rotation and stabilize UI element scaling
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 13:58:58 -07:00
08820659d4 fix: Fix erratic camera distance during rotation
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 13:14:24 -07:00
94304bd2e3 feat: Add mouseReleaseEvent declaration
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 13:07:38 -07:00
88199a9d51 feat: Implement middle-mouse rotation around grid intersection with visual pivot
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 13:04:33 -07:00
68eeeb11ec fix: Adjust camera distance text position in viewport 2026-02-17 13:04:30 -07:00
e00af9a8e3 feat: Scale axis length with grid size
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 12:53:16 -07:00
ef55eac997 feat: Adjust grid scaling thresholds and parameters 2026-02-17 12:53:14 -07:00
483b673229 feat: Display camera zoom level in viewport
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 12:39:24 -07:00
e8afc0a4b4 fix: Correct dynamic grid scaling based on camera distance
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 12:34:54 -07:00
1779725d53 feat: Implement dynamic sketch grid based on camera zoom
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 12:32:02 -07:00
b056ccbfec style: Refine sketch grid line appearance 2026-02-17 12:31:59 -07:00
3a7cd78fb2 style: Lighten major grid lines and rename line vectors
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 12:25:08 -07:00
d274b4f59f refactor: Move axis label drawing logic from ViewportWidget to SketchGrid
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 12:19:46 -07:00
a0dbc537cf fix: Increase far clip plane for greater draw distance
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 12:19:46 -07:00
ddf6f6fd85 feat: Implement pixel-perfect camera panning
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 12:19:39 -07:00
f3a1f73f45 fix: Scale pan speed with zoom level for consistent movement
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 11:53:07 -07:00
3bb8d65fd4 feat: Adjust zoom speed based on distance for consistent feel
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 11:48:29 -07:00
6721caca9f fix: Update Qt API usage for QWheelEvent and QMatrix4x4
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 11:37:42 -07:00
38e931bc79 feat: Implement mouse wheel zoom to cursor position
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 11:36:44 -07:00
a66dc50daf refactor: Move camera mouse event handling to Camera class
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 11:34:25 -07:00
2e2f99f2c2 refactor: Move camera restore state animation to Camera
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 11:27:36 -07:00
f29f40277d refactor: Move sketch mode camera animations to Camera class
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 11:26:41 -07:00
a5e8257eb4 build: Automate source file discovery for C++ sources in src/
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 11:22:08 -07:00
ec63a23247 feat: Add sketch, line, rectangle tools and snapping 2026-02-17 11:22:07 -07:00
d708ab9827 refactor: Extract snapping logic into dedicated Snapping class
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 11:19:29 -07:00
e86a775b46 feat: Add snapping functionality 2026-02-17 11:19:27 -07:00
9334508b67 fix: Ensure viewport updates and consistent key handling in drawing tools
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 11:09:42 -07:00
b93f6158ef fix: Enable line tool functionality
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 11:02:54 -07:00
35cad74367 fix: Move line tool specific logic from ViewportWidget to LineTool
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 10:57:02 -07:00
2394727724 refactor: Move rectangle tool logic to RectangleTool class
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 10:53:02 -07:00
95a651b6b0 refactor: Move LineTool event handling to LineTool and add tool APIs
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 10:44:56 -07:00
d015d171ec refactor: Move LineTool paintGL and paint2D logic to LineTool
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 10:38:51 -07:00
1584bfd5a0 fix: Deactivate active tool on Escape key press 2026-02-17 10:38:47 -07:00
3e2f464de9 refactor: Introduce SketchTool base class and derived tool skeletons
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 10:18:36 -07:00
e64755ea0c feat: Make rectangle corners snappable
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 10:01:00 -07:00
b144efbe05 feat: Allow editable rectangle dimensions and fix Tab crash
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 09:57:36 -07:00
966ab037b5 fix: Connect rectangleAdded signal to ApplicationController
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-17 09:52:11 -07:00
246372b847 refactor: Implement Rectangle tool with snapping and dimensions
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-16 20:45:39 -07:00
2b455f57d4 fix: Set YZ plane line angle reference to horizontal
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-16 20:37:08 -07:00
ed88730edb fix: Correctly place dimension labels based on angle difference
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-16 20:32:23 -07:00
7f304bf1f3 fix: Position linear dimension opposite angle to avoid overlap
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-16 20:28:17 -07:00
f5c7f6d326 fix: Normalize angle for dimension text to align with arc
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-16 20:23:39 -07:00
c43330fe5e fix: Adjust chained line angle ref dir for free drawing
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-16 20:13:21 -07:00
9cacbf4e0e fix: Correctly position angle dimension text in all quadrants
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-16 19:53:48 -07:00
8febc50fec fix: Correct dimensioning arc direction and align text angle snapping
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-16 19:50:09 -07:00
c9c1b38f45 fix: Redefine angle dimension quadrant snapping
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-16 19:47:03 -07:00
c117ff3a8a fix: Adjust angle dimension arc direction on quadrant snap
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-16 19:31:23 -07:00
34cecc38d5 fix: Apply typed dimensions/angles on mouse click for lines
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-16 19:26:58 -07:00
2f7d2a4189 fix: Ensure angle dimension arrows always point outward
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-16 19:24:01 -07:00
1fb211cc34 feat: Highlight active dimension input blue by default
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-16 19:21:12 -07:00
b2d5cd19d4 feat: Prevent Tab key from moving focus outside active viewport tools 2026-02-16 18:51:57 -07:00
d89b7e42bc fix: Resolve variable redeclaration and font metrics scope in paintGL
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-16 17:45:05 -07:00
9d72fe2155 feat: Add editable angle dimensions to line drawing
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-16 17:42:05 -07:00
93282fce52 feat: Implement interactive dimension input for line drawing
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-16 17:23:35 -07:00
a18435bb15 style: Reduce radius of unattached sketch vertices 2026-02-16 17:04:13 -07:00
ec75ab41c5 style: Render unattached sketch vertices as filled circles with outline
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-16 16:51:11 -07:00
aaaf9a44ff feat: Billboard unattached sketch vertices
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-16 16:48:31 -07:00
bc2e84a537 fix: Replace qPi() with M_PI to resolve build error
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-16 16:45:59 -07:00
f842555582 style: Render unattached sketch vertices as unfilled circles
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-16 16:45:22 -07:00
a980ad52be fix: Replace QMap with std::map for custom comparator support
Co-authored-by: aider (gemini/gemini-2.5-pro) <aider@aider.chat>
2026-02-16 16:41:59 -07:00
46 changed files with 4224 additions and 508 deletions

View File

@@ -28,20 +28,33 @@ endif()
message(STATUS "OpenCASCADE_INCLUDE_DIRS: ${OpenCASCADE_INCLUDE_DIRS}") message(STATUS "OpenCASCADE_INCLUDE_DIRS: ${OpenCASCADE_INCLUDE_DIRS}")
message(STATUS "OpenCASCADE_LIBRARIES: ${OpenCASCADE_LIBRARIES}") message(STATUS "OpenCASCADE_LIBRARIES: ${OpenCASCADE_LIBRARIES}")
# Automatically find resource files and generate resources.qrc
set(GENERATED_QRC_FILE "${CMAKE_CURRENT_BINARY_DIR}/resources.qrc")
set(QRC_CONTENT "")
file(GLOB ICON_FILES "icons/*.svg")
string(APPEND QRC_CONTENT " <qresource prefix=\"/icons\">\n")
foreach(ICON_FILE IN LISTS ICON_FILES)
get_filename_component(ICON_ALIAS ${ICON_FILE} NAME)
string(APPEND QRC_CONTENT " <file alias=\"${ICON_ALIAS}\">${ICON_FILE}</file>\n")
endforeach()
string(APPEND QRC_CONTENT " </qresource>\n")
file(GLOB SHADER_FILES "src/shaders/*")
string(APPEND QRC_CONTENT " <qresource prefix=\"/shaders\">\n")
foreach(SHADER_FILE IN LISTS SHADER_FILES)
get_filename_component(SHADER_ALIAS ${SHADER_FILE} NAME)
string(APPEND QRC_CONTENT " <file alias=\"${SHADER_ALIAS}\">${SHADER_FILE}</file>\n")
endforeach()
string(APPEND QRC_CONTENT " </qresource>\n")
file(WRITE ${GENERATED_QRC_FILE} "<RCC>\n${QRC_CONTENT}</RCC>\n")
file(GLOB SOURCES "src/*.cpp")
add_executable(OpenCAD add_executable(OpenCAD
src/main.cpp ${SOURCES}
src/MainWindow.cpp ${GENERATED_QRC_FILE}
src/ViewportWidget.cpp
src/ViewCube.cpp
src/SketchGrid.cpp
src/Document.cpp
src/Feature.cpp
src/SketchFeature.cpp
src/SketchLine.cpp
src/FeatureBrowser.cpp
src/ApplicationController.cpp
src/Camera.cpp
resources.qrc
) )
target_include_directories(OpenCAD SYSTEM PRIVATE ${OpenCASCADE_INCLUDE_DIRS}) target_include_directories(OpenCAD SYSTEM PRIVATE ${OpenCASCADE_INCLUDE_DIRS})

674
LICENSE.txt Normal file
View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
{{ project }} Copyright (C) {{ year }} {{ organization }}
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

28
README.md Normal file
View File

@@ -0,0 +1,28 @@
# Unnamed CAD Software
## Development
### Building
On Debian 12:
```bash
$ sudo apt install cmake qt6-base-dev qt6-svg-dev libtbb-dev libfontconfig1-dev
$ sudo apt install libocct-foundation-dev libocct-modeling-data-dev libocct-modeling-algorithms-dev libocct-visualization-dev
$ mkdir build
$ cd build/
$ cmake ..
$ make
$ ./OpenCAD
```
## License
This program is free and open-source software licensed under the GNU GPLv3 (or later). Please see the `LICENSE.txt` file for details.
That means you have the right to study, change, and distribute the software and source code to anyone and for any purpose as long as you grant the same rights when distributing it.

42
icons/home.svg Normal file
View File

@@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
viewBox="0 0 24 24"
fill="currentColor"
class="size-6"
version="1.1"
id="svg2"
sodipodi:docname="home.svg"
inkscape:version="1.4 (e7c3feb100, 2024-10-09)"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns="http://www.w3.org/2000/svg"
xmlns:svg="http://www.w3.org/2000/svg">
<defs
id="defs2" />
<sodipodi:namedview
id="namedview2"
pagecolor="#ffffff"
bordercolor="#000000"
borderopacity="0.25"
inkscape:showpageshadow="2"
inkscape:pageopacity="0.0"
inkscape:pagecheckerboard="0"
inkscape:deskcolor="#d1d1d1"
inkscape:zoom="14.574147"
inkscape:cx="6.9643869"
inkscape:cy="8.6797532"
inkscape:window-width="1440"
inkscape:window-height="831"
inkscape:window-x="0"
inkscape:window-y="0"
inkscape:window-maximized="1"
inkscape:current-layer="svg2" />
<path
d="M11.47 3.841a.75.75 0 0 1 1.06 0l8.69 8.69a.75.75 0 1 0 1.06-1.061l-8.689-8.69a2.25 2.25 0 0 0-3.182 0l-8.69 8.69a.75.75 0 1 0 1.061 1.06l8.69-8.689Z"
id="path1"
style="fill:#ffffff" />
<path
d="m12 5.432 8.159 8.159c.03.03.06.058.091.086v6.198c0 1.035-.84 1.875-1.875 1.875H15a.75.75 0 0 1-.75-.75v-4.5a.75.75 0 0 0-.75-.75h-3a.75.75 0 0 0-.75.75V21a.75.75 0 0 1-.75.75H5.625a1.875 1.875 0 0 1-1.875-1.875v-6.198a2.29 2.29 0 0 0 .091-.086L12 5.432Z"
id="path2"
style="fill:#ffffff" />
</svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@@ -1,17 +0,0 @@
<RCC>
<qresource prefix="/">
<file>icons/create-sketch.svg</file>
<file>icons/extrude.svg</file>
<file>icons/line.svg</file>
<file>icons/rectangle.svg</file>
<file>icons/circle.svg</file>
<file>icons/save-sketch.svg</file>
<file>icons/cursor.svg</file>
</qresource>
<qresource prefix="/shaders">
<file alias="simple.vert">src/shaders/simple.vert</file>
<file alias="simple.frag">src/shaders/simple.frag</file>
<file alias="texture.vert">src/shaders/texture.vert</file>
<file alias="texture.frag">src/shaders/texture.frag</file>
</qresource>
</RCC>

View File

@@ -1,7 +1,16 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#include "ApplicationController.h" #include "ApplicationController.h"
#include "Document.h" #include "Document.h"
#include "SketchFeature.h" #include "SketchFeature.h"
#include "SketchLine.h" #include "SketchLine.h"
#include "SketchRectangle.h"
#include "SketchCircle.h"
#include "MainWindow.h" #include "MainWindow.h"
#include <QInputDialog> #include <QInputDialog>
@@ -140,6 +149,20 @@ void ApplicationController::addLine(const gp_Pnt& start, const gp_Pnt& end)
} }
} }
void ApplicationController::addRectangle(const gp_Pnt& corner1, const gp_Pnt& corner2)
{
if (m_activeSketch) {
m_activeSketch->addObject(new SketchRectangle(corner1, corner2));
}
}
void ApplicationController::addCircle(const gp_Pnt& center, double radius)
{
if (m_activeSketch) {
m_activeSketch->addObject(new SketchCircle(center, radius));
}
}
void ApplicationController::endSketch() void ApplicationController::endSketch()
{ {
m_activeSketch = nullptr; m_activeSketch = nullptr;

View File

@@ -1,3 +1,10 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#ifndef APPLICATIONCONTROLLER_H #ifndef APPLICATIONCONTROLLER_H
#define APPLICATIONCONTROLLER_H #define APPLICATIONCONTROLLER_H
@@ -32,6 +39,8 @@ public:
public slots: public slots:
void setActiveTool(ToolType tool); void setActiveTool(ToolType tool);
void addLine(const gp_Pnt& start, const gp_Pnt& end); void addLine(const gp_Pnt& start, const gp_Pnt& end);
void addRectangle(const gp_Pnt& corner1, const gp_Pnt& corner2);
void addCircle(const gp_Pnt& center, double radius);
void newDocument(); void newDocument();
bool openDocument(); bool openDocument();
bool saveDocument(); bool saveDocument();

View File

@@ -1,9 +1,21 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#include "Camera.h" #include "Camera.h"
#include "ViewportWidget.h"
#include <QApplication> #include <QApplication>
#include <QWheelEvent> #include <QWheelEvent>
#include <QPropertyAnimation>
#include <QParallelAnimationGroup>
#include <QtMath>
Camera::Camera(QObject *parent) : QObject(parent) Camera::Camera(QObject *parent) : QObject(parent)
{ {
m_lastPos = QPoint();
// Set initial view to an isometric angle on the XY plane // Set initial view to an isometric angle on the XY plane
m_xRot = 30 * 16; m_xRot = 30 * 16;
m_yRot = -45 * 16; m_yRot = -45 * 16;
@@ -12,29 +24,72 @@ Camera::Camera(QObject *parent) : QObject(parent)
m_panY = 0.0f; m_panY = 0.0f;
} }
void Camera::processMouseMovement(QMouseEvent* event, const QPoint& lastPos) void Camera::mousePressEvent(QMouseEvent* event)
{ {
int dx = event->pos().x() - lastPos.x(); m_lastPos = event->pos();
int dy = event->pos().y() - lastPos.y(); }
if (event->buttons() & Qt::MiddleButton) { void Camera::mouseMoveEvent(QMouseEvent* event, int viewportHeight)
{
int dx = event->pos().x() - m_lastPos.x();
int dy = event->pos().y() - m_lastPos.y();
if ((event->buttons() & Qt::MiddleButton) || (event->buttons() == (Qt::LeftButton | Qt::RightButton))) {
if (QApplication::keyboardModifiers() & Qt::ShiftModifier) { if (QApplication::keyboardModifiers() & Qt::ShiftModifier) {
// Pan // Pan
setPanX(m_panX + dx / 100.0f); if (viewportHeight == 0) viewportHeight = 1;
setPanY(m_panY - dy / 100.0f);
// This logic is based on a 45-degree field of view.
float fov = 45.0f;
float dist = -m_zoom;
float world_height = 2.0f * dist * tan(qDegreesToRadians(fov / 2.0f));
float pixels_to_world = world_height / viewportHeight;
setPanX(m_panX + dx * pixels_to_world);
setPanY(m_panY - dy * pixels_to_world);
} else { } else {
// Rotate // Rotate
setXRotation(m_xRot + 8 * dy); setXRotation(m_xRot + 8 * dy);
setYRotation(m_yRot + 8 * dx); setYRotation(m_yRot + 8 * dx);
} }
} }
m_lastPos = event->pos();
} }
void Camera::processWheel(QWheelEvent* event) void Camera::wheelEvent(QWheelEvent* event, const QVector3D& worldPos)
{ {
QPoint numDegrees = event->angleDelta() / 8; QPoint numDegrees = event->angleDelta() / 8;
if (!numDegrees.isNull()) { if (!numDegrees.isNull()) {
setZoom(m_zoom + numDegrees.y() / 5.0f); // Make zoom speed proportional to distance, with a minimum speed and a cap.
// The factors are chosen to match the original zoom speed at the default zoom level.
float dist = -m_zoom;
dist = qMin(dist, 200.0f); // Cap distance to avoid crazy fast zoom out.
float zoomFactor = dist * 0.009f + 0.02f;
float zoomAmount = numDegrees.y() * zoomFactor;
float oldZoom = m_zoom;
float newZoom = oldZoom + zoomAmount;
QMatrix4x4 rotation;
rotation.rotate(m_xRot / 16.0f, 1, 0, 0);
rotation.rotate(m_yRot / 16.0f, 0, 1, 0);
rotation.rotate(-90.0f, 1, 0, 0);
QVector3D p_camera = rotation.map(worldPos);
if (std::abs(p_camera.z() + oldZoom) < 1e-6) {
setZoom(newZoom);
return;
}
float ratio = (p_camera.z() + newZoom) / (p_camera.z() + oldZoom);
float newPanX = (p_camera.x() + m_panX) * ratio - p_camera.x();
float newPanY = (p_camera.y() + m_panY) * ratio - p_camera.y();
setZoom(newZoom);
setPanX(newPanX);
setPanY(newPanY);
} }
} }
@@ -42,8 +97,21 @@ QMatrix4x4 Camera::modelViewMatrix() const
{ {
QMatrix4x4 model; QMatrix4x4 model;
model.translate(m_panX, m_panY, m_zoom); model.translate(m_panX, m_panY, m_zoom);
QMatrix4x4 zup_rotation;
zup_rotation.rotate(-90.0f, 1, 0, 0);
QVector3D pivot_yup = zup_rotation.map(m_rotationPivot);
if (m_isRotating) {
model.translate(pivot_yup);
}
model.rotate(m_xRot / 16.0f, 1, 0, 0); model.rotate(m_xRot / 16.0f, 1, 0, 0);
model.rotate(m_yRot / 16.0f, 0, 1, 0); model.rotate(m_yRot / 16.0f, 0, 1, 0);
if (m_isRotating) {
model.translate(-pivot_yup);
}
model.rotate(-90.0f, 1, 0, 0); // For Z-up system
return model; return model;
} }
@@ -68,6 +136,14 @@ void Camera::setYRotation(float angle)
float Camera::zoom() const { return m_zoom; } float Camera::zoom() const { return m_zoom; }
void Camera::setZoom(float value) void Camera::setZoom(float value)
{ {
const float max_dist = 5000.0f;
float remaining_dist_sq = max_dist * max_dist - m_panX * m_panX - m_panY * m_panY;
if (remaining_dist_sq < 0) {
remaining_dist_sq = 0;
}
float max_val = qSqrt(remaining_dist_sq);
value = qBound(-max_val, value, 0.0f); // Zoom is negative or zero
if (value != m_zoom) { if (value != m_zoom) {
m_zoom = value; m_zoom = value;
emit cameraChanged(); emit cameraChanged();
@@ -77,6 +153,14 @@ void Camera::setZoom(float value)
float Camera::panX() const { return m_panX; } float Camera::panX() const { return m_panX; }
void Camera::setPanX(float value) void Camera::setPanX(float value)
{ {
const float max_dist = 5000.0f;
float remaining_dist_sq = max_dist * max_dist - m_panY * m_panY - m_zoom * m_zoom;
if (remaining_dist_sq < 0) {
remaining_dist_sq = 0;
}
float max_val = qSqrt(remaining_dist_sq);
value = qBound(-max_val, value, max_val);
if (value != m_panX) { if (value != m_panX) {
m_panX = value; m_panX = value;
emit cameraChanged(); emit cameraChanged();
@@ -86,6 +170,14 @@ void Camera::setPanX(float value)
float Camera::panY() const { return m_panY; } float Camera::panY() const { return m_panY; }
void Camera::setPanY(float value) void Camera::setPanY(float value)
{ {
const float max_dist = 5000.0f;
float remaining_dist_sq = max_dist * max_dist - m_panX * m_panX - m_zoom * m_zoom;
if (remaining_dist_sq < 0) {
remaining_dist_sq = 0;
}
float max_val = qSqrt(remaining_dist_sq);
value = qBound(-max_val, value, max_val);
if (value != m_panY) { if (value != m_panY) {
m_panY = value; m_panY = value;
emit cameraChanged(); emit cameraChanged();
@@ -109,3 +201,272 @@ void Camera::restoreState()
setPanY(m_savedPanY); setPanY(m_savedPanY);
setZoom(m_savedZoom); setZoom(m_savedZoom);
} }
void Camera::animateToPlaneView(int plane)
{
float targetXRot = xRotation();
float targetYRot = yRotation();
switch (static_cast<ViewportWidget::SketchPlane>(plane)) {
case ViewportWidget::SketchPlane::XY: // Top view
targetXRot = 90 * 16;
targetYRot = 0;
break;
case ViewportWidget::SketchPlane::XZ: // Front view
targetXRot = 0;
targetYRot = 0;
break;
case ViewportWidget::SketchPlane::YZ: // Right view
targetXRot = 0;
targetYRot = -90 * 16;
break;
case ViewportWidget::SketchPlane::NONE:
break;
}
auto* animGroup = new QParallelAnimationGroup(this);
const float full_circle = 360.0f * 16.0f;
float currentXRot = xRotation();
float diffX = targetXRot - currentXRot;
diffX = fmod(diffX, full_circle);
if (diffX > full_circle / 2.0f) {
diffX -= full_circle;
} else if (diffX < -full_circle / 2.0f) {
diffX += full_circle;
}
auto* xRotAnim = new QPropertyAnimation(this, "xRotation");
xRotAnim->setDuration(300);
xRotAnim->setStartValue(currentXRot);
xRotAnim->setEndValue(currentXRot + diffX);
xRotAnim->setEasingCurve(QEasingCurve::InOutQuad);
animGroup->addAnimation(xRotAnim);
float currentYRot = yRotation();
float diffY = targetYRot - currentYRot;
diffY = fmod(diffY, full_circle);
if (diffY > full_circle / 2.0f) {
diffY -= full_circle;
} else if (diffY < -full_circle / 2.0f) {
diffY += full_circle;
}
auto* yRotAnim = new QPropertyAnimation(this, "yRotation");
yRotAnim->setDuration(300);
yRotAnim->setStartValue(currentYRot);
yRotAnim->setEndValue(currentYRot + diffY);
yRotAnim->setEasingCurve(QEasingCurve::InOutQuad);
animGroup->addAnimation(yRotAnim);
auto* panXAnim = new QPropertyAnimation(this, "panX");
panXAnim->setDuration(300);
panXAnim->setStartValue(panX());
panXAnim->setEndValue(0.0f);
panXAnim->setEasingCurve(QEasingCurve::InOutQuad);
animGroup->addAnimation(panXAnim);
auto* panYAnim = new QPropertyAnimation(this, "panY");
panYAnim->setDuration(300);
panYAnim->setStartValue(panY());
panYAnim->setEndValue(0.0f);
panYAnim->setEasingCurve(QEasingCurve::InOutQuad);
animGroup->addAnimation(panYAnim);
auto* zoomAnim = new QPropertyAnimation(this, "zoom");
zoomAnim->setDuration(300);
zoomAnim->setStartValue(zoom());
zoomAnim->setEndValue(-20.0f);
zoomAnim->setEasingCurve(QEasingCurve::InOutQuad);
animGroup->addAnimation(zoomAnim);
animGroup->start(QAbstractAnimation::DeleteWhenStopped);
}
void Camera::animateToHomeView()
{
auto* animGroup = new QParallelAnimationGroup(this);
const float full_circle = 360.0f * 16.0f;
float currentXRot = xRotation();
float targetXRot = 30 * 16;
float diffX = targetXRot - currentXRot;
diffX = fmod(diffX, full_circle);
if (diffX > full_circle / 2.0f) {
diffX -= full_circle;
} else if (diffX < -full_circle / 2.0f) {
diffX += full_circle;
}
auto* xRotAnim = new QPropertyAnimation(this, "xRotation");
xRotAnim->setDuration(300);
xRotAnim->setStartValue(currentXRot);
xRotAnim->setEndValue(currentXRot + diffX);
xRotAnim->setEasingCurve(QEasingCurve::InOutQuad);
animGroup->addAnimation(xRotAnim);
float currentYRot = yRotation();
float targetYRot = -45 * 16;
float diffY = targetYRot - currentYRot;
diffY = fmod(diffY, full_circle);
if (diffY > full_circle / 2.0f) {
diffY -= full_circle;
} else if (diffY < -full_circle / 2.0f) {
diffY += full_circle;
}
auto* yRotAnim = new QPropertyAnimation(this, "yRotation");
yRotAnim->setDuration(300);
yRotAnim->setStartValue(currentYRot);
yRotAnim->setEndValue(currentYRot + diffY);
yRotAnim->setEasingCurve(QEasingCurve::InOutQuad);
animGroup->addAnimation(yRotAnim);
auto* panXAnim = new QPropertyAnimation(this, "panX");
panXAnim->setDuration(300);
panXAnim->setStartValue(panX());
panXAnim->setEndValue(0.0f);
panXAnim->setEasingCurve(QEasingCurve::InOutQuad);
animGroup->addAnimation(panXAnim);
auto* panYAnim = new QPropertyAnimation(this, "panY");
panYAnim->setDuration(300);
panYAnim->setStartValue(panY());
panYAnim->setEndValue(0.0f);
panYAnim->setEasingCurve(QEasingCurve::InOutQuad);
animGroup->addAnimation(panYAnim);
auto* zoomAnim = new QPropertyAnimation(this, "zoom");
zoomAnim->setDuration(300);
zoomAnim->setStartValue(zoom());
zoomAnim->setEndValue(-20.0f);
zoomAnim->setEasingCurve(QEasingCurve::InOutQuad);
animGroup->addAnimation(zoomAnim);
animGroup->start(QAbstractAnimation::DeleteWhenStopped);
}
void Camera::startRotation(const QVector3D& pivot)
{
m_rotationPivot = pivot;
if (m_rotationPivot.length() > 1000.0f) {
m_rotationPivot = m_rotationPivot.normalized() * 1000.0f;
}
m_stableZoom = m_zoom;
QMatrix4x4 zup_rotation;
zup_rotation.rotate(-90.0f, 1, 0, 0);
QVector3D pivot_yup = zup_rotation.map(m_rotationPivot);
QMatrix4x4 rotation;
rotation.rotate(m_xRot / 16.0f, 1, 0, 0);
rotation.rotate(m_yRot / 16.0f, 0, 1, 0);
QVector3D p_rotated = rotation.map(pivot_yup);
QVector3D p_diff = p_rotated - pivot_yup;
setPanX(m_panX + p_diff.x());
setPanY(m_panY + p_diff.y());
setZoom(m_zoom + p_diff.z());
m_isRotating = true;
}
void Camera::stopRotation()
{
if (!m_isRotating) {
return;
}
QMatrix4x4 zup_rotation;
zup_rotation.rotate(-90.0f, 1, 0, 0);
QVector3D pivot_yup = zup_rotation.map(m_rotationPivot);
QMatrix4x4 rotation;
rotation.rotate(m_xRot / 16.0f, 1, 0, 0);
rotation.rotate(m_yRot / 16.0f, 0, 1, 0);
QVector3D p_rotated = rotation.map(pivot_yup);
QVector3D p_diff = p_rotated - pivot_yup;
setPanX(m_panX - p_diff.x());
setPanY(m_panY - p_diff.y());
setZoom(m_zoom - p_diff.z());
m_isRotating = false;
}
void Camera::animateRestoreState()
{
auto* animGroup = new QParallelAnimationGroup(this);
const float full_circle = 360.0f * 16.0f;
float currentXRot = xRotation();
float targetXRot = savedXRot();
float diffX = targetXRot - currentXRot;
diffX = fmod(diffX, full_circle);
if (diffX > full_circle / 2.0f) {
diffX -= full_circle;
} else if (diffX < -full_circle / 2.0f) {
diffX += full_circle;
}
auto* xRotAnim = new QPropertyAnimation(this, "xRotation");
xRotAnim->setDuration(300);
xRotAnim->setStartValue(currentXRot);
xRotAnim->setEndValue(currentXRot + diffX);
xRotAnim->setEasingCurve(QEasingCurve::InOutQuad);
animGroup->addAnimation(xRotAnim);
float currentYRot = yRotation();
float targetYRot = savedYRot();
float diffY = targetYRot - currentYRot;
diffY = fmod(diffY, full_circle);
if (diffY > full_circle / 2.0f) {
diffY -= full_circle;
} else if (diffY < -full_circle / 2.0f) {
diffY += full_circle;
}
auto* yRotAnim = new QPropertyAnimation(this, "yRotation");
yRotAnim->setDuration(300);
yRotAnim->setStartValue(currentYRot);
yRotAnim->setEndValue(currentYRot + diffY);
yRotAnim->setEasingCurve(QEasingCurve::InOutQuad);
animGroup->addAnimation(yRotAnim);
auto* panXAnim = new QPropertyAnimation(this, "panX");
panXAnim->setDuration(300);
panXAnim->setStartValue(panX());
panXAnim->setEndValue(savedPanX());
panXAnim->setEasingCurve(QEasingCurve::InOutQuad);
animGroup->addAnimation(panXAnim);
auto* panYAnim = new QPropertyAnimation(this, "panY");
panYAnim->setDuration(300);
panYAnim->setStartValue(panY());
panYAnim->setEndValue(savedPanY());
panYAnim->setEasingCurve(QEasingCurve::InOutQuad);
animGroup->addAnimation(panYAnim);
auto* zoomAnim = new QPropertyAnimation(this, "zoom");
zoomAnim->setDuration(300);
zoomAnim->setStartValue(zoom());
zoomAnim->setEndValue(savedZoom());
zoomAnim->setEasingCurve(QEasingCurve::InOutQuad);
animGroup->addAnimation(zoomAnim);
connect(animGroup, &QParallelAnimationGroup::finished, this, &Camera::restoreStateAnimationFinished);
animGroup->start(QAbstractAnimation::DeleteWhenStopped);
}
float Camera::uiCameraDistance() const
{
if (m_isRotating) {
return m_stableZoom;
}
return m_zoom;
}

View File

@@ -1,3 +1,10 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#ifndef CAMERA_H #ifndef CAMERA_H
#define CAMERA_H #define CAMERA_H
@@ -19,8 +26,9 @@ class Camera : public QObject
public: public:
explicit Camera(QObject *parent = nullptr); explicit Camera(QObject *parent = nullptr);
void processMouseMovement(QMouseEvent* event, const QPoint& lastPos); void mousePressEvent(QMouseEvent* event);
void processWheel(QWheelEvent* event); void mouseMoveEvent(QMouseEvent* event, int viewportHeight);
void wheelEvent(QWheelEvent* event, const QVector3D& worldPos);
QMatrix4x4 modelViewMatrix() const; QMatrix4x4 modelViewMatrix() const;
@@ -38,6 +46,16 @@ public:
void saveState(); void saveState();
void restoreState(); void restoreState();
void animateToPlaneView(int plane);
void animateRestoreState();
void animateToHomeView();
void startRotation(const QVector3D& pivot);
void stopRotation();
bool isRotating() const { return m_isRotating; }
const QVector3D& rotationPivot() const { return m_rotationPivot; }
float uiCameraDistance() const;
float savedXRot() const { return m_savedXRot; } float savedXRot() const { return m_savedXRot; }
float savedYRot() const { return m_savedYRot; } float savedYRot() const { return m_savedYRot; }
float savedZoom() const { return m_savedZoom; } float savedZoom() const { return m_savedZoom; }
@@ -46,14 +64,20 @@ public:
signals: signals:
void cameraChanged(); void cameraChanged();
void restoreStateAnimationFinished();
private: private:
QPoint m_lastPos;
float m_xRot; float m_xRot;
float m_yRot; float m_yRot;
float m_zoom; float m_zoom;
float m_panX; float m_panX;
float m_panY; float m_panY;
QVector3D m_rotationPivot;
bool m_isRotating = false;
float m_stableZoom = 0;
float m_savedXRot = 0; float m_savedXRot = 0;
float m_savedYRot = 0; float m_savedYRot = 0;
float m_savedZoom = -5.0f; float m_savedZoom = -5.0f;

274
src/CircleTool.cpp Normal file
View File

@@ -0,0 +1,274 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#include "CircleTool.h"
#include "ViewportWidget.h"
#include "Camera.h"
#include <QMouseEvent>
#include <QKeyEvent>
#include <QPainter>
#include <QVector>
#include <QOpenGLShaderProgram>
#include <cmath>
#include <QtMath>
CircleTool::CircleTool(ViewportWidget* viewport)
: SketchTool(viewport)
{
}
void CircleTool::activate()
{
SketchTool::activate();
m_dimensionModes.clear();
m_dimensionModes << "diameter";
m_dimensionPropertyNames.clear();
m_dimensionPropertyNames["diameter"] = "diameterInput";
m_viewport->setProperty("diameterInput", "");
m_viewport->setProperty("dimensionEditMode", "diameter");
}
void CircleTool::mousePressEvent(QMouseEvent *event)
{
gp_Pnt p;
if (!m_isDefining) {
if (m_viewport->isSnappingOrigin()) {
p.SetCoord(0, 0, 0);
} else if (m_viewport->isSnappingVertex()) {
p = m_viewport->snapVertex();
} else {
QVector3D worldPos = m_viewport->unproject(event->pos(), m_viewport->currentPlane());
p.SetCoord(worldPos.x(), worldPos.y(), worldPos.z());
}
m_centerPoint = p;
m_isDefining = true;
m_dimensionModes.clear();
m_dimensionModes << "diameter";
m_dimensionPropertyNames.clear();
m_dimensionPropertyNames["diameter"] = "diameterInput";
m_viewport->setProperty("diameterInput", "");
m_viewport->setProperty("dimensionEditMode", "diameter");
} else {
QVector3D worldPos;
QVector3D centerPos(m_centerPoint.X(), m_centerPoint.Y(), m_centerPoint.Z());
QString diameterInput = m_viewport->property("diameterInput").toString();
bool diameterFromInput = false;
double inputDiameter = 0;
if (!diameterInput.isEmpty()) {
bool ok;
inputDiameter = diameterInput.toDouble(&ok);
if (ok) diameterFromInput = true;
}
if (diameterFromInput) {
QVector3D mousePos = m_viewport->unproject(event->pos(), m_viewport->currentPlane());
QVector3D mouseDir = mousePos - centerPos;
if (mouseDir.lengthSquared() < 1e-9) {
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY || m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) {
mouseDir = QVector3D(1, 0, 0);
} else { // YZ
mouseDir = QVector3D(0, 1, 0);
}
}
double radius = inputDiameter / 2.0;
worldPos = centerPos + mouseDir.normalized() * radius;
} else {
if (m_viewport->isSnappingOrigin()) {
worldPos.setX(0); worldPos.setY(0); worldPos.setZ(0);
} else if (m_viewport->isSnappingVertex()) {
worldPos = QVector3D(m_viewport->snapVertex().X(), m_viewport->snapVertex().Y(), m_viewport->snapVertex().Z());
} else {
worldPos = m_viewport->unproject(event->pos(), m_viewport->currentPlane());
}
}
p.SetCoord(worldPos.x(), worldPos.y(), worldPos.z());
emit m_viewport->circleAdded(m_centerPoint, m_centerPoint.Distance(p));
deactivate();
}
}
void CircleTool::mouseMoveEvent(QMouseEvent *event)
{
// To be implemented
}
void CircleTool::finalizeCreation()
{
QVector3D worldPos;
QVector3D centerPos(m_centerPoint.X(), m_centerPoint.Y(), m_centerPoint.Z());
QString diameterInput = m_viewport->property("diameterInput").toString();
bool diameterFromInput = false;
double inputDiameter = 0;
if (!diameterInput.isEmpty()) {
bool ok;
inputDiameter = diameterInput.toDouble(&ok);
if (ok) diameterFromInput = true;
}
if (diameterFromInput) {
QVector3D mousePos = m_viewport->unproject(m_viewport->currentMousePos(), m_viewport->currentPlane());
QVector3D mouseDir = mousePos - centerPos;
if (mouseDir.lengthSquared() < 1e-9) {
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY || m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) {
mouseDir = QVector3D(1, 0, 0);
} else { // YZ
mouseDir = QVector3D(0, 1, 0);
}
}
double radius = inputDiameter / 2.0;
worldPos = centerPos + mouseDir.normalized() * radius;
} else {
worldPos = m_viewport->unproject(m_viewport->currentMousePos(), m_viewport->currentPlane());
}
gp_Pnt p;
p.SetCoord(worldPos.x(), worldPos.y(), worldPos.z());
emit m_viewport->circleAdded(m_centerPoint, m_centerPoint.Distance(p));
deactivate();
}
void CircleTool::paintGL()
{
if (m_isDefining) {
QVector<GLfloat> vertices;
QVector3D worldPos;
QVector3D centerPos(m_centerPoint.X(), m_centerPoint.Y(), m_centerPoint.Z());
QString diameterInput = m_viewport->property("diameterInput").toString();
bool diameterFromInput = false;
double inputDiameter = 0;
if (!diameterInput.isEmpty()) {
bool ok;
inputDiameter = diameterInput.toDouble(&ok);
if (ok) diameterFromInput = true;
}
QVector3D mousePos = m_viewport->unproject(m_viewport->currentMousePos(), m_viewport->currentPlane());
double radius;
if (diameterFromInput) {
radius = inputDiameter / 2.0;
} else {
worldPos = mousePos;
if (m_viewport->isSnappingOrigin()) {
worldPos.setX(0); worldPos.setY(0); worldPos.setZ(0);
} else if (m_viewport->isSnappingVertex()) {
worldPos.setX(m_viewport->snapVertex().X()); worldPos.setY(m_viewport->snapVertex().Y()); worldPos.setZ(m_viewport->snapVertex().Z());
}
radius = (worldPos - centerPos).length();
}
const int segments = 64;
for (int i = 0; i < segments; ++i) {
double angle1 = i * 2.0 * M_PI / segments;
double angle2 = (i + 1) * 2.0 * M_PI / segments;
QVector3D p1, p2;
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) {
p1.setX(centerPos.x() + radius * qCos(angle1));
p1.setY(centerPos.y() + radius * qSin(angle1));
p1.setZ(centerPos.z());
p2.setX(centerPos.x() + radius * qCos(angle2));
p2.setY(centerPos.y() + radius * qSin(angle2));
p2.setZ(centerPos.z());
} else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) {
p1.setX(centerPos.x() + radius * qCos(angle1));
p1.setY(centerPos.y());
p1.setZ(centerPos.z() + radius * qSin(angle1));
p2.setX(centerPos.x() + radius * qCos(angle2));
p2.setY(centerPos.y());
p2.setZ(centerPos.z() + radius * qSin(angle2));
} else { // YZ
p1.setX(centerPos.x());
p1.setY(centerPos.y() + radius * qCos(angle1));
p1.setZ(centerPos.z() + radius * qSin(angle1));
p2.setX(centerPos.x());
p2.setY(centerPos.y() + radius * qCos(angle2));
p2.setZ(centerPos.z() + radius * qSin(angle2));
}
vertices << p1.x() << p1.y() << p1.z();
vertices << p2.x() << p2.y() << p2.z();
}
m_viewport->shaderProgram()->setUniformValue(m_viewport->colorLoc(), QVector4D(1.0f, 1.0f, 0.0f, 1.0f));
m_viewport->vbo().bind();
m_viewport->vbo().allocate(vertices.constData(), vertices.size() * sizeof(GLfloat));
glDrawArrays(GL_LINES, 0, segments * 2);
}
}
void CircleTool::paint2D(QPainter& painter, const QMatrix4x4& modelView, const QMatrix4x4& projection)
{
if (m_isDefining) {
QVector3D worldPos;
QVector3D centerPos(m_centerPoint.X(), m_centerPoint.Y(), m_centerPoint.Z());
QString diameterInput = m_viewport->property("diameterInput").toString();
bool diameterFromInput = false;
double inputDiameter = 0;
if (!diameterInput.isEmpty()) {
bool ok;
inputDiameter = diameterInput.toDouble(&ok);
if (ok) diameterFromInput = true;
}
QVector3D mousePos = m_viewport->unproject(m_viewport->currentMousePos(), m_viewport->currentPlane());
QVector3D edgePos;
double diameter;
if (diameterFromInput) {
diameter = inputDiameter;
QVector3D mouseDir = mousePos - centerPos;
if (mouseDir.lengthSquared() < 1e-9) {
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY || m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) {
mouseDir = QVector3D(1, 0, 0);
} else { // YZ
mouseDir = QVector3D(0, 1, 0);
}
}
edgePos = centerPos + mouseDir.normalized() * (diameter / 2.0);
} else {
edgePos = mousePos;
if (m_viewport->isSnappingOrigin()) {
edgePos.setX(0); edgePos.setY(0); edgePos.setZ(0);
} else if (m_viewport->isSnappingVertex()) {
edgePos.setX(m_viewport->snapVertex().X()); edgePos.setY(m_viewport->snapVertex().Y()); edgePos.setZ(m_viewport->snapVertex().Z());
}
diameter = (edgePos - centerPos).length() * 2.0;
}
painter.setRenderHint(QPainter::Antialiasing);
QFontMetrics fm(painter.font());
// Diameter dimension
QVector3D diameterTextPos3D = (centerPos + edgePos) / 2.0f;
QVector3D screenPosD = m_viewport->project(diameterTextPos3D, modelView, projection, m_viewport->rect());
if (screenPosD.z() < 1.0f) {
QString diameterText = diameterFromInput ? diameterInput : QString::number(diameter, 'f', 2);
QRect textRect = fm.boundingRect(diameterText + "__");
textRect.moveCenter(screenPosD.toPoint());
if (m_viewport->property("dimensionEditMode").toString() == "diameter") {
painter.fillRect(textRect.adjusted(-4, -2, 4, 2), QColor(64, 128, 255));
} else {
painter.fillRect(textRect.adjusted(-4, -2, 4, 2), QColor(50, 50, 50));
}
painter.setPen(Qt::white);
painter.drawText(textRect, Qt::AlignCenter, diameterText);
}
}
}

35
src/CircleTool.h Normal file
View File

@@ -0,0 +1,35 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#ifndef CIRCLETOOL_H
#define CIRCLETOOL_H
#include "SketchTool.h"
#include <gp_Pnt.hxx>
class CircleTool : public SketchTool
{
Q_OBJECT
public:
explicit CircleTool(ViewportWidget* viewport);
void mousePressEvent(QMouseEvent *event) override;
void mouseMoveEvent(QMouseEvent *event) override;
void paintGL() override;
void paint2D(QPainter& painter, const QMatrix4x4& modelView, const QMatrix4x4& projection) override;
void activate() override;
protected:
void finalizeCreation() override;
private:
gp_Pnt m_centerPoint;
};
#endif // CIRCLETOOL_H

55
src/DebugWindow.cpp Normal file
View File

@@ -0,0 +1,55 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#include "DebugWindow.h"
#include "Camera.h"
#include <QVBoxLayout>
#include <QTextEdit>
#include <QString>
DebugWindow::DebugWindow(QWidget *parent)
: QDialog(parent)
{
setWindowTitle("Debug Info");
resize(600, 400);
QVBoxLayout* layout = new QVBoxLayout(this);
m_textEdit = new QTextEdit();
m_textEdit->setReadOnly(true);
m_textEdit->setText("Debug window is active.");
layout->addWidget(m_textEdit);
setLayout(layout);
}
DebugWindow::~DebugWindow()
{
}
void DebugWindow::updateCameraInfo(const Camera* camera)
{
if (!camera) {
m_textEdit->setText("Camera not available.");
return;
}
QString info;
info += "Camera Info:\n";
info += "----------------\n";
info += QString("Rotation (X, Y): (%1, %2)\n").arg(camera->xRotation()).arg(camera->yRotation());
info += QString("Zoom: %1\n").arg(camera->zoom());
info += QString("Pan (X, Y): (%1, %2)\n").arg(camera->panX()).arg(camera->panY());
info += QString("UI Camera Distance: %1\n").arg(camera->uiCameraDistance());
info += "\n";
info += "Saved State:\n";
info += "----------------\n";
info += QString("Rotation (X, Y): (%1, %2)\n").arg(camera->savedXRot()).arg(camera->savedYRot());
info += QString("Zoom: %1\n").arg(camera->savedZoom());
info += QString("Pan (X, Y): (%1, %2)\n").arg(camera->savedPanX()).arg(camera->savedPanY());
m_textEdit->setText(info);
}

30
src/DebugWindow.h Normal file
View File

@@ -0,0 +1,30 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#ifndef DEBUGWINDOW_H
#define DEBUGWINDOW_H
#include <QDialog>
class QTextEdit;
class Camera;
class DebugWindow : public QDialog
{
Q_OBJECT
public:
explicit DebugWindow(QWidget *parent = nullptr);
~DebugWindow();
void updateCameraInfo(const Camera* camera);
private:
QTextEdit* m_textEdit;
};
#endif // DEBUGWINDOW_H

View File

@@ -1,3 +1,10 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#include "Document.h" #include "Document.h"
#include "Feature.h" #include "Feature.h"
#include "SketchFeature.h" #include "SketchFeature.h"

View File

@@ -1,3 +1,10 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#ifndef DOCUMENT_H #ifndef DOCUMENT_H
#define DOCUMENT_H #define DOCUMENT_H

View File

@@ -1,3 +1,10 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#include "Feature.h" #include "Feature.h"
Feature::Feature(const QString& name) : m_name(name) Feature::Feature(const QString& name) : m_name(name)

View File

@@ -1,3 +1,10 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#ifndef FEATURE_H #ifndef FEATURE_H
#define FEATURE_H #define FEATURE_H

View File

@@ -1,3 +1,10 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#include "FeatureBrowser.h" #include "FeatureBrowser.h"
#include "Document.h" #include "Document.h"
#include "Feature.h" #include "Feature.h"

View File

@@ -1,3 +1,10 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#ifndef FEATUREBROWSER_H #ifndef FEATUREBROWSER_H
#define FEATUREBROWSER_H #define FEATUREBROWSER_H

859
src/LineTool.cpp Normal file
View File

@@ -0,0 +1,859 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#include "LineTool.h"
#include "ViewportWidget.h"
#include "Camera.h"
#include <QMouseEvent>
#include <QKeyEvent>
#include <QPainter>
#include <QOpenGLShaderProgram>
#include <QtMath>
LineTool::LineTool(ViewportWidget* viewport)
: SketchTool(viewport)
{
}
void LineTool::activate()
{
SketchTool::activate();
m_dimensionModes << "length" << "angle";
m_dimensionPropertyNames["length"] = "dimensionInput";
m_dimensionPropertyNames["angle"] = "angleInput";
m_viewport->setProperty("dimensionInput", "");
m_viewport->setProperty("angleInput", "");
m_viewport->setProperty("dimensionEditMode", "length");
m_viewport->setProperty("isChainedLine", false);
}
void LineTool::mousePressEvent(QMouseEvent *event)
{
gp_Pnt p;
QString dimInput = m_viewport->property("dimensionInput").toString();
QString angleInput = m_viewport->property("angleInput").toString();
bool lengthFromInput = false;
bool angleFromInput = false;
double inputLength = 0;
double inputAngleDegrees = 0;
if (m_isDefining) {
if (!dimInput.isEmpty()) {
bool ok;
inputLength = dimInput.toDouble(&ok);
if (ok) lengthFromInput = true;
}
if (!angleInput.isEmpty()) {
bool ok;
inputAngleDegrees = angleInput.toDouble(&ok);
if (ok) angleFromInput = true;
}
}
if (m_isDefining && (lengthFromInput || angleFromInput)) {
QVector3D worldPos;
QVector3D startPos(m_firstLinePoint.X(), m_firstLinePoint.Y(), m_firstLinePoint.Z());
if (angleFromInput) {
QVector3D refDir;
if (m_viewport->property("isChainedLine").toBool()) {
refDir = m_viewport->property("previousLineDirection").value<QVector3D>();
} else {
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY || m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) refDir = QVector3D(1, 0, 0);
else refDir = QVector3D(0, 1, 0);
}
QVector3D currentMouseWorldPos = m_viewport->unproject(event->pos(), m_viewport->currentPlane());
QVector3D mouseVec = currentMouseWorldPos - startPos;
double mouseAngle;
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) mouseAngle = qRadiansToDegrees(atan2(mouseVec.y(), mouseVec.x()));
else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) mouseAngle = qRadiansToDegrees(atan2(mouseVec.z(), mouseVec.x()));
else mouseAngle = qRadiansToDegrees(atan2(mouseVec.z(), mouseVec.y()));
double refAngle;
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) refAngle = qRadiansToDegrees(atan2(refDir.y(), refDir.x()));
else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) refAngle = qRadiansToDegrees(atan2(refDir.z(), refDir.x()));
else refAngle = qRadiansToDegrees(atan2(refDir.z(), refDir.y()));
double relativeMouseAngle = mouseAngle - refAngle;
while (relativeMouseAngle <= -180.0) relativeMouseAngle += 360.0;
while (relativeMouseAngle > 180.0) relativeMouseAngle -= 360.0;
double snappedAngle = 0;
if (relativeMouseAngle >= 0 && relativeMouseAngle < 90) { // Quadrant 1
snappedAngle = inputAngleDegrees;
} else if (relativeMouseAngle >= 90 && relativeMouseAngle <= 180) { // Quadrant 2
snappedAngle = 180.0 - inputAngleDegrees;
} else if (relativeMouseAngle < -90) { // Quadrant 3
snappedAngle = -180.0 + inputAngleDegrees;
} else { // Quadrant 4
snappedAngle = -inputAngleDegrees;
}
double finalAngleRad = qDegreesToRadians(refAngle + snappedAngle);
QVector3D finalDir;
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) finalDir = QVector3D(cos(finalAngleRad), sin(finalAngleRad), 0);
else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) finalDir = QVector3D(cos(finalAngleRad), 0, sin(finalAngleRad));
else finalDir = QVector3D(0, cos(finalAngleRad), sin(finalAngleRad));
double lineLength;
if (lengthFromInput) lineLength = inputLength;
else {
lineLength = QVector3D::dotProduct(mouseVec, finalDir);
if (lineLength < 0) lineLength = 0;
}
worldPos = startPos + lineLength * finalDir;
} else if (lengthFromInput) {
QVector3D currentMouseWorldPos = m_viewport->unproject(event->pos(), m_viewport->currentPlane());
QVector3D dir = (currentMouseWorldPos - startPos);
if (dir.length() > 1e-6) {
dir.normalize();
worldPos = startPos + inputLength * dir;
} else {
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY || m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) worldPos = startPos + QVector3D(inputLength, 0, 0);
else worldPos = startPos + QVector3D(0, inputLength, 0);
}
}
p.SetCoord(worldPos.x(), worldPos.y(), worldPos.z());
} else {
if (m_viewport->isSnappingOrigin()) {
p.SetCoord(0, 0, 0);
} else if (m_viewport->isSnappingVertex()) {
p = m_viewport->snapVertex();
} else {
QVector3D worldPos = m_viewport->unproject(event->pos(), m_viewport->currentPlane());
if (m_viewport->isSnappingHorizontal()) {
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) worldPos.setY(m_firstLinePoint.Y());
else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) worldPos.setZ(m_firstLinePoint.Z());
else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::YZ) worldPos.setZ(m_firstLinePoint.Z());
} else if (m_viewport->isSnappingVertical()) {
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) worldPos.setX(m_firstLinePoint.X());
else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) worldPos.setX(m_firstLinePoint.X());
else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::YZ) worldPos.setY(m_firstLinePoint.Y());
}
p.SetCoord(worldPos.x(), worldPos.y(), worldPos.z());
}
}
if (!m_isDefining) {
m_firstLinePoint = p;
m_isDefining = true;
m_viewport->setProperty("dimensionInput", QVariant(""));
m_viewport->setProperty("angleInput", QVariant(""));
m_viewport->setProperty("dimensionEditMode", "length");
m_viewport->setProperty("isChainedLine", false);
} else {
QVector3D start(m_firstLinePoint.X(), m_firstLinePoint.Y(), m_firstLinePoint.Z());
QVector3D end(p.X(), p.Y(), p.Z());
m_viewport->setProperty("previousLineDirection", QVariant::fromValue((end - start).normalized()));
m_viewport->addLine(m_firstLinePoint, p);
m_firstLinePoint = p;
m_viewport->setProperty("dimensionInput", QVariant(""));
m_viewport->setProperty("angleInput", QVariant(""));
m_viewport->setProperty("dimensionEditMode", "length");
m_viewport->setProperty("isChainedLine", true);
}
}
void LineTool::mouseMoveEvent(QMouseEvent *event)
{
bool oldIsSnappingHorizontal = m_viewport->isSnappingHorizontal();
bool oldIsSnappingVertical = m_viewport->isSnappingVertical();
m_viewport->setSnappingHorizontal(false);
m_viewport->setSnappingVertical(false);
if (m_isDefining && !m_viewport->isSnappingOrigin() && !m_viewport->isSnappingVertex()) {
QVector3D worldPos = m_viewport->unproject(m_viewport->currentMousePos(), m_viewport->currentPlane());
QVector3D startPos(m_firstLinePoint.X(), m_firstLinePoint.Y(), m_firstLinePoint.Z());
QVector3D delta = worldPos - startPos;
if (delta.length() > 1e-6) {
const double snapAngleThreshold = qDegreesToRadians(2.0);
double angle = 0;
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) {
angle = atan2(delta.y(), delta.x());
} else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) {
angle = atan2(delta.z(), delta.x());
} else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::YZ) {
angle = atan2(delta.z(), delta.y());
}
if (qAbs(sin(angle)) < sin(snapAngleThreshold)) {
m_viewport->setSnappingHorizontal(true);
} else if (qAbs(cos(angle)) < sin(snapAngleThreshold)) {
m_viewport->setSnappingVertical(true);
}
}
}
if (oldIsSnappingHorizontal != m_viewport->isSnappingHorizontal() || oldIsSnappingVertical != m_viewport->isSnappingVertical()) {
m_viewport->update();
}
}
void LineTool::finalizeCreation()
{
QVector3D worldPos;
QVector3D startPos(m_firstLinePoint.X(), m_firstLinePoint.Y(), m_firstLinePoint.Z());
// This is duplicated from paintGL to ensure consistent line creation
QString dimInput = m_viewport->property("dimensionInput").toString();
QString angleInput = m_viewport->property("angleInput").toString();
bool lengthFromInput = false;
bool angleFromInput = false;
double inputLength = 0;
double inputAngleDegrees = 0;
if (!dimInput.isEmpty()) {
bool ok;
inputLength = dimInput.toDouble(&ok);
if (ok) lengthFromInput = true;
}
if (!angleInput.isEmpty()) {
bool ok;
inputAngleDegrees = angleInput.toDouble(&ok);
if (ok) angleFromInput = true;
}
if (angleFromInput) {
QVector3D refDir;
if (m_viewport->property("isChainedLine").toBool()) {
refDir = m_viewport->property("previousLineDirection").value<QVector3D>();
} else {
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY || m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) refDir = QVector3D(1, 0, 0);
else refDir = QVector3D(0, 1, 0);
}
QVector3D currentMouseWorldPos = m_viewport->unproject(m_viewport->currentMousePos(), m_viewport->currentPlane());
QVector3D mouseVec = currentMouseWorldPos - startPos;
double mouseAngle;
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) mouseAngle = qRadiansToDegrees(atan2(mouseVec.y(), mouseVec.x()));
else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) mouseAngle = qRadiansToDegrees(atan2(mouseVec.z(), mouseVec.x()));
else mouseAngle = qRadiansToDegrees(atan2(mouseVec.z(), mouseVec.y()));
double refAngle;
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) refAngle = qRadiansToDegrees(atan2(refDir.y(), refDir.x()));
else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) refAngle = qRadiansToDegrees(atan2(refDir.z(), refDir.x()));
else refAngle = qRadiansToDegrees(atan2(refDir.z(), refDir.y()));
double relativeMouseAngle = mouseAngle - refAngle;
while (relativeMouseAngle <= -180.0) relativeMouseAngle += 360.0;
while (relativeMouseAngle > 180.0) relativeMouseAngle -= 360.0;
double snappedAngle = 0;
if (relativeMouseAngle >= 0 && relativeMouseAngle < 90) { // Quadrant 1
snappedAngle = inputAngleDegrees;
} else if (relativeMouseAngle >= 90 && relativeMouseAngle <= 180) { // Quadrant 2
snappedAngle = 180.0 - inputAngleDegrees;
} else if (relativeMouseAngle < -90) { // Quadrant 3
snappedAngle = -180.0 + inputAngleDegrees;
} else { // Quadrant 4
snappedAngle = -inputAngleDegrees;
}
double finalAngleRad = qDegreesToRadians(refAngle + snappedAngle);
QVector3D finalDir;
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) finalDir = QVector3D(cos(finalAngleRad), sin(finalAngleRad), 0);
else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) finalDir = QVector3D(cos(finalAngleRad), 0, sin(finalAngleRad));
else finalDir = QVector3D(0, cos(finalAngleRad), sin(finalAngleRad));
double lineLength;
if (lengthFromInput) lineLength = inputLength;
else {
lineLength = QVector3D::dotProduct(mouseVec, finalDir);
if (lineLength < 0) lineLength = 0;
}
worldPos = startPos + lineLength * finalDir;
} else if (lengthFromInput) {
QVector3D currentMouseWorldPos = m_viewport->unproject(m_viewport->currentMousePos(), m_viewport->currentPlane());
QVector3D dir = (currentMouseWorldPos - startPos);
if (dir.length() > 1e-6) {
dir.normalize();
worldPos = startPos + inputLength * dir;
} else {
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY || m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) worldPos = startPos + QVector3D(inputLength, 0, 0);
else worldPos = startPos + QVector3D(0, inputLength, 0);
}
} else {
worldPos = m_viewport->unproject(m_viewport->currentMousePos(), m_viewport->currentPlane());
}
gp_Pnt p;
p.SetCoord(worldPos.x(), worldPos.y(), worldPos.z());
QVector3D prevDir = (worldPos - startPos).normalized();
m_viewport->setProperty("previousLineDirection", QVariant::fromValue(prevDir));
m_viewport->addLine(m_firstLinePoint, p);
m_firstLinePoint = p;
m_viewport->setProperty("dimensionInput", QVariant(""));
m_viewport->setProperty("angleInput", QVariant(""));
m_viewport->setProperty("dimensionEditMode", "length");
m_viewport->setProperty("isChainedLine", true);
}
void LineTool::paintGL()
{
if (m_isDefining) {
QVector<GLfloat> vertices;
QVector3D worldPos;
QVector3D startPos(m_firstLinePoint.X(), m_firstLinePoint.Y(), m_firstLinePoint.Z());
QString dimInput = m_viewport->property("dimensionInput").toString();
QString angleInput = m_viewport->property("angleInput").toString();
bool lengthFromInput = false;
bool angleFromInput = false;
double inputLength = 0;
double inputAngleDegrees = 0;
if (!dimInput.isEmpty()) {
bool ok;
inputLength = dimInput.toDouble(&ok);
if (ok) lengthFromInput = true;
}
if (!angleInput.isEmpty()) {
bool ok;
inputAngleDegrees = angleInput.toDouble(&ok);
if (ok) angleFromInput = true;
}
if (angleFromInput) {
QVector3D refDir;
if (m_viewport->property("isChainedLine").toBool()) {
refDir = m_viewport->property("previousLineDirection").value<QVector3D>();
} else {
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY || m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) {
refDir = QVector3D(1, 0, 0);
} else { // YZ
refDir = QVector3D(0, 1, 0);
}
}
QVector3D currentMouseWorldPos = m_viewport->unproject(m_viewport->currentMousePos(), m_viewport->currentPlane());
QVector3D mouseVec = currentMouseWorldPos - startPos;
// Quadrant snapping
double mouseAngle;
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) mouseAngle = qRadiansToDegrees(atan2(mouseVec.y(), mouseVec.x()));
else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) mouseAngle = qRadiansToDegrees(atan2(mouseVec.z(), mouseVec.x()));
else mouseAngle = qRadiansToDegrees(atan2(mouseVec.z(), mouseVec.y()));
double refAngle;
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) refAngle = qRadiansToDegrees(atan2(refDir.y(), refDir.x()));
else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) refAngle = qRadiansToDegrees(atan2(refDir.z(), refDir.x()));
else refAngle = qRadiansToDegrees(atan2(refDir.z(), refDir.y()));
double relativeMouseAngle = mouseAngle - refAngle;
while (relativeMouseAngle <= -180.0) relativeMouseAngle += 360.0;
while (relativeMouseAngle > 180.0) relativeMouseAngle -= 360.0;
double snappedAngle = 0;
if (relativeMouseAngle >= 0 && relativeMouseAngle < 90) { // Quadrant 1
snappedAngle = inputAngleDegrees;
} else if (relativeMouseAngle >= 90 && relativeMouseAngle <= 180) { // Quadrant 2
snappedAngle = 180.0 - inputAngleDegrees;
} else if (relativeMouseAngle < -90) { // Quadrant 3
snappedAngle = -180.0 + inputAngleDegrees;
} else { // Quadrant 4
snappedAngle = -inputAngleDegrees;
}
double finalAngleRad = qDegreesToRadians(refAngle + snappedAngle);
QVector3D finalDir;
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) finalDir = QVector3D(cos(finalAngleRad), sin(finalAngleRad), 0);
else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) finalDir = QVector3D(cos(finalAngleRad), 0, sin(finalAngleRad));
else finalDir = QVector3D(0, cos(finalAngleRad), sin(finalAngleRad));
double lineLength;
if (lengthFromInput) {
lineLength = inputLength;
} else {
lineLength = QVector3D::dotProduct(mouseVec, finalDir);
if (lineLength < 0) lineLength = 0;
}
worldPos = startPos + lineLength * finalDir;
} else if (lengthFromInput) {
QVector3D currentMouseWorldPos = m_viewport->unproject(m_viewport->currentMousePos(), m_viewport->currentPlane());
QVector3D dir = (currentMouseWorldPos - startPos);
if (dir.length() > 1e-6) {
dir.normalize();
worldPos = startPos + inputLength * dir;
} else {
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY || m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) {
worldPos = startPos + QVector3D(inputLength, 0, 0);
} else {
worldPos = startPos + QVector3D(0, inputLength, 0);
}
}
} else {
worldPos = m_viewport->unproject(m_viewport->currentMousePos(), m_viewport->currentPlane());
if (m_viewport->isSnappingOrigin()) {
worldPos.setX(0); worldPos.setY(0); worldPos.setZ(0);
} else if (m_viewport->isSnappingVertex()) {
worldPos.setX(m_viewport->snapVertex().X()); worldPos.setY(m_viewport->snapVertex().Y()); worldPos.setZ(m_viewport->snapVertex().Z());
} else if (m_viewport->isSnappingHorizontal()) {
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) worldPos.setY(m_firstLinePoint.Y());
else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) worldPos.setZ(m_firstLinePoint.Z());
else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::YZ) worldPos.setZ(m_firstLinePoint.Z());
} else if (m_viewport->isSnappingVertical()) {
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) worldPos.setX(m_firstLinePoint.X());
else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) worldPos.setX(m_firstLinePoint.X());
else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::YZ) worldPos.setY(m_firstLinePoint.Y());
}
}
vertices << m_firstLinePoint.X() << m_firstLinePoint.Y() << m_firstLinePoint.Z();
vertices << worldPos.x() << worldPos.y() << worldPos.z();
m_viewport->shaderProgram()->setUniformValue(m_viewport->colorLoc(), QVector4D(1.0f, 1.0f, 0.0f, 1.0f));
m_viewport->vbo().bind();
m_viewport->vbo().allocate(vertices.constData(), vertices.size() * sizeof(GLfloat));
glDrawArrays(GL_LINES, 0, 2);
// Draw dimension line
QVector3D lineVec = worldPos - startPos;
float lineLength = lineVec.length();
if (lineLength > 1e-6) {
double refAngle, lineAngle, angleDiff;
{
QVector3D refDir;
if (m_viewport->property("isChainedLine").toBool()) {
refDir = m_viewport->property("previousLineDirection").value<QVector3D>();
} else {
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY || m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) refDir = QVector3D(1, 0, 0);
else refDir = QVector3D(0, 1, 0);
}
if (angleFromInput) {
QVector3D currentMouseWorldPos = m_viewport->unproject(m_viewport->currentMousePos(), m_viewport->currentPlane());
QVector3D mouseVec = currentMouseWorldPos - startPos;
double mouseAngle;
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) mouseAngle = qRadiansToDegrees(atan2(mouseVec.y(), mouseVec.x()));
else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) mouseAngle = qRadiansToDegrees(atan2(mouseVec.z(), mouseVec.x()));
else mouseAngle = qRadiansToDegrees(atan2(mouseVec.z(), mouseVec.y()));
double refAngleForQuadrant;
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) refAngleForQuadrant = qRadiansToDegrees(atan2(refDir.y(), refDir.x()));
else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) refAngleForQuadrant = qRadiansToDegrees(atan2(refDir.z(), refDir.x()));
else refAngleForQuadrant = qRadiansToDegrees(atan2(refDir.z(), refDir.y()));
double relativeMouseAngle = mouseAngle - refAngleForQuadrant;
while (relativeMouseAngle <= -180.0) relativeMouseAngle += 360.0;
while (relativeMouseAngle > 180.0) relativeMouseAngle -= 360.0;
if (relativeMouseAngle >= 90 || relativeMouseAngle < -90) {
refDir = -refDir;
}
} else {
if (m_viewport->property("isChainedLine").toBool()) {
refDir = -refDir;
}
}
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) {
refAngle = atan2(refDir.y(), refDir.x());
lineAngle = atan2(lineVec.y(), lineVec.x());
} else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) {
refAngle = atan2(refDir.z(), refDir.x());
lineAngle = atan2(lineVec.z(), lineVec.x());
} else { // YZ
refAngle = atan2(refDir.z(), refDir.y());
lineAngle = atan2(lineVec.z(), lineVec.y());
}
angleDiff = lineAngle - refAngle;
while (angleDiff <= -M_PI) angleDiff += 2 * M_PI;
while (angleDiff > M_PI) angleDiff -= 2 * M_PI;
lineAngle = refAngle + angleDiff;
}
vertices.clear();
QVector3D perpVec;
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) {
perpVec = QVector3D(-lineVec.y(), lineVec.x(), 0).normalized();
} else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) {
perpVec = QVector3D(-lineVec.z(), 0, lineVec.x()).normalized();
} else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::YZ) {
perpVec = QVector3D(0, -lineVec.z(), lineVec.y()).normalized();
}
if (angleDiff < 0) {
perpVec = -perpVec;
}
float offset = 0.05f * -m_viewport->camera()->zoom();
QVector3D dimStart = startPos + offset * perpVec;
QVector3D dimEnd = worldPos + offset * perpVec;
vertices << dimStart.x() << dimStart.y() << dimStart.z();
vertices << dimEnd.x() << dimEnd.y() << dimEnd.z();
float arrowLength = 0.02f * -m_viewport->camera()->zoom();
float arrowWidth = 0.005f * -m_viewport->camera()->zoom();
QVector3D lineDir = lineVec.normalized();
QVector3D arrow_base_end = dimEnd - arrowLength * lineDir;
QVector3D arrowP1_end = arrow_base_end + arrowWidth * perpVec;
QVector3D arrowP2_end = arrow_base_end - arrowWidth * perpVec;
vertices << dimEnd.x() << dimEnd.y() << dimEnd.z();
vertices << arrowP1_end.x() << arrowP1_end.y() << arrowP1_end.z();
vertices << dimEnd.x() << dimEnd.y() << dimEnd.z();
vertices << arrowP2_end.x() << arrowP2_end.y() << arrowP2_end.z();
QVector3D arrow_base_start = dimStart + arrowLength * lineDir;
QVector3D arrowP1_start = arrow_base_start + arrowWidth * perpVec;
QVector3D arrowP2_start = arrow_base_start - arrowWidth * perpVec;
vertices << dimStart.x() << dimStart.y() << dimStart.z();
vertices << arrowP1_start.x() << arrowP1_start.y() << arrowP1_start.z();
vertices << dimStart.x() << dimStart.y() << dimStart.z();
vertices << arrowP2_start.x() << arrowP2_start.y() << arrowP2_start.z();
m_viewport->shaderProgram()->setUniformValue(m_viewport->colorLoc(), QVector4D(0.7f, 0.7f, 0.7f, 1.0f));
glLineWidth(1.0f);
m_viewport->vbo().bind();
m_viewport->vbo().allocate(vertices.constData(), vertices.size() * sizeof(GLfloat));
glDrawArrays(GL_LINES, 0, vertices.size() / 3);
glLineWidth(2.0f);
// Draw angle dimension
vertices.clear();
const int numSegments = 30;
const float radius = 0.1f * -m_viewport->camera()->zoom();
for (int i = 0; i <= numSegments; ++i) {
double angle = refAngle + (lineAngle - refAngle) * i / numSegments;
QVector3D p;
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) p = startPos + radius * QVector3D(cos(angle), sin(angle), 0);
else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) p = startPos + radius * QVector3D(cos(angle), 0, sin(angle));
else p = startPos + radius * QVector3D(0, cos(angle), sin(angle));
vertices << p.x() << p.y() << p.z();
}
glLineWidth(1.0f);
m_viewport->vbo().bind();
m_viewport->vbo().allocate(vertices.constData(), vertices.size() * sizeof(GLfloat));
glDrawArrays(GL_LINE_STRIP, 0, vertices.size() / 3);
// Arrowheads for arc
QVector<GLfloat> arrowVertices;
float arcArrowLength = 0.02f * -m_viewport->camera()->zoom();
float arcArrowWidth = 0.005f * -m_viewport->camera()->zoom();
double sign = (angleDiff >= 0) ? 1.0 : -1.0;
// End arrowhead
QVector3D endPoint(vertices[vertices.size()-3], vertices[vertices.size()-2], vertices[vertices.size()-1]);
double endAngle = lineAngle;
QVector3D radialDir_end, tangentDir_end;
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) {
radialDir_end = QVector3D(cos(endAngle), sin(endAngle), 0);
tangentDir_end = QVector3D(-sin(endAngle), cos(endAngle), 0);
} else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) {
radialDir_end = QVector3D(cos(endAngle), 0, sin(endAngle));
tangentDir_end = QVector3D(-sin(endAngle), 0, cos(endAngle));
} else {
radialDir_end = QVector3D(0, cos(endAngle), sin(endAngle));
tangentDir_end = QVector3D(0, -sin(endAngle), cos(endAngle));
}
QVector3D arc_arrow_base_end = endPoint - sign * arcArrowLength * tangentDir_end;
QVector3D arc_arrowP1_end = arc_arrow_base_end + arcArrowWidth * radialDir_end;
QVector3D arc_arrowP2_end = arc_arrow_base_end - arcArrowWidth * radialDir_end;
arrowVertices << endPoint.x() << endPoint.y() << endPoint.z() << arc_arrowP1_end.x() << arc_arrowP1_end.y() << arc_arrowP1_end.z();
arrowVertices << endPoint.x() << endPoint.y() << endPoint.z() << arc_arrowP2_end.x() << arc_arrowP2_end.y() << arc_arrowP2_end.z();
// Start arrowhead
QVector3D startPoint(vertices[0], vertices[1], vertices[2]);
double startAngle = refAngle;
QVector3D radialDir_start, tangentDir_start;
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) {
radialDir_start = QVector3D(cos(startAngle), sin(startAngle), 0);
tangentDir_start = QVector3D(-sin(startAngle), cos(startAngle), 0);
} else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) {
radialDir_start = QVector3D(cos(startAngle), 0, sin(startAngle));
tangentDir_start = QVector3D(-sin(startAngle), 0, cos(startAngle));
} else {
radialDir_start = QVector3D(0, cos(startAngle), sin(startAngle));
tangentDir_start = QVector3D(0, -sin(startAngle), cos(startAngle));
}
QVector3D arc_arrow_base_start = startPoint + sign * arcArrowLength * tangentDir_start;
QVector3D arc_arrowP1_start = arc_arrow_base_start + arcArrowWidth * radialDir_start;
QVector3D arc_arrowP2_start = arc_arrow_base_start - arcArrowWidth * radialDir_start;
arrowVertices << startPoint.x() << startPoint.y() << startPoint.z() << arc_arrowP1_start.x() << arc_arrowP1_start.y() << arc_arrowP1_start.z();
arrowVertices << startPoint.x() << startPoint.y() << startPoint.z() << arc_arrowP2_start.x() << arc_arrowP2_start.y() << arc_arrowP2_start.z();
m_viewport->vbo().bind();
m_viewport->vbo().allocate(arrowVertices.constData(), arrowVertices.size() * sizeof(GLfloat));
glDrawArrays(GL_LINES, 0, arrowVertices.size() / 3);
glLineWidth(2.0f);
}
if (!lengthFromInput && !angleFromInput && (m_viewport->isSnappingHorizontal() || m_viewport->isSnappingVertical())) {
vertices.clear();
QVector3D startPos(m_firstLinePoint.X(), m_firstLinePoint.Y(), m_firstLinePoint.Z());
QVector3D midPoint = (startPos + worldPos) / 2.0;
const float indicatorSize = 0.02f * -m_viewport->camera()->zoom();
const float indicatorOffset = 0.02f * -m_viewport->camera()->zoom();
if (m_viewport->isSnappingHorizontal()) {
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) {
vertices << midPoint.x() - indicatorSize << midPoint.y() + indicatorOffset << midPoint.z();
vertices << midPoint.x() + indicatorSize << midPoint.y() + indicatorOffset << midPoint.z();
} else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) {
vertices << midPoint.x() - indicatorSize << midPoint.y() << midPoint.z() + indicatorOffset;
vertices << midPoint.x() + indicatorSize << midPoint.y() << midPoint.z() + indicatorOffset;
} else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::YZ) {
vertices << midPoint.x() << midPoint.y() - indicatorSize << midPoint.z() + indicatorOffset;
vertices << midPoint.x() << midPoint.y() + indicatorSize << midPoint.z() + indicatorOffset;
}
} else { // m_isSnappingVertical
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) {
vertices << midPoint.x() + indicatorOffset << midPoint.y() - indicatorSize << midPoint.z();
vertices << midPoint.x() + indicatorOffset << midPoint.y() + indicatorSize << midPoint.z();
} else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) {
vertices << midPoint.x() + indicatorOffset << midPoint.y() << midPoint.z() - indicatorSize;
vertices << midPoint.x() + indicatorOffset << midPoint.y() << midPoint.z() + indicatorSize;
} else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::YZ) {
vertices << midPoint.x() << midPoint.y() + indicatorOffset << midPoint.z() - indicatorSize;
vertices << midPoint.x() << midPoint.y() + indicatorOffset << midPoint.z() + indicatorSize;
}
}
m_viewport->vbo().bind();
m_viewport->vbo().allocate(vertices.constData(), vertices.size() * sizeof(GLfloat));
glDrawArrays(GL_LINES, 0, 2);
}
}
}
void LineTool::paint2D(QPainter& painter, const QMatrix4x4& modelView, const QMatrix4x4& projection)
{
if (m_isDefining) {
QVector3D worldPos;
QVector3D startPos(m_firstLinePoint.X(), m_firstLinePoint.Y(), m_firstLinePoint.Z());
QString dimText;
QString angleText;
QString dimInput = m_viewport->property("dimensionInput").toString();
QString angleInput = m_viewport->property("angleInput").toString();
bool lengthFromInput = false;
bool angleFromInput = false;
double inputLength = 0;
double inputAngleDegrees = 0;
double lineLength = 0;
if (!dimInput.isEmpty()) {
bool ok;
inputLength = dimInput.toDouble(&ok);
if (ok) lengthFromInput = true;
}
if (!angleInput.isEmpty()) {
bool ok;
inputAngleDegrees = angleInput.toDouble(&ok);
if (ok) angleFromInput = true;
}
if (angleFromInput) {
QVector3D refDir;
if (m_viewport->property("isChainedLine").toBool()) {
refDir = m_viewport->property("previousLineDirection").value<QVector3D>();
} else {
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY || m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) {
refDir = QVector3D(1, 0, 0);
} else { // YZ
refDir = QVector3D(0, 1, 0);
}
}
QVector3D currentMouseWorldPos = m_viewport->unproject(m_viewport->currentMousePos(), m_viewport->currentPlane());
QVector3D mouseVec = currentMouseWorldPos - startPos;
double mouseAngle;
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) mouseAngle = qRadiansToDegrees(atan2(mouseVec.y(), mouseVec.x()));
else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) mouseAngle = qRadiansToDegrees(atan2(mouseVec.z(), mouseVec.x()));
else mouseAngle = qRadiansToDegrees(atan2(mouseVec.z(), mouseVec.y()));
double refAngle;
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) refAngle = qRadiansToDegrees(atan2(refDir.y(), refDir.x()));
else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) refAngle = qRadiansToDegrees(atan2(refDir.z(), refDir.x()));
else refAngle = qRadiansToDegrees(atan2(refDir.z(), refDir.y()));
double relativeMouseAngle = mouseAngle - refAngle;
while (relativeMouseAngle <= -180.0) relativeMouseAngle += 360.0;
while (relativeMouseAngle > 180.0) relativeMouseAngle -= 360.0;
double snappedAngle = 0;
if (relativeMouseAngle >= 0 && relativeMouseAngle < 90) { // Quadrant 1
snappedAngle = inputAngleDegrees;
} else if (relativeMouseAngle >= 90 && relativeMouseAngle <= 180) { // Quadrant 2
snappedAngle = 180.0 - inputAngleDegrees;
} else if (relativeMouseAngle < -90) { // Quadrant 3
snappedAngle = -180.0 + inputAngleDegrees;
} else { // Quadrant 4
snappedAngle = -inputAngleDegrees;
}
double finalAngleRad = qDegreesToRadians(refAngle + snappedAngle);
QVector3D finalDir;
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) finalDir = QVector3D(cos(finalAngleRad), sin(finalAngleRad), 0);
else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) finalDir = QVector3D(cos(finalAngleRad), 0, sin(finalAngleRad));
else finalDir = QVector3D(0, cos(finalAngleRad), sin(finalAngleRad));
if (lengthFromInput) {
lineLength = inputLength;
} else {
lineLength = QVector3D::dotProduct(mouseVec, finalDir);
if (lineLength < 0) lineLength = 0;
}
worldPos = startPos + lineLength * finalDir;
} else if (lengthFromInput) {
lineLength = inputLength;
QVector3D currentMouseWorldPos = m_viewport->unproject(m_viewport->currentMousePos(), m_viewport->currentPlane());
QVector3D dir = (currentMouseWorldPos - startPos);
if (dir.length() > 1e-6) {
dir.normalize();
worldPos = startPos + inputLength * dir;
} else {
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY || m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) {
worldPos = startPos + QVector3D(inputLength, 0, 0);
} else {
worldPos = startPos + QVector3D(0, inputLength, 0);
}
}
} else {
worldPos = m_viewport->unproject(m_viewport->currentMousePos(), m_viewport->currentPlane());
if (m_viewport->isSnappingOrigin()) {
worldPos.setX(0); worldPos.setY(0); worldPos.setZ(0);
} else if (m_viewport->isSnappingVertex()) {
worldPos.setX(m_viewport->snapVertex().X()); worldPos.setY(m_viewport->snapVertex().Y()); worldPos.setZ(m_viewport->snapVertex().Z());
} else if (m_viewport->isSnappingHorizontal()) {
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) worldPos.setY(m_firstLinePoint.Y());
else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) worldPos.setZ(m_firstLinePoint.Z());
else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::YZ) worldPos.setZ(m_firstLinePoint.Z());
} else if (m_viewport->isSnappingVertical()) {
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) worldPos.setX(m_firstLinePoint.X());
else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) worldPos.setX(m_firstLinePoint.X());
else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::YZ) worldPos.setY(m_firstLinePoint.Y());
}
lineLength = (worldPos - startPos).length();
}
QVector3D lineVec = worldPos - startPos;
if (lineVec.length() > 1e-6) {
double refAngle, lineAngle;
QVector3D refDir;
if (m_viewport->property("isChainedLine").toBool()) {
refDir = m_viewport->property("previousLineDirection").value<QVector3D>();
} else {
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY || m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) refDir = QVector3D(1, 0, 0);
else refDir = QVector3D(0, 1, 0);
}
QVector3D currentMouseWorldPosForText = m_viewport->unproject(m_viewport->currentMousePos(), m_viewport->currentPlane());
QVector3D mouseVecForText = currentMouseWorldPosForText - startPos;
if (angleFromInput) {
if (mouseVecForText.length() > 1e-6) {
double mouseAngle;
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) mouseAngle = qRadiansToDegrees(atan2(mouseVecForText.y(), mouseVecForText.x()));
else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) mouseAngle = qRadiansToDegrees(atan2(mouseVecForText.z(), mouseVecForText.x()));
else mouseAngle = qRadiansToDegrees(atan2(mouseVecForText.z(), mouseVecForText.y()));
double refAngleForQuadrant;
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) refAngleForQuadrant = qRadiansToDegrees(atan2(refDir.y(), refDir.x()));
else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) refAngleForQuadrant = qRadiansToDegrees(atan2(refDir.z(), refDir.x()));
else refAngleForQuadrant = qRadiansToDegrees(atan2(refDir.z(), refDir.y()));
double relativeMouseAngle = mouseAngle - refAngleForQuadrant;
while (relativeMouseAngle <= -180.0) relativeMouseAngle += 360.0;
while (relativeMouseAngle > 180.0) relativeMouseAngle -= 360.0;
if (relativeMouseAngle >= 90 || relativeMouseAngle < -90) {
refDir = -refDir;
}
}
} else {
if (m_viewport->property("isChainedLine").toBool()) {
refDir = -refDir;
}
}
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) {
refAngle = atan2(refDir.y(), refDir.x());
lineAngle = atan2(lineVec.y(), lineVec.x());
} else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) {
refAngle = atan2(refDir.z(), refDir.x());
lineAngle = atan2(lineVec.z(), lineVec.x());
} else { // YZ
refAngle = atan2(refDir.z(), refDir.y());
lineAngle = atan2(lineVec.z(), lineVec.y());
}
double angleDiff = lineAngle - refAngle;
while (angleDiff <= -M_PI) angleDiff += 2 * M_PI;
while (angleDiff > M_PI) angleDiff -= 2 * M_PI;
lineAngle = refAngle + angleDiff;
QVector3D perpVec;
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) {
perpVec = QVector3D(-lineVec.y(), lineVec.x(), 0).normalized();
} else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) {
perpVec = QVector3D(-lineVec.z(), 0, lineVec.x()).normalized();
} else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::YZ) {
perpVec = QVector3D(0, -lineVec.z(), lineVec.y()).normalized();
}
if (angleDiff < 0) {
perpVec = -perpVec;
}
float offset = 0.05f * -m_viewport->camera()->zoom();
QVector3D dimStart = startPos + offset * perpVec;
QVector3D dimEnd = worldPos + offset * perpVec;
QVector3D textPos3D = (dimStart + dimEnd) / 2.0f + 0.015f * -m_viewport->camera()->zoom() * perpVec;
QVector3D screenPos = m_viewport->project(textPos3D, modelView, projection, m_viewport->rect());
painter.setRenderHint(QPainter::Antialiasing);
QFontMetrics fm(painter.font());
if (screenPos.z() < 1.0f) {
dimText = lengthFromInput ? dimInput : QString::number(lineLength, 'f', 2);
QRect textRect = fm.boundingRect(dimText + "_");
textRect.moveCenter(screenPos.toPoint());
if (m_viewport->property("dimensionEditMode").toString() == "length") {
painter.fillRect(textRect.adjusted(-4, -2, 4, 2), QColor(64, 128, 255));
} else {
painter.fillRect(textRect.adjusted(-4, -2, 4, 2), QColor(50, 50, 50));
}
painter.setPen(Qt::white);
painter.drawText(textRect, Qt::AlignCenter, dimText);
}
// Angle dimension text
double angleDiffDegrees = qRadiansToDegrees(angleDiff);
while (angleDiffDegrees <= -180.0) angleDiffDegrees += 360.0;
while (angleDiffDegrees > 180.0) angleDiffDegrees -= 360.0;
angleText = angleFromInput ? angleInput : QString::number(qAbs(angleDiffDegrees), 'f', 1) + QChar(0x00B0);
const float radius = 0.1f * -m_viewport->camera()->zoom();
double midAngle = refAngle + (lineAngle - refAngle) / 2.0;
QVector3D textPos3DAngle;
float textOffset = 0.035f * -m_viewport->camera()->zoom();
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) textPos3DAngle = startPos + (radius + textOffset) * QVector3D(cos(midAngle), sin(midAngle), 0);
else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) textPos3DAngle = startPos + (radius + textOffset) * QVector3D(cos(midAngle), 0, sin(midAngle));
else textPos3DAngle = startPos + (radius + textOffset) * QVector3D(0, cos(midAngle), sin(midAngle));
QVector3D screenPosAngle = m_viewport->project(textPos3DAngle, modelView, projection, m_viewport->rect());
if (screenPosAngle.z() < 1.0f) {
QRect angleTextRect = fm.boundingRect(angleText + "_");
angleTextRect.moveCenter(screenPosAngle.toPoint());
if (m_viewport->property("dimensionEditMode").toString() == "angle") {
painter.fillRect(angleTextRect.adjusted(-4, -2, 4, 2), QColor(64, 128, 255));
} else {
painter.fillRect(angleTextRect.adjusted(-4, -2, 4, 2), QColor(50, 50, 50));
}
painter.setPen(Qt::white);
painter.drawText(angleTextRect, Qt::AlignCenter, angleText);
}
}
}
}

35
src/LineTool.h Normal file
View File

@@ -0,0 +1,35 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#ifndef LINETOOL_H
#define LINETOOL_H
#include "SketchTool.h"
#include <gp_Pnt.hxx>
class LineTool : public SketchTool
{
Q_OBJECT
public:
explicit LineTool(ViewportWidget* viewport);
void mousePressEvent(QMouseEvent *event) override;
void mouseMoveEvent(QMouseEvent *event) override;
void paintGL() override;
void paint2D(QPainter& painter, const QMatrix4x4& modelView, const QMatrix4x4& projection) override;
void activate() override;
protected:
void finalizeCreation() override;
private:
gp_Pnt m_firstLinePoint;
};
#endif // LINETOOL_H

View File

@@ -1,9 +1,18 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#include "MainWindow.h" #include "MainWindow.h"
#include "ViewportWidget.h" #include "ViewportWidget.h"
#include "Document.h" #include "Document.h"
#include "SketchFeature.h" #include "SketchFeature.h"
#include "Feature.h" #include "Feature.h"
#include "ApplicationController.h" #include "ApplicationController.h"
#include "DebugWindow.h"
#include "Camera.h"
#include <QMenuBar> #include <QMenuBar>
#include <QMenu> #include <QMenu>
@@ -17,11 +26,15 @@
#include <QIcon> #include <QIcon>
#include <QInputDialog> #include <QInputDialog>
#include <QStringList> #include <QStringList>
#include <QKeyEvent>
#include <QApplication>
#include <QProcessEnvironment>
MainWindow::MainWindow(ApplicationController* appController, QWidget *parent) MainWindow::MainWindow(ApplicationController* appController, QWidget *parent)
: QMainWindow(parent) : QMainWindow(parent)
, m_appController(appController) , m_appController(appController)
{ {
qApp->installEventFilter(this);
setWindowTitle("OpenCAD"); setWindowTitle("OpenCAD");
resize(1920, 1080); resize(1920, 1080);
@@ -38,6 +51,10 @@ MainWindow::MainWindow(ApplicationController* appController, QWidget *parent)
QAction *saveAsAction = fileMenu->addAction("Save &As..."); QAction *saveAsAction = fileMenu->addAction("Save &As...");
connect(saveAsAction, &QAction::triggered, this, &MainWindow::saveAs); connect(saveAsAction, &QAction::triggered, this, &MainWindow::saveAs);
QMenu *helpMenu = menuBar()->addMenu("&Help");
QAction *debugAction = helpMenu->addAction("&Debug");
connect(debugAction, &QAction::triggered, this, &MainWindow::showDebugWindow);
QToolBar* mainToolBar = addToolBar("Main Toolbar"); QToolBar* mainToolBar = addToolBar("Main Toolbar");
mainToolBar->setMovable(false); mainToolBar->setMovable(false);
@@ -143,9 +160,18 @@ MainWindow::MainWindow(ApplicationController* appController, QWidget *parent)
connect(m_appController, &ApplicationController::planeSelectionModeStarted, m_viewport, &ViewportWidget::onPlaneSelectionModeStarted); connect(m_appController, &ApplicationController::planeSelectionModeStarted, m_viewport, &ViewportWidget::onPlaneSelectionModeStarted);
connect(m_viewport, &ViewportWidget::lineAdded, m_appController, &ApplicationController::addLine); connect(m_viewport, &ViewportWidget::lineAdded, m_appController, &ApplicationController::addLine);
connect(m_viewport, &ViewportWidget::rectangleAdded, m_appController, &ApplicationController::addRectangle);
connect(m_viewport, &ViewportWidget::circleAdded, m_appController, &ApplicationController::addCircle);
connect(m_viewport, &ViewportWidget::planeSelected, m_appController, &ApplicationController::onPlaneSelected); connect(m_viewport, &ViewportWidget::planeSelected, m_appController, &ApplicationController::onPlaneSelected);
connect(m_viewport, &ViewportWidget::toolDeactivated, m_appController, [this]() { m_appController->setActiveTool(ApplicationController::ToolType::None); }); connect(m_viewport, &ViewportWidget::toolDeactivated, m_appController, [this]() { m_appController->setActiveTool(ApplicationController::ToolType::None); });
connect(m_viewport->camera(), &Camera::cameraChanged, this, &MainWindow::updateDebugInfo);
m_debugWindow = new DebugWindow(this);
if (QProcessEnvironment::systemEnvironment().value("DEBUG") == "true") {
showDebugWindow();
}
updateWindowTitle(QString()); updateWindowTitle(QString());
} }
@@ -179,6 +205,17 @@ bool MainWindow::saveAs()
return m_appController->saveDocumentAs(); return m_appController->saveDocumentAs();
} }
void MainWindow::showDebugWindow()
{
updateDebugInfo();
m_debugWindow->show();
}
void MainWindow::updateDebugInfo()
{
m_debugWindow->updateCameraInfo(m_viewport->camera());
}
void MainWindow::enterSketchMode() void MainWindow::enterSketchMode()
{ {
m_tabWidget->removeTab(m_tabWidget->indexOf(m_toolsTab)); m_tabWidget->removeTab(m_tabWidget->indexOf(m_toolsTab));
@@ -204,3 +241,19 @@ void MainWindow::updateWindowTitle(const QString& filePath)
shownName = "Untitled"; shownName = "Untitled";
setWindowTitle(tr("%1[*] - %2").arg(QFileInfo(shownName).fileName(), tr("OpenCAD"))); setWindowTitle(tr("%1[*] - %2").arg(QFileInfo(shownName).fileName(), tr("OpenCAD")));
} }
bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
if (m_appController->activeTool() != ApplicationController::ToolType::None && event->type() == QEvent::KeyPress) {
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
if (keyEvent->key() == Qt::Key_Tab || keyEvent->key() == Qt::Key_Backtab) {
if (watched == m_viewport) {
return false; // Let the viewport handle its own event
}
// Forward event to viewport and consume it
QApplication::sendEvent(m_viewport, keyEvent);
return true;
}
}
return QMainWindow::eventFilter(watched, event);
}

View File

@@ -1,14 +1,23 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#ifndef MAINWINDOW_H #ifndef MAINWINDOW_H
#define MAINWINDOW_H #define MAINWINDOW_H
#include <QMainWindow> #include <QMainWindow>
class QEvent;
class ViewportWidget; class ViewportWidget;
class Document; class Document;
class Feature; class Feature;
class QTabWidget; class QTabWidget;
class QWidget; class QWidget;
class ApplicationController; class ApplicationController;
class DebugWindow;
class MainWindow : public QMainWindow class MainWindow : public QMainWindow
{ {
@@ -25,13 +34,20 @@ private slots:
void createSketch(); void createSketch();
void saveSketch(); void saveSketch();
void showDebugWindow();
void updateDebugInfo();
void enterSketchMode(); void enterSketchMode();
void exitSketchMode(); void exitSketchMode();
void updateWindowTitle(const QString& filePath); void updateWindowTitle(const QString& filePath);
protected:
bool eventFilter(QObject *watched, QEvent *event) override;
private: private:
ApplicationController* m_appController; ApplicationController* m_appController;
ViewportWidget *m_viewport; ViewportWidget *m_viewport;
DebugWindow* m_debugWindow;
QTabWidget *m_tabWidget; QTabWidget *m_tabWidget;
QWidget *m_solidTab; QWidget *m_solidTab;

399
src/RectangleTool.cpp Normal file
View File

@@ -0,0 +1,399 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#include "RectangleTool.h"
#include "ViewportWidget.h"
#include "Camera.h"
#include <QMouseEvent>
#include <QKeyEvent>
#include <QPainter>
#include <QVector>
#include <QOpenGLShaderProgram>
#include <cmath>
#include <QtMath>
RectangleTool::RectangleTool(ViewportWidget* viewport)
: SketchTool(viewport)
{
}
void RectangleTool::activate()
{
SketchTool::activate();
m_dimensionModes << "height" << "width";
m_dimensionPropertyNames["height"] = "heightInput";
m_dimensionPropertyNames["width"] = "widthInput";
m_viewport->setProperty("widthInput", "");
m_viewport->setProperty("heightInput", "");
m_viewport->setProperty("dimensionEditMode", "height");
}
void RectangleTool::mousePressEvent(QMouseEvent *event)
{
gp_Pnt p;
if (!m_isDefining) {
if (m_viewport->isSnappingOrigin()) {
p.SetCoord(0, 0, 0);
} else if (m_viewport->isSnappingVertex()) {
p = m_viewport->snapVertex();
} else {
QVector3D worldPos = m_viewport->unproject(event->pos(), m_viewport->currentPlane());
p.SetCoord(worldPos.x(), worldPos.y(), worldPos.z());
}
m_firstRectanglePoint = p;
m_isDefining = true;
m_viewport->setProperty("widthInput", "");
m_viewport->setProperty("heightInput", "");
m_viewport->setProperty("dimensionEditMode", "height");
} else {
QVector3D worldPos;
QVector3D startPos(m_firstRectanglePoint.X(), m_firstRectanglePoint.Y(), m_firstRectanglePoint.Z());
QString widthInput = m_viewport->property("widthInput").toString();
QString heightInput = m_viewport->property("heightInput").toString();
bool widthFromInput = false, heightFromInput = false;
double inputWidth = 0, inputHeight = 0;
if (!widthInput.isEmpty()) {
bool ok;
inputWidth = widthInput.toDouble(&ok);
if (ok) widthFromInput = true;
}
if (!heightInput.isEmpty()) {
bool ok;
inputHeight = heightInput.toDouble(&ok);
if (ok) heightFromInput = true;
}
if (widthFromInput || heightFromInput) {
QVector3D mousePos = m_viewport->unproject(event->pos(), m_viewport->currentPlane());
QVector3D mouseDir = mousePos - startPos;
double current_w, current_h;
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) {
current_w = qAbs(mouseDir.x());
current_h = qAbs(mouseDir.y());
} else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) {
current_w = qAbs(mouseDir.x());
current_h = qAbs(mouseDir.z());
} else { // YZ
current_w = qAbs(mouseDir.y());
current_h = qAbs(mouseDir.z());
}
double rect_w = widthFromInput ? inputWidth : current_w;
double rect_h = heightFromInput ? inputHeight : current_h;
int signX = (mouseDir.x() >= 0) ? 1 : -1;
int signY = (mouseDir.y() >= 0) ? 1 : -1;
int signZ = (mouseDir.z() >= 0) ? 1 : -1;
worldPos = startPos;
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) {
worldPos.setX(startPos.x() + signX * rect_w);
worldPos.setY(startPos.y() + signY * rect_h);
} else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) {
worldPos.setX(startPos.x() + signX * rect_w);
worldPos.setZ(startPos.z() + signZ * rect_h);
} else { // YZ
worldPos.setY(startPos.y() + signY * rect_w);
worldPos.setZ(startPos.z() + signZ * rect_h);
}
} else {
if (m_viewport->isSnappingOrigin()) {
worldPos.setX(0); worldPos.setY(0); worldPos.setZ(0);
} else if (m_viewport->isSnappingVertex()) {
worldPos = QVector3D(m_viewport->snapVertex().X(), m_viewport->snapVertex().Y(), m_viewport->snapVertex().Z());
} else {
worldPos = m_viewport->unproject(event->pos(), m_viewport->currentPlane());
}
}
p.SetCoord(worldPos.x(), worldPos.y(), worldPos.z());
emit m_viewport->rectangleAdded(m_firstRectanglePoint, p);
deactivate();
}
}
void RectangleTool::mouseMoveEvent(QMouseEvent *event)
{
// To be implemented
}
void RectangleTool::finalizeCreation()
{
QVector3D worldPos;
QVector3D startPos(m_firstRectanglePoint.X(), m_firstRectanglePoint.Y(), m_firstRectanglePoint.Z());
QString widthInput = m_viewport->property("widthInput").toString();
QString heightInput = m_viewport->property("heightInput").toString();
bool widthFromInput = false, heightFromInput = false;
double inputWidth = 0, inputHeight = 0;
if (!widthInput.isEmpty()) {
bool ok;
inputWidth = widthInput.toDouble(&ok);
if (ok) widthFromInput = true;
}
if (!heightInput.isEmpty()) {
bool ok;
inputHeight = heightInput.toDouble(&ok);
if (ok) heightFromInput = true;
}
if (widthFromInput || heightFromInput) {
QVector3D mousePos = m_viewport->unproject(m_viewport->currentMousePos(), m_viewport->currentPlane());
QVector3D mouseDir = mousePos - startPos;
double current_w, current_h;
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) {
current_w = qAbs(mouseDir.x());
current_h = qAbs(mouseDir.y());
} else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) {
current_w = qAbs(mouseDir.x());
current_h = qAbs(mouseDir.z());
} else { // YZ
current_w = qAbs(mouseDir.y());
current_h = qAbs(mouseDir.z());
}
double rect_w = widthFromInput ? inputWidth : current_w;
double rect_h = heightFromInput ? inputHeight : current_h;
int signX = (mouseDir.x() >= 0) ? 1 : -1;
int signY = (mouseDir.y() >= 0) ? 1 : -1;
int signZ = (mouseDir.z() >= 0) ? 1 : -1;
worldPos = startPos;
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) {
worldPos.setX(startPos.x() + signX * rect_w);
worldPos.setY(startPos.y() + signY * rect_h);
} else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) {
worldPos.setX(startPos.x() + signX * rect_w);
worldPos.setZ(startPos.z() + signZ * rect_h);
} else { // YZ
worldPos.setY(startPos.y() + signY * rect_w);
worldPos.setZ(startPos.z() + signZ * rect_h);
}
} else {
worldPos = m_viewport->unproject(m_viewport->currentMousePos(), m_viewport->currentPlane());
}
gp_Pnt p;
p.SetCoord(worldPos.x(), worldPos.y(), worldPos.z());
emit m_viewport->rectangleAdded(m_firstRectanglePoint, p);
deactivate();
}
void RectangleTool::paintGL()
{
if (m_isDefining) {
QVector<GLfloat> vertices;
QVector3D worldPos;
QVector3D startPos(m_firstRectanglePoint.X(), m_firstRectanglePoint.Y(), m_firstRectanglePoint.Z());
QString widthInput = m_viewport->property("widthInput").toString();
QString heightInput = m_viewport->property("heightInput").toString();
bool widthFromInput = false;
bool heightFromInput = false;
double inputWidth = 0, inputHeight = 0;
if (!widthInput.isEmpty()) {
bool ok;
inputWidth = widthInput.toDouble(&ok);
if (ok) widthFromInput = true;
}
if (!heightInput.isEmpty()) {
bool ok;
inputHeight = heightInput.toDouble(&ok);
if (ok) heightFromInput = true;
}
QVector3D mousePos = m_viewport->unproject(m_viewport->currentMousePos(), m_viewport->currentPlane());
if (widthFromInput || heightFromInput) {
QVector3D mouseDir = mousePos - startPos;
double current_w, current_h;
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) {
current_w = qAbs(mouseDir.x());
current_h = qAbs(mouseDir.y());
} else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) {
current_w = qAbs(mouseDir.x());
current_h = qAbs(mouseDir.z());
} else { // YZ
current_w = qAbs(mouseDir.y());
current_h = qAbs(mouseDir.z());
}
double rect_w = widthFromInput ? inputWidth : current_w;
double rect_h = heightFromInput ? inputHeight : current_h;
int signX = (mouseDir.x() >= 0) ? 1 : -1;
int signY = (mouseDir.y() >= 0) ? 1 : -1;
int signZ = (mouseDir.z() >= 0) ? 1 : -1;
worldPos = startPos;
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) {
worldPos.setX(startPos.x() + signX * rect_w);
worldPos.setY(startPos.y() + signY * rect_h);
} else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) {
worldPos.setX(startPos.x() + signX * rect_w);
worldPos.setZ(startPos.z() + signZ * rect_h);
} else { // YZ
worldPos.setY(startPos.y() + signY * rect_w);
worldPos.setZ(startPos.z() + signZ * rect_h);
}
} else {
worldPos = mousePos;
if (m_viewport->isSnappingOrigin()) {
worldPos.setX(0); worldPos.setY(0); worldPos.setZ(0);
} else if (m_viewport->isSnappingVertex()) {
worldPos.setX(m_viewport->snapVertex().X()); worldPos.setY(m_viewport->snapVertex().Y()); worldPos.setZ(m_viewport->snapVertex().Z());
}
}
QVector3D p1 = startPos;
QVector3D p2, p3, p4;
p3 = worldPos;
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) {
p2.setX(p3.x()); p2.setY(p1.y()); p2.setZ(p1.z());
p4.setX(p1.x()); p4.setY(p3.y()); p4.setZ(p1.z());
} else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) {
p2.setX(p3.x()); p2.setY(p1.y()); p2.setZ(p1.z());
p4.setX(p1.x()); p4.setY(p1.y()); p4.setZ(p3.z());
} else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::YZ) {
p2.setX(p1.x()); p2.setY(p3.y()); p2.setZ(p1.z());
p4.setX(p1.x()); p4.setY(p1.y()); p4.setZ(p3.z());
}
vertices << p1.x() << p1.y() << p1.z();
vertices << p2.x() << p2.y() << p2.z();
vertices << p2.x() << p2.y() << p2.z();
vertices << p3.x() << p3.y() << p3.z();
vertices << p3.x() << p3.y() << p3.z();
vertices << p4.x() << p4.y() << p4.z();
vertices << p4.x() << p4.y() << p4.z();
vertices << p1.x() << p1.y() << p1.z();
m_viewport->shaderProgram()->setUniformValue(m_viewport->colorLoc(), QVector4D(1.0f, 1.0f, 0.0f, 1.0f));
m_viewport->vbo().bind();
m_viewport->vbo().allocate(vertices.constData(), vertices.size() * sizeof(GLfloat));
glDrawArrays(GL_LINES, 0, 8);
}
}
void RectangleTool::paint2D(QPainter& painter, const QMatrix4x4& modelView, const QMatrix4x4& projection)
{
if (m_isDefining) {
QVector3D worldPos;
QVector3D p1_3d(m_firstRectanglePoint.X(), m_firstRectanglePoint.Y(), m_firstRectanglePoint.Z());
QString widthInput = m_viewport->property("widthInput").toString();
QString heightInput = m_viewport->property("heightInput").toString();
bool widthFromInput = false;
bool heightFromInput = false;
double inputWidth = 0, inputHeight = 0;
if (!widthInput.isEmpty()) {
bool ok;
inputWidth = widthInput.toDouble(&ok);
if (ok) widthFromInput = true;
}
if (!heightInput.isEmpty()) {
bool ok;
inputHeight = heightInput.toDouble(&ok);
if (ok) heightFromInput = true;
}
QVector3D mousePos = m_viewport->unproject(m_viewport->currentMousePos(), m_viewport->currentPlane());
if (widthFromInput || heightFromInput) {
QVector3D mouseDir = mousePos - p1_3d;
double current_w, current_h;
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) {
current_w = qAbs(mouseDir.x());
current_h = qAbs(mouseDir.y());
} else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) {
current_w = qAbs(mouseDir.x());
current_h = qAbs(mouseDir.z());
} else { // YZ
current_w = qAbs(mouseDir.y());
current_h = qAbs(mouseDir.z());
}
double rect_w = widthFromInput ? inputWidth : current_w;
double rect_h = heightFromInput ? inputHeight : current_h;
int signX = (mouseDir.x() >= 0) ? 1 : -1;
int signY = (mouseDir.y() >= 0) ? 1 : -1;
int signZ = (mouseDir.z() >= 0) ? 1 : -1;
worldPos = p1_3d;
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) {
worldPos.setX(p1_3d.x() + signX * rect_w);
worldPos.setY(p1_3d.y() + signY * rect_h);
} else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) {
worldPos.setX(p1_3d.x() + signX * rect_w);
worldPos.setZ(p1_3d.z() + signZ * rect_h);
} else { // YZ
worldPos.setY(p1_3d.y() + signY * rect_w);
worldPos.setZ(p1_3d.z() + signZ * rect_h);
}
} else {
worldPos = mousePos;
if (m_viewport->isSnappingOrigin()) {
worldPos.setX(0); worldPos.setY(0); worldPos.setZ(0);
} else if (m_viewport->isSnappingVertex()) {
worldPos.setX(m_viewport->snapVertex().X()); worldPos.setY(m_viewport->snapVertex().Y()); worldPos.setZ(m_viewport->snapVertex().Z());
}
}
QVector3D p3_3d = worldPos;
QVector3D p2_3d, p4_3d;
double w, h;
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) {
p2_3d.setX(p3_3d.x()); p2_3d.setY(p1_3d.y()); p2_3d.setZ(p1_3d.z());
p4_3d.setX(p1_3d.x()); p4_3d.setY(p3_3d.y()); p4_3d.setZ(p1_3d.z());
w = qAbs(p3_3d.x() - p1_3d.x());
h = qAbs(p3_3d.y() - p1_3d.y());
} else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) {
p2_3d.setX(p3_3d.x()); p2_3d.setY(p1_3d.y()); p2_3d.setZ(p1_3d.z());
p4_3d.setX(p1_3d.x()); p4_3d.setY(p1_3d.y()); p4_3d.setZ(p3_3d.z());
w = qAbs(p3_3d.x() - p1_3d.x());
h = qAbs(p3_3d.z() - p1_3d.z());
} else { // YZ
p2_3d.setX(p1_3d.x()); p2_3d.setY(p3_3d.y()); p2_3d.setZ(p1_3d.z());
p4_3d.setX(p1_3d.x()); p4_3d.setY(p1_3d.y()); p4_3d.setZ(p3_3d.z());
w = qAbs(p3_3d.y() - p1_3d.y());
h = qAbs(p3_3d.z() - p1_3d.z());
}
painter.setRenderHint(QPainter::Antialiasing);
QFontMetrics fm(painter.font());
// Width dimension
QVector3D widthTextPos3D = (p1_3d + p2_3d) / 2.0f;
QVector3D screenPosW = m_viewport->project(widthTextPos3D, modelView, projection, m_viewport->rect());
if (screenPosW.z() < 1.0f) {
QString widthText = widthFromInput ? widthInput : QString::number(w, 'f', 2);
QRect textRect = fm.boundingRect(widthText + "__");
textRect.moveCenter(screenPosW.toPoint() + QPoint(0, (p3_3d.z() > p1_3d.z() || p3_3d.y() > p1_3d.y()) ? -15 : 15));
if (m_viewport->property("dimensionEditMode").toString() == "width") {
painter.fillRect(textRect.adjusted(-4, -2, 4, 2), QColor(64, 128, 255));
} else {
painter.fillRect(textRect.adjusted(-4, -2, 4, 2), QColor(50, 50, 50));
}
painter.setPen(Qt::white);
painter.drawText(textRect, Qt::AlignCenter, widthText);
}
// Height dimension
QVector3D heightTextPos3D = (p2_3d + p3_3d) / 2.0f;
QVector3D screenPosH = m_viewport->project(heightTextPos3D, modelView, projection, m_viewport->rect());
if (screenPosH.z() < 1.0f) {
QString heightText = heightFromInput ? heightInput : QString::number(h, 'f', 2);
QRect textRect = fm.boundingRect(heightText + "__");
textRect.moveCenter(screenPosH.toPoint() + QPoint((p3_3d.x() > p1_3d.x()) ? 15 : -15, 0));
if (m_viewport->property("dimensionEditMode").toString() == "height") {
painter.fillRect(textRect.adjusted(-4, -2, 4, 2), QColor(64, 128, 255));
} else {
painter.fillRect(textRect.adjusted(-4, -2, 4, 2), QColor(50, 50, 50));
}
painter.setPen(Qt::white);
painter.drawText(textRect, Qt::AlignCenter, heightText);
}
}
}

35
src/RectangleTool.h Normal file
View File

@@ -0,0 +1,35 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#ifndef RECTANGLETOOL_H
#define RECTANGLETOOL_H
#include "SketchTool.h"
#include <gp_Pnt.hxx>
class RectangleTool : public SketchTool
{
Q_OBJECT
public:
explicit RectangleTool(ViewportWidget* viewport);
void mousePressEvent(QMouseEvent *event) override;
void mouseMoveEvent(QMouseEvent *event) override;
void paintGL() override;
void paint2D(QPainter& painter, const QMatrix4x4& modelView, const QMatrix4x4& projection) override;
void activate() override;
protected:
void finalizeCreation() override;
private:
gp_Pnt m_firstRectanglePoint;
};
#endif // RECTANGLETOOL_H

63
src/SketchCircle.cpp Normal file
View File

@@ -0,0 +1,63 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#include "SketchCircle.h"
#include <QJsonArray>
namespace
{
void pointToJson(const gp_Pnt& p, QJsonArray& arr)
{
arr.append(p.X());
arr.append(p.Y());
arr.append(p.Z());
}
gp_Pnt jsonToPoint(const QJsonArray& arr)
{
return gp_Pnt(arr[0].toDouble(), arr[1].toDouble(), arr[2].toDouble());
}
}
SketchCircle::SketchCircle() : m_radius(0.0)
{
}
SketchCircle::SketchCircle(const gp_Pnt& center, double radius)
: m_center(center), m_radius(radius)
{
}
SketchObject::ObjectType SketchCircle::type() const
{
return ObjectType::Circle;
}
void SketchCircle::read(const QJsonObject& json)
{
m_center = jsonToPoint(json["center"].toArray());
m_radius = json["radius"].toDouble();
}
void SketchCircle::write(QJsonObject& json) const
{
QJsonArray centerArr;
pointToJson(m_center, centerArr);
json["center"] = centerArr;
json["radius"] = m_radius;
json["type"] = "Circle";
}
const gp_Pnt& SketchCircle::center() const
{
return m_center;
}
double SketchCircle::radius() const
{
return m_radius;
}

33
src/SketchCircle.h Normal file
View File

@@ -0,0 +1,33 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#ifndef SKETCHCIRCLE_H
#define SKETCHCIRCLE_H
#include "SketchObject.h"
#include <gp_Pnt.hxx>
class SketchCircle : public SketchObject
{
public:
SketchCircle();
SketchCircle(const gp_Pnt& center, double radius);
ObjectType type() const override;
void read(const QJsonObject& json) override;
void write(QJsonObject& json) const override;
const gp_Pnt& center() const;
double radius() const;
private:
gp_Pnt m_center;
double m_radius;
};
#endif // SKETCHCIRCLE_H

View File

@@ -1,6 +1,14 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#include "SketchFeature.h" #include "SketchFeature.h"
#include "SketchObject.h" #include "SketchObject.h"
#include "SketchLine.h" #include "SketchLine.h"
#include "SketchRectangle.h"
#include <QJsonArray> #include <QJsonArray>
@@ -66,6 +74,10 @@ void SketchFeature::read(const QJsonObject& json)
auto line = new SketchLine(); auto line = new SketchLine();
line->read(objectJson); line->read(objectJson);
m_objects.append(line); m_objects.append(line);
} else if (type == "Rectangle") {
auto rect = new SketchRectangle();
rect->read(objectJson);
m_objects.append(rect);
} }
} }
} }

View File

@@ -1,3 +1,10 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#ifndef SKETCHFEATURE_H #ifndef SKETCHFEATURE_H
#define SKETCHFEATURE_H #define SKETCHFEATURE_H

View File

@@ -1,10 +1,43 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#include "SketchGrid.h" #include "SketchGrid.h"
#include "ViewportWidget.h"
#include "Camera.h"
#include <QOpenGLContext> #include <QOpenGLContext>
#include <QOpenGLExtraFunctions> #include <QOpenGLExtraFunctions>
#include <QOpenGLShaderProgram> #include <QOpenGLShaderProgram>
#include <QPainter>
#include <QVector> #include <QVector>
SketchGrid::SketchGrid() namespace {
struct GridParams {
float minorIncrement;
float majorIncrement;
int gridSize;
};
GridParams getGridParams(float distance)
{
if (distance > 500.0f) {
return { 20.0f, 100.0f, 1000 };
} else if (distance > 250.0f) {
return { 10.0f, 50.0f, 1000 };
} else if (distance > 50.0f) {
return { 5.0f, 25.0f, 1000 };
} else if (distance > 10.0f) {
return { 1.0f, 5.0f, 100 };
} else { // zoomed in
return { 0.2f, 1.0f, 10 };
}
}
} // namespace
SketchGrid::SketchGrid(ViewportWidget* viewport) : m_viewport(viewport)
{ {
} }
@@ -46,45 +79,51 @@ void SketchGrid::paintGL(SketchPlane plane, QOpenGLShaderProgram* shaderProgram,
void SketchGrid::drawGridLines(SketchPlane plane, QOpenGLShaderProgram* shaderProgram, int colorLoc) void SketchGrid::drawGridLines(SketchPlane plane, QOpenGLShaderProgram* shaderProgram, int colorLoc)
{ {
const int gridSize = 50; auto params = getGridParams(-m_viewport->camera()->uiCameraDistance());
const float darkFactor = 0.8f; const float minorIncrement = params.minorIncrement;
QVector<GLfloat> lightLines; const int gridSize = params.gridSize;
QVector<GLfloat> darkLines;
for (int i = -gridSize; i <= gridSize; ++i) QVector<GLfloat> minorLines;
{ QVector<GLfloat> majorLines;
if (i == 0) continue;
QVector<GLfloat>& current_vector = (i % 5 == 0) ? darkLines : lightLines; int numLines = gridSize / minorIncrement;
for (int i = -numLines; i <= numLines; ++i) {
if (i == 0)
continue;
float pos = i * minorIncrement;
QVector<GLfloat>& current_vector = (i % 5 == 0) ? majorLines : minorLines;
if (plane == XY) { if (plane == XY) {
current_vector << i << 0 << -gridSize << i << 0 << gridSize; current_vector << pos << -gridSize << 0 << pos << gridSize << 0;
current_vector << -gridSize << 0 << i << gridSize << 0 << i; current_vector << -gridSize << pos << 0 << gridSize << pos << 0;
} else if (plane == XZ) { } else if (plane == XZ) {
current_vector << i << -gridSize << 0 << i << gridSize << 0; current_vector << pos << 0 << -gridSize << pos << 0 << gridSize;
current_vector << -gridSize << i << 0 << gridSize << i << 0; current_vector << -gridSize << 0 << pos << gridSize << 0 << pos;
} else { // YZ } else { // YZ
current_vector << 0 << i << -gridSize << 0 << i << gridSize; current_vector << 0 << pos << -gridSize << 0 << pos << gridSize;
current_vector << 0 << -gridSize << i << 0 << gridSize << i; current_vector << 0 << -gridSize << pos << 0 << gridSize << pos;
} }
} }
m_vbo.bind(); m_vbo.bind();
// Draw lighter lines // Draw minor lines
shaderProgram->setUniformValue(colorLoc, QVector4D(0.5f, 0.5f, 0.5f, 1.0f)); shaderProgram->setUniformValue(colorLoc, QVector4D(0.4f, 0.4f, 0.4f, 1.0f));
glLineWidth(1.0f); glLineWidth(1.0f);
m_vbo.allocate(lightLines.constData(), lightLines.size() * sizeof(GLfloat)); m_vbo.allocate(minorLines.constData(), minorLines.size() * sizeof(GLfloat));
glDrawArrays(GL_LINES, 0, lightLines.size() / 3); glDrawArrays(GL_LINES, 0, minorLines.size() / 3);
// Draw darker lines // Draw major lines
shaderProgram->setUniformValue(colorLoc, QVector4D(0.5f * darkFactor, 0.5f * darkFactor, 0.5f * darkFactor, 1.0f)); shaderProgram->setUniformValue(colorLoc, QVector4D(0.6f, 0.6f, 0.6f, 1.0f));
glLineWidth(1.5f); glLineWidth(1.0f);
m_vbo.allocate(darkLines.constData(), darkLines.size() * sizeof(GLfloat)); m_vbo.allocate(majorLines.constData(), majorLines.size() * sizeof(GLfloat));
glDrawArrays(GL_LINES, 0, darkLines.size() / 3); glDrawArrays(GL_LINES, 0, majorLines.size() / 3);
} }
void SketchGrid::drawAxes(SketchPlane plane, QOpenGLShaderProgram* shaderProgram, int colorLoc) void SketchGrid::drawAxes(SketchPlane plane, QOpenGLShaderProgram* shaderProgram, int colorLoc)
{ {
const int axisLength = 50; auto params = getGridParams(-m_viewport->camera()->uiCameraDistance());
const int axisLength = params.gridSize;
QVector<GLfloat> vertices; QVector<GLfloat> vertices;
glLineWidth(2.0f); glLineWidth(2.0f);
@@ -101,7 +140,7 @@ void SketchGrid::drawAxes(SketchPlane plane, QOpenGLShaderProgram* shaderProgram
// Y Axis (Green) // Y Axis (Green)
if (plane == XY || plane == YZ) { if (plane == XY || plane == YZ) {
vertices.clear(); vertices.clear();
vertices << 0 << 0 << -axisLength << 0 << 0 << axisLength; vertices << 0 << -axisLength << 0 << 0 << axisLength << 0;
shaderProgram->setUniformValue(colorLoc, QVector4D(0.0f, 1.0f, 0.0f, 1.0f)); shaderProgram->setUniformValue(colorLoc, QVector4D(0.0f, 1.0f, 0.0f, 1.0f));
m_vbo.allocate(vertices.constData(), vertices.size() * sizeof(GLfloat)); m_vbo.allocate(vertices.constData(), vertices.size() * sizeof(GLfloat));
glDrawArrays(GL_LINES, 0, 2); glDrawArrays(GL_LINES, 0, 2);
@@ -109,7 +148,7 @@ void SketchGrid::drawAxes(SketchPlane plane, QOpenGLShaderProgram* shaderProgram
// Z Axis (Blue) // Z Axis (Blue)
if (plane == XZ || plane == YZ) { if (plane == XZ || plane == YZ) {
vertices.clear(); vertices.clear();
vertices << 0 << -axisLength << 0 << 0 << axisLength << 0; vertices << 0 << 0 << -axisLength << 0 << 0 << axisLength;
shaderProgram->setUniformValue(colorLoc, QVector4D(0.0f, 0.0f, 1.0f, 1.0f)); shaderProgram->setUniformValue(colorLoc, QVector4D(0.0f, 0.0f, 1.0f, 1.0f));
m_vbo.allocate(vertices.constData(), vertices.size() * sizeof(GLfloat)); m_vbo.allocate(vertices.constData(), vertices.size() * sizeof(GLfloat));
glDrawArrays(GL_LINES, 0, 2); glDrawArrays(GL_LINES, 0, 2);
@@ -123,3 +162,41 @@ void SketchGrid::drawAxes(SketchPlane plane, QOpenGLShaderProgram* shaderProgram
m_vbo.allocate(vertices.constData(), vertices.size() * sizeof(GLfloat)); m_vbo.allocate(vertices.constData(), vertices.size() * sizeof(GLfloat));
glDrawArrays(GL_POINTS, 0, 1); glDrawArrays(GL_POINTS, 0, 1);
} }
void SketchGrid::paintAxisLabels(QPainter& painter, SketchGrid::SketchPlane plane, const QMatrix4x4& modelView, const QMatrix4x4& projection)
{
painter.setPen(Qt::white);
painter.setFont(QFont("Arial", 10));
auto params = getGridParams(-m_viewport->camera()->uiCameraDistance());
const float majorIncrement = params.majorIncrement;
const int range = params.gridSize;
auto drawLabelsForAxis = [&](int axis_idx) {
int numLabels = range / majorIncrement;
for (int i = -numLabels; i <= numLabels; ++i) {
if (i == 0)
continue;
float val = i * majorIncrement;
QVector3D worldCoord;
worldCoord[axis_idx] = val;
QVector3D screenPos = m_viewport->project(worldCoord, modelView, projection, m_viewport->rect());
if (screenPos.z() < 1.0f) { // Not clipped
painter.drawText(screenPos.toPoint(), QString::number(val));
}
}
};
if (plane == SketchGrid::XY) {
drawLabelsForAxis(0); // X
drawLabelsForAxis(1); // Y
} else if (plane == SketchGrid::XZ) {
drawLabelsForAxis(0); // X
drawLabelsForAxis(2); // Z
} else if (plane == SketchGrid::YZ) {
drawLabelsForAxis(1); // Y
drawLabelsForAxis(2); // Z
}
}

View File

@@ -1,3 +1,10 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#ifndef SKETCHGRID_H #ifndef SKETCHGRID_H
#define SKETCHGRID_H #define SKETCHGRID_H
@@ -7,6 +14,8 @@
#include <QOpenGLBuffer> #include <QOpenGLBuffer>
class QOpenGLShaderProgram; class QOpenGLShaderProgram;
class QPainter;
class ViewportWidget;
class SketchGrid : protected QOpenGLFunctions class SketchGrid : protected QOpenGLFunctions
{ {
@@ -17,11 +26,12 @@ public:
YZ = 3 YZ = 3
}; };
SketchGrid(); explicit SketchGrid(ViewportWidget* viewport);
~SketchGrid(); ~SketchGrid();
void initializeGL(); void initializeGL();
void paintGL(SketchPlane plane, QOpenGLShaderProgram* shaderProgram, int colorLoc); void paintGL(SketchPlane plane, QOpenGLShaderProgram* shaderProgram, int colorLoc);
void paintAxisLabels(QPainter& painter, SketchPlane plane, const QMatrix4x4& modelView, const QMatrix4x4& projection);
private: private:
void drawGridLines(SketchPlane plane, QOpenGLShaderProgram* shaderProgram, int colorLoc); void drawGridLines(SketchPlane plane, QOpenGLShaderProgram* shaderProgram, int colorLoc);
@@ -29,6 +39,7 @@ private:
QOpenGLVertexArrayObject m_vao; QOpenGLVertexArrayObject m_vao;
QOpenGLBuffer m_vbo; QOpenGLBuffer m_vbo;
ViewportWidget* m_viewport = nullptr;
}; };
#endif // SKETCHGRID_H #endif // SKETCHGRID_H

View File

@@ -1,3 +1,10 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#include "SketchLine.h" #include "SketchLine.h"
#include <QJsonObject> #include <QJsonObject>

View File

@@ -1,3 +1,10 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#ifndef SKETCHLINE_H #ifndef SKETCHLINE_H
#define SKETCHLINE_H #define SKETCHLINE_H

View File

@@ -1,3 +1,10 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#ifndef SKETCHOBJECT_H #ifndef SKETCHOBJECT_H
#define SKETCHOBJECT_H #define SKETCHOBJECT_H
@@ -7,7 +14,9 @@ class SketchObject
{ {
public: public:
enum class ObjectType { enum class ObjectType {
Line Line,
Rectangle,
Circle
}; };
SketchObject() = default; SketchObject() = default;

68
src/SketchRectangle.cpp Normal file
View File

@@ -0,0 +1,68 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#include "SketchRectangle.h"
#include <QJsonArray>
namespace
{
void pointToJson(const gp_Pnt& p, QJsonArray& arr)
{
arr.append(p.X());
arr.append(p.Y());
arr.append(p.Z());
}
gp_Pnt jsonToPoint(const QJsonArray& arr)
{
return gp_Pnt(arr[0].toDouble(), arr[1].toDouble(), arr[2].toDouble());
}
}
SketchRectangle::SketchRectangle()
{
}
SketchRectangle::SketchRectangle(const gp_Pnt& corner1, const gp_Pnt& corner2)
: m_corner1(corner1), m_corner2(corner2)
{
}
SketchObject::ObjectType SketchRectangle::type() const
{
return ObjectType::Rectangle;
}
void SketchRectangle::read(const QJsonObject& json)
{
if (json.contains("corner1") && json["corner1"].isArray()) {
m_corner1 = jsonToPoint(json["corner1"].toArray());
}
if (json.contains("corner2") && json["corner2"].isArray()) {
m_corner2 = jsonToPoint(json["corner2"].toArray());
}
}
void SketchRectangle::write(QJsonObject& json) const
{
json["type"] = "Rectangle";
QJsonArray c1, c2;
pointToJson(m_corner1, c1);
pointToJson(m_corner2, c2);
json["corner1"] = c1;
json["corner2"] = c2;
}
const gp_Pnt& SketchRectangle::corner1() const
{
return m_corner1;
}
const gp_Pnt& SketchRectangle::corner2() const
{
return m_corner2;
}

33
src/SketchRectangle.h Normal file
View File

@@ -0,0 +1,33 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#ifndef SKETCHRECTANGLE_H
#define SKETCHRECTANGLE_H
#include "SketchObject.h"
#include <gp_Pnt.hxx>
class SketchRectangle : public SketchObject
{
public:
SketchRectangle();
SketchRectangle(const gp_Pnt& corner1, const gp_Pnt& corner2);
ObjectType type() const override;
void read(const QJsonObject& json) override;
void write(QJsonObject& json) const override;
const gp_Pnt& corner1() const;
const gp_Pnt& corner2() const;
private:
gp_Pnt m_corner1;
gp_Pnt m_corner2;
};
#endif // SKETCHRECTANGLE_H

86
src/SketchTool.cpp Normal file
View File

@@ -0,0 +1,86 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#include "SketchTool.h"
#include "ViewportWidget.h"
#include <QKeyEvent>
SketchTool::SketchTool(ViewportWidget* viewport)
: QObject(viewport), m_viewport(viewport)
{
}
void SketchTool::activate()
{
m_isDefining = false;
}
void SketchTool::deactivate()
{
m_isDefining = false;
for (const QString& propName : m_dimensionPropertyNames.values()) {
m_viewport->setProperty(propName.toUtf8().constData(), "");
}
m_dimensionModes.clear();
m_dimensionPropertyNames.clear();
}
void SketchTool::keyPressEvent(QKeyEvent *event)
{
if (m_isDefining) {
if (event->key() == Qt::Key_Tab) {
if (m_dimensionModes.size() > 1) {
QString currentMode = m_viewport->property("dimensionEditMode").toString();
int currentIndex = m_dimensionModes.indexOf(currentMode);
if (currentIndex != -1) {
int nextIndex = (currentIndex + 1) % m_dimensionModes.size();
m_viewport->setProperty("dimensionEditMode", m_dimensionModes[nextIndex]);
m_viewport->update();
}
}
return;
}
QString editMode = m_viewport->property("dimensionEditMode").toString();
if (m_dimensionPropertyNames.contains(editMode)) {
QString propertyName = m_dimensionPropertyNames[editMode];
QString currentInput = m_viewport->property(propertyName.toUtf8().constData()).toString();
if (event->key() >= Qt::Key_0 && event->key() <= Qt::Key_9) {
currentInput += event->text();
m_viewport->setProperty(propertyName.toUtf8().constData(), currentInput);
m_viewport->update();
return;
} else if (event->key() == Qt::Key_Period) {
if (!currentInput.contains('.')) {
currentInput += '.';
m_viewport->setProperty(propertyName.toUtf8().constData(), currentInput);
m_viewport->update();
}
return;
} else if (event->key() == Qt::Key_Backspace) {
if (!currentInput.isEmpty()) {
currentInput.chop(1);
m_viewport->setProperty(propertyName.toUtf8().constData(), currentInput);
m_viewport->update();
}
return;
}
}
if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) {
finalizeCreation();
m_viewport->update();
return;
} else if (event->key() == Qt::Key_Escape) {
deactivate();
m_viewport->deactivateActiveTool();
m_viewport->update();
return;
}
}
}

47
src/SketchTool.h Normal file
View File

@@ -0,0 +1,47 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#ifndef SKETCHTOOL_H
#define SKETCHTOOL_H
#include <QObject>
#include <QStringList>
#include <QMap>
class QMouseEvent;
class QKeyEvent;
class ViewportWidget;
class QOpenGLShaderProgram;
class QPainter;
class QMatrix4x4;
class SketchTool : public QObject
{
Q_OBJECT
public:
explicit SketchTool(ViewportWidget* viewport);
virtual ~SketchTool() = default;
virtual void mousePressEvent(QMouseEvent *event) = 0;
virtual void mouseMoveEvent(QMouseEvent *event) = 0;
virtual void keyPressEvent(QKeyEvent *event);
virtual void paintGL() = 0;
virtual void paint2D(QPainter& painter, const QMatrix4x4& modelView, const QMatrix4x4& projection) = 0;
virtual void activate();
virtual void deactivate();
protected:
virtual void finalizeCreation() = 0;
ViewportWidget* m_viewport;
bool m_isDefining = false;
QStringList m_dimensionModes;
QMap<QString, QString> m_dimensionPropertyNames;
};
#endif // SKETCHTOOL_H

192
src/Snapping.cpp Normal file
View File

@@ -0,0 +1,192 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#include "Snapping.h"
#include "ViewportWidget.h"
#include "Camera.h"
#include "Document.h"
#include "SketchFeature.h"
#include "SketchLine.h"
#include "SketchRectangle.h"
#include "SketchObject.h"
#include "ApplicationController.h"
#include <QOpenGLShaderProgram>
#include <QVector>
#include <QtMath>
Snapping::Snapping(ViewportWidget* viewport) : m_viewport(viewport)
{
}
bool Snapping::update(const QPoint& mousePos)
{
bool oldIsSnappingOrigin = m_isSnappingOrigin;
bool oldIsSnappingVertex = m_isSnappingVertex;
bool shouldSnap = false;
if (m_viewport->currentPlane() != ViewportWidget::SketchPlane::NONE && m_viewport->activeTool() != static_cast<int>(ApplicationController::ToolType::None)) {
QVector3D worldPos = m_viewport->unproject(mousePos, m_viewport->currentPlane());
const float snapRectHalfSize = 0.0075f * -m_viewport->camera()->zoom();
switch (m_viewport->currentPlane()) {
case ViewportWidget::SketchPlane::XY:
shouldSnap = qAbs(worldPos.x()) < snapRectHalfSize && qAbs(worldPos.y()) < snapRectHalfSize;
break;
case ViewportWidget::SketchPlane::XZ:
shouldSnap = qAbs(worldPos.x()) < snapRectHalfSize && qAbs(worldPos.z()) < snapRectHalfSize;
break;
case ViewportWidget::SketchPlane::YZ:
shouldSnap = qAbs(worldPos.y()) < snapRectHalfSize && qAbs(worldPos.z()) < snapRectHalfSize;
break;
case ViewportWidget::SketchPlane::NONE:
break;
}
}
m_isSnappingOrigin = shouldSnap;
if (m_isSnappingOrigin) {
m_isSnappingVertex = false;
}
m_isSnappingVertex = false;
if (!m_isSnappingOrigin && m_viewport->document() && m_viewport->currentPlane() != ViewportWidget::SketchPlane::NONE && m_viewport->activeTool() != static_cast<int>(ApplicationController::ToolType::None)) {
QVector3D worldPos = m_viewport->unproject(mousePos, m_viewport->currentPlane());
const float snapRectHalfSize = 0.0075f * -m_viewport->camera()->zoom();
for (Feature* feature : m_viewport->document()->features()) {
if (auto sketch = dynamic_cast<SketchFeature*>(feature)) {
for (const auto& obj : sketch->objects()) {
if (obj->type() == SketchObject::ObjectType::Line) {
auto line = static_cast<const SketchLine*>(obj);
const gp_Pnt vertices[] = {line->startPoint(), line->endPoint()};
for (const auto& vertex : vertices) {
bool isClose = false;
switch (m_viewport->currentPlane()) {
case ViewportWidget::SketchPlane::XY:
isClose = qAbs(worldPos.x() - vertex.X()) < snapRectHalfSize && qAbs(worldPos.y() - vertex.Y()) < snapRectHalfSize;
break;
case ViewportWidget::SketchPlane::XZ:
isClose = qAbs(worldPos.x() - vertex.X()) < snapRectHalfSize && qAbs(worldPos.z() - vertex.Z()) < snapRectHalfSize;
break;
case ViewportWidget::SketchPlane::YZ:
isClose = qAbs(worldPos.y() - vertex.Y()) < snapRectHalfSize && qAbs(worldPos.z() - vertex.Z()) < snapRectHalfSize;
break;
case ViewportWidget::SketchPlane::NONE:
break;
}
if (isClose) {
m_isSnappingVertex = true;
m_snapVertex = vertex;
goto end_snap_check;
}
}
} else if (obj->type() == SketchObject::ObjectType::Rectangle) {
auto rect = static_cast<const SketchRectangle*>(obj);
const auto& p1 = rect->corner1();
const auto& p3 = rect->corner2();
gp_Pnt p2, p4;
if (sketch->plane() == SketchFeature::SketchPlane::XY) {
p2.SetCoord(p3.X(), p1.Y(), p1.Z());
p4.SetCoord(p1.X(), p3.Y(), p1.Z());
} else if (sketch->plane() == SketchFeature::SketchPlane::XZ) {
p2.SetCoord(p3.X(), p1.Y(), p1.Z());
p4.SetCoord(p1.X(), p1.Y(), p3.Z());
} else if (sketch->plane() == SketchFeature::SketchPlane::YZ) {
p2.SetCoord(p1.X(), p3.Y(), p1.Z());
p4.SetCoord(p1.X(), p1.Y(), p3.Z());
}
const gp_Pnt vertices[] = {p1, p2, p3, p4};
for (const auto& vertex : vertices) {
bool isClose = false;
switch (m_viewport->currentPlane()) {
case ViewportWidget::SketchPlane::XY:
isClose = qAbs(worldPos.x() - vertex.X()) < snapRectHalfSize && qAbs(worldPos.y() - vertex.Y()) < snapRectHalfSize;
break;
case ViewportWidget::SketchPlane::XZ:
isClose = qAbs(worldPos.x() - vertex.X()) < snapRectHalfSize && qAbs(worldPos.z() - vertex.Z()) < snapRectHalfSize;
break;
case ViewportWidget::SketchPlane::YZ:
isClose = qAbs(worldPos.y() - vertex.Y()) < snapRectHalfSize && qAbs(worldPos.z() - vertex.Z()) < snapRectHalfSize;
break;
case ViewportWidget::SketchPlane::NONE:
break;
}
if (isClose) {
m_isSnappingVertex = true;
m_snapVertex = vertex;
goto end_snap_check;
}
}
}
}
}
}
end_snap_check:;
}
return (oldIsSnappingOrigin != m_isSnappingOrigin) || (oldIsSnappingVertex != m_isSnappingVertex);
}
void Snapping::paintGL() const
{
if (!m_isSnappingOrigin && !m_isSnappingVertex) {
return;
}
QVector<GLfloat> vertices;
if (m_isSnappingOrigin) {
const float rectSize = 0.0075f * -m_viewport->camera()->zoom();
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) {
vertices << -rectSize << -rectSize << 0 << rectSize << -rectSize << 0;
vertices << rectSize << -rectSize << 0 << rectSize << rectSize << 0;
vertices << rectSize << rectSize << 0 << -rectSize << rectSize << 0;
vertices << -rectSize << rectSize << 0 << -rectSize << -rectSize << 0;
} else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) {
vertices << -rectSize << 0 << -rectSize << rectSize << 0 << -rectSize;
vertices << rectSize << 0 << -rectSize << rectSize << 0 << rectSize;
vertices << rectSize << 0 << rectSize << -rectSize << 0 << rectSize;
vertices << -rectSize << 0 << rectSize << -rectSize << 0 << -rectSize;
} else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::YZ) {
vertices << 0 << -rectSize << -rectSize << 0 << rectSize << -rectSize;
vertices << 0 << rectSize << -rectSize << 0 << rectSize << rectSize;
vertices << 0 << rectSize << rectSize << 0 << -rectSize << rectSize;
vertices << 0 << -rectSize << rectSize << 0 << -rectSize << -rectSize;
}
} else if (m_isSnappingVertex) {
const float rectSize = 0.0075f * -m_viewport->camera()->zoom();
const auto& v = m_snapVertex;
if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XY) {
vertices << v.X() - rectSize << v.Y() - rectSize << v.Z() << v.X() + rectSize << v.Y() - rectSize << v.Z();
vertices << v.X() + rectSize << v.Y() - rectSize << v.Z() << v.X() + rectSize << v.Y() + rectSize << v.Z();
vertices << v.X() + rectSize << v.Y() + rectSize << v.Z() << v.X() - rectSize << v.Y() + rectSize << v.Z();
vertices << v.X() - rectSize << v.Y() + rectSize << v.Z() << v.X() - rectSize << v.Y() - rectSize << v.Z();
} else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::XZ) {
vertices << v.X() - rectSize << v.Y() << v.Z() - rectSize << v.X() + rectSize << v.Y() << v.Z() - rectSize;
vertices << v.X() + rectSize << v.Y() << v.Z() - rectSize << v.X() + rectSize << v.Y() << v.Z() + rectSize;
vertices << v.X() + rectSize << v.Y() << v.Z() + rectSize << v.X() - rectSize << v.Y() << v.Z() + rectSize;
vertices << v.X() - rectSize << v.Y() << v.Z() + rectSize << v.X() - rectSize << v.Y() << v.Z() - rectSize;
} else if (m_viewport->currentPlane() == ViewportWidget::SketchPlane::YZ) {
vertices << v.X() << v.Y() - rectSize << v.Z() - rectSize << v.X() << v.Y() + rectSize << v.Z() - rectSize;
vertices << v.X() << v.Y() + rectSize << v.Z() - rectSize << v.X() << v.Y() + rectSize << v.Z() + rectSize;
vertices << v.X() << v.Y() + rectSize << v.Z() + rectSize << v.X() << v.Y() - rectSize << v.Z() + rectSize;
vertices << v.X() << v.Y() - rectSize << v.Z() + rectSize << v.X() << v.Y() - rectSize << v.Z() - rectSize;
}
}
m_viewport->shaderProgram()->setUniformValue(m_viewport->colorLoc(), QVector4D(1.0f, 1.0f, 0.0f, 0.5f));
m_viewport->vbo().bind();
m_viewport->vbo().allocate(vertices.constData(), vertices.size() * sizeof(GLfloat));
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDrawArrays(GL_LINES, 0, vertices.size() / 3);
glDisable(GL_BLEND);
}

35
src/Snapping.h Normal file
View File

@@ -0,0 +1,35 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#ifndef SNAPPING_H
#define SNAPPING_H
#include <gp_Pnt.hxx>
#include <QPoint>
class ViewportWidget;
class Snapping
{
public:
explicit Snapping(ViewportWidget* viewport);
bool update(const QPoint& mousePos);
void paintGL() const;
bool isSnappingOrigin() const { return m_isSnappingOrigin; }
bool isSnappingVertex() const { return m_isSnappingVertex; }
const gp_Pnt& snapVertex() const { return m_snapVertex; }
private:
ViewportWidget* m_viewport = nullptr;
bool m_isSnappingOrigin = false;
bool m_isSnappingVertex = false;
gp_Pnt m_snapVertex;
};
#endif // SNAPPING_H

View File

@@ -1,12 +1,38 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#include "ViewCube.h" #include "ViewCube.h"
#include <QGuiApplication>
#include <QPainter> #include <QPainter>
#include <QFont> #include <QFont>
#include <QOpenGLShaderProgram> #include <QOpenGLShaderProgram>
#include <QOpenGLTexture> #include <QOpenGLTexture>
#include <QScreen>
#include <QSvgRenderer>
#include <QVector> #include <QVector>
#include <QVector3D>
namespace
{
QRect getHomeButtonRect(int widgetWidth) {
const int viewCubeSize = 150; // logical pixels
const int buttonSize = 24;
const int buttonOffsetX = 16;
const int buttonOffsetY = 16;
const int viewCubeX = widgetWidth - viewCubeSize;
return QRect(viewCubeX + buttonOffsetX, buttonOffsetY, buttonSize, buttonSize);
}
}
ViewCube::ViewCube() ViewCube::ViewCube()
{ {
m_homeButtonRenderer = new QSvgRenderer(QString(":/icons/home.svg"));
for (int i = 0; i < 6; ++i) { for (int i = 0; i < 6; ++i) {
m_faceTextures[i] = nullptr; m_faceTextures[i] = nullptr;
} }
@@ -18,6 +44,7 @@ ViewCube::~ViewCube()
delete m_faceTextures[i]; delete m_faceTextures[i];
} }
delete m_textureShaderProgram; delete m_textureShaderProgram;
delete m_homeButtonRenderer;
m_cubeVbo.destroy(); m_cubeVbo.destroy();
m_cubeVao.destroy(); m_cubeVao.destroy();
m_axesVbo.destroy(); m_axesVbo.destroy();
@@ -32,17 +59,59 @@ void ViewCube::initializeGL()
setupBuffers(); setupBuffers();
} }
void ViewCube::paintGL(QOpenGLShaderProgram* simpleShader, int simpleShaderColorLoc, const QMatrix4x4& viewMatrix, int width, int height) void ViewCube::paintGL(QOpenGLShaderProgram* simpleShader, int simpleShaderColorLoc, const QMatrix4x4& viewMatrix, int width, int height, const QPoint& mousePos)
{ {
int viewCubeSize = 150; int viewCubeSize = 150 * QGuiApplication::primaryScreen()->devicePixelRatio();
glViewport(width - viewCubeSize, height - viewCubeSize, viewCubeSize, viewCubeSize); glViewport(width - viewCubeSize, height - viewCubeSize, viewCubeSize, viewCubeSize);
QRect viewCubeRect(width - viewCubeSize, 0, viewCubeSize, viewCubeSize);
QPoint physicalMousePos = mousePos * QGuiApplication::primaryScreen()->devicePixelRatio();
m_isHovered = viewCubeRect.contains(physicalMousePos);
float opacity = m_isHovered ? 1.0f : 0.5f;
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glClear(GL_DEPTH_BUFFER_BIT); glClear(GL_DEPTH_BUFFER_BIT);
QMatrix4x4 viewCubeProjection; QMatrix4x4 viewCubeProjection;
viewCubeProjection.ortho(-2, 2, -2, 2, -10, 10); viewCubeProjection.ortho(-2, 2, -2, 2, -10, 10);
drawViewCube(viewCubeProjection, viewMatrix); drawViewCube(viewCubeProjection, viewMatrix, opacity);
drawAxes(simpleShader, simpleShaderColorLoc, viewCubeProjection, viewMatrix); drawAxes(simpleShader, simpleShaderColorLoc, viewCubeProjection, viewMatrix);
QMatrix4x4 mvp = viewCubeProjection * viewMatrix;
const float axisLen = 1.7f;
QVector3D xAxisEnd(axisLen, 0.0f, 0.0f);
QVector3D yAxisEnd(0.0f, 0.0f, axisLen);
QVector3D zAxisEnd(0.0f, axisLen, 0.0f);
QVector3D xAxisNdc = mvp.map(xAxisEnd);
QVector3D yAxisNdc = mvp.map(yAxisEnd);
QVector3D zAxisNdc = mvp.map(zAxisEnd);
const int vpX = width - viewCubeSize;
const int vpY = 0;
const int vpW = viewCubeSize;
const int vpH = viewCubeSize;
const float dpr = QGuiApplication::primaryScreen()->devicePixelRatio();
m_xAxisLabelPos.setX( (xAxisNdc.x() + 1.0f) * vpW / 2.0f + vpX );
m_xAxisLabelPos.setY( (1.0f - xAxisNdc.y()) * vpH / 2.0f + vpY );
m_xAxisLabelPos /= dpr;
m_yAxisLabelPos.setX( (yAxisNdc.x() + 1.0f) * vpW / 2.0f + vpX );
m_yAxisLabelPos.setY( (1.0f - yAxisNdc.y()) * vpH / 2.0f + vpY );
m_yAxisLabelPos /= dpr;
m_zAxisLabelPos.setX( (zAxisNdc.x() + 1.0f) * vpW / 2.0f + vpX );
m_zAxisLabelPos.setY( (1.0f - zAxisNdc.y()) * vpH / 2.0f + vpY );
m_zAxisLabelPos /= dpr;
glDisable(GL_BLEND);
} }
void ViewCube::createFaceTextures() void ViewCube::createFaceTextures()
@@ -144,7 +213,7 @@ void ViewCube::setupBuffers()
m_axesVbo.release(); m_axesVbo.release();
} }
void ViewCube::drawViewCube(const QMatrix4x4& projection, const QMatrix4x4& view) void ViewCube::drawViewCube(const QMatrix4x4& projection, const QMatrix4x4& view, float opacity)
{ {
if (!m_textureShaderProgram || !m_textureShaderProgram->isLinked()) return; if (!m_textureShaderProgram || !m_textureShaderProgram->isLinked()) return;
@@ -153,6 +222,7 @@ void ViewCube::drawViewCube(const QMatrix4x4& projection, const QMatrix4x4& view
m_textureShaderProgram->setUniformValue("projectionMatrix", projection); m_textureShaderProgram->setUniformValue("projectionMatrix", projection);
m_textureShaderProgram->setUniformValue("modelViewMatrix", view); m_textureShaderProgram->setUniformValue("modelViewMatrix", view);
m_textureShaderProgram->setUniformValue("texture_diffuse1", 0); m_textureShaderProgram->setUniformValue("texture_diffuse1", 0);
m_textureShaderProgram->setUniformValue("opacity", opacity);
QOpenGLVertexArrayObject::Binder vaoBinder(&m_cubeVao); QOpenGLVertexArrayObject::Binder vaoBinder(&m_cubeVao);
for (int i = 0; i < 6; ++i) { for (int i = 0; i < 6; ++i) {
@@ -193,3 +263,44 @@ void ViewCube::drawAxes(QOpenGLShaderProgram* simpleShader, int colorLoc, const
glLineWidth(1.0f); glLineWidth(1.0f);
} }
void ViewCube::paint2D(QPainter& painter, int widgetWidth, int widgetHeight)
{
QFont font("Arial", 10, QFont::Bold);
painter.setFont(font);
painter.setPen(Qt::white);
QFontMetrics fm(font);
QRect xRect = fm.boundingRect("X");
xRect.moveCenter(m_xAxisLabelPos);
painter.drawText(xRect, Qt::AlignCenter, "X");
QRect yRect = fm.boundingRect("Y");
yRect.moveCenter(m_yAxisLabelPos);
painter.drawText(yRect, Qt::AlignCenter, "Y");
QRect zRect = fm.boundingRect("Z");
zRect.moveCenter(m_zAxisLabelPos);
painter.drawText(zRect, Qt::AlignCenter, "Z");
if (!m_isHovered) {
return;
}
m_homeButtonRect = getHomeButtonRect(widgetWidth);
if (m_homeButtonRenderer && m_homeButtonRenderer->isValid()) {
m_homeButtonRenderer->render(&painter, m_homeButtonRect);
}
}
bool ViewCube::handleMousePress(const QPoint& pos, int widgetWidth, int widgetHeight)
{
if (!m_isHovered) {
return false;
}
QRect homeButtonRect = getHomeButtonRect(widgetWidth);
return homeButtonRect.contains(pos);
}

View File

@@ -1,3 +1,10 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#ifndef VIEWCUBE_H #ifndef VIEWCUBE_H
#define VIEWCUBE_H #define VIEWCUBE_H
@@ -5,9 +12,12 @@
#include <QMatrix4x4> #include <QMatrix4x4>
#include <QOpenGLVertexArrayObject> #include <QOpenGLVertexArrayObject>
#include <QOpenGLBuffer> #include <QOpenGLBuffer>
#include <QPoint>
class QOpenGLShaderProgram; class QOpenGLShaderProgram;
class QOpenGLTexture; class QOpenGLTexture;
class QPainter;
class QSvgRenderer;
class ViewCube : protected QOpenGLFunctions class ViewCube : protected QOpenGLFunctions
{ {
@@ -16,15 +26,25 @@ public:
~ViewCube(); ~ViewCube();
void initializeGL(); void initializeGL();
void paintGL(QOpenGLShaderProgram* simpleShader, int simpleShaderColorLoc, const QMatrix4x4& viewMatrix, int width, int height); void paintGL(QOpenGLShaderProgram* simpleShader, int simpleShaderColorLoc, const QMatrix4x4& viewMatrix, int width, int height, const QPoint& mousePos);
void paint2D(QPainter& painter, int widgetWidth, int widgetHeight);
bool handleMousePress(const QPoint& pos, int widgetWidth, int widgetHeight);
private: private:
void createFaceTextures(); void createFaceTextures();
void initShaders(); void initShaders();
void setupBuffers(); void setupBuffers();
void drawViewCube(const QMatrix4x4& projection, const QMatrix4x4& view); void drawViewCube(const QMatrix4x4& projection, const QMatrix4x4& view, float opacity);
void drawAxes(QOpenGLShaderProgram* simpleShader, int colorLoc, const QMatrix4x4& projection, const QMatrix4x4& view); void drawAxes(QOpenGLShaderProgram* simpleShader, int colorLoc, const QMatrix4x4& projection, const QMatrix4x4& view);
bool m_isHovered = false;
QRect m_homeButtonRect;
QSvgRenderer* m_homeButtonRenderer = nullptr;
QPoint m_xAxisLabelPos;
QPoint m_yAxisLabelPos;
QPoint m_zAxisLabelPos;
QOpenGLTexture* m_faceTextures[6]; QOpenGLTexture* m_faceTextures[6];
QOpenGLShaderProgram* m_textureShaderProgram = nullptr; QOpenGLShaderProgram* m_textureShaderProgram = nullptr;

View File

@@ -1,4 +1,12 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#include "ViewportWidget.h" #include "ViewportWidget.h"
#include "Snapping.h"
#include "Camera.h" #include "Camera.h"
#include "ViewCube.h" #include "ViewCube.h"
#include "SketchGrid.h" #include "SketchGrid.h"
@@ -6,8 +14,13 @@
#include "FeatureBrowser.h" #include "FeatureBrowser.h"
#include "SketchFeature.h" #include "SketchFeature.h"
#include "SketchLine.h" #include "SketchLine.h"
#include "SketchRectangle.h"
#include "SketchCircle.h"
#include "SketchObject.h" #include "SketchObject.h"
#include "ApplicationController.h" #include "ApplicationController.h"
#include "RectangleTool.h"
#include "LineTool.h"
#include "CircleTool.h"
#include <QMouseEvent> #include <QMouseEvent>
#include <QKeyEvent> #include <QKeyEvent>
#include <QWheelEvent> #include <QWheelEvent>
@@ -18,13 +31,11 @@
#include <QSvgRenderer> #include <QSvgRenderer>
#include <QWheelEvent> #include <QWheelEvent>
#include <QApplication> #include <QApplication>
#include <QPropertyAnimation>
#include <QParallelAnimationGroup>
#include <cmath> #include <cmath>
#include <QtMath> #include <QtMath>
#include <QOpenGLShaderProgram> #include <QOpenGLShaderProgram>
#include <QVector> #include <QVector>
#include <QMap> #include <map>
struct PntComparator { struct PntComparator {
bool operator()(const gp_Pnt& a, const gp_Pnt& b) const { bool operator()(const gp_Pnt& a, const gp_Pnt& b) const {
@@ -42,8 +53,9 @@ ViewportWidget::ViewportWidget(QWidget *parent)
{ {
m_camera = new Camera(this); m_camera = new Camera(this);
connect(m_camera, &Camera::cameraChanged, this, QOverload<>::of(&QWidget::update)); connect(m_camera, &Camera::cameraChanged, this, QOverload<>::of(&QWidget::update));
connect(m_camera, &Camera::restoreStateAnimationFinished, this, &ViewportWidget::onRestoreStateAnimationFinished);
m_viewCube = new ViewCube(); m_viewCube = new ViewCube();
m_sketchGrid = new SketchGrid(); m_sketchGrid = new SketchGrid(this);
m_featureBrowser = new FeatureBrowser(); m_featureBrowser = new FeatureBrowser();
setMouseTracking(true); setMouseTracking(true);
setFocusPolicy(Qt::StrongFocus); setFocusPolicy(Qt::StrongFocus);
@@ -55,6 +67,12 @@ ViewportWidget::ViewportWidget(QWidget *parent)
m_toolIcons.insert(static_cast<int>(ApplicationController::ToolType::Circle), new QSvgRenderer(QString(":/icons/circle.svg"), this)); m_toolIcons.insert(static_cast<int>(ApplicationController::ToolType::Circle), new QSvgRenderer(QString(":/icons/circle.svg"), this));
m_cursorRenderer = new QSvgRenderer(QString(":/icons/cursor.svg"), this); m_cursorRenderer = new QSvgRenderer(QString(":/icons/cursor.svg"), this);
m_sketchTools.insert(static_cast<int>(ApplicationController::ToolType::Line), new LineTool(this));
m_sketchTools.insert(static_cast<int>(ApplicationController::ToolType::Rectangle), new RectangleTool(this));
m_sketchTools.insert(static_cast<int>(ApplicationController::ToolType::Circle), new CircleTool(this));
m_snapping = new Snapping(this);
} }
ViewportWidget::~ViewportWidget() ViewportWidget::~ViewportWidget()
@@ -68,6 +86,7 @@ ViewportWidget::~ViewportWidget()
doneCurrent(); doneCurrent();
delete m_featureBrowser; delete m_featureBrowser;
delete m_snapping;
} }
void ViewportWidget::setDocument(Document* document) void ViewportWidget::setDocument(Document* document)
@@ -102,8 +121,10 @@ void ViewportWidget::initializeGL()
void ViewportWidget::paintGL() void ViewportWidget::paintGL()
{ {
const qreal retinaScale = devicePixelRatio();
// Main scene rendering // Main scene rendering
glViewport(0, 0, width(), height()); glViewport(0, 0, width() * retinaScale, height() * retinaScale);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (!m_shaderProgram || !m_shaderProgram->isLinked()) { if (!m_shaderProgram || !m_shaderProgram->isLinked()) {
@@ -142,117 +163,33 @@ void ViewportWidget::paintGL()
} }
} }
QVector<GLfloat> vertices; m_snapping->paintGL();
if (m_isSnappingOrigin) {
const float rectSize = 0.0075f * -m_camera->zoom(); if (m_camera->isRotating()) {
if (m_currentPlane == SketchPlane::XY) { const float radius = 0.004f * -m_camera->uiCameraDistance();
vertices << -rectSize << 0 << -rectSize << rectSize << 0 << -rectSize; const int numSegments = 16;
vertices << rectSize << 0 << -rectSize << rectSize << 0 << rectSize; QMatrix4x4 invModelView = m_camera->modelViewMatrix().inverted();
vertices << rectSize << 0 << rectSize << -rectSize << 0 << rectSize; QVector3D rightVec = invModelView.column(0).toVector3D();
vertices << -rectSize << 0 << rectSize << -rectSize << 0 << -rectSize; QVector3D upVec = invModelView.column(1).toVector3D();
} else if (m_currentPlane == SketchPlane::XZ) {
vertices << -rectSize << -rectSize << 0 << rectSize << -rectSize << 0; QVector<GLfloat> circleFillVertices;
vertices << rectSize << -rectSize << 0 << rectSize << rectSize << 0; QVector3D center = m_camera->rotationPivot();
vertices << rectSize << rectSize << 0 << -rectSize << rectSize << 0;
vertices << -rectSize << rectSize << 0 << -rectSize << -rectSize << 0; circleFillVertices << center.x() << center.y() << center.z(); // Center vertex for fan
} else if (m_currentPlane == SketchPlane::YZ) { for (int i = 0; i <= numSegments; ++i) { // <= to close the circle
vertices << 0 << -rectSize << -rectSize << 0 << rectSize << -rectSize; float angle = (2.0f * M_PI * float(i)) / float(numSegments);
vertices << 0 << rectSize << -rectSize << 0 << rectSize << rectSize; QVector3D p = center + radius * (cos(angle) * rightVec + sin(angle) * upVec);
vertices << 0 << rectSize << rectSize << 0 << -rectSize << rectSize; circleFillVertices << p.x() << p.y() << p.z();
vertices << 0 << -rectSize << rectSize << 0 << -rectSize << -rectSize;
} }
m_shaderProgram->setUniformValue(m_colorLoc, QVector4D(1.0f, 1.0f, 0.0f, 0.5f));
m_shaderProgram->setUniformValue(m_colorLoc, QVector4D(0.0f, 0.0f, 1.0f, 1.0f)); // Blue
m_vbo.bind(); m_vbo.bind();
m_vbo.allocate(vertices.constData(), vertices.size() * sizeof(GLfloat)); m_vbo.allocate(circleFillVertices.constData(), circleFillVertices.size() * sizeof(GLfloat));
glEnable(GL_BLEND); glDrawArrays(GL_TRIANGLE_FAN, 0, circleFillVertices.size() / 3);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDrawArrays(GL_LINES, 0, vertices.size() / 3);
glDisable(GL_BLEND);
} else if (m_isSnappingVertex) {
const float rectSize = 0.0075f * -m_camera->zoom();
const auto& v = m_snapVertex;
if (m_currentPlane == SketchPlane::XY) {
vertices << v.X() - rectSize << v.Y() << v.Z() - rectSize << v.X() + rectSize << v.Y() << v.Z() - rectSize;
vertices << v.X() + rectSize << v.Y() << v.Z() - rectSize << v.X() + rectSize << v.Y() << v.Z() + rectSize;
vertices << v.X() + rectSize << v.Y() << v.Z() + rectSize << v.X() - rectSize << v.Y() << v.Z() + rectSize;
vertices << v.X() - rectSize << v.Y() << v.Z() + rectSize << v.X() - rectSize << v.Y() << v.Z() - rectSize;
} else if (m_currentPlane == SketchPlane::XZ) {
vertices << v.X() - rectSize << v.Y() - rectSize << v.Z() << v.X() + rectSize << v.Y() - rectSize << v.Z();
vertices << v.X() + rectSize << v.Y() - rectSize << v.Z() << v.X() + rectSize << v.Y() + rectSize << v.Z();
vertices << v.X() + rectSize << v.Y() + rectSize << v.Z() << v.X() - rectSize << v.Y() + rectSize << v.Z();
vertices << v.X() - rectSize << v.Y() + rectSize << v.Z() << v.X() - rectSize << v.Y() - rectSize << v.Z();
} else if (m_currentPlane == SketchPlane::YZ) {
vertices << v.X() << v.Y() - rectSize << v.Z() - rectSize << v.X() << v.Y() + rectSize << v.Z() - rectSize;
vertices << v.X() << v.Y() + rectSize << v.Z() - rectSize << v.X() << v.Y() + rectSize << v.Z() + rectSize;
vertices << v.X() << v.Y() + rectSize << v.Z() + rectSize << v.X() << v.Y() - rectSize << v.Z() + rectSize;
vertices << v.X() << v.Y() - rectSize << v.Z() + rectSize << v.X() << v.Y() - rectSize << v.Z() - rectSize;
}
m_shaderProgram->setUniformValue(m_colorLoc, QVector4D(1.0f, 1.0f, 0.0f, 0.5f));
m_vbo.bind();
m_vbo.allocate(vertices.constData(), vertices.size() * sizeof(GLfloat));
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDrawArrays(GL_LINES, 0, vertices.size() / 3);
glDisable(GL_BLEND);
} }
if (m_isDefiningLine && m_activeTool == static_cast<int>(ApplicationController::ToolType::Line)) { if (m_activeSketchTool) {
vertices.clear(); m_activeSketchTool->paintGL();
QVector3D worldPos = unproject(m_currentMousePos, m_currentPlane);
if (m_isSnappingOrigin) {
worldPos.setX(0); worldPos.setY(0); worldPos.setZ(0);
} else if (m_isSnappingVertex) {
worldPos.setX(m_snapVertex.X()); worldPos.setY(m_snapVertex.Y()); worldPos.setZ(m_snapVertex.Z());
} else if (m_isSnappingHorizontal) {
if (m_currentPlane == SketchPlane::XY) worldPos.setZ(m_firstLinePoint.Z());
else if (m_currentPlane == SketchPlane::XZ) worldPos.setY(m_firstLinePoint.Y());
else if (m_currentPlane == SketchPlane::YZ) worldPos.setZ(m_firstLinePoint.Z());
} else if (m_isSnappingVertical) {
if (m_currentPlane == SketchPlane::XY) worldPos.setX(m_firstLinePoint.X());
else if (m_currentPlane == SketchPlane::XZ) worldPos.setX(m_firstLinePoint.X());
else if (m_currentPlane == SketchPlane::YZ) worldPos.setY(m_firstLinePoint.Y());
}
vertices << m_firstLinePoint.X() << m_firstLinePoint.Y() << m_firstLinePoint.Z();
vertices << worldPos.x() << worldPos.y() << worldPos.z();
m_shaderProgram->setUniformValue(m_colorLoc, QVector4D(1.0f, 1.0f, 0.0f, 1.0f));
m_vbo.bind();
m_vbo.allocate(vertices.constData(), vertices.size() * sizeof(GLfloat));
glDrawArrays(GL_LINES, 0, 2);
if (m_isSnappingHorizontal || m_isSnappingVertical) {
vertices.clear();
QVector3D startPos(m_firstLinePoint.X(), m_firstLinePoint.Y(), m_firstLinePoint.Z());
QVector3D midPoint = (startPos + worldPos) / 2.0;
const float indicatorSize = 0.02f * -m_camera->zoom();
const float indicatorOffset = 0.02f * -m_camera->zoom();
if (m_isSnappingHorizontal) {
if (m_currentPlane == SketchPlane::XY) {
vertices << midPoint.x() - indicatorSize << midPoint.y() << midPoint.z() + indicatorOffset;
vertices << midPoint.x() + indicatorSize << midPoint.y() << midPoint.z() + indicatorOffset;
} else if (m_currentPlane == SketchPlane::XZ) {
vertices << midPoint.x() - indicatorSize << midPoint.y() + indicatorOffset << midPoint.z();
vertices << midPoint.x() + indicatorSize << midPoint.y() + indicatorOffset << midPoint.z();
} else if (m_currentPlane == SketchPlane::YZ) {
vertices << midPoint.x() << midPoint.y() - indicatorSize << midPoint.z() + indicatorOffset;
vertices << midPoint.x() << midPoint.y() + indicatorSize << midPoint.z() + indicatorOffset;
}
} else { // m_isSnappingVertical
if (m_currentPlane == SketchPlane::XY) {
vertices << midPoint.x() + indicatorOffset << midPoint.y() << midPoint.z() - indicatorSize;
vertices << midPoint.x() + indicatorOffset << midPoint.y() << midPoint.z() + indicatorSize;
} else if (m_currentPlane == SketchPlane::XZ) {
vertices << midPoint.x() + indicatorOffset << midPoint.y() - indicatorSize << midPoint.z();
vertices << midPoint.x() + indicatorOffset << midPoint.y() + indicatorSize << midPoint.z();
} else if (m_currentPlane == SketchPlane::YZ) {
vertices << midPoint.x() << midPoint.y() + indicatorOffset << midPoint.z() - indicatorSize;
vertices << midPoint.x() << midPoint.y() + indicatorOffset << midPoint.z() + indicatorSize;
}
}
m_vbo.bind();
m_vbo.allocate(vertices.constData(), vertices.size() * sizeof(GLfloat));
glDrawArrays(GL_LINES, 0, 2);
}
} }
m_shaderProgram->release(); m_shaderProgram->release();
@@ -261,17 +198,26 @@ void ViewportWidget::paintGL()
QMatrix4x4 viewCubeModel; QMatrix4x4 viewCubeModel;
viewCubeModel.rotate(m_camera->xRotation() / 16.0f, 1, 0, 0); viewCubeModel.rotate(m_camera->xRotation() / 16.0f, 1, 0, 0);
viewCubeModel.rotate(m_camera->yRotation() / 16.0f, 0, 1, 0); viewCubeModel.rotate(m_camera->yRotation() / 16.0f, 0, 1, 0);
m_viewCube->paintGL(m_shaderProgram, m_colorLoc, viewCubeModel, width(), height()); m_viewCube->paintGL(m_shaderProgram, m_colorLoc, viewCubeModel, width() * retinaScale, height() * retinaScale, m_currentMousePos);
glViewport(0, 0, width(), height()); glViewport(0, 0, width() * retinaScale, height() * retinaScale);
glDisable(GL_DEPTH_TEST); glDisable(GL_DEPTH_TEST);
glDisable(GL_CULL_FACE); glDisable(GL_CULL_FACE);
QPainter painter(this); QPainter painter(this);
if (m_currentPlane != SketchPlane::NONE) { if (m_currentPlane != SketchPlane::NONE) {
drawAxisLabels(painter, model, projection); m_sketchGrid->paintAxisLabels(painter, static_cast<SketchGrid::SketchPlane>(m_currentPlane), model, projection);
} }
m_featureBrowser->paint(painter, width(), height()); m_featureBrowser->paint(painter, width(), height());
m_viewCube->paint2D(painter, width(), height());
if (m_activeSketchTool) {
m_activeSketchTool->paint2D(painter, model, projection);
}
painter.setPen(Qt::white);
painter.drawText(width() - 350, height() - 10, QString("Camera Distance: %1").arg(-m_camera->uiCameraDistance()));
painter.end(); painter.end();
} }
@@ -279,12 +225,25 @@ void ViewportWidget::paintGL()
void ViewportWidget::resizeGL(int w, int h) void ViewportWidget::resizeGL(int w, int h)
{ {
projection.setToIdentity(); projection.setToIdentity();
projection.perspective(45.0f, w / float(h), 0.01f, 100.0f); projection.perspective(45.0f, w / float(h), 0.01f, 10000.0f);
} }
void ViewportWidget::mousePressEvent(QMouseEvent *event) void ViewportWidget::mousePressEvent(QMouseEvent *event)
{ {
m_camera->mousePressEvent(event);
if (event->button() == Qt::MiddleButton && !(QApplication::keyboardModifiers() & Qt::ShiftModifier)) {
m_camera->startRotation(unproject(event->pos(), m_currentPlane));
update();
}
if (event->button() == Qt::LeftButton) { if (event->button() == Qt::LeftButton) {
if (m_viewCube->handleMousePress(event->pos(), width(), height())) {
m_camera->animateToHomeView();
update();
return;
}
if (m_isSelectingPlane) { if (m_isSelectingPlane) {
if (m_highlightedPlane != SketchPlane::NONE) { if (m_highlightedPlane != SketchPlane::NONE) {
emit planeSelected(m_highlightedPlane); emit planeSelected(m_highlightedPlane);
@@ -295,37 +254,12 @@ void ViewportWidget::mousePressEvent(QMouseEvent *event)
return; return;
} }
if (m_currentPlane != SketchPlane::NONE && m_activeTool == static_cast<int>(ApplicationController::ToolType::Line)) { if (m_activeSketchTool) {
gp_Pnt p; m_activeSketchTool->mousePressEvent(event);
if (m_isSnappingOrigin) { update();
p.SetCoord(0, 0, 0); return;
} else if (m_isSnappingVertex) {
p = m_snapVertex;
} else {
QVector3D worldPos = unproject(event->pos(), m_currentPlane);
if (m_isSnappingHorizontal) {
if (m_currentPlane == SketchPlane::XY) worldPos.setZ(m_firstLinePoint.Z());
else if (m_currentPlane == SketchPlane::XZ) worldPos.setY(m_firstLinePoint.Y());
else if (m_currentPlane == SketchPlane::YZ) worldPos.setZ(m_firstLinePoint.Z());
} else if (m_isSnappingVertical) {
if (m_currentPlane == SketchPlane::XY) worldPos.setX(m_firstLinePoint.X());
else if (m_currentPlane == SketchPlane::XZ) worldPos.setX(m_firstLinePoint.X());
else if (m_currentPlane == SketchPlane::YZ) worldPos.setY(m_firstLinePoint.Y());
}
p.SetCoord(worldPos.x(), worldPos.y(), worldPos.z());
} }
if (!m_isDefiningLine) {
m_firstLinePoint = p;
m_isDefiningLine = true;
} else {
emit lineAdded(m_firstLinePoint, p);
m_firstLinePoint = p;
}
update();
}
} else {
lastPos = event->pos();
} }
} }
@@ -341,208 +275,106 @@ void ViewportWidget::mouseMoveEvent(QMouseEvent *event)
} }
} }
bool shouldSnap = false; if (m_snapping->update(m_currentMousePos)) {
if (m_currentPlane != SketchPlane::NONE && m_activeTool != static_cast<int>(ApplicationController::ToolType::None)) {
QVector3D worldPos = unproject(m_currentMousePos, m_currentPlane);
const float snapRectHalfSize = 0.0075f * -m_camera->zoom();
switch (m_currentPlane) {
case SketchPlane::XY:
shouldSnap = qAbs(worldPos.x()) < snapRectHalfSize && qAbs(worldPos.z()) < snapRectHalfSize;
break;
case SketchPlane::XZ:
shouldSnap = qAbs(worldPos.x()) < snapRectHalfSize && qAbs(worldPos.y()) < snapRectHalfSize;
break;
case SketchPlane::YZ:
shouldSnap = qAbs(worldPos.y()) < snapRectHalfSize && qAbs(worldPos.z()) < snapRectHalfSize;
break;
case SketchPlane::NONE:
break;
}
}
if (shouldSnap != m_isSnappingOrigin) {
m_isSnappingOrigin = shouldSnap;
if (m_isSnappingOrigin) {
m_isSnappingVertex = false;
}
update(); update();
} }
bool oldIsSnappingVertex = m_isSnappingVertex; if (m_activeSketchTool) {
m_isSnappingVertex = false; m_activeSketchTool->mouseMoveEvent(event);
if (!m_isSnappingOrigin && m_document && m_currentPlane != SketchPlane::NONE && m_activeTool != static_cast<int>(ApplicationController::ToolType::None)) {
QVector3D worldPos = unproject(m_currentMousePos, m_currentPlane);
const float snapRectHalfSize = 0.0075f * -m_camera->zoom();
for (Feature* feature : m_document->features()) {
if (auto sketch = dynamic_cast<SketchFeature*>(feature)) {
for (const auto& obj : sketch->objects()) {
if (obj->type() == SketchObject::ObjectType::Line) {
auto line = static_cast<const SketchLine*>(obj);
const gp_Pnt vertices[] = {line->startPoint(), line->endPoint()};
for (const auto& vertex : vertices) {
bool isClose = false;
switch (m_currentPlane) {
case SketchPlane::XY:
isClose = qAbs(worldPos.x() - vertex.X()) < snapRectHalfSize && qAbs(worldPos.z() - vertex.Z()) < snapRectHalfSize;
break;
case SketchPlane::XZ:
isClose = qAbs(worldPos.x() - vertex.X()) < snapRectHalfSize && qAbs(worldPos.y() - vertex.Y()) < snapRectHalfSize;
break;
case SketchPlane::YZ:
isClose = qAbs(worldPos.y() - vertex.Y()) < snapRectHalfSize && qAbs(worldPos.z() - vertex.Z()) < snapRectHalfSize;
break;
case SketchPlane::NONE:
break;
}
if (isClose) {
m_isSnappingVertex = true;
m_snapVertex = vertex;
goto end_snap_check;
}
}
}
}
}
}
end_snap_check:;
} }
if (oldIsSnappingVertex != m_isSnappingVertex) { m_camera->mouseMoveEvent(event, height());
update();
}
bool oldIsSnappingHorizontal = m_isSnappingHorizontal;
bool oldIsSnappingVertical = m_isSnappingVertical;
m_isSnappingHorizontal = false;
m_isSnappingVertical = false;
if (m_isDefiningLine && !m_isSnappingOrigin && !m_isSnappingVertex) {
QVector3D worldPos = unproject(m_currentMousePos, m_currentPlane);
QVector3D startPos(m_firstLinePoint.X(), m_firstLinePoint.Y(), m_firstLinePoint.Z());
QVector3D delta = worldPos - startPos;
if (delta.length() > 1e-6) {
const double snapAngleThreshold = qDegreesToRadians(2.0);
double angle = 0;
if (m_currentPlane == SketchPlane::XY) {
angle = atan2(delta.z(), delta.x());
} else if (m_currentPlane == SketchPlane::XZ) {
angle = atan2(delta.y(), delta.x());
} else if (m_currentPlane == SketchPlane::YZ) {
angle = atan2(delta.z(), delta.y());
}
if (qAbs(sin(angle)) < sin(snapAngleThreshold)) {
m_isSnappingHorizontal = true;
} else if (qAbs(cos(angle)) < sin(snapAngleThreshold)) {
m_isSnappingVertical = true;
}
}
}
if (oldIsSnappingHorizontal != m_isSnappingHorizontal || oldIsSnappingVertical != m_isSnappingVertical) {
update();
}
if (event->buttons() & Qt::MiddleButton) {
m_camera->processMouseMovement(event, lastPos);
}
lastPos = event->pos();
update(); update();
} }
void ViewportWidget::wheelEvent(QWheelEvent *event) void ViewportWidget::wheelEvent(QWheelEvent *event)
{ {
m_camera->processWheel(event); QVector3D worldPos = unproject(event->position().toPoint(), m_currentPlane);
m_camera->wheelEvent(event, worldPos);
} }
void ViewportWidget::keyPressEvent(QKeyEvent *event) void ViewportWidget::keyPressEvent(QKeyEvent *event)
{ {
if (m_activeSketchTool) {
m_activeSketchTool->keyPressEvent(event);
return;
}
if (event->key() == Qt::Key_Escape) { if (event->key() == Qt::Key_Escape) {
if (m_isDefiningLine) { if (m_isSelectingPlane) {
m_isDefiningLine = false;
emit toolDeactivated();
update();
return;
}
if (m_isSelectingPlane) {
m_isSelectingPlane = false; m_isSelectingPlane = false;
m_highlightedPlane = SketchPlane::NONE; m_highlightedPlane = SketchPlane::NONE;
m_currentPlane = SketchPlane::XY; m_currentPlane = SketchPlane::XY;
update(); update();
return; return;
}
else if (m_activeTool) {
emit toolDeactivated();
update();
return;
} }
} }
QOpenGLWidget::keyPressEvent(event); QOpenGLWidget::keyPressEvent(event);
} }
void ViewportWidget::mouseReleaseEvent(QMouseEvent *event)
{
if (event->button() == Qt::MiddleButton) {
m_camera->stopRotation();
update();
}
QOpenGLWidget::mouseReleaseEvent(event);
}
void ViewportWidget::addLine(const gp_Pnt& start, const gp_Pnt& end)
{
emit lineAdded(start, end);
}
void ViewportWidget::deactivateActiveTool()
{
emit toolDeactivated();
}
bool ViewportWidget::isSnappingOrigin() const
{
return m_snapping->isSnappingOrigin();
}
bool ViewportWidget::isSnappingVertex() const
{
return m_snapping->isSnappingVertex();
}
const gp_Pnt& ViewportWidget::snapVertex() const
{
return m_snapping->snapVertex();
}
void ViewportWidget::setSnappingHorizontal(bool snapping)
{
m_isSnappingHorizontal = snapping;
}
void ViewportWidget::setSnappingVertical(bool snapping)
{
m_isSnappingVertical = snapping;
}
bool ViewportWidget::focusNextPrevChild(bool next)
{
if (m_activeTool != static_cast<int>(ApplicationController::ToolType::None)) {
return false;
}
return QOpenGLWidget::focusNextPrevChild(next);
}
void ViewportWidget::onSketchModeStarted(SketchPlane plane) void ViewportWidget::onSketchModeStarted(SketchPlane plane)
{ {
m_currentPlane = plane; m_currentPlane = plane;
m_camera->saveState(); m_camera->saveState();
m_camera->animateToPlaneView(static_cast<int>(plane));
float targetXRot = m_camera->xRotation();
float targetYRot = m_camera->yRotation();
switch (plane) {
case SketchPlane::XY: // Top view
targetXRot = 90 * 16;
targetYRot = 0;
break;
case SketchPlane::XZ: // Front view
targetXRot = 0;
targetYRot = 0;
break;
case SketchPlane::YZ: // Right view
targetXRot = 0;
targetYRot = -90 * 16;
break;
case SketchPlane::NONE:
break;
}
auto* animGroup = new QParallelAnimationGroup(this);
auto* xRotAnim = new QPropertyAnimation(m_camera, "xRotation");
xRotAnim->setDuration(300);
xRotAnim->setStartValue(m_camera->xRotation());
xRotAnim->setEndValue(targetXRot);
xRotAnim->setEasingCurve(QEasingCurve::InOutQuad);
animGroup->addAnimation(xRotAnim);
auto* yRotAnim = new QPropertyAnimation(m_camera, "yRotation");
yRotAnim->setDuration(300);
yRotAnim->setStartValue(m_camera->yRotation());
yRotAnim->setEndValue(targetYRot);
yRotAnim->setEasingCurve(QEasingCurve::InOutQuad);
animGroup->addAnimation(yRotAnim);
auto* panXAnim = new QPropertyAnimation(m_camera, "panX");
panXAnim->setDuration(300);
panXAnim->setStartValue(m_camera->panX());
panXAnim->setEndValue(0.0f);
panXAnim->setEasingCurve(QEasingCurve::InOutQuad);
animGroup->addAnimation(panXAnim);
auto* panYAnim = new QPropertyAnimation(m_camera, "panY");
panYAnim->setDuration(300);
panYAnim->setStartValue(m_camera->panY());
panYAnim->setEndValue(0.0f);
panYAnim->setEasingCurve(QEasingCurve::InOutQuad);
animGroup->addAnimation(panYAnim);
auto* zoomAnim = new QPropertyAnimation(m_camera, "zoom");
zoomAnim->setDuration(300);
zoomAnim->setStartValue(m_camera->zoom());
zoomAnim->setEndValue(-20.0f);
zoomAnim->setEasingCurve(QEasingCurve::InOutQuad);
animGroup->addAnimation(zoomAnim);
animGroup->start(QAbstractAnimation::DeleteWhenStopped);
} }
void ViewportWidget::onPlaneSelectionModeStarted() void ViewportWidget::onPlaneSelectionModeStarted()
@@ -555,50 +387,14 @@ void ViewportWidget::onPlaneSelectionModeStarted()
void ViewportWidget::onSketchModeEnded() void ViewportWidget::onSketchModeEnded()
{ {
auto* animGroup = new QParallelAnimationGroup(this); m_camera->animateRestoreState();
}
auto* xRotAnim = new QPropertyAnimation(m_camera, "xRotation"); void ViewportWidget::onRestoreStateAnimationFinished()
xRotAnim->setDuration(300); {
xRotAnim->setStartValue(m_camera->xRotation()); // Return to showing the base XY grid when not in a sketch
xRotAnim->setEndValue(m_camera->savedXRot()); m_currentPlane = SketchPlane::XY;
xRotAnim->setEasingCurve(QEasingCurve::InOutQuad); update();
animGroup->addAnimation(xRotAnim);
auto* yRotAnim = new QPropertyAnimation(m_camera, "yRotation");
yRotAnim->setDuration(300);
yRotAnim->setStartValue(m_camera->yRotation());
yRotAnim->setEndValue(m_camera->savedYRot());
yRotAnim->setEasingCurve(QEasingCurve::InOutQuad);
animGroup->addAnimation(yRotAnim);
auto* panXAnim = new QPropertyAnimation(m_camera, "panX");
panXAnim->setDuration(300);
panXAnim->setStartValue(m_camera->panX());
panXAnim->setEndValue(m_camera->savedPanX());
panXAnim->setEasingCurve(QEasingCurve::InOutQuad);
animGroup->addAnimation(panXAnim);
auto* panYAnim = new QPropertyAnimation(m_camera, "panY");
panYAnim->setDuration(300);
panYAnim->setStartValue(m_camera->panY());
panYAnim->setEndValue(m_camera->savedPanY());
panYAnim->setEasingCurve(QEasingCurve::InOutQuad);
animGroup->addAnimation(panYAnim);
auto* zoomAnim = new QPropertyAnimation(m_camera, "zoom");
zoomAnim->setDuration(300);
zoomAnim->setStartValue(m_camera->zoom());
zoomAnim->setEndValue(m_camera->savedZoom());
zoomAnim->setEasingCurve(QEasingCurve::InOutQuad);
animGroup->addAnimation(zoomAnim);
connect(animGroup, &QParallelAnimationGroup::finished, this, [this]() {
// Return to showing the base XY grid when not in a sketch
m_currentPlane = SketchPlane::XY;
update();
});
animGroup->start(QAbstractAnimation::DeleteWhenStopped);
} }
QVector3D ViewportWidget::project(const QVector3D& worldCoord, const QMatrix4x4& modelView, const QMatrix4x4& projection, const QRect& viewport) QVector3D ViewportWidget::project(const QVector3D& worldCoord, const QMatrix4x4& modelView, const QMatrix4x4& projection, const QRect& viewport)
@@ -616,43 +412,19 @@ QVector3D ViewportWidget::project(const QVector3D& worldCoord, const QMatrix4x4&
return QVector3D(winX, winY, (ndc.z() + 1.0) / 2.0); return QVector3D(winX, winY, (ndc.z() + 1.0) / 2.0);
} }
void ViewportWidget::drawAxisLabels(QPainter& painter, const QMatrix4x4& modelView, const QMatrix4x4& projection)
{
painter.setPen(Qt::white);
painter.setFont(QFont("Arial", 10));
const int range = 50;
const int step = 5;
auto drawLabelsForAxis = [&](int axis_idx) {
for (int i = -range; i <= range; i += step) {
if (i == 0) continue;
QVector3D worldCoord;
worldCoord[axis_idx] = i;
QVector3D screenPos = project(worldCoord, modelView, projection, rect());
if (screenPos.z() < 1.0f) { // Not clipped
painter.drawText(screenPos.toPoint(), QString::number(i));
}
}
};
if (m_currentPlane == SketchPlane::XY) {
drawLabelsForAxis(0); // X
drawLabelsForAxis(2); // Y
} else if (m_currentPlane == SketchPlane::XZ) {
drawLabelsForAxis(0); // X
drawLabelsForAxis(1); // Z
} else if (m_currentPlane == SketchPlane::YZ) {
drawLabelsForAxis(1); // Y
drawLabelsForAxis(2); // Z
}
}
void ViewportWidget::onActiveToolChanged(int tool) void ViewportWidget::onActiveToolChanged(int tool)
{ {
if (m_activeSketchTool) {
m_activeSketchTool->deactivate();
m_activeSketchTool = nullptr;
}
m_activeTool = tool; m_activeTool = tool;
m_isDefiningLine = false;
if (m_sketchTools.contains(tool)) {
m_activeSketchTool = m_sketchTools.value(tool);
m_activeSketchTool->activate();
}
if (tool == static_cast<int>(ApplicationController::ToolType::None)) { if (tool == static_cast<int>(ApplicationController::ToolType::None)) {
unsetCursor(); unsetCursor();
@@ -724,8 +496,8 @@ QVector3D ViewportWidget::unproject(const QPoint& screenPos, SketchPlane plane)
QVector3D planeNormal; QVector3D planeNormal;
switch (plane) { switch (plane) {
case SketchPlane::XY: planeNormal = QVector3D(0, 1, 0); break; case SketchPlane::XY: planeNormal = QVector3D(0, 0, 1); break;
case SketchPlane::XZ: planeNormal = QVector3D(0, 0, 1); break; case SketchPlane::XZ: planeNormal = QVector3D(0, 1, 0); break;
case SketchPlane::YZ: planeNormal = QVector3D(1, 0, 0); break; case SketchPlane::YZ: planeNormal = QVector3D(1, 0, 0); break;
case SketchPlane::NONE: return QVector3D(); case SketchPlane::NONE: return QVector3D();
} }
@@ -744,10 +516,9 @@ void ViewportWidget::drawSketch(const SketchFeature* sketch)
{ {
glDisable(GL_DEPTH_TEST); glDisable(GL_DEPTH_TEST);
glLineWidth(2.0f); glLineWidth(2.0f);
glPointSize(5.0f);
QVector<GLfloat> lineVertices; QVector<GLfloat> lineVertices;
QMap<gp_Pnt, int, PntComparator> vertexCounts; std::map<gp_Pnt, int, PntComparator> vertexCounts;
for (const auto& obj : sketch->objects()) { for (const auto& obj : sketch->objects()) {
if (obj->type() == SketchObject::ObjectType::Line) { if (obj->type() == SketchObject::ObjectType::Line) {
@@ -759,14 +530,69 @@ void ViewportWidget::drawSketch(const SketchFeature* sketch)
vertexCounts[start]++; vertexCounts[start]++;
vertexCounts[end]++; vertexCounts[end]++;
} } else if (obj->type() == SketchObject::ObjectType::Circle) {
} auto circle = static_cast<const SketchCircle*>(obj);
const auto& center = circle->center();
double radius = circle->radius();
QVector3D centerPos(center.X(), center.Y(), center.Z());
QVector<GLfloat> pointVertices; const int numSegments = 64;
for (auto it = vertexCounts.constBegin(); it != vertexCounts.constEnd(); ++it) { QVector3D u_axis, v_axis;
if (it.value() == 1) { switch (sketch->plane()) {
const gp_Pnt& p = it.key(); case SketchFeature::SketchPlane::XY: // Top
pointVertices << p.X() << p.Y() << p.Z(); u_axis = QVector3D(1, 0, 0);
v_axis = QVector3D(0, 1, 0);
break;
case SketchFeature::SketchPlane::XZ: // Front
u_axis = QVector3D(1, 0, 0);
v_axis = QVector3D(0, 0, 1);
break;
case SketchFeature::SketchPlane::YZ: // Right
u_axis = QVector3D(0, 1, 0);
v_axis = QVector3D(0, 0, 1);
break;
}
for (int i = 0; i < numSegments; ++i) {
double angle1 = 2.0 * M_PI * double(i) / double(numSegments);
QVector3D p1 = centerPos + radius * (cos(angle1) * u_axis + sin(angle1) * v_axis);
double angle2 = 2.0 * M_PI * double(i + 1) / double(numSegments);
QVector3D p2 = centerPos + radius * (cos(angle2) * u_axis + sin(angle2) * v_axis);
lineVertices << p1.x() << p1.y() << p1.z();
lineVertices << p2.x() << p2.y() << p2.z();
}
} else if (obj->type() == SketchObject::ObjectType::Rectangle) {
auto rect = static_cast<const SketchRectangle*>(obj);
const auto& p1 = rect->corner1();
const auto& p3 = rect->corner2();
gp_Pnt p2, p4;
if (sketch->plane() == SketchFeature::SketchPlane::XY) {
p2.SetCoord(p3.X(), p1.Y(), p1.Z());
p4.SetCoord(p1.X(), p3.Y(), p1.Z());
} else if (sketch->plane() == SketchFeature::SketchPlane::XZ) {
p2.SetCoord(p3.X(), p1.Y(), p1.Z());
p4.SetCoord(p1.X(), p1.Y(), p3.Z());
} else if (sketch->plane() == SketchFeature::SketchPlane::YZ) {
p2.SetCoord(p1.X(), p3.Y(), p1.Z());
p4.SetCoord(p1.X(), p1.Y(), p3.Z());
}
lineVertices << p1.X() << p1.Y() << p1.Z();
lineVertices << p2.X() << p2.Y() << p2.Z();
lineVertices << p2.X() << p2.Y() << p2.Z();
lineVertices << p3.X() << p3.Y() << p3.Z();
lineVertices << p3.X() << p3.Y() << p3.Z();
lineVertices << p4.X() << p4.Y() << p4.Z();
lineVertices << p4.X() << p4.Y() << p4.Z();
lineVertices << p1.X() << p1.Y() << p1.Z();
vertexCounts[p1] += 2;
vertexCounts[p2] += 2;
vertexCounts[p3] += 2;
vertexCounts[p4] += 2;
} }
} }
@@ -777,14 +603,57 @@ void ViewportWidget::drawSketch(const SketchFeature* sketch)
m_vbo.allocate(lineVertices.constData(), lineVertices.size() * sizeof(GLfloat)); m_vbo.allocate(lineVertices.constData(), lineVertices.size() * sizeof(GLfloat));
glDrawArrays(GL_LINES, 0, lineVertices.size() / 3); glDrawArrays(GL_LINES, 0, lineVertices.size() / 3);
} }
if (!pointVertices.isEmpty()) {
glEnable(GL_POINT_SMOOTH); QVector<gp_Pnt> unattachedVertices;
glEnable(GL_BLEND); for (const auto& pair : vertexCounts) {
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); if (pair.second == 1) {
m_vbo.allocate(pointVertices.constData(), pointVertices.size() * sizeof(GLfloat)); unattachedVertices.append(pair.first);
glDrawArrays(GL_POINTS, 0, pointVertices.size() / 3); }
glDisable(GL_BLEND); }
glDisable(GL_POINT_SMOOTH);
if (!unattachedVertices.isEmpty()) {
const float radius = 0.004f * -m_camera->uiCameraDistance();
const int numSegments = 16;
QMatrix4x4 invModelView = m_camera->modelViewMatrix().inverted();
QVector3D rightVec = invModelView.column(0).toVector3D();
QVector3D upVec = invModelView.column(1).toVector3D();
QVector<GLfloat> circleFillVertices;
QVector<GLfloat> circleOutlineVertices;
for (const auto& centerPnt : unattachedVertices) {
QVector3D center(centerPnt.X(), centerPnt.Y(), centerPnt.Z());
circleFillVertices << center.x() << center.y() << center.z(); // Center vertex for fan
QVector3D firstCircumferencePoint;
for (int i = 0; i < numSegments; ++i) {
float angle = (2.0f * M_PI * float(i)) / float(numSegments);
QVector3D p = center + radius * (cos(angle) * rightVec + sin(angle) * upVec);
if (i == 0) {
firstCircumferencePoint = p;
}
circleFillVertices << p.x() << p.y() << p.z();
circleOutlineVertices << p.x() << p.y() << p.z();
}
circleFillVertices << firstCircumferencePoint.x() << firstCircumferencePoint.y() << firstCircumferencePoint.z();
}
// Draw fills
m_shaderProgram->setUniformValue(m_colorLoc, QVector4D(0.2f, 0.3f, 0.3f, 1.0f));
m_vbo.allocate(circleFillVertices.constData(), circleFillVertices.size() * sizeof(GLfloat));
const int vertsPerFan = numSegments + 2;
for (size_t i = 0; i < unattachedVertices.size(); ++i) {
glDrawArrays(GL_TRIANGLE_FAN, i * vertsPerFan, vertsPerFan);
}
// Draw outlines
m_shaderProgram->setUniformValue(m_colorLoc, QVector4D(1.0f, 1.0f, 1.0f, 1.0f));
m_vbo.allocate(circleOutlineVertices.constData(), circleOutlineVertices.size() * sizeof(GLfloat));
const int vertsPerLoop = numSegments;
for (size_t i = 0; i < unattachedVertices.size(); ++i) {
glDrawArrays(GL_LINE_LOOP, i * vertsPerLoop, vertsPerLoop);
}
} }
glEnable(GL_DEPTH_TEST); glEnable(GL_DEPTH_TEST);
@@ -840,18 +709,18 @@ void ViewportWidget::drawSelectionPlanes()
}; };
// XY Plane (Top) // XY Plane (Top)
QVector<GLfloat> xyQuad = { planeOffset, 0, planeOffset, planeOffset + planeSize, 0, planeOffset, QVector<GLfloat> xyQuad = { planeOffset, -planeOffset, 0, planeOffset + planeSize, -planeOffset, 0,
planeOffset + planeSize, 0, planeOffset + planeSize, planeOffset, 0, planeOffset + planeSize }; planeOffset + planeSize, -planeOffset - planeSize, 0, planeOffset, -planeOffset - planeSize, 0 };
drawPlane(xyQuad, m_highlightedPlane == SketchPlane::XY); drawPlane(xyQuad, m_highlightedPlane == SketchPlane::XY);
// XZ Plane (Front) // XZ Plane (Front)
QVector<GLfloat> xzQuad = { planeOffset, planeOffset, 0, planeOffset + planeSize, planeOffset, 0, QVector<GLfloat> xzQuad = { planeOffset, 0, planeOffset, planeOffset + planeSize, 0, planeOffset,
planeOffset + planeSize, planeOffset + planeSize, 0, planeOffset, planeOffset + planeSize, 0 }; planeOffset + planeSize, 0, planeOffset + planeSize, planeOffset, 0, planeOffset + planeSize };
drawPlane(xzQuad, m_highlightedPlane == SketchPlane::XZ); drawPlane(xzQuad, m_highlightedPlane == SketchPlane::XZ);
// YZ Plane (Right) // YZ Plane (Right)
QVector<GLfloat> yzQuad = { 0, planeOffset, planeOffset, 0, planeOffset + planeSize, planeOffset, QVector<GLfloat> yzQuad = { 0, -planeOffset, planeOffset, 0, -planeOffset, planeOffset + planeSize,
0, planeOffset + planeSize, planeOffset + planeSize, 0, planeOffset, planeOffset + planeSize }; 0, -planeOffset - planeSize, planeOffset + planeSize, 0, -planeOffset - planeSize, planeOffset };
drawPlane(yzQuad, m_highlightedPlane == SketchPlane::YZ); drawPlane(yzQuad, m_highlightedPlane == SketchPlane::YZ);
glEnable(GL_CULL_FACE); glEnable(GL_CULL_FACE);
@@ -869,7 +738,7 @@ ViewportWidget::SketchPlane ViewportWidget::checkPlaneSelection(const QPoint& sc
// Check front to back to handle overlaps // Check front to back to handle overlaps
// YZ plane (Right) // YZ plane (Right)
intersection = unproject(screenPos, SketchPlane::YZ); intersection = unproject(screenPos, SketchPlane::YZ);
if (intersection.y() >= planeOffset && intersection.y() <= planeOffset + planeSize && if (intersection.y() >= -planeOffset - planeSize && intersection.y() <= -planeOffset &&
intersection.z() >= planeOffset && intersection.z() <= planeOffset + planeSize) { intersection.z() >= planeOffset && intersection.z() <= planeOffset + planeSize) {
return SketchPlane::YZ; return SketchPlane::YZ;
} }
@@ -877,14 +746,14 @@ ViewportWidget::SketchPlane ViewportWidget::checkPlaneSelection(const QPoint& sc
// XZ plane (Front) // XZ plane (Front)
intersection = unproject(screenPos, SketchPlane::XZ); intersection = unproject(screenPos, SketchPlane::XZ);
if (intersection.x() >= planeOffset && intersection.x() <= planeOffset + planeSize && if (intersection.x() >= planeOffset && intersection.x() <= planeOffset + planeSize &&
intersection.y() >= planeOffset && intersection.y() <= planeOffset + planeSize) { intersection.z() >= planeOffset && intersection.z() <= planeOffset + planeSize) {
return SketchPlane::XZ; return SketchPlane::XZ;
} }
// XY plane (Top) // XY plane (Top)
intersection = unproject(screenPos, SketchPlane::XY); intersection = unproject(screenPos, SketchPlane::XY);
if (intersection.x() >= planeOffset && intersection.x() <= planeOffset + planeSize && if (intersection.x() >= planeOffset && intersection.x() <= planeOffset + planeSize &&
intersection.z() >= planeOffset && intersection.z() <= planeOffset + planeSize) { intersection.y() >= -planeOffset - planeSize && intersection.y() <= -planeOffset) {
return SketchPlane::XY; return SketchPlane::XY;
} }

View File

@@ -1,3 +1,10 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#ifndef VIEWPORTWIDGET_H #ifndef VIEWPORTWIDGET_H
#define VIEWPORTWIDGET_H #define VIEWPORTWIDGET_H
@@ -20,6 +27,8 @@ class Document;
class FeatureBrowser; class FeatureBrowser;
class SketchFeature; class SketchFeature;
class Camera; class Camera;
class SketchTool;
class Snapping;
class ViewportWidget : public QOpenGLWidget, protected QOpenGLFunctions class ViewportWidget : public QOpenGLWidget, protected QOpenGLFunctions
{ {
@@ -38,6 +47,27 @@ public:
void setDocument(Document* document); void setDocument(Document* document);
QVector3D project(const QVector3D& worldCoord, const QMatrix4x4& modelView, const QMatrix4x4& projection, const QRect& viewport);
QVector3D unproject(const QPoint& screenPos, SketchPlane plane);
QOpenGLShaderProgram* shaderProgram() { return m_shaderProgram; }
QOpenGLBuffer& vbo() { return m_vbo; }
int colorLoc() const { return m_colorLoc; }
Camera* camera() const { return m_camera; }
Document* document() const { return m_document; }
SketchPlane currentPlane() const { return m_currentPlane; }
const QPoint& currentMousePos() const { return m_currentMousePos; }
bool isSnappingOrigin() const;
bool isSnappingVertex() const;
const gp_Pnt& snapVertex() const;
int activeTool() const { return m_activeTool; }
bool isSnappingHorizontal() const { return m_isSnappingHorizontal; }
bool isSnappingVertical() const { return m_isSnappingVertical; }
void setSnappingHorizontal(bool snapping);
void setSnappingVertical(bool snapping);
void addLine(const gp_Pnt& start, const gp_Pnt& end);
void deactivateActiveTool();
public slots: public slots:
void onSketchModeStarted(SketchPlane plane); void onSketchModeStarted(SketchPlane plane);
void onSketchModeEnded(); void onSketchModeEnded();
@@ -46,24 +76,28 @@ public slots:
signals: signals:
void lineAdded(const gp_Pnt& start, const gp_Pnt& end); void lineAdded(const gp_Pnt& start, const gp_Pnt& end);
void rectangleAdded(const gp_Pnt& corner1, const gp_Pnt& corner2);
void circleAdded(const gp_Pnt& center, double radius);
void planeSelected(SketchPlane plane); void planeSelected(SketchPlane plane);
void toolDeactivated(); void toolDeactivated();
private slots:
void onRestoreStateAnimationFinished();
protected: protected:
void initializeGL() override; void initializeGL() override;
void paintGL() override; void paintGL() override;
void resizeGL(int w, int h) override; void resizeGL(int w, int h) override;
void mousePressEvent(QMouseEvent *event) override; void mousePressEvent(QMouseEvent *event) override;
void mouseReleaseEvent(QMouseEvent *event) override;
void mouseMoveEvent(QMouseEvent *event) override; void mouseMoveEvent(QMouseEvent *event) override;
void wheelEvent(QWheelEvent *event) override; void wheelEvent(QWheelEvent *event) override;
void keyPressEvent(QKeyEvent *event) override; void keyPressEvent(QKeyEvent *event) override;
bool focusNextPrevChild(bool next) override;
private: private:
void initShaders(); void initShaders();
QVector3D project(const QVector3D& worldCoord, const QMatrix4x4& modelView, const QMatrix4x4& projection, const QRect& viewport);
QVector3D unproject(const QPoint& screenPos, SketchPlane plane);
void drawAxisLabels(QPainter& painter, const QMatrix4x4& modelView, const QMatrix4x4& projection);
void drawSketch(const SketchFeature* sketch); void drawSketch(const SketchFeature* sketch);
void drawSelectionPlanes(); void drawSelectionPlanes();
ViewportWidget::SketchPlane checkPlaneSelection(const QPoint& screenPos); ViewportWidget::SketchPlane checkPlaneSelection(const QPoint& screenPos);
@@ -88,19 +122,15 @@ private:
SketchPlane m_highlightedPlane = SketchPlane::NONE; SketchPlane m_highlightedPlane = SketchPlane::NONE;
int m_activeTool = 0; int m_activeTool = 0;
bool m_isDefiningLine = false; SketchTool* m_activeSketchTool = nullptr;
gp_Pnt m_firstLinePoint; QMap<int, SketchTool*> m_sketchTools;
QPoint m_currentMousePos; QPoint m_currentMousePos;
bool m_isSnappingOrigin = false; Snapping* m_snapping = nullptr;
bool m_isSnappingVertex = false;
gp_Pnt m_snapVertex;
bool m_isSnappingHorizontal = false; bool m_isSnappingHorizontal = false;
bool m_isSnappingVertical = false; bool m_isSnappingVertical = false;
QMap<int, QSvgRenderer*> m_toolIcons; QMap<int, QSvgRenderer*> m_toolIcons;
QSvgRenderer* m_cursorRenderer = nullptr; QSvgRenderer* m_cursorRenderer = nullptr;
QPoint lastPos;
}; };
#endif // VIEWPORTWIDGET_H #endif // VIEWPORTWIDGET_H

View File

@@ -1,3 +1,10 @@
// Unnamed CAD Software
//
// License: GPLv3 (or later)
// Language: C++17
// Notes:
// - use a right-handed, Z-up coordinate system to match Open CASCADE
#include <QApplication> #include <QApplication>
#include "MainWindow.h" #include "MainWindow.h"
#include "ApplicationController.h" #include "ApplicationController.h"

View File

@@ -5,8 +5,10 @@ out vec4 FragColor;
in vec2 TexCoord; in vec2 TexCoord;
uniform sampler2D texture_diffuse1; uniform sampler2D texture_diffuse1;
uniform float opacity;
void main() void main()
{ {
FragColor = texture(texture_diffuse1, TexCoord); vec4 texColor = texture(texture_diffuse1, TexCoord);
FragColor = vec4(texColor.rgb, texColor.a * opacity);
} }